From 094039ba95d69adae767ad9ac86540c80b25b719 Mon Sep 17 00:00:00 2001 From: yura Date: Thu, 29 Oct 2026 16:27:29 +0300 Subject: [PATCH 1/2] =?UTF-8?q?=D0=9B=D0=A0=203=20=E2=80=94=20=D0=91=D0=9F?= =?UTF-8?q?=D0=982303=20=E2=80=94=20=D0=9B=D0=B0=D0=B7=D0=B0=D1=80=D0=B5?= =?UTF-8?q?=D0=B2=20=E2=80=94=20=D0=BD=D0=B0=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 27 +- Dockerfile | 30 + REPORT.md | 187 +++- compose.yaml | 123 +++ evidence/before-fix/login-flood-events.txt | 5 + evidence/before-fix/login-flood.json | 54 + evidence/before-fix/overload-c192.json | 303 ++++++ evidence/before-fix/overload-c64.json | 387 +++++++ evidence/db-hang-readiness.txt | 5 + evidence/failover-each.txt | 21 + evidence/failover-kill-mtusi-lab3-api-1.json | 514 +++++++++ evidence/failover-kill-mtusi-lab3-api-2.json | 521 +++++++++ evidence/failover-stop-mtusi-lab3-api-1.json | 517 +++++++++ evidence/failover-stop-mtusi-lab3-api-2.json | 517 +++++++++ evidence/failover.txt | 4 + evidence/idempotency-concurrency.json | 23 + evidence/login-flood-app-only.json | 46 + evidence/login-flood.json | 47 + evidence/overload-c192.json | 351 ++++++ evidence/overload-c64.json | 375 +++++++ evidence/persistence.txt | 3 + evidence/pre-submit-cursor.txt | 1 + evidence/pre-submit-failover.txt | 4 + evidence/pre-submit-idempotency.json | 23 + evidence/pre-submit-idempotency.txt | 24 + evidence/pre-submit-persistence.txt | 3 + evidence/pre-submit-rolling-action.txt | 10 + evidence/pre-submit-rolling-update.json | 1018 +++++++++++++++++ evidence/pre-submit-rolling-update.txt | 74 ++ evidence/pre-submit-script-errors.txt | 2 + evidence/pre-submit-smoke.txt | 2 + evidence/rolling-update.json | 1020 ++++++++++++++++++ evidence/rolling-update.txt | 20 + evidence/smoke.txt | 2 + infra/haproxy/haproxy.cfg | 98 ++ migrations/001_init.sql | 40 + migrations/002_idempotency.sql | 17 + requirements.txt | 3 + scripts/failover-each.sh | 50 + scripts/init-secrets.sh | 19 + scripts/restart.sh | 7 + scripts/rolling-update.sh | 57 + scripts/start-all.sh | 7 + scripts/stop-one.sh | 21 + src/migrate.py | 28 + src/security.py | 53 + src/server.py | 655 +++++++++++ src/store.py | 296 +++++ student-tests/cursor_validation.py | 32 + student-tests/failover_bench.py | 264 +++++ student-tests/idempotency_concurrency.py | 130 +++ student-tests/login_flood.py | 172 +++ 52 files changed, 8192 insertions(+), 20 deletions(-) create mode 100644 Dockerfile create mode 100644 compose.yaml create mode 100644 evidence/before-fix/login-flood-events.txt create mode 100644 evidence/before-fix/login-flood.json create mode 100644 evidence/before-fix/overload-c192.json create mode 100644 evidence/before-fix/overload-c64.json create mode 100644 evidence/db-hang-readiness.txt create mode 100644 evidence/failover-each.txt create mode 100644 evidence/failover-kill-mtusi-lab3-api-1.json create mode 100644 evidence/failover-kill-mtusi-lab3-api-2.json create mode 100644 evidence/failover-stop-mtusi-lab3-api-1.json create mode 100644 evidence/failover-stop-mtusi-lab3-api-2.json create mode 100644 evidence/failover.txt create mode 100644 evidence/idempotency-concurrency.json create mode 100644 evidence/login-flood-app-only.json create mode 100644 evidence/login-flood.json create mode 100644 evidence/overload-c192.json create mode 100644 evidence/overload-c64.json create mode 100644 evidence/persistence.txt create mode 100644 evidence/pre-submit-cursor.txt create mode 100644 evidence/pre-submit-failover.txt create mode 100644 evidence/pre-submit-idempotency.json create mode 100644 evidence/pre-submit-idempotency.txt create mode 100644 evidence/pre-submit-persistence.txt create mode 100644 evidence/pre-submit-rolling-action.txt create mode 100644 evidence/pre-submit-rolling-update.json create mode 100644 evidence/pre-submit-rolling-update.txt create mode 100644 evidence/pre-submit-script-errors.txt create mode 100644 evidence/pre-submit-smoke.txt create mode 100644 evidence/rolling-update.json create mode 100644 evidence/rolling-update.txt create mode 100644 evidence/smoke.txt create mode 100644 infra/haproxy/haproxy.cfg create mode 100644 migrations/001_init.sql create mode 100644 migrations/002_idempotency.sql create mode 100644 requirements.txt create mode 100755 scripts/failover-each.sh create mode 100755 scripts/init-secrets.sh create mode 100755 scripts/restart.sh create mode 100755 scripts/rolling-update.sh create mode 100755 scripts/start-all.sh create mode 100755 scripts/stop-one.sh create mode 100644 src/migrate.py create mode 100644 src/security.py create mode 100644 src/server.py create mode 100644 src/store.py create mode 100644 student-tests/cursor_validation.py create mode 100644 student-tests/failover_bench.py create mode 100644 student-tests/idempotency_concurrency.py create mode 100644 student-tests/login_flood.py diff --git a/.env.example b/.env.example index d32b9be0..47d106a8 100644 --- a/.env.example +++ b/.env.example @@ -1,13 +1,30 @@ # Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. +# scripts/init-secrets.sh делает это сам и создаёт secrets/postgres_password. APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab SESSION_TTL_SECONDS=3600 -# Choose credentials locally. File paths contain no secret values. -DATABASE_URL_FILE=/run/secrets/database_url -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: +# Пароль БД НЕ задаётся здесь: он в файле secrets/postgres_password (Docker secret), +# в контейнерах виден как /run/secrets/postgres_password (POSTGRES_PASSWORD_FILE). +# Вместо DATABASE_URL_FILE из skeleton используется POSTGRES_* + POSTGRES_PASSWORD_FILE; +# приложение понимает и DATABASE_URL_FILE (см. REPORT.md). +POSTGRES_DB=messenger +POSTGRES_USER=messenger +# Сессии хранятся в PostgreSQL (lab2), Redis/Valkey не используется: SESSION_STORE=postgres -CACHE_URL_FILE=/run/secrets/cache_url API_REPLICAS=2 IDEMPOTENCY_TTL_SECONDS=86400 +DB_POOL_SIZE=10 +# Graceful shutdown реплики: пауза с ready=503 и лимит на дообслуживание запросов. +DRAIN_SECONDS=3 +SHUTDOWN_TIMEOUT_SECONDS=10 +LB_PORT=8080 +APP_VERSION=1 +# Защита от OOM при шторме входов: одновременных scrypt на реплику и ожидание слота (с). +PASSWORD_HASH_CONCURRENCY=2 +PASSWORD_HASH_WAIT_SECONDS=0.5 +# Readiness: фоновый пинг БД (с) и сколько секунд без успешного пинга реплика ещё «готова». +DB_HEALTH_INTERVAL_SECONDS=1 +READY_STALE_SECONDS=3 +# Попыток POST /auth/sessions за 10 с с одного IP на LB (сверх — 429). +LOGIN_RATE_LIMIT=20 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..c61c3b94 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,30 @@ +# Lab3: мессенджер на Python + PostgreSQL. Один образ для API-реплик и job миграций. +FROM python:3.12.7-slim + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + APP_HOST=0.0.0.0 \ + APP_PORT=8080 + +WORKDIR /app + +# Сначала зависимости (закреплённые версии) — слой кэшируется, пока не изменится requirements.txt. +COPY requirements.txt /app/ +RUN pip install --no-cache-dir -r requirements.txt + +COPY src/ /app/src/ +COPY migrations/ /app/migrations/ + +# Метка версии сборки (rolling update: scripts/rolling-update.sh собирает с новым значением). +ARG APP_VERSION=1 +ENV APP_VERSION=${APP_VERSION} + +RUN useradd --no-create-home --uid 10001 app +USER app + +EXPOSE 8080 +# Python-процесс — PID 1 (exec-форма), сам обрабатывает SIGTERM (graceful shutdown). +STOPSIGNAL SIGTERM +HEALTHCHECK --interval=5s --timeout=2s --start-period=10s --retries=2 \ + CMD ["python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2).status == 200 else 1)"] +CMD ["python", "/app/src/server.py"] diff --git a/REPORT.md b/REPORT.md index c2679005..395f94ec 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,194 @@ # Отчёт — лабораторная 3 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Лазарев Юрий Сергеевич, БПИ2303 +- Целевая оценка; выбранный трек 5, если нужен: **3**, трек 5 не заявлен +- Ветка решения: `codex/lab3-bpi2303-lazarev`; fork: [zemiles/mtusi2026lab3](https://gitea.privcloud.tech/zemiles/mtusi2026lab3). +- Использованные источники, библиотеки и помощь ИИ: Python 3.12 (стандартная библиотека: `http.server`, `hashlib`, `secrets`, `threading`), `psycopg[binary]==3.2.3`, `psycopg-pool==3.2.4`; образы `python:3.12.7-slim`, `postgres:16.4-alpine` (`sha256:5660c2cb…e64c`), `haproxy:3.0.5-alpine` (`sha256:43a2591a…e949`). Документация: Docker Compose (services, secrets, deploy.resources), HAProxy 3.0 Configuration Manual (`server-template`, `resolvers`, `http-check`, `retry-on`), PostgreSQL (row locks, advisory locks). Код перенесён из моей lab2 и доработан с помощью ИИ-ассистента (Claude); проверен и запущен автором. Дополнительная проверка и исправления перед публикацией 29.10.2026 выполнены с помощью ChatGPT/Codex. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Проверено: MacBook Air M3, 16 GB RAM, macOS 26.4; Docker Desktop 28.0.4 (VM: 8 vCPU, 7.7 GiB), Compose v2.34.0; Python 3.12 на хосте только для тестов. Порты `127.0.0.1:8080` (LB) и `127.0.0.1:8404` (статистика HAProxy) должны быть свободны. + +```sh +# 0. Локальные секреты и .env (не коммитятся; значения не печатаются; повторный запуск ничего не перезаписывает) +./scripts/init-secrets.sh # secrets/postgres_password + .env из .env.example + +# 1. Проверка конфигурации, сборка, миграции (однократный job), запуск, ожидание готовности +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build --wait +# порядок: db (healthy) -> migrate (exit 0) -> api x2 (healthy) -> lb +docker compose ps # api-1, api-2 healthy; migrate Exited (0); порты только у lb + +# 2. Проверки +make test +make test-persistence ACTION_SCRIPT=scripts/restart.sh +make test-failover ACTION_SCRIPT=scripts/stop-one.sh && ./scripts/start-all.sh +python3 student-tests/idempotency_concurrency.py --rounds 20 --parallel 16 +./scripts/failover-each.sh stop kill # уровень 4: каждая реплика, SIGTERM и SIGKILL +python3 student-tests/failover_bench.py --duration 75 --action-at 10 \ + --action "scripts/rolling-update.sh 3" --output evidence/rolling-update.json + +# 3. Безопасная остановка (данные сохраняются в volume pgdata) +docker compose stop # или: docker compose down (контейнеры удаляются, volume остаётся) + +# 4. Намеренное удаление учебных данных (НЕОБРАТИМО: удаляет volume с БД) +docker compose down -v +``` + +Время прогрева: от `up` до готовности ~15 с (сборка из кэша), без кэша ~1 мин. Действия оператора, кроме перечисленных, не требуются. Масштабирование: `docker compose up -d --no-deps --scale api=3 api` — конфигурацию LB менять не нужно (до 8 реплик). ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +``` +клиент ──HTTP──> lb (HAProxy 3.0, 127.0.0.1:8080) ──roundrobin──> api × N (по умолчанию 2, без опубликованных портов) + │ + migrate (однократный job перед api) ──────────> db (PostgreSQL 16, volume pgdata) +``` + +| Роль | Service | Образ | Health/readiness | Volume | Сеть / порт | Credentials | +| --- | --- | --- | --- | --- | --- | --- | +| LB | `lb` | `haproxy:3.0.5-alpine` | проверка конфигурации; сам проверяет API | — | frontend+backend; `127.0.0.1:8080`, `127.0.0.1:8404` | нет | +| API | `api` (×`API_REPLICAS`) | `mtusi-messenger:lab3` (собирается из `Dockerfile`) | `/health/live`, `/health/ready` (Docker healthcheck + HAProxy) | — (без состояния) | backend; `8080` только внутри | secret `postgres_password` | +| Миграции | `migrate` | тот же образ, `python src/migrate.py` | exit 0 | — | backend | secret `postgres_password` | +| БД | `db` | `postgres:16.4-alpine` | `pg_isready` | `pgdata` | backend (`internal: true`) | secret `postgres_password` | + +- **Источник истины — PostgreSQL:** пользователи, чаты, сообщения, сессии (как в lab2) и ключи идемпотентности. В памяти API нет ничего, от чего зависит корректность, поэтому любой запрос может обслужить любая реплика. Sticky sessions не используются (`balance roundrobin`, без cookie/stick-table). +- **Из lab2 перенесено:** REST API, scrypt, Bearer-сессии в PostgreSQL, keyset-пагинация, формат ошибок. В lab2 (на 4) был кэш сессий в Valkey. В lab3 он не перенесён: контракт разрешает хранить сессии в PostgreSQL, а лишняя зависимость — лишняя точка отказа на пути запроса. +- **Изменено в lab3:** + - `X-Instance-Id` в каждом ответе (hostname контейнера = короткий ID контейнера Docker; стабилен на жизнь процесса); + - обязательный `Idempotency-Key` для POST сообщения; + - миграции вынесены из старта API в job `migrate`; + - graceful shutdown по SIGTERM; + - пароль БД — Docker secret (файл) вместо переменной окружения; + - дополнительный заголовок `X-App-Version` (версия образа, нужна для проверки rolling update). Он обратно совместим и не меняет обязательный контракт. +- **Идемпотентность** (`migrations/002_idempotency.sql`, `Store.add_message`). Таблица `idempotency_keys`, PK `(user_id, chat_id, idem_key)`: метод всегда POST, путь однозначно задаётся `chat_id`. В одной транзакции выполняется: + 1. `SELECT … FOR UPDATE` строки чата с проверкой членства (сериализует запись в один чат); + 2. поиск ключа: тот же SHA-256 канонического JSON тела → вернуть сохранённое сообщение с тем же 201; другой хеш → 409; + 3. иначе `INSERT` сообщения и ключа. + + Сообщение и ключ фиксируются атомарно: при ошибке/обрыве не сохраняется ни то, ни другое, и клиент безопасно повторяет запрос с тем же ключом. Конкурентные повторы через разные реплики ждут блокировку строки чата и после COMMIT первого видят его ключ; PK — дополнительная страховка. Ключ живёт `IDEMPOTENCY_TTL_SECONDS` = 24 ч; ключ с истёкшим сроком при повторе освобождается. Перед ответом из ключа заново проверяются сессия и доступ к чату. +- **Транзакционные границы:** создание чата с участниками — одна транзакция; отправка сообщения вместе с ключом — одна транзакция. Цена: запись в **один** чат сериализована (блокировка строки чата) — это осознанное ограничение ради монотонного `created_at` в keyset-пагинации. + +### Health, таймауты и остановка (согласованы между собой) + +| Параметр | Значение | Где | +| --- | --- | --- | +| Период проверки readiness HAProxy | `inter 1s`, после первой неудачи `fastinter 500ms`; `fall 2` / `rise 2`; `timeout check 1s` | `infra/haproxy/haproxy.cfg` | +| **Максимальное время обнаружения отказа** | ≈ 1 с (ожидание очередной проверки) + 1 с (таймаут) + 0,5 с + 1 с ≈ **3,5 с**; для ready=503/refused без таймаутов ≈ 1,5 с. Измерено: 1,3–1,7 с | расчёт + `evidence/failover-*.json` (`lb_events`) | +| Обновление адресов backend | DNS Docker `127.0.0.11`, `server-template api 8 api:8080`, `hold * 2s` | haproxy.cfg | +| LB → API | `timeout connect 500ms`, `timeout server 10s`, `retries 2` + `retry-on conn-failure` + `option redispatch` (повтор только если соединение НЕ установлено → безопасно и для POST) | haproxy.cfg | +| Конкуренция на реплику | `maxconn 10` на сервер (= `DB_POOL_SIZE`): избыток ждёт в очереди LB `timeout queue 5s`, переполнение → 503 JSON | haproxy.cfg | +| Ошибки самого LB | 400/408/429/500/502/503/504 HAProxy отдаёт в общем JSON-формате ошибки (`http-error … lf-string`), `request_id` = `X-Request-Id` = UUID; у 502/503/504 `Retry-After: 1` | haproxy.cfg | +| Вход (`POST /auth/sessions`) | LB: не более `LOGIN_RATE_LIMIT=20` попыток за 10 с с IP → 429 `rate_limited`, `Retry-After: 10`. API: не более `PASSWORD_HASH_CONCURRENCY=2` одновременных scrypt, слот ждём `PASSWORD_HASH_WAIT_SECONDS=0.5` → иначе 503 + `Retry-After: 1` | haproxy.cfg, `src/server.py` | +| Клиент → LB | `timeout http-request 10s`, `timeout client 30s` | haproxy.cfg | +| API → PostgreSQL | `connect_timeout 3s`, ожидание соединения из пула 3 с (`PoolTimeout` → 503), `statement_timeout 5s` (→ 503) | `src/server.py`, `src/store.py` | +| Сокет клиента в API | 30 с | `CLIENT_SOCKET_TIMEOUT_SECONDS` | +| SIGTERM | ready → 503 и `Connection: close` → `DRAIN_SECONDS=3` реплика ещё обслуживает запросы (LB успевает её исключить: 3 с > 1,5 с) → listener закрывается → ожидание in-flight до `SHUTDOWN_TIMEOUT_SECONDS=10` → выход | `src/server.py` | +| `stop_grace_period` API | 20 с > 3 + 10: Docker не пошлёт SIGKILL раньше завершения drain | `compose.yaml` | + +Согласованность: `statement_timeout 5s` и ожидание пула 3 с меньше `timeout server 10s`, поэтому на зависшую БД API отвечает 503 раньше, чем LB оборвёт запрос. Critical dependency для `/health/ready` — только PostgreSQL. Её состояние проверяет фоновый поток `DbHealth` со **своим** соединением (вне пула запросов): `SELECT 1` каждые `DB_HEALTH_INTERVAL_SECONDS=1` с, реплика «готова», пока последний успешный пинг не старше `READY_STALE_SECONDS=3` с. Поэтому проверка готовности не ждёт соединение из пула под нагрузкой и не может из-за перегрузки одновременно увести все реплики в DOWN. Цена: отказ БД обнаруживается за ≤ 3 с (staleness) + ≈1,5 с (HAProxy) вместо ≈1,5 с. Опция `on-marked-down shutdown-sessions` проверялась и отклонена: при штатной остановке она обрывала запросы, которые реплика ещё дообслуживала (1 лишний 502 на прогон). + +### Ресурсы, порты, секреты + +- Лимиты: `api` 0.5 CPU / 256 MiB на реплику, `db` 1 CPU / 512 MiB, `lb` 0.5 CPU / 128 MiB, `migrate` 0.5 CPU / 128 MiB (`deploy.resources.limits`, применяются Compose v2: `docker stats` показывает лимит 256MiB). +- Наружу опубликован только `lb` и только на `127.0.0.1`. У `api` есть только `expose`, сеть `backend` — `internal: true`. `container_name` нигде не задан, `api` масштабируется через `--scale`. +- Пароль БД — Docker secret `postgres_password` (`secrets/postgres_password`, создаётся `init-secrets.sh`). Он подключён только `db`, `migrate`, `api`; у `lb` его нет. Volume `pgdata` есть только у `db`. + +### Миграции и совместимость + +`migrate` выполняется **один раз** перед стартом/заменой API (`depends_on: service_completed_successfully`; в rolling update — `docker compose run --rm migrate`). Внутри — `pg_advisory_lock`: повторный параллельный запуск job не устроит гонку; каждый файл применяется в своей транзакции и фиксируется в `schema_migrations`. Реплики миграции **не применяют**: при старте они ждут, пока схема дойдёт до версии их образа. Миграция `002` только добавляет таблицу (expand-only), поэтому совместима с работающей предыдущей версией. **Ограничение:** удаляющие/переименовывающие изменения схемы так безопасно не выкатить — нужен цикл expand → замена реплик → contract отдельным релизом; в этой работе таких изменений нет. + +### Соответствие `.env.example` + +| Переменная skeleton | Реализация | +| --- | --- | +| `APP_HOST`, `APP_PORT`, `APP_ENV`, `SESSION_TTL_SECONDS`, `IDEMPOTENCY_TTL_SECONDS`, `API_REPLICAS` | используются как есть | +| `DATABASE_URL_FILE` | поддерживается приложением; в compose используется `POSTGRES_HOST/PORT/DB/USER` + `POSTGRES_PASSWORD_FILE=/run/secrets/postgres_password` (тот же секрет нужен образу postgres) | +| `SESSION_STORE=postgres` | сессии в PostgreSQL | +| `CACHE_URL_FILE` | не используется (Redis/Valkey в lab3 нет) | +| добавлены | `POSTGRES_DB`, `POSTGRES_USER`, `DB_POOL_SIZE`, `DRAIN_SECONDS`, `SHUTDOWN_TIMEOUT_SECONDS`, `LB_PORT`, `APP_VERSION`, `PASSWORD_HASH_CONCURRENCY`, `PASSWORD_HASH_WAIT_SECONDS`, `DB_HEALTH_INTERVAL_SECONDS`, `READY_STALE_SECONDS`, `LOGIN_RATE_LIMIT` (для `lb`) | ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Публичный smoke | `make test` | PASS | `evidence/smoke.txt` | +| 3: стенд в compose.yaml, ≥2 API, одна точка входа, одна БД, общие сессии | `docker compose up -d --build --wait`, `docker compose ps` | api-1/api-2 healthy, порт только у lb | `compose.yaml`, `evidence/failover.txt` | +| 3: запросы одного пользователя на разных репликах без повторного входа | `make test-failover` (40 запросов `/users/me` одним токеном); `curl -sD- localhost:8080/health/ready` ×4 | `observed_instances_before: 2`; `X-Instance-Id` чередуются | `evidence/failover.txt` | +| 3: остановка любой реплики, восстановление ≤10 с, подтверждённые сообщения на месте | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` ×2 + `failover-each.sh` | PASS, 0 неуспешных попыток, восстановление 3,3–3,9 с от старта hook (hook сам длится ~3,5 с из-за drain); остановленный контейнер `Exited (0)` | `evidence/failover.txt`, `evidence/failover-each.txt` | +| 3: тот же Idempotency-Key не создаёт дубль, в т.ч. конкурентно и через другую реплику | `student-tests/idempotency_concurrency.py --rounds 20 --parallel 16` | 640 запросов на 2 реплики (по 160 на каждую в сериях с одинаковым телом): одинаковое тело — 320×201 и один id на серию; разные тела — 160×201 + 160×409; 40 сообщений в истории, 0 дублей | `evidence/idempotency-concurrency.json` | +| 3: persistence | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS; `StartedAt` всех контейнеров (db, api×2, lb) изменился — перезапуск реальный, тот же токен действителен | `evidence/persistence.txt` | +| 4: health/readiness, timeouts, SIGTERM согласованы; LB исключает backend | см. таблицу выше; `failover-each.sh stop` | HAProxy пометил реплику DOWN через 1,46/1,39 с после SIGTERM, последний ответ от неё — через 1,53/1,39 с; **0 ошибок** | `evidence/failover-stop-*.json` | +| 4: поочерёдно остановить каждую реплику под нагрузкой; RPS, ошибки, восстановление | `scripts/failover-each.sh stop kill` | 4 прогона, все PASS — см. таблицу экспериментов | `evidence/failover-{stop,kill}-mtusi-lab3-api-{1,2}.json` | +| 4: параллельные запросы с одним ключом | `idempotency_concurrency.py`; в failover-bench повторы с исходным ключом после ошибки | см. выше; в kill-прогонах 5 и 1 POST повторены с тем же ключом, дублей 0 | `evidence/idempotency-concurrency.json`, `evidence/failover-kill-*.json` | +| 4: лимиты CPU/RAM, API без внешних портов, секреты/хранилища только где нужно, нет container_name | `docker compose config`, `docker stats`, `docker compose ps` | см. раздел «Ресурсы» | `compose.yaml` | +| 4: rolling update под нагрузкой; миграции однократно и совместимы | `failover_bench.py --action "scripts/rolling-update.sh 4"` | 0 ошибок из 25 013 запросов; версии v3 → смесь v3/v4 → только v4; migrate выполнен 1 раз | `evidence/rolling-update.txt` (вкл. лог скрипта), `evidence/rolling-update.json` | +| Перегрузка: шторм входов не роняет реплики | `student-tests/login_flood.py --parallel 24 --duration 20` | до доработки: OOM-kill обеих реплик (exit 137), 502/таймауты; после: 0 OOM, 0 рестартов, параллельный «пользователь» 300/300 × 200 | `evidence/before-fix/login-flood*.{json,txt}`, `evidence/login-flood.json`, `evidence/login-flood-app-only.json` | +| Ошибки LB в формате контракта | `docker compose stop api` → `curl -D- …/users/me`; шторм входов | 503/429 от HAProxy: `application/json`, `{"error":{"code","message","request_id"}}`, `X-Request-Id`, `Retry-After` | `infra/haproxy/haproxy.cfg`, `evidence/login-flood.json` (`non_contract_error_bodies: {}`) | +| Readiness не зависит от пула запросов; зависание БД обнаруживается | `docker compose pause db` / `unpause db` | `/health/ready` через LB → 503 `unavailable` через 2,92 с; после `unpause` → 200 через 0,11 с | `evidence/db-hang-readiness.txt` | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +**Методика.** `student-tests/failover_bench.py`: 8 потоков closed-loop через LB, смесь 1:1 `POST /messages` (уникальный Idempotency-Key; после ошибки/таймаута — повтор с тем же ключом и телом) и `GET /messages?limit=20`. Таймаут клиента 2 с, длительность 40 с (rolling — 75 с), действие на 10-й секунде, первая секунда — прогрев. Параллельно каждые 200 мс опрашивается статистика HAProxy (переходы UP/DOWN). В конце вся история читается тем же токеном: проверяются потерянные подтверждённые сообщения и дубли. Набор данных: новый чат на прогон, 2,5–12 тыс. сообщений к концу. Лимиты: 0.5 CPU/256 MiB на API, 1 CPU на БД. Каждая конфигурация отказа прогнана по одному разу на каждую реплику, всего 4 прогона. В репозитории сохранён результат rolling v3→v4; более ранние прогоны не используются в таблице. Это иллюстрация, а не статистика. Hardware: Apple M3, Docker Desktop VM 8 vCPU. Восстановление = конец окна ошибок (после него все запросы успешны). | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| `docker stop` api-1 (SIGTERM, drain) | без ошибок | базово 287 ok RPS → 77 RPS на одной реплике; 0 ошибок; LB DOWN через 1,46 с; последний ответ реплики 1,53 с | 0 с / 0 потерь, 0 дублей | +| `docker stop` api-2 (SIGTERM) | без ошибок | 262 → 77 RPS; 0 ошибок; DOWN 1,39 с | 0 с / 0 / 0 | +| `docker kill` api-1 (SIGKILL) | ошибки только у запросов в обработке | 282 → 80 RPS; 7×502 в окне 0,039–0,049 с; HAProxy исключил по DNS/проверке через 1,72 с; новые запросы к мёртвому адресу ушли в retry (conn-failure) | 0,05 с / 0 потерь, 0 дублей (5 POST повторены тем же ключом) | +| `docker kill` api-2 (SIGKILL) | то же | 278 → 79 RPS; 3×502 на 0,033 с; DOWN через 1,75 с | 0,03 с / 0 / 0 (1 POST повторён) | +| rolling update v3→v4 (под нагрузкой) | без ошибок, ≥2 реплик всё время | 279 RPS до, 291 после; 0 ошибок из 25 013; p50/p95/p99 = 8,8/84/100 мс; замена 2 реплик за 24 с | — / 0 потерь, 0 дублей | +| `make test-persistence` (рестарт db, api, lb) | данные и токен сохраняются | PASS, все контейнеры перезапущены (новый `StartedAt`) | в пределах лимита теста (hook ≤90 с + готовность ≤90 с) / 0 | + +p50/p95/p99 успешных запросов в прогонах отказов: ≈ 30–69 / 176–183 / 290–390 мс (большая часть прогона — на одной перегруженной реплике); в rolling update v3→v4 — 8,8/84,3/100,1 мс (`evidence/rolling-update.json`). + +**Наблюдение о мощности.** Две реплики вместе давали ~262–287 ok RPS, одна оставшаяся — ~77–80, т.е. меньше половины. **Гипотеза (не проверена):** при лимите 0.5 CPU на реплику и вдвое большей конкуренции (8 потоков на одну реплику) растут CPU-троттлинг CFS и конкуренция потоков за GIL Python. Проверка: `cpu.stat` (nr_throttled) реплики при разной конкуренции. Вывод для эксплуатации: при N=2 потеря реплики не вызывает ошибок, но запас мощности должен покрывать нагрузку одной реплики — либо нужно N≥3. + +### Защита от перегрузки (доработка после ревью) + +Ревью нашло два способа уронить сервис перегрузкой, хотя отказы отдельных реплик стенд уже переживал. Все прогоны ниже — по одному разу на этой машине, это иллюстрация, а не статистика. + +1. **Шторм входов → OOM.** scrypt (`N=2^15, r=8`) берёт `128·r·N` = 32 MiB на проверку, лимит реплики 256 MiB. Локально 8 параллельных scrypt заняли 269 MiB. Исправление: семафор `PASSWORD_HASH_CONCURRENCY=2` на вход и регистрацию (слот ждём 0,5 с, иначе 503 + `Retry-After: 1`) и лимит частоты входов на LB (`LOGIN_RATE_LIMIT=20` за 10 с с IP → 429 `rate_limited`). +2. **Readiness делила пул соединений с запросами.** Под перегрузкой проверка могла ждать соединение дольше `timeout check 1s` и одновременно увести все реплики в DOWN. Исправление: фоновый `DbHealth` со своим соединением, а на LB — `maxconn 10` на реплику (= размер пула) с очередью `timeout queue 5s`, чтобы избыток ждал в LB, а не плодил потоки в Python-процессе. **Сам каскад воспроизвести не удалось** даже при 192 клиентах (`lb_events` пусты и до, и после), поэтому это профилактика, а не исправление наблюдённого сбоя. +3. **Ошибки HAProxy были HTML-страницами.** Теперь это JSON общего формата ошибки (`http-error … lf-string`). + +| Сценарий (`login_flood.py`, `failover_bench.py --action true`) | До | После | +| --- | --- | --- | +| 24 параллельных неверных входа, 20 с | обе реплики OOM-kill (exit 137, `docker events`); 27×502 + 15 таймаутов; 28 ответов не в формате контракта; у параллельного «пользователя» 1 ошибка из 32 | 0 OOM, 0 рестартов; LB: 429 `rate_limited`; «пользователь» 300/300 × 200; 0 ответов вне контракта | +| то же, лимит LB выключен (`LOGIN_RATE_LIMIT=1000000`) — работает только семафор | — | 0 OOM, 0 рестартов; 315×401 + 346×503 (все с `Retry-After`); «пользователь» 91/91 × 200 | +| 64 клиента, смесь POST/GET, 30 с | 237 ok RPS; p50/p95/p99 = 205/596/1398 мс; 0 ошибок; DOWN нет | 286 ok RPS; 192/412/665 мс; 0 ошибок; DOWN нет | +| 192 клиента, 30 с | 194 ok RPS; 619/1522/10970 мс; 0 ошибок; DOWN нет | 277 ok RPS; 562/975/6780 мс; 0 ошибок; DOWN нет | + +Файлы: `evidence/before-fix/` (до), `evidence/login-flood*.json`, `evidence/overload-c{64,192}.json` (после). Рост RPS и снижение хвостов при перегрузке объясняются `maxconn`: избыток ждёт в очереди LB, а не конкурирует внутри реплики за 0,5 CPU и GIL. Доля мощности одной реплики при отказе другой (`capacity_ratio` ≈ 0,27–0,29) от этого **не изменилась**: гипотеза о CFS-троттлинге остаётся непроверенной. + +**Ограничения измерений:** closed-loop генератор (coordinated omission), клиент и стенд на одном ноутбуке, по одному прогону на сценарий; RPS сравнимы только между прогонами этого скрипта на этой машине. ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- **Выдерживается:** остановка/падение одной API-реплики (штатная и SIGKILL), поочерёдная замена всех реплик, рестарт всего стенда с сохранением volume. +- **Не выдерживается:** отказ PostgreSQL (одна БД без реплики → `/health/ready` = 503 у всех API, запросы → 503), отказ HAProxy (единственный LB), потеря Docker-host. Несколько API-процессов на одном хосте не делают стенд высокодоступным. +- Ошибки при SIGKILL (502 у запросов в обработке) неустранимы на уровне LB без небезопасного повтора POST; клиент повторяет с тем же Idempotency-Key — это и проверено. +- Запись в один чат сериализована блокировкой строки чата — предел пропускной способности одного «горячего» чата. +- Очистка истёкших ключей идемпотентности не автоматизирована: истёкший ключ перезаписывается при повторном использовании, остальные остаются в таблице. Следующий шаг — периодический `DELETE … WHERE expires_at < now()` пачками. +- Rolling update сделан скриптом поверх Compose (`--scale N+1` → healthy → UP в HAProxy по IP → stop старой). Это не атомарная операция оркестратора: при падении скрипта посередине останется N+1 реплик разных версий (без потери данных), их нужно сократить вручную. +- Лимит входов на LB считается по IP источника. За NAT все клиенты делят один лимит, а в Docker Desktop все клиенты с хоста приходят с одного адреса. Счётчик отказанных попыток тоже растёт, поэтому перебирающий пароль клиент остаётся заблокирован, пока не замолчит на 10 с. Таблица живёт в памяти единственного LB и сбрасывается при его перезапуске. Это защита от перебора и шторма, а не точная квота. +- Отказ БД теперь обнаруживается за ≤ 3 с (порог `READY_STALE_SECONDS`) + ≈1,5 с (HAProxy) — цена независимости readiness от пула запросов. +- `X-Instance-Id` раскрывает короткий ID контейнера — допустимо в lab3; в lab7 заменить на случайный alias. + +## Проверка перед публикацией — 29.10.2026 + +Заявляемая оценка: **3**. Исправлен ответ на cursor с датой за границами Python datetime: теперь 400 вместо 500, добавлена проверка для истории сообщений и списка чатов. Скрипты восстановления/обновления больше не скрывают неуспешный запуск Docker или миграций; агрегатор отказов возвращает ошибку при FAIL. Обязательные `tests/` и `contracts/` не изменены. + +На исправленном коде выполнены: + +- `make check`, `git diff --check`, `docker compose --env-file .env config --quiet`; сборка и запуск через `docker compose --env-file .env up -d --build --wait`. +- `make test`: PASS (`evidence/pre-submit-smoke.txt`). +- `python3 student-tests/cursor_validation.py`: PASS, 6 проверок (`evidence/pre-submit-cursor.txt`). +- `python3 student-tests/idempotency_concurrency.py --rounds 20 --parallel 16`: PASS, 640 запросов через 2 реплики, 40 сообщений, 0 дублей (`evidence/pre-submit-idempotency.json`). +- `make test-persistence ACTION_SCRIPT=scripts/restart.sh`: PASS (`evidence/pre-submit-persistence.txt`). +- `make test-failover ACTION_SCRIPT=scripts/stop-one.sh`: PASS, наблюдались 2 реплики, 129 успешных записей, 0 неуспешных попыток; восстановление по метрике публичного теста 3,692 с (`evidence/pre-submit-failover.txt`). Реплика затем восстановлена. +- Проверка ошибок shell-скриптов подставным Docker: код 42 не скрывается, после неудачной миграции замена реплик не начинается, `.env` не меняется (`evidence/pre-submit-script-errors.txt`). + +Дополнительно повторена поочерёдная замена v4→v5 под нагрузкой: `python3 student-tests/failover_bench.py --duration 75 --action-at 10 --action "scripts/rolling-update.sh 5"`. Результат: PASS, 25368 успешных запросов, 0 ошибок, потерь 0, дублей 0; p50/p95/p99 = 9.7/81.3/104.6 мс. Полный результат — `evidence/pre-submit-rolling-update.json`, журнал действий — `evidence/pre-submit-rolling-action.txt`. Эта серия отделена от результатов 24.10.2026 выше. + +После проверок работают две healthy API-реплики, PostgreSQL и HAProxy. Секрет БД, `.env` и приватные ключи исключены из состава коммита; локальные данные сохранены. diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..3898ca81 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,123 @@ +# Lab3: HAProxy -> API x N (по умолчанию 2) -> общая PostgreSQL (данные + сессии + ключи идемпотентности). +# Запуск: ./scripts/init-secrets.sh && docker compose --env-file .env up -d --build --wait +name: mtusi-lab3 + +x-api-image: &api-image + build: + context: . + args: + APP_VERSION: ${APP_VERSION:-1} + image: mtusi-messenger:lab3 + +x-db-env: &db-env + POSTGRES_HOST: db + POSTGRES_PORT: "5432" + POSTGRES_DB: ${POSTGRES_DB:-messenger} + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + +services: + db: + image: postgres:16.4-alpine + environment: + POSTGRES_DB: ${POSTGRES_DB:-messenger} + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: [postgres_password] + volumes: + - pgdata:/var/lib/postgresql/data # данные переживают перезапуск контейнера + networks: [backend] + healthcheck: + test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""] + interval: 2s + timeout: 3s + retries: 30 + stop_grace_period: 30s + deploy: + resources: + limits: {cpus: "1.0", memory: 512M} + + # Однократный job миграций: выполняется до старта API и завершается (exit 0). + # Реплики миграции не применяют, а только ждут нужной версии схемы. + migrate: + <<: *api-image + command: ["python", "/app/src/migrate.py"] + environment: + <<: *db-env + secrets: [postgres_password] + networks: [backend] + healthcheck: {disable: true} + restart: "no" + depends_on: + db: {condition: service_healthy} + deploy: + resources: + limits: {cpus: "0.5", memory: 128M} + + api: + <<: *api-image + # Без container_name и без ports: масштабируется `--scale api=N`, доступен только через LB. + expose: ["8080"] + environment: + <<: *db-env + APP_HOST: 0.0.0.0 + APP_PORT: "8080" + APP_ENV: ${APP_ENV:-lab} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + DB_POOL_SIZE: ${DB_POOL_SIZE:-10} + DRAIN_SECONDS: ${DRAIN_SECONDS:-3} + SHUTDOWN_TIMEOUT_SECONDS: ${SHUTDOWN_TIMEOUT_SECONDS:-10} + # Не более 2 одновременных scrypt (~32 MiB каждый) при лимите 256 MiB на реплику. + PASSWORD_HASH_CONCURRENCY: ${PASSWORD_HASH_CONCURRENCY:-2} + PASSWORD_HASH_WAIT_SECONDS: ${PASSWORD_HASH_WAIT_SECONDS:-0.5} + DB_HEALTH_INTERVAL_SECONDS: ${DB_HEALTH_INTERVAL_SECONDS:-1} + READY_STALE_SECONDS: ${READY_STALE_SECONDS:-3} + secrets: [postgres_password] + networks: [backend] + restart: unless-stopped + # DRAIN(3) + дообслуживание(<=10) < 20: Docker не убьёт процесс SIGKILL раньше. + stop_grace_period: 20s + depends_on: + db: {condition: service_healthy} + migrate: {condition: service_completed_successfully} + deploy: + replicas: ${API_REPLICAS:-2} + resources: + limits: {cpus: "0.5", memory: 256M} + + lb: + image: haproxy:3.0.5-alpine + volumes: + - ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + environment: + # Попыток входа за 10 с с одного IP (frontend stick-table в haproxy.cfg). + LOGIN_RATE_LIMIT: ${LOGIN_RATE_LIMIT:-20} + ports: + - "127.0.0.1:${LB_PORT:-8080}:8080" # единственная публичная точка API + - "127.0.0.1:8404:8404" # статистика HAProxy, только localhost + networks: [frontend, backend] + restart: unless-stopped + healthcheck: + test: ["CMD", "haproxy", "-c", "-q", "-f", "/usr/local/etc/haproxy/haproxy.cfg"] + interval: 10s + timeout: 3s + retries: 3 + depends_on: + api: {condition: service_started} + deploy: + resources: + limits: {cpus: "0.5", memory: 128M} + +# Секрет нужен только db, migrate и api; у LB его нет. +secrets: + postgres_password: + file: ./secrets/postgres_password + +networks: + frontend: {} + backend: + internal: true # db и api недоступны извне, кроме как через LB + +volumes: + pgdata: {} diff --git a/evidence/before-fix/login-flood-events.txt b/evidence/before-fix/login-flood-events.txt new file mode 100644 index 00000000..b6cbb0c6 --- /dev/null +++ b/evidence/before-fix/login-flood-events.txt @@ -0,0 +1,5 @@ +1792853107 die mtusi-lab3-migrate-1 exit=0 +1792853165 oom mtusi-lab3-api-2 exit= +1792853165 die mtusi-lab3-api-2 exit=137 +1792853169 oom mtusi-lab3-api-1 exit= +1792853169 die mtusi-lab3-api-1 exit=137 diff --git a/evidence/before-fix/login-flood.json b/evidence/before-fix/login-flood.json new file mode 100644 index 00000000..cc637515 --- /dev/null +++ b/evidence/before-fix/login-flood.json @@ -0,0 +1,54 @@ +{ + "parallel": 24, + "duration_s": 25.8, + "flood_statuses": { + "401": 105, + "exc:TimeoutError": 15, + "502": 27, + "503": 1 + }, + "flood_rps": 5.7, + "flood_503_with_retry_after": "0/1", + "victim_statuses": { + "200": 31, + "502": 1 + }, + "victim_error_rate": 0.0312, + "non_contract_error_bodies": { + "502": 28 + }, + "containers_before": { + "mtusi-lab3-api-1": { + "status": "running", + "oom_killed": false, + "restart_count": 0, + "started_at": "2026-10-24T14:45:08.148914882Z" + }, + "mtusi-lab3-api-2": { + "status": "running", + "oom_killed": false, + "restart_count": 0, + "started_at": "2026-10-24T14:45:08.219078174Z" + } + }, + "containers_after": { + "mtusi-lab3-api-1": { + "status": "running", + "oom_killed": false, + "restart_count": 1, + "started_at": "2026-10-24T14:46:09.779499716Z" + }, + "mtusi-lab3-api-2": { + "status": "running", + "oom_killed": false, + "restart_count": 1, + "started_at": "2026-10-24T14:46:05.172108464Z" + } + }, + "oom_killed": [], + "restarted": [ + "mtusi-lab3-api-1", + "mtusi-lab3-api-2" + ], + "pass": false +} diff --git a/evidence/before-fix/overload-c192.json b/evidence/before-fix/overload-c192.json new file mode 100644 index 00000000..3aa92bcc --- /dev/null +++ b/evidence/before-fix/overload-c192.json @@ -0,0 +1,303 @@ +{ + "label": "overload c=192 before", + "concurrency": 192, + "duration_s": 30.0, + "request_timeout_s": 2.0, + "action": { + "command": "true", + "started_s": 5.079, + "finished_s": 5.09, + "exit_code": 0 + }, + "baseline_ok_rps": 0, + "overall_ok_rps": 194.0, + "requests_ok": 5821, + "errors_total": 0, + "error_rate": 0.0, + "errors_by_kind": {}, + "error_window_s": null, + "recovery_s": 0.0, + "post_action_ok_rps": 268.9, + "capacity_ratio": null, + "latency_ok_ms": { + "p50": 619.3, + "p95": 1521.6, + "p99": 10969.5 + }, + "target_instance": null, + "target_last_seen_s": null, + "lb_events": [], + "posts_retried_same_key": 0, + "confirmed_messages": 2965, + "history_messages": 2965, + "lost_confirmed": 0, + "duplicate_ids": 0, + "duplicate_texts": 0, + "timeline": [ + { + "t": 9, + "ok": 182, + "err": 0, + "instances": { + "d0cda5a67630": 92, + "e48bc201f2d2": 90 + }, + "versions": { + "3": 182 + } + }, + { + "t": 10, + "ok": 180, + "err": 0, + "instances": { + "d0cda5a67630": 106, + "e48bc201f2d2": 74 + }, + "versions": { + "3": 180 + } + }, + { + "t": 11, + "ok": 316, + "err": 0, + "instances": { + "d0cda5a67630": 180, + "e48bc201f2d2": 136 + }, + "versions": { + "3": 316 + } + }, + { + "t": 12, + "ok": 200, + "err": 0, + "instances": { + "e48bc201f2d2": 110, + "d0cda5a67630": 90 + }, + "versions": { + "3": 200 + } + }, + { + "t": 13, + "ok": 326, + "err": 0, + "instances": { + "d0cda5a67630": 135, + "e48bc201f2d2": 191 + }, + "versions": { + "3": 326 + } + }, + { + "t": 14, + "ok": 300, + "err": 0, + "instances": { + "e48bc201f2d2": 120, + "d0cda5a67630": 180 + }, + "versions": { + "3": 300 + } + }, + { + "t": 15, + "ok": 199, + "err": 0, + "instances": { + "d0cda5a67630": 114, + "e48bc201f2d2": 85 + }, + "versions": { + "3": 199 + } + }, + { + "t": 16, + "ok": 314, + "err": 0, + "instances": { + "d0cda5a67630": 195, + "e48bc201f2d2": 119 + }, + "versions": { + "3": 314 + } + }, + { + "t": 17, + "ok": 249, + "err": 0, + "instances": { + "e48bc201f2d2": 117, + "d0cda5a67630": 132 + }, + "versions": { + "3": 249 + } + }, + { + "t": 18, + "ok": 249, + "err": 0, + "instances": { + "d0cda5a67630": 113, + "e48bc201f2d2": 136 + }, + "versions": { + "3": 249 + } + }, + { + "t": 19, + "ok": 339, + "err": 0, + "instances": { + "e48bc201f2d2": 172, + "d0cda5a67630": 167 + }, + "versions": { + "3": 339 + } + }, + { + "t": 20, + "ok": 356, + "err": 0, + "instances": { + "e48bc201f2d2": 190, + "d0cda5a67630": 166 + }, + "versions": { + "3": 356 + } + }, + { + "t": 21, + "ok": 257, + "err": 0, + "instances": { + "e48bc201f2d2": 144, + "d0cda5a67630": 113 + }, + "versions": { + "3": 257 + } + }, + { + "t": 22, + "ok": 204, + "err": 0, + "instances": { + "d0cda5a67630": 109, + "e48bc201f2d2": 95 + }, + "versions": { + "3": 204 + } + }, + { + "t": 23, + "ok": 280, + "err": 0, + "instances": { + "e48bc201f2d2": 144, + "d0cda5a67630": 136 + }, + "versions": { + "3": 280 + } + }, + { + "t": 24, + "ok": 226, + "err": 0, + "instances": { + "e48bc201f2d2": 134, + "d0cda5a67630": 92 + }, + "versions": { + "3": 226 + } + }, + { + "t": 25, + "ok": 301, + "err": 0, + "instances": { + "e48bc201f2d2": 155, + "d0cda5a67630": 146 + }, + "versions": { + "3": 301 + } + }, + { + "t": 26, + "ok": 316, + "err": 0, + "instances": { + "d0cda5a67630": 157, + "e48bc201f2d2": 159 + }, + "versions": { + "3": 316 + } + }, + { + "t": 27, + "ok": 337, + "err": 0, + "instances": { + "d0cda5a67630": 182, + "e48bc201f2d2": 155 + }, + "versions": { + "3": 337 + } + }, + { + "t": 28, + "ok": 248, + "err": 0, + "instances": { + "e48bc201f2d2": 79, + "d0cda5a67630": 169 + }, + "versions": { + "3": 248 + } + }, + { + "t": 29, + "ok": 249, + "err": 0, + "instances": { + "e48bc201f2d2": 148, + "d0cda5a67630": 101 + }, + "versions": { + "3": 249 + } + }, + { + "t": 30, + "ok": 193, + "err": 0, + "instances": { + "d0cda5a67630": 36, + "e48bc201f2d2": 157 + }, + "versions": { + "3": 193 + } + } + ], + "pass": true +} diff --git a/evidence/before-fix/overload-c64.json b/evidence/before-fix/overload-c64.json new file mode 100644 index 00000000..977a4fab --- /dev/null +++ b/evidence/before-fix/overload-c64.json @@ -0,0 +1,387 @@ +{ + "label": "overload c=64 before", + "concurrency": 64, + "duration_s": 30.0, + "request_timeout_s": 2.0, + "action": { + "command": "true", + "started_s": 5.052, + "finished_s": 5.064, + "exit_code": 0 + }, + "baseline_ok_rps": 184.7, + "overall_ok_rps": 236.8, + "requests_ok": 7105, + "errors_total": 0, + "error_rate": 0.0, + "errors_by_kind": {}, + "error_window_s": null, + "recovery_s": 0.0, + "post_action_ok_rps": 246.9, + "capacity_ratio": 1.34, + "latency_ok_ms": { + "p50": 205.3, + "p95": 596.3, + "p99": 1397.8 + }, + "target_instance": null, + "target_last_seen_s": null, + "lb_events": [], + "posts_retried_same_key": 0, + "confirmed_messages": 3570, + "history_messages": 3570, + "lost_confirmed": 0, + "duplicate_ids": 0, + "duplicate_texts": 0, + "timeline": [ + { + "t": 2, + "ok": 93, + "err": 0, + "instances": { + "d0cda5a67630": 38, + "e48bc201f2d2": 55 + }, + "versions": { + "3": 93 + } + }, + { + "t": 3, + "ok": 257, + "err": 0, + "instances": { + "d0cda5a67630": 113, + "e48bc201f2d2": 144 + }, + "versions": { + "3": 257 + } + }, + { + "t": 4, + "ok": 204, + "err": 0, + "instances": { + "e48bc201f2d2": 94, + "d0cda5a67630": 110 + }, + "versions": { + "3": 204 + } + }, + { + "t": 5, + "ok": 343, + "err": 0, + "instances": { + "e48bc201f2d2": 145, + "d0cda5a67630": 198 + }, + "versions": { + "3": 343 + } + }, + { + "t": 6, + "ok": 355, + "err": 0, + "instances": { + "d0cda5a67630": 191, + "e48bc201f2d2": 164 + }, + "versions": { + "3": 355 + } + }, + { + "t": 7, + "ok": 244, + "err": 0, + "instances": { + "d0cda5a67630": 124, + "e48bc201f2d2": 120 + }, + "versions": { + "3": 244 + } + }, + { + "t": 8, + "ok": 221, + "err": 0, + "instances": { + "e48bc201f2d2": 124, + "d0cda5a67630": 97 + }, + "versions": { + "3": 221 + } + }, + { + "t": 9, + "ok": 310, + "err": 0, + "instances": { + "e48bc201f2d2": 175, + "d0cda5a67630": 135 + }, + "versions": { + "3": 310 + } + }, + { + "t": 10, + "ok": 224, + "err": 0, + "instances": { + "e48bc201f2d2": 95, + "d0cda5a67630": 129 + }, + "versions": { + "3": 224 + } + }, + { + "t": 11, + "ok": 372, + "err": 0, + "instances": { + "e48bc201f2d2": 179, + "d0cda5a67630": 193 + }, + "versions": { + "3": 372 + } + }, + { + "t": 12, + "ok": 248, + "err": 0, + "instances": { + "d0cda5a67630": 133, + "e48bc201f2d2": 115 + }, + "versions": { + "3": 248 + } + }, + { + "t": 13, + "ok": 247, + "err": 0, + "instances": { + "d0cda5a67630": 118, + "e48bc201f2d2": 129 + }, + "versions": { + "3": 247 + } + }, + { + "t": 14, + "ok": 221, + "err": 0, + "instances": { + "d0cda5a67630": 116, + "e48bc201f2d2": 105 + }, + "versions": { + "3": 221 + } + }, + { + "t": 15, + "ok": 190, + "err": 0, + "instances": { + "e48bc201f2d2": 89, + "d0cda5a67630": 101 + }, + "versions": { + "3": 190 + } + }, + { + "t": 16, + "ok": 84, + "err": 0, + "instances": { + "d0cda5a67630": 37, + "e48bc201f2d2": 47 + }, + "versions": { + "3": 84 + } + }, + { + "t": 17, + "ok": 207, + "err": 0, + "instances": { + "e48bc201f2d2": 103, + "d0cda5a67630": 104 + }, + "versions": { + "3": 207 + } + }, + { + "t": 18, + "ok": 246, + "err": 0, + "instances": { + "e48bc201f2d2": 124, + "d0cda5a67630": 122 + }, + "versions": { + "3": 246 + } + }, + { + "t": 19, + "ok": 242, + "err": 0, + "instances": { + "e48bc201f2d2": 134, + "d0cda5a67630": 108 + }, + "versions": { + "3": 242 + } + }, + { + "t": 20, + "ok": 300, + "err": 0, + "instances": { + "d0cda5a67630": 139, + "e48bc201f2d2": 161 + }, + "versions": { + "3": 300 + } + }, + { + "t": 21, + "ok": 278, + "err": 0, + "instances": { + "d0cda5a67630": 144, + "e48bc201f2d2": 134 + }, + "versions": { + "3": 278 + } + }, + { + "t": 22, + "ok": 194, + "err": 0, + "instances": { + "d0cda5a67630": 115, + "e48bc201f2d2": 79 + }, + "versions": { + "3": 194 + } + }, + { + "t": 23, + "ok": 232, + "err": 0, + "instances": { + "d0cda5a67630": 118, + "e48bc201f2d2": 114 + }, + "versions": { + "3": 232 + } + }, + { + "t": 24, + "ok": 244, + "err": 0, + "instances": { + "e48bc201f2d2": 124, + "d0cda5a67630": 120 + }, + "versions": { + "3": 244 + } + }, + { + "t": 25, + "ok": 205, + "err": 0, + "instances": { + "d0cda5a67630": 82, + "e48bc201f2d2": 123 + }, + "versions": { + "3": 205 + } + }, + { + "t": 26, + "ok": 338, + "err": 0, + "instances": { + "e48bc201f2d2": 186, + "d0cda5a67630": 152 + }, + "versions": { + "3": 338 + } + }, + { + "t": 27, + "ok": 322, + "err": 0, + "instances": { + "d0cda5a67630": 149, + "e48bc201f2d2": 173 + }, + "versions": { + "3": 322 + } + }, + { + "t": 28, + "ok": 262, + "err": 0, + "instances": { + "d0cda5a67630": 157, + "e48bc201f2d2": 105 + }, + "versions": { + "3": 262 + } + }, + { + "t": 29, + "ok": 358, + "err": 0, + "instances": { + "e48bc201f2d2": 155, + "d0cda5a67630": 203 + }, + "versions": { + "3": 358 + } + }, + { + "t": 30, + "ok": 64, + "err": 0, + "instances": { + "d0cda5a67630": 7, + "e48bc201f2d2": 57 + }, + "versions": { + "3": 64 + } + } + ], + "pass": true +} diff --git a/evidence/db-hang-readiness.txt b/evidence/db-hang-readiness.txt new file mode 100644 index 00000000..5e169986 --- /dev/null +++ b/evidence/db-hang-readiness.txt @@ -0,0 +1,5 @@ +ready before: (200, '') +db paused (hang: TCP alive, no answers) +LB ready -> 503: 2.92s status=503 code=unavailable +db unpaused +LB ready -> 200: 0.11s status=200 code= diff --git a/evidence/failover-each.txt b/evidence/failover-each.txt new file mode 100644 index 00000000..f6258225 --- /dev/null +++ b/evidence/failover-each.txt @@ -0,0 +1,21 @@ +== stop mtusi-lab3-api-1 (832acbc47567) 2026-10-24T14:54:23Z +{"baseline_ok_rps": 286.8, "post_action_ok_rps": 76.7, "capacity_ratio": 0.27, "errors_total": 0, "errors_by_kind": {}, "error_window_s": null, "recovery_s": 0.0, "target_last_seen_s": 1.531, "lb_events": [{"t": 1.46, "server": "api1", "addr": "172.19.0.4:8080", "from": "UP", "to": "DOWN"}, {"t": 5.41, "server": "api1", "addr": "", "from": "DOWN", "to": "MAINT"}], "lost_confirmed": 0, "duplicate_texts": 0, "pass": true} +-- state after action: +mtusi-lab3-api-1 Exited (0) 27 seconds ago +mtusi-lab3-api-2 Up About a minute (healthy) +== stop mtusi-lab3-api-2 (617f40442335) 2026-10-24T14:55:10Z +{"baseline_ok_rps": 262.2, "post_action_ok_rps": 76.8, "capacity_ratio": 0.29, "errors_total": 0, "errors_by_kind": {}, "error_window_s": null, "recovery_s": 0.0, "target_last_seen_s": 1.387, "lb_events": [{"t": 1.39, "server": "api2", "addr": "172.19.0.3:8080", "from": "UP", "to": "DOWN"}, {"t": 5.48, "server": "api2", "addr": "", "from": "DOWN", "to": "MAINT"}], "lost_confirmed": 0, "duplicate_texts": 0, "pass": true} +-- state after action: +mtusi-lab3-api-1 Up 46 seconds (healthy) +mtusi-lab3-api-2 Exited (0) 26 seconds ago +== kill mtusi-lab3-api-1 (832acbc47567) 2026-10-24T14:55:56Z +{"baseline_ok_rps": 282.3, "post_action_ok_rps": 79.7, "capacity_ratio": 0.28, "errors_total": 7, "errors_by_kind": {"http_502": 7}, "error_window_s": [0.039, 0.049], "recovery_s": 0.049, "target_last_seen_s": 0.029, "lb_events": [{"t": 1.72, "server": "api1", "addr": "", "from": "UP", "to": "MAINT"}], "lost_confirmed": 0, "duplicate_texts": 0, "pass": true} +-- state after action: +mtusi-lab3-api-1 Exited (137) 30 seconds ago +mtusi-lab3-api-2 Up 46 seconds (healthy) +== kill mtusi-lab3-api-2 (617f40442335) 2026-10-24T14:56:43Z +{"baseline_ok_rps": 277.6, "post_action_ok_rps": 79.2, "capacity_ratio": 0.29, "errors_total": 3, "errors_by_kind": {"http_502": 3}, "error_window_s": [0.033, 0.033], "recovery_s": 0.033, "target_last_seen_s": 0.028, "lb_events": [{"t": 1.75, "server": "api2", "addr": "172.19.0.3:8080", "from": "UP", "to": "DOWN"}, {"t": 1.96, "server": "api2", "addr": "", "from": "DOWN", "to": "MAINT"}], "lost_confirmed": 0, "duplicate_texts": 0, "pass": true} +-- state after action: +mtusi-lab3-api-1 Up 46 seconds (healthy) +mtusi-lab3-api-2 Exited (137) 30 seconds ago +== restored: mtusi-lab3-api-1 Up 52 seconds (healthy);mtusi-lab3-api-2 Up 5 seconds (healthy); diff --git a/evidence/failover-kill-mtusi-lab3-api-1.json b/evidence/failover-kill-mtusi-lab3-api-1.json new file mode 100644 index 00000000..a23c5148 --- /dev/null +++ b/evidence/failover-kill-mtusi-lab3-api-1.json @@ -0,0 +1,514 @@ +{ + "label": "kill mtusi-lab3-api-1", + "concurrency": 8, + "duration_s": 40.0, + "request_timeout_s": 2.0, + "action": { + "command": "docker kill 832acbc475675355489483b84dbf15784e0991adec4770a9249bc3d1648877b3", + "started_s": 10.009, + "finished_s": 10.197, + "exit_code": 0 + }, + "baseline_ok_rps": 282.3, + "overall_ok_rps": 126.9, + "requests_ok": 5075, + "errors_total": 7, + "error_rate": 0.00138, + "errors_by_kind": { + "http_502": 7 + }, + "error_window_s": [ + 0.039, + 0.049 + ], + "recovery_s": 0.049, + "post_action_ok_rps": 79.7, + "capacity_ratio": 0.28, + "latency_ok_ms": { + "p50": 65.0, + "p95": 182.6, + "p99": 387.2 + }, + "target_instance": "832acbc47567", + "target_last_seen_s": 0.029, + "lb_events": [ + { + "t": 1.72, + "server": "api1", + "addr": "", + "from": "UP", + "to": "MAINT" + } + ], + "posts_retried_same_key": 5, + "confirmed_messages": 2538, + "history_messages": 2538, + "lost_confirmed": 0, + "duplicate_ids": 0, + "duplicate_texts": 0, + "timeline": [ + { + "t": 0, + "ok": 195, + "err": 0, + "instances": { + "832acbc47567": 98, + "617f40442335": 97 + }, + "versions": { + "3": 195 + } + }, + { + "t": 1, + "ok": 350, + "err": 0, + "instances": { + "617f40442335": 172, + "832acbc47567": 178 + }, + "versions": { + "3": 350 + } + }, + { + "t": 2, + "ok": 270, + "err": 0, + "instances": { + "617f40442335": 135, + "832acbc47567": 135 + }, + "versions": { + "3": 270 + } + }, + { + "t": 3, + "ok": 337, + "err": 0, + "instances": { + "617f40442335": 170, + "832acbc47567": 167 + }, + "versions": { + "3": 337 + } + }, + { + "t": 4, + "ok": 141, + "err": 0, + "instances": { + "832acbc47567": 72, + "617f40442335": 69 + }, + "versions": { + "3": 141 + } + }, + { + "t": 5, + "ok": 177, + "err": 0, + "instances": { + "617f40442335": 94, + "832acbc47567": 83 + }, + "versions": { + "3": 177 + } + }, + { + "t": 6, + "ok": 280, + "err": 0, + "instances": { + "832acbc47567": 138, + "617f40442335": 142 + }, + "versions": { + "3": 280 + } + }, + { + "t": 7, + "ok": 325, + "err": 0, + "instances": { + "832acbc47567": 170, + "617f40442335": 155 + }, + "versions": { + "3": 325 + } + }, + { + "t": 8, + "ok": 335, + "err": 0, + "instances": { + "617f40442335": 174, + "832acbc47567": 161 + }, + "versions": { + "3": 335 + } + }, + { + "t": 9, + "ok": 326, + "err": 0, + "instances": { + "832acbc47567": 162, + "617f40442335": 164 + }, + "versions": { + "3": 326 + } + }, + { + "t": 10, + "ok": 30, + "err": 7, + "instances": { + "832acbc47567": 1, + "617f40442335": 29 + }, + "versions": { + "3": 30 + } + }, + { + "t": 11, + "ok": 55, + "err": 0, + "instances": { + "617f40442335": 55 + }, + "versions": { + "3": 55 + } + }, + { + "t": 12, + "ok": 88, + "err": 0, + "instances": { + "617f40442335": 88 + }, + "versions": { + "3": 88 + } + }, + { + "t": 13, + "ok": 86, + "err": 0, + "instances": { + "617f40442335": 86 + }, + "versions": { + "3": 86 + } + }, + { + "t": 14, + "ok": 86, + "err": 0, + "instances": { + "617f40442335": 86 + }, + "versions": { + "3": 86 + } + }, + { + "t": 15, + "ok": 63, + "err": 0, + "instances": { + "617f40442335": 63 + }, + "versions": { + "3": 63 + } + }, + { + "t": 16, + "ok": 40, + "err": 0, + "instances": { + "617f40442335": 40 + }, + "versions": { + "3": 40 + } + }, + { + "t": 17, + "ok": 97, + "err": 0, + "instances": { + "617f40442335": 97 + }, + "versions": { + "3": 97 + } + }, + { + "t": 18, + "ok": 92, + "err": 0, + "instances": { + "617f40442335": 92 + }, + "versions": { + "3": 92 + } + }, + { + "t": 19, + "ok": 90, + "err": 0, + "instances": { + "617f40442335": 90 + }, + "versions": { + "3": 90 + } + }, + { + "t": 20, + "ok": 97, + "err": 0, + "instances": { + "617f40442335": 97 + }, + "versions": { + "3": 97 + } + }, + { + "t": 21, + "ok": 85, + "err": 0, + "instances": { + "617f40442335": 85 + }, + "versions": { + "3": 85 + } + }, + { + "t": 22, + "ok": 30, + "err": 0, + "instances": { + "617f40442335": 30 + }, + "versions": { + "3": 30 + } + }, + { + "t": 23, + "ok": 70, + "err": 0, + "instances": { + "617f40442335": 70 + }, + "versions": { + "3": 70 + } + }, + { + "t": 24, + "ok": 100, + "err": 0, + "instances": { + "617f40442335": 100 + }, + "versions": { + "3": 100 + } + }, + { + "t": 25, + "ok": 84, + "err": 0, + "instances": { + "617f40442335": 84 + }, + "versions": { + "3": 84 + } + }, + { + "t": 26, + "ok": 83, + "err": 0, + "instances": { + "617f40442335": 83 + }, + "versions": { + "3": 83 + } + }, + { + "t": 27, + "ok": 116, + "err": 0, + "instances": { + "617f40442335": 116 + }, + "versions": { + "3": 116 + } + }, + { + "t": 28, + "ok": 65, + "err": 0, + "instances": { + "617f40442335": 65 + }, + "versions": { + "3": 65 + } + }, + { + "t": 29, + "ok": 30, + "err": 0, + "instances": { + "617f40442335": 30 + }, + "versions": { + "3": 30 + } + }, + { + "t": 30, + "ok": 97, + "err": 0, + "instances": { + "617f40442335": 97 + }, + "versions": { + "3": 97 + } + }, + { + "t": 31, + "ok": 94, + "err": 0, + "instances": { + "617f40442335": 94 + }, + "versions": { + "3": 94 + } + }, + { + "t": 32, + "ok": 86, + "err": 0, + "instances": { + "617f40442335": 86 + }, + "versions": { + "3": 86 + } + }, + { + "t": 33, + "ok": 83, + "err": 0, + "instances": { + "617f40442335": 83 + }, + "versions": { + "3": 83 + } + }, + { + "t": 34, + "ok": 91, + "err": 0, + "instances": { + "617f40442335": 91 + }, + "versions": { + "3": 91 + } + }, + { + "t": 35, + "ok": 35, + "err": 0, + "instances": { + "617f40442335": 35 + }, + "versions": { + "3": 35 + } + }, + { + "t": 36, + "ok": 62, + "err": 0, + "instances": { + "617f40442335": 62 + }, + "versions": { + "3": 62 + } + }, + { + "t": 37, + "ok": 93, + "err": 0, + "instances": { + "617f40442335": 93 + }, + "versions": { + "3": 93 + } + }, + { + "t": 38, + "ok": 110, + "err": 0, + "instances": { + "617f40442335": 110 + }, + "versions": { + "3": 110 + } + }, + { + "t": 39, + "ok": 93, + "err": 0, + "instances": { + "617f40442335": 93 + }, + "versions": { + "3": 93 + } + }, + { + "t": 40, + "ok": 8, + "err": 0, + "instances": { + "617f40442335": 8 + }, + "versions": { + "3": 8 + } + } + ], + "pass": true +} diff --git a/evidence/failover-kill-mtusi-lab3-api-2.json b/evidence/failover-kill-mtusi-lab3-api-2.json new file mode 100644 index 00000000..be6284c6 --- /dev/null +++ b/evidence/failover-kill-mtusi-lab3-api-2.json @@ -0,0 +1,521 @@ +{ + "label": "kill mtusi-lab3-api-2", + "concurrency": 8, + "duration_s": 40.0, + "request_timeout_s": 2.0, + "action": { + "command": "docker kill 617f40442335bb8315280b690d0bd9fb56a3bb0a760d8daa3461bb6c6af8133b", + "started_s": 10.014, + "finished_s": 10.142, + "exit_code": 0 + }, + "baseline_ok_rps": 277.6, + "overall_ok_rps": 125.6, + "requests_ok": 5025, + "errors_total": 3, + "error_rate": 0.0006, + "errors_by_kind": { + "http_502": 3 + }, + "error_window_s": [ + 0.033, + 0.033 + ], + "recovery_s": 0.033, + "post_action_ok_rps": 79.2, + "capacity_ratio": 0.29, + "latency_ok_ms": { + "p50": 68.2, + "p95": 182.6, + "p99": 389.8 + }, + "target_instance": "617f40442335", + "target_last_seen_s": 0.028, + "lb_events": [ + { + "t": 1.75, + "server": "api2", + "addr": "172.19.0.3:8080", + "from": "UP", + "to": "DOWN" + }, + { + "t": 1.96, + "server": "api2", + "addr": "", + "from": "DOWN", + "to": "MAINT" + } + ], + "posts_retried_same_key": 1, + "confirmed_messages": 2516, + "history_messages": 2516, + "lost_confirmed": 0, + "duplicate_ids": 0, + "duplicate_texts": 0, + "timeline": [ + { + "t": 0, + "ok": 152, + "err": 0, + "instances": { + "617f40442335": 79, + "832acbc47567": 73 + }, + "versions": { + "3": 152 + } + }, + { + "t": 1, + "ok": 332, + "err": 0, + "instances": { + "832acbc47567": 166, + "617f40442335": 166 + }, + "versions": { + "3": 332 + } + }, + { + "t": 2, + "ok": 282, + "err": 0, + "instances": { + "617f40442335": 140, + "832acbc47567": 142 + }, + "versions": { + "3": 282 + } + }, + { + "t": 3, + "ok": 299, + "err": 0, + "instances": { + "832acbc47567": 151, + "617f40442335": 148 + }, + "versions": { + "3": 299 + } + }, + { + "t": 4, + "ok": 141, + "err": 0, + "instances": { + "832acbc47567": 71, + "617f40442335": 70 + }, + "versions": { + "3": 141 + } + }, + { + "t": 5, + "ok": 170, + "err": 0, + "instances": { + "617f40442335": 84, + "832acbc47567": 86 + }, + "versions": { + "3": 170 + } + }, + { + "t": 6, + "ok": 330, + "err": 0, + "instances": { + "617f40442335": 169, + "832acbc47567": 161 + }, + "versions": { + "3": 330 + } + }, + { + "t": 7, + "ok": 328, + "err": 0, + "instances": { + "617f40442335": 164, + "832acbc47567": 164 + }, + "versions": { + "3": 328 + } + }, + { + "t": 8, + "ok": 307, + "err": 0, + "instances": { + "832acbc47567": 155, + "617f40442335": 152 + }, + "versions": { + "3": 307 + } + }, + { + "t": 9, + "ok": 309, + "err": 0, + "instances": { + "617f40442335": 156, + "832acbc47567": 153 + }, + "versions": { + "3": 309 + } + }, + { + "t": 10, + "ok": 56, + "err": 3, + "instances": { + "617f40442335": 11, + "832acbc47567": 45 + }, + "versions": { + "3": 56 + } + }, + { + "t": 11, + "ok": 85, + "err": 0, + "instances": { + "832acbc47567": 85 + }, + "versions": { + "3": 85 + } + }, + { + "t": 12, + "ok": 105, + "err": 0, + "instances": { + "832acbc47567": 105 + }, + "versions": { + "3": 105 + } + }, + { + "t": 13, + "ok": 94, + "err": 0, + "instances": { + "832acbc47567": 94 + }, + "versions": { + "3": 94 + } + }, + { + "t": 14, + "ok": 88, + "err": 0, + "instances": { + "832acbc47567": 88 + }, + "versions": { + "3": 88 + } + }, + { + "t": 15, + "ok": 65, + "err": 0, + "instances": { + "832acbc47567": 65 + }, + "versions": { + "3": 65 + } + }, + { + "t": 16, + "ok": 32, + "err": 0, + "instances": { + "832acbc47567": 32 + }, + "versions": { + "3": 32 + } + }, + { + "t": 17, + "ok": 79, + "err": 0, + "instances": { + "832acbc47567": 79 + }, + "versions": { + "3": 79 + } + }, + { + "t": 18, + "ok": 87, + "err": 0, + "instances": { + "832acbc47567": 87 + }, + "versions": { + "3": 87 + } + }, + { + "t": 19, + "ok": 93, + "err": 0, + "instances": { + "832acbc47567": 93 + }, + "versions": { + "3": 93 + } + }, + { + "t": 20, + "ok": 96, + "err": 0, + "instances": { + "832acbc47567": 96 + }, + "versions": { + "3": 96 + } + }, + { + "t": 21, + "ok": 96, + "err": 0, + "instances": { + "832acbc47567": 96 + }, + "versions": { + "3": 96 + } + }, + { + "t": 22, + "ok": 40, + "err": 0, + "instances": { + "832acbc47567": 40 + }, + "versions": { + "3": 40 + } + }, + { + "t": 23, + "ok": 85, + "err": 0, + "instances": { + "832acbc47567": 85 + }, + "versions": { + "3": 85 + } + }, + { + "t": 24, + "ok": 92, + "err": 0, + "instances": { + "832acbc47567": 92 + }, + "versions": { + "3": 92 + } + }, + { + "t": 25, + "ok": 90, + "err": 0, + "instances": { + "832acbc47567": 90 + }, + "versions": { + "3": 90 + } + }, + { + "t": 26, + "ok": 86, + "err": 0, + "instances": { + "832acbc47567": 86 + }, + "versions": { + "3": 86 + } + }, + { + "t": 27, + "ok": 89, + "err": 0, + "instances": { + "832acbc47567": 89 + }, + "versions": { + "3": 89 + } + }, + { + "t": 28, + "ok": 43, + "err": 0, + "instances": { + "832acbc47567": 43 + }, + "versions": { + "3": 43 + } + }, + { + "t": 29, + "ok": 29, + "err": 0, + "instances": { + "832acbc47567": 29 + }, + "versions": { + "3": 29 + } + }, + { + "t": 30, + "ok": 94, + "err": 0, + "instances": { + "832acbc47567": 94 + }, + "versions": { + "3": 94 + } + }, + { + "t": 31, + "ok": 96, + "err": 0, + "instances": { + "832acbc47567": 96 + }, + "versions": { + "3": 96 + } + }, + { + "t": 32, + "ok": 96, + "err": 0, + "instances": { + "832acbc47567": 96 + }, + "versions": { + "3": 96 + } + }, + { + "t": 33, + "ok": 93, + "err": 0, + "instances": { + "832acbc47567": 93 + }, + "versions": { + "3": 93 + } + }, + { + "t": 34, + "ok": 85, + "err": 0, + "instances": { + "832acbc47567": 85 + }, + "versions": { + "3": 85 + } + }, + { + "t": 35, + "ok": 33, + "err": 0, + "instances": { + "832acbc47567": 33 + }, + "versions": { + "3": 33 + } + }, + { + "t": 36, + "ok": 59, + "err": 0, + "instances": { + "832acbc47567": 59 + }, + "versions": { + "3": 59 + } + }, + { + "t": 37, + "ok": 96, + "err": 0, + "instances": { + "832acbc47567": 96 + }, + "versions": { + "3": 96 + } + }, + { + "t": 38, + "ok": 97, + "err": 0, + "instances": { + "832acbc47567": 97 + }, + "versions": { + "3": 97 + } + }, + { + "t": 39, + "ok": 88, + "err": 0, + "instances": { + "832acbc47567": 88 + }, + "versions": { + "3": 88 + } + }, + { + "t": 40, + "ok": 8, + "err": 0, + "instances": { + "832acbc47567": 8 + }, + "versions": { + "3": 8 + } + } + ], + "pass": true +} diff --git a/evidence/failover-stop-mtusi-lab3-api-1.json b/evidence/failover-stop-mtusi-lab3-api-1.json new file mode 100644 index 00000000..1b47a5aa --- /dev/null +++ b/evidence/failover-stop-mtusi-lab3-api-1.json @@ -0,0 +1,517 @@ +{ + "label": "stop mtusi-lab3-api-1", + "concurrency": 8, + "duration_s": 40.0, + "request_timeout_s": 2.0, + "action": { + "command": "docker stop -t 20 832acbc475675355489483b84dbf15784e0991adec4770a9249bc3d1648877b3", + "started_s": 10.015, + "finished_s": 13.396, + "exit_code": 0 + }, + "baseline_ok_rps": 286.8, + "overall_ok_rps": 138.6, + "requests_ok": 5543, + "errors_total": 0, + "error_rate": 0.0, + "errors_by_kind": {}, + "error_window_s": null, + "recovery_s": 0.0, + "post_action_ok_rps": 76.7, + "capacity_ratio": 0.27, + "latency_ok_ms": { + "p50": 29.7, + "p95": 175.6, + "p99": 290.4 + }, + "target_instance": "832acbc47567", + "target_last_seen_s": 1.531, + "lb_events": [ + { + "t": 1.46, + "server": "api1", + "addr": "172.19.0.4:8080", + "from": "UP", + "to": "DOWN" + }, + { + "t": 5.41, + "server": "api1", + "addr": "", + "from": "DOWN", + "to": "MAINT" + } + ], + "posts_retried_same_key": 0, + "confirmed_messages": 2774, + "history_messages": 2774, + "lost_confirmed": 0, + "duplicate_ids": 0, + "duplicate_texts": 0, + "timeline": [ + { + "t": 0, + "ok": 206, + "err": 0, + "instances": { + "832acbc47567": 102, + "617f40442335": 104 + }, + "versions": { + "3": 206 + } + }, + { + "t": 1, + "ok": 225, + "err": 0, + "instances": { + "832acbc47567": 110, + "617f40442335": 115 + }, + "versions": { + "3": 225 + } + }, + { + "t": 2, + "ok": 242, + "err": 0, + "instances": { + "832acbc47567": 121, + "617f40442335": 121 + }, + "versions": { + "3": 242 + } + }, + { + "t": 3, + "ok": 354, + "err": 0, + "instances": { + "832acbc47567": 179, + "617f40442335": 175 + }, + "versions": { + "3": 354 + } + }, + { + "t": 4, + "ok": 344, + "err": 0, + "instances": { + "832acbc47567": 173, + "617f40442335": 171 + }, + "versions": { + "3": 344 + } + }, + { + "t": 5, + "ok": 370, + "err": 0, + "instances": { + "832acbc47567": 189, + "617f40442335": 181 + }, + "versions": { + "3": 370 + } + }, + { + "t": 6, + "ok": 233, + "err": 0, + "instances": { + "617f40442335": 118, + "832acbc47567": 115 + }, + "versions": { + "3": 233 + } + }, + { + "t": 7, + "ok": 241, + "err": 0, + "instances": { + "617f40442335": 126, + "832acbc47567": 115 + }, + "versions": { + "3": 241 + } + }, + { + "t": 8, + "ok": 276, + "err": 0, + "instances": { + "832acbc47567": 138, + "617f40442335": 138 + }, + "versions": { + "3": 276 + } + }, + { + "t": 9, + "ok": 296, + "err": 0, + "instances": { + "832acbc47567": 150, + "617f40442335": 146 + }, + "versions": { + "3": 296 + } + }, + { + "t": 10, + "ok": 372, + "err": 0, + "instances": { + "617f40442335": 182, + "832acbc47567": 190 + }, + "versions": { + "3": 372 + } + }, + { + "t": 11, + "ok": 193, + "err": 0, + "instances": { + "617f40442335": 122, + "832acbc47567": 71 + }, + "versions": { + "3": 193 + } + }, + { + "t": 12, + "ok": 88, + "err": 0, + "instances": { + "617f40442335": 88 + }, + "versions": { + "3": 88 + } + }, + { + "t": 13, + "ok": 73, + "err": 0, + "instances": { + "617f40442335": 73 + }, + "versions": { + "3": 73 + } + }, + { + "t": 14, + "ok": 98, + "err": 0, + "instances": { + "617f40442335": 98 + }, + "versions": { + "3": 98 + } + }, + { + "t": 15, + "ok": 90, + "err": 0, + "instances": { + "617f40442335": 90 + }, + "versions": { + "3": 90 + } + }, + { + "t": 16, + "ok": 86, + "err": 0, + "instances": { + "617f40442335": 86 + }, + "versions": { + "3": 86 + } + }, + { + "t": 17, + "ok": 90, + "err": 0, + "instances": { + "617f40442335": 90 + }, + "versions": { + "3": 90 + } + }, + { + "t": 18, + "ok": 73, + "err": 0, + "instances": { + "617f40442335": 73 + }, + "versions": { + "3": 73 + } + }, + { + "t": 19, + "ok": 25, + "err": 0, + "instances": { + "617f40442335": 25 + }, + "versions": { + "3": 25 + } + }, + { + "t": 20, + "ok": 79, + "err": 0, + "instances": { + "617f40442335": 79 + }, + "versions": { + "3": 79 + } + }, + { + "t": 21, + "ok": 112, + "err": 0, + "instances": { + "617f40442335": 112 + }, + "versions": { + "3": 112 + } + }, + { + "t": 22, + "ok": 87, + "err": 0, + "instances": { + "617f40442335": 87 + }, + "versions": { + "3": 87 + } + }, + { + "t": 23, + "ok": 93, + "err": 0, + "instances": { + "617f40442335": 93 + }, + "versions": { + "3": 93 + } + }, + { + "t": 24, + "ok": 100, + "err": 0, + "instances": { + "617f40442335": 100 + }, + "versions": { + "3": 100 + } + }, + { + "t": 25, + "ok": 38, + "err": 0, + "instances": { + "617f40442335": 38 + }, + "versions": { + "3": 38 + } + }, + { + "t": 26, + "ok": 67, + "err": 0, + "instances": { + "617f40442335": 67 + }, + "versions": { + "3": 67 + } + }, + { + "t": 27, + "ok": 84, + "err": 0, + "instances": { + "617f40442335": 84 + }, + "versions": { + "3": 84 + } + }, + { + "t": 28, + "ok": 84, + "err": 0, + "instances": { + "617f40442335": 84 + }, + "versions": { + "3": 84 + } + }, + { + "t": 29, + "ok": 78, + "err": 0, + "instances": { + "617f40442335": 78 + }, + "versions": { + "3": 78 + } + }, + { + "t": 30, + "ok": 80, + "err": 0, + "instances": { + "617f40442335": 80 + }, + "versions": { + "3": 80 + } + }, + { + "t": 31, + "ok": 60, + "err": 0, + "instances": { + "617f40442335": 60 + }, + "versions": { + "3": 60 + } + }, + { + "t": 32, + "ok": 75, + "err": 0, + "instances": { + "617f40442335": 75 + }, + "versions": { + "3": 75 + } + }, + { + "t": 33, + "ok": 87, + "err": 0, + "instances": { + "617f40442335": 87 + }, + "versions": { + "3": 87 + } + }, + { + "t": 34, + "ok": 85, + "err": 0, + "instances": { + "617f40442335": 85 + }, + "versions": { + "3": 85 + } + }, + { + "t": 35, + "ok": 84, + "err": 0, + "instances": { + "617f40442335": 84 + }, + "versions": { + "3": 84 + } + }, + { + "t": 36, + "ok": 86, + "err": 0, + "instances": { + "617f40442335": 86 + }, + "versions": { + "3": 86 + } + }, + { + "t": 37, + "ok": 52, + "err": 0, + "instances": { + "617f40442335": 52 + }, + "versions": { + "3": 52 + } + }, + { + "t": 38, + "ok": 45, + "err": 0, + "instances": { + "617f40442335": 45 + }, + "versions": { + "3": 45 + } + }, + { + "t": 39, + "ok": 84, + "err": 0, + "instances": { + "617f40442335": 84 + }, + "versions": { + "3": 84 + } + }, + { + "t": 40, + "ok": 8, + "err": 0, + "instances": { + "617f40442335": 8 + }, + "versions": { + "3": 8 + } + } + ], + "pass": true +} diff --git a/evidence/failover-stop-mtusi-lab3-api-2.json b/evidence/failover-stop-mtusi-lab3-api-2.json new file mode 100644 index 00000000..9640c10f --- /dev/null +++ b/evidence/failover-stop-mtusi-lab3-api-2.json @@ -0,0 +1,517 @@ +{ + "label": "stop mtusi-lab3-api-2", + "concurrency": 8, + "duration_s": 40.0, + "request_timeout_s": 2.0, + "action": { + "command": "docker stop -t 20 617f40442335bb8315280b690d0bd9fb56a3bb0a760d8daa3461bb6c6af8133b", + "started_s": 10.011, + "finished_s": 13.559, + "exit_code": 0 + }, + "baseline_ok_rps": 262.2, + "overall_ok_rps": 129.5, + "requests_ok": 5179, + "errors_total": 0, + "error_rate": 0.0, + "errors_by_kind": {}, + "error_window_s": null, + "recovery_s": 0.0, + "post_action_ok_rps": 76.8, + "capacity_ratio": 0.29, + "latency_ok_ms": { + "p50": 69.0, + "p95": 178.4, + "p99": 301.6 + }, + "target_instance": "617f40442335", + "target_last_seen_s": 1.387, + "lb_events": [ + { + "t": 1.39, + "server": "api2", + "addr": "172.19.0.3:8080", + "from": "UP", + "to": "DOWN" + }, + { + "t": 5.48, + "server": "api2", + "addr": "", + "from": "DOWN", + "to": "MAINT" + } + ], + "posts_retried_same_key": 0, + "confirmed_messages": 2593, + "history_messages": 2593, + "lost_confirmed": 0, + "duplicate_ids": 0, + "duplicate_texts": 0, + "timeline": [ + { + "t": 0, + "ok": 187, + "err": 0, + "instances": { + "617f40442335": 97, + "832acbc47567": 90 + }, + "versions": { + "3": 187 + } + }, + { + "t": 1, + "ok": 287, + "err": 0, + "instances": { + "832acbc47567": 144, + "617f40442335": 143 + }, + "versions": { + "3": 287 + } + }, + { + "t": 2, + "ok": 218, + "err": 0, + "instances": { + "832acbc47567": 115, + "617f40442335": 103 + }, + "versions": { + "3": 218 + } + }, + { + "t": 3, + "ok": 282, + "err": 0, + "instances": { + "617f40442335": 144, + "832acbc47567": 138 + }, + "versions": { + "3": 282 + } + }, + { + "t": 4, + "ok": 199, + "err": 0, + "instances": { + "617f40442335": 102, + "832acbc47567": 97 + }, + "versions": { + "3": 199 + } + }, + { + "t": 5, + "ok": 286, + "err": 0, + "instances": { + "832acbc47567": 142, + "617f40442335": 144 + }, + "versions": { + "3": 286 + } + }, + { + "t": 6, + "ok": 328, + "err": 0, + "instances": { + "832acbc47567": 164, + "617f40442335": 164 + }, + "versions": { + "3": 328 + } + }, + { + "t": 7, + "ok": 267, + "err": 0, + "instances": { + "832acbc47567": 141, + "617f40442335": 126 + }, + "versions": { + "3": 267 + } + }, + { + "t": 8, + "ok": 208, + "err": 0, + "instances": { + "617f40442335": 104, + "832acbc47567": 104 + }, + "versions": { + "3": 208 + } + }, + { + "t": 9, + "ok": 285, + "err": 0, + "instances": { + "617f40442335": 150, + "832acbc47567": 135 + }, + "versions": { + "3": 285 + } + }, + { + "t": 10, + "ok": 235, + "err": 0, + "instances": { + "832acbc47567": 119, + "617f40442335": 116 + }, + "versions": { + "3": 235 + } + }, + { + "t": 11, + "ok": 168, + "err": 0, + "instances": { + "832acbc47567": 114, + "617f40442335": 54 + }, + "versions": { + "3": 168 + } + }, + { + "t": 12, + "ok": 90, + "err": 0, + "instances": { + "832acbc47567": 90 + }, + "versions": { + "3": 90 + } + }, + { + "t": 13, + "ok": 100, + "err": 0, + "instances": { + "832acbc47567": 100 + }, + "versions": { + "3": 100 + } + }, + { + "t": 14, + "ok": 102, + "err": 0, + "instances": { + "832acbc47567": 102 + }, + "versions": { + "3": 102 + } + }, + { + "t": 15, + "ok": 66, + "err": 0, + "instances": { + "832acbc47567": 66 + }, + "versions": { + "3": 66 + } + }, + { + "t": 16, + "ok": 37, + "err": 0, + "instances": { + "832acbc47567": 37 + }, + "versions": { + "3": 37 + } + }, + { + "t": 17, + "ok": 98, + "err": 0, + "instances": { + "832acbc47567": 98 + }, + "versions": { + "3": 98 + } + }, + { + "t": 18, + "ok": 87, + "err": 0, + "instances": { + "832acbc47567": 87 + }, + "versions": { + "3": 87 + } + }, + { + "t": 19, + "ok": 85, + "err": 0, + "instances": { + "832acbc47567": 85 + }, + "versions": { + "3": 85 + } + }, + { + "t": 20, + "ok": 85, + "err": 0, + "instances": { + "832acbc47567": 85 + }, + "versions": { + "3": 85 + } + }, + { + "t": 21, + "ok": 91, + "err": 0, + "instances": { + "832acbc47567": 91 + }, + "versions": { + "3": 91 + } + }, + { + "t": 22, + "ok": 37, + "err": 0, + "instances": { + "832acbc47567": 37 + }, + "versions": { + "3": 37 + } + }, + { + "t": 23, + "ok": 56, + "err": 0, + "instances": { + "832acbc47567": 56 + }, + "versions": { + "3": 56 + } + }, + { + "t": 24, + "ok": 104, + "err": 0, + "instances": { + "832acbc47567": 104 + }, + "versions": { + "3": 104 + } + }, + { + "t": 25, + "ok": 98, + "err": 0, + "instances": { + "832acbc47567": 98 + }, + "versions": { + "3": 98 + } + }, + { + "t": 26, + "ok": 100, + "err": 0, + "instances": { + "832acbc47567": 100 + }, + "versions": { + "3": 100 + } + }, + { + "t": 27, + "ok": 92, + "err": 0, + "instances": { + "832acbc47567": 92 + }, + "versions": { + "3": 92 + } + }, + { + "t": 28, + "ok": 68, + "err": 0, + "instances": { + "832acbc47567": 68 + }, + "versions": { + "3": 68 + } + }, + { + "t": 29, + "ok": 35, + "err": 0, + "instances": { + "832acbc47567": 35 + }, + "versions": { + "3": 35 + } + }, + { + "t": 30, + "ok": 76, + "err": 0, + "instances": { + "832acbc47567": 76 + }, + "versions": { + "3": 76 + } + }, + { + "t": 31, + "ok": 86, + "err": 0, + "instances": { + "832acbc47567": 86 + }, + "versions": { + "3": 86 + } + }, + { + "t": 32, + "ok": 89, + "err": 0, + "instances": { + "832acbc47567": 89 + }, + "versions": { + "3": 89 + } + }, + { + "t": 33, + "ok": 91, + "err": 0, + "instances": { + "832acbc47567": 91 + }, + "versions": { + "3": 91 + } + }, + { + "t": 34, + "ok": 100, + "err": 0, + "instances": { + "832acbc47567": 100 + }, + "versions": { + "3": 100 + } + }, + { + "t": 35, + "ok": 39, + "err": 0, + "instances": { + "832acbc47567": 39 + }, + "versions": { + "3": 39 + } + }, + { + "t": 36, + "ok": 39, + "err": 0, + "instances": { + "832acbc47567": 39 + }, + "versions": { + "3": 39 + } + }, + { + "t": 37, + "ok": 93, + "err": 0, + "instances": { + "832acbc47567": 93 + }, + "versions": { + "3": 93 + } + }, + { + "t": 38, + "ok": 92, + "err": 0, + "instances": { + "832acbc47567": 92 + }, + "versions": { + "3": 92 + } + }, + { + "t": 39, + "ok": 85, + "err": 0, + "instances": { + "832acbc47567": 85 + }, + "versions": { + "3": 85 + } + }, + { + "t": 40, + "ok": 8, + "err": 0, + "instances": { + "832acbc47567": 8 + }, + "versions": { + "3": 8 + } + } + ], + "pass": true +} diff --git a/evidence/failover.txt b/evidence/failover.txt new file mode 100644 index 00000000..1180e4ab --- /dev/null +++ b/evidence/failover.txt @@ -0,0 +1,4 @@ +python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 125, "failed_attempts": 0, "first_recovery_seconds": 3.75} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/idempotency-concurrency.json b/evidence/idempotency-concurrency.json new file mode 100644 index 00000000..0b1596eb --- /dev/null +++ b/evidence/idempotency-concurrency.json @@ -0,0 +1,23 @@ +{ + "rounds": 20, + "parallel_per_burst": 16, + "requests_total": 640, + "status_counts": { + "same_body": { + "201": 320 + }, + "conflicting_body": { + "201": 160, + "409": 160 + } + }, + "replicas_answered": 2, + "requests_per_replica": [ + 160, + 160 + ], + "messages_in_history": 40, + "expected_messages": 40, + "duplicates": 0, + "problems": [] +} diff --git a/evidence/login-flood-app-only.json b/evidence/login-flood-app-only.json new file mode 100644 index 00000000..78db0ad5 --- /dev/null +++ b/evidence/login-flood-app-only.json @@ -0,0 +1,46 @@ +{ + "parallel": 24, + "duration_s": 20.8, + "flood_statuses": { + "401": 315, + "503": 346 + }, + "flood_rps": 31.7, + "flood_503_with_retry_after": "346/346", + "victim_statuses": { + "200": 91 + }, + "victim_error_rate": 0.0, + "non_contract_error_bodies": {}, + "containers_before": { + "mtusi-lab3-api-1": { + "status": "running", + "oom_killed": false, + "restart_count": 0, + "started_at": "2026-10-24T14:50:12.798945093Z" + }, + "mtusi-lab3-api-2": { + "status": "running", + "oom_killed": false, + "restart_count": 0, + "started_at": "2026-10-24T14:50:12.878423426Z" + } + }, + "containers_after": { + "mtusi-lab3-api-1": { + "status": "running", + "oom_killed": false, + "restart_count": 0, + "started_at": "2026-10-24T14:50:12.798945093Z" + }, + "mtusi-lab3-api-2": { + "status": "running", + "oom_killed": false, + "restart_count": 0, + "started_at": "2026-10-24T14:50:12.878423426Z" + } + }, + "oom_events": {}, + "restarted": [], + "pass": true +} diff --git a/evidence/login-flood.json b/evidence/login-flood.json new file mode 100644 index 00000000..8b4b127b --- /dev/null +++ b/evidence/login-flood.json @@ -0,0 +1,47 @@ +{ + "parallel": 24, + "duration_s": 20.0, + "flood_statuses": { + "429": 78268, + "401": 11, + "503": 8 + }, + "flood_rps": 3908.6, + "flood_503_with_retry_after": "8/8", + "victim_statuses": { + "200": 300 + }, + "victim_error_rate": 0.0, + "non_contract_error_bodies": {}, + "containers_before": { + "mtusi-lab3-api-1": { + "status": "running", + "oom_killed": false, + "restart_count": 0, + "started_at": "2026-10-24T14:52:02.014070171Z" + }, + "mtusi-lab3-api-2": { + "status": "running", + "oom_killed": false, + "restart_count": 0, + "started_at": "2026-10-24T14:52:02.082161296Z" + } + }, + "containers_after": { + "mtusi-lab3-api-1": { + "status": "running", + "oom_killed": false, + "restart_count": 0, + "started_at": "2026-10-24T14:52:02.014070171Z" + }, + "mtusi-lab3-api-2": { + "status": "running", + "oom_killed": false, + "restart_count": 0, + "started_at": "2026-10-24T14:52:02.082161296Z" + } + }, + "oom_events": {}, + "restarted": [], + "pass": true +} diff --git a/evidence/overload-c192.json b/evidence/overload-c192.json new file mode 100644 index 00000000..96be23ed --- /dev/null +++ b/evidence/overload-c192.json @@ -0,0 +1,351 @@ +{ + "label": "overload c=192 after", + "concurrency": 192, + "duration_s": 30.0, + "request_timeout_s": 2.0, + "action": { + "command": "true", + "started_s": 5.096, + "finished_s": 5.133, + "exit_code": 0 + }, + "baseline_ok_rps": 0, + "overall_ok_rps": 277.0, + "requests_ok": 8310, + "errors_total": 0, + "error_rate": 0.0, + "errors_by_kind": {}, + "error_window_s": null, + "recovery_s": 0.0, + "post_action_ok_rps": 329.0, + "capacity_ratio": null, + "latency_ok_ms": { + "p50": 562.2, + "p95": 974.5, + "p99": 6779.8 + }, + "target_instance": null, + "target_last_seen_s": null, + "lb_events": [], + "posts_retried_same_key": 0, + "confirmed_messages": 4205, + "history_messages": 4205, + "lost_confirmed": 0, + "duplicate_ids": 0, + "duplicate_texts": 0, + "timeline": [ + { + "t": 5, + "ok": 356, + "err": 0, + "instances": { + "832acbc47567": 177, + "617f40442335": 179 + }, + "versions": { + "3": 356 + } + }, + { + "t": 6, + "ok": 307, + "err": 0, + "instances": { + "617f40442335": 158, + "832acbc47567": 149 + }, + "versions": { + "3": 307 + } + }, + { + "t": 7, + "ok": 195, + "err": 0, + "instances": { + "832acbc47567": 104, + "617f40442335": 91 + }, + "versions": { + "3": 195 + } + }, + { + "t": 8, + "ok": 359, + "err": 0, + "instances": { + "832acbc47567": 169, + "617f40442335": 190 + }, + "versions": { + "3": 359 + } + }, + { + "t": 9, + "ok": 345, + "err": 0, + "instances": { + "832acbc47567": 173, + "617f40442335": 172 + }, + "versions": { + "3": 345 + } + }, + { + "t": 10, + "ok": 352, + "err": 0, + "instances": { + "617f40442335": 175, + "832acbc47567": 177 + }, + "versions": { + "3": 352 + } + }, + { + "t": 11, + "ok": 383, + "err": 0, + "instances": { + "832acbc47567": 178, + "617f40442335": 205 + }, + "versions": { + "3": 383 + } + }, + { + "t": 12, + "ok": 230, + "err": 0, + "instances": { + "832acbc47567": 113, + "617f40442335": 117 + }, + "versions": { + "3": 230 + } + }, + { + "t": 13, + "ok": 316, + "err": 0, + "instances": { + "832acbc47567": 154, + "617f40442335": 162 + }, + "versions": { + "3": 316 + } + }, + { + "t": 14, + "ok": 372, + "err": 0, + "instances": { + "832acbc47567": 183, + "617f40442335": 189 + }, + "versions": { + "3": 372 + } + }, + { + "t": 15, + "ok": 332, + "err": 0, + "instances": { + "832acbc47567": 176, + "617f40442335": 156 + }, + "versions": { + "3": 332 + } + }, + { + "t": 16, + "ok": 365, + "err": 0, + "instances": { + "832acbc47567": 187, + "617f40442335": 178 + }, + "versions": { + "3": 365 + } + }, + { + "t": 17, + "ok": 347, + "err": 0, + "instances": { + "832acbc47567": 156, + "617f40442335": 191 + }, + "versions": { + "3": 347 + } + }, + { + "t": 18, + "ok": 222, + "err": 0, + "instances": { + "832acbc47567": 112, + "617f40442335": 110 + }, + "versions": { + "3": 222 + } + }, + { + "t": 19, + "ok": 356, + "err": 0, + "instances": { + "617f40442335": 186, + "832acbc47567": 170 + }, + "versions": { + "3": 356 + } + }, + { + "t": 20, + "ok": 306, + "err": 0, + "instances": { + "617f40442335": 149, + "832acbc47567": 157 + }, + "versions": { + "3": 306 + } + }, + { + "t": 21, + "ok": 315, + "err": 0, + "instances": { + "617f40442335": 167, + "832acbc47567": 148 + }, + "versions": { + "3": 315 + } + }, + { + "t": 22, + "ok": 401, + "err": 0, + "instances": { + "832acbc47567": 199, + "617f40442335": 202 + }, + "versions": { + "3": 401 + } + }, + { + "t": 23, + "ok": 247, + "err": 0, + "instances": { + "832acbc47567": 108, + "617f40442335": 139 + }, + "versions": { + "3": 247 + } + }, + { + "t": 24, + "ok": 308, + "err": 0, + "instances": { + "832acbc47567": 137, + "617f40442335": 171 + }, + "versions": { + "3": 308 + } + }, + { + "t": 25, + "ok": 359, + "err": 0, + "instances": { + "617f40442335": 193, + "832acbc47567": 166 + }, + "versions": { + "3": 359 + } + }, + { + "t": 26, + "ok": 358, + "err": 0, + "instances": { + "617f40442335": 172, + "832acbc47567": 186 + }, + "versions": { + "3": 358 + } + }, + { + "t": 27, + "ok": 370, + "err": 0, + "instances": { + "832acbc47567": 164, + "617f40442335": 206 + }, + "versions": { + "3": 370 + } + }, + { + "t": 28, + "ok": 401, + "err": 0, + "instances": { + "617f40442335": 210, + "832acbc47567": 191 + }, + "versions": { + "3": 401 + } + }, + { + "t": 29, + "ok": 216, + "err": 0, + "instances": { + "832acbc47567": 108, + "617f40442335": 108 + }, + "versions": { + "3": 216 + } + }, + { + "t": 30, + "ok": 192, + "err": 0, + "instances": { + "832acbc47567": 88, + "617f40442335": 104 + }, + "versions": { + "3": 192 + } + } + ], + "pass": true +} diff --git a/evidence/overload-c64.json b/evidence/overload-c64.json new file mode 100644 index 00000000..8e7f5a39 --- /dev/null +++ b/evidence/overload-c64.json @@ -0,0 +1,375 @@ +{ + "label": "overload c=64 after", + "concurrency": 64, + "duration_s": 30.0, + "request_timeout_s": 2.0, + "action": { + "command": "true", + "started_s": 5.042, + "finished_s": 5.053, + "exit_code": 0 + }, + "baseline_ok_rps": 212.0, + "overall_ok_rps": 285.7, + "requests_ok": 8571, + "errors_total": 0, + "error_rate": 0.0, + "errors_by_kind": {}, + "error_window_s": null, + "recovery_s": 0.0, + "post_action_ok_rps": 326.0, + "capacity_ratio": 1.54, + "latency_ok_ms": { + "p50": 191.5, + "p95": 411.9, + "p99": 664.7 + }, + "target_instance": null, + "target_last_seen_s": null, + "lb_events": [], + "posts_retried_same_key": 0, + "confirmed_messages": 4306, + "history_messages": 4306, + "lost_confirmed": 0, + "duplicate_ids": 0, + "duplicate_texts": 0, + "timeline": [ + { + "t": 3, + "ok": 256, + "err": 0, + "instances": { + "617f40442335": 125, + "832acbc47567": 131 + }, + "versions": { + "3": 256 + } + }, + { + "t": 4, + "ok": 168, + "err": 0, + "instances": { + "832acbc47567": 95, + "617f40442335": 73 + }, + "versions": { + "3": 168 + } + }, + { + "t": 5, + "ok": 251, + "err": 0, + "instances": { + "617f40442335": 134, + "832acbc47567": 117 + }, + "versions": { + "3": 251 + } + }, + { + "t": 6, + "ok": 304, + "err": 0, + "instances": { + "832acbc47567": 164, + "617f40442335": 140 + }, + "versions": { + "3": 304 + } + }, + { + "t": 7, + "ok": 358, + "err": 0, + "instances": { + "832acbc47567": 162, + "617f40442335": 196 + }, + "versions": { + "3": 358 + } + }, + { + "t": 8, + "ok": 402, + "err": 0, + "instances": { + "617f40442335": 205, + "832acbc47567": 197 + }, + "versions": { + "3": 402 + } + }, + { + "t": 9, + "ok": 367, + "err": 0, + "instances": { + "617f40442335": 200, + "832acbc47567": 167 + }, + "versions": { + "3": 367 + } + }, + { + "t": 10, + "ok": 168, + "err": 0, + "instances": { + "832acbc47567": 93, + "617f40442335": 75 + }, + "versions": { + "3": 168 + } + }, + { + "t": 11, + "ok": 230, + "err": 0, + "instances": { + "617f40442335": 127, + "832acbc47567": 103 + }, + "versions": { + "3": 230 + } + }, + { + "t": 12, + "ok": 334, + "err": 0, + "instances": { + "617f40442335": 151, + "832acbc47567": 183 + }, + "versions": { + "3": 334 + } + }, + { + "t": 13, + "ok": 373, + "err": 0, + "instances": { + "617f40442335": 182, + "832acbc47567": 191 + }, + "versions": { + "3": 373 + } + }, + { + "t": 14, + "ok": 391, + "err": 0, + "instances": { + "617f40442335": 204, + "832acbc47567": 187 + }, + "versions": { + "3": 391 + } + }, + { + "t": 15, + "ok": 359, + "err": 0, + "instances": { + "617f40442335": 194, + "832acbc47567": 165 + }, + "versions": { + "3": 359 + } + }, + { + "t": 16, + "ok": 170, + "err": 0, + "instances": { + "832acbc47567": 92, + "617f40442335": 78 + }, + "versions": { + "3": 170 + } + }, + { + "t": 17, + "ok": 349, + "err": 0, + "instances": { + "832acbc47567": 150, + "617f40442335": 199 + }, + "versions": { + "3": 349 + } + }, + { + "t": 18, + "ok": 361, + "err": 0, + "instances": { + "832acbc47567": 182, + "617f40442335": 179 + }, + "versions": { + "3": 361 + } + }, + { + "t": 19, + "ok": 353, + "err": 0, + "instances": { + "617f40442335": 169, + "832acbc47567": 184 + }, + "versions": { + "3": 353 + } + }, + { + "t": 20, + "ok": 401, + "err": 0, + "instances": { + "617f40442335": 198, + "832acbc47567": 203 + }, + "versions": { + "3": 401 + } + }, + { + "t": 21, + "ok": 323, + "err": 0, + "instances": { + "617f40442335": 169, + "832acbc47567": 154 + }, + "versions": { + "3": 323 + } + }, + { + "t": 22, + "ok": 233, + "err": 0, + "instances": { + "617f40442335": 117, + "832acbc47567": 116 + }, + "versions": { + "3": 233 + } + }, + { + "t": 23, + "ok": 377, + "err": 0, + "instances": { + "832acbc47567": 188, + "617f40442335": 189 + }, + "versions": { + "3": 377 + } + }, + { + "t": 24, + "ok": 338, + "err": 0, + "instances": { + "832acbc47567": 170, + "617f40442335": 168 + }, + "versions": { + "3": 338 + } + }, + { + "t": 25, + "ok": 390, + "err": 0, + "instances": { + "617f40442335": 197, + "832acbc47567": 193 + }, + "versions": { + "3": 390 + } + }, + { + "t": 26, + "ok": 365, + "err": 0, + "instances": { + "832acbc47567": 187, + "617f40442335": 178 + }, + "versions": { + "3": 365 + } + }, + { + "t": 27, + "ok": 248, + "err": 0, + "instances": { + "832acbc47567": 123, + "617f40442335": 125 + }, + "versions": { + "3": 248 + } + }, + { + "t": 28, + "ok": 282, + "err": 0, + "instances": { + "617f40442335": 142, + "832acbc47567": 140 + }, + "versions": { + "3": 282 + } + }, + { + "t": 29, + "ok": 356, + "err": 0, + "instances": { + "617f40442335": 194, + "832acbc47567": 162 + }, + "versions": { + "3": 356 + } + }, + { + "t": 30, + "ok": 64, + "err": 0, + "instances": { + "617f40442335": 30, + "832acbc47567": 34 + }, + "versions": { + "3": 64 + } + } + ], + "pass": true +} diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 00000000..933c59c7 --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/pre-submit-cursor.txt b/evidence/pre-submit-cursor.txt new file mode 100644 index 00000000..a34908db --- /dev/null +++ b/evidence/pre-submit-cursor.txt @@ -0,0 +1 @@ +PASS: 6 cursor date boundary checks; invalid dates return 400. diff --git a/evidence/pre-submit-failover.txt b/evidence/pre-submit-failover.txt new file mode 100644 index 00000000..e1f4b52d --- /dev/null +++ b/evidence/pre-submit-failover.txt @@ -0,0 +1,4 @@ +python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 129, "failed_attempts": 0, "first_recovery_seconds": 3.692} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/pre-submit-idempotency.json b/evidence/pre-submit-idempotency.json new file mode 100644 index 00000000..4b5abac3 --- /dev/null +++ b/evidence/pre-submit-idempotency.json @@ -0,0 +1,23 @@ +{ + "rounds": 20, + "parallel_per_burst": 16, + "requests_total": 640, + "status_counts": { + "same_body": { + "201": 320 + }, + "conflicting_body": { + "409": 160, + "201": 160 + } + }, + "replicas_answered": 2, + "requests_per_replica": [ + 160, + 160 + ], + "messages_in_history": 40, + "expected_messages": 40, + "duplicates": 0, + "problems": [] +} diff --git a/evidence/pre-submit-idempotency.txt b/evidence/pre-submit-idempotency.txt new file mode 100644 index 00000000..3f9172f6 --- /dev/null +++ b/evidence/pre-submit-idempotency.txt @@ -0,0 +1,24 @@ +{ + "rounds": 20, + "parallel_per_burst": 16, + "requests_total": 640, + "status_counts": { + "same_body": { + "201": 320 + }, + "conflicting_body": { + "409": 160, + "201": 160 + } + }, + "replicas_answered": 2, + "requests_per_replica": [ + 160, + 160 + ], + "messages_in_history": 40, + "expected_messages": 40, + "duplicates": 0, + "problems": [] +} +PASS diff --git a/evidence/pre-submit-persistence.txt b/evidence/pre-submit-persistence.txt new file mode 100644 index 00000000..933c59c7 --- /dev/null +++ b/evidence/pre-submit-persistence.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/pre-submit-rolling-action.txt b/evidence/pre-submit-rolling-action.txt new file mode 100644 index 00000000..abb3684c --- /dev/null +++ b/evidence/pre-submit-rolling-action.txt @@ -0,0 +1,10 @@ +2026-10-29T13:25:19Z build version 5 + api Built +2026-10-29T13:25:21Z migrate (once) +2026-10-29 13:25:22,059 INFO migrations done; applied now: nothing +2026-10-29T13:25:22Z replacing 2 replicas +2026-10-29T13:25:29Z up mtusi-lab3-api-5 version=5 ip=172.19.0.6 UP in LB (UP slots: 4) +2026-10-29T13:25:32Z gone mtusi-lab3-api-3 (graceful SIGTERM) +2026-10-29T13:25:39Z up mtusi-lab3-api-6 version=5 ip=172.19.0.2 UP in LB (UP slots: 4) +2026-10-29T13:25:42Z gone mtusi-lab3-api-4 (graceful SIGTERM) +2026-10-29T13:25:42Z done: mtusi-lab3-api-5 mtusi-lab3-api-6 diff --git a/evidence/pre-submit-rolling-update.json b/evidence/pre-submit-rolling-update.json new file mode 100644 index 00000000..92cb0320 --- /dev/null +++ b/evidence/pre-submit-rolling-update.json @@ -0,0 +1,1018 @@ +{ + "label": "Проверка перед сдачей 2026-10-29: rolling v4→v5", + "concurrency": 8, + "duration_s": 75.0, + "request_timeout_s": 2.0, + "action": { + "command": "scripts/rolling-update.sh 5", + "started_s": 10.017, + "finished_s": 36.172, + "exit_code": 0 + }, + "baseline_ok_rps": 278.9, + "overall_ok_rps": 338.2, + "requests_ok": 25368, + "errors_total": 0, + "error_rate": 0.0, + "errors_by_kind": {}, + "error_window_s": null, + "recovery_s": 0.0, + "post_action_ok_rps": 312.8, + "capacity_ratio": 1.12, + "latency_ok_ms": { + "p50": 9.7, + "p95": 81.3, + "p99": 104.6 + }, + "target_instance": null, + "target_last_seen_s": null, + "lb_events": [ + { + "t": 6.94, + "server": "api3", + "addr": "172.19.0.6:8080", + "from": "MAINT", + "to": "UP" + }, + { + "t": 13.28, + "server": "api1", + "addr": "172.19.0.2:8080", + "from": "UP", + "to": "DOWN" + }, + { + "t": 18.21, + "server": "api1", + "addr": "172.19.0.2:8080", + "from": "DOWN", + "to": "UP" + }, + { + "t": 23.44, + "server": "api2", + "addr": "172.19.0.3:8080", + "from": "UP", + "to": "DOWN" + }, + { + "t": 27.94, + "server": "api2", + "addr": "", + "from": "DOWN", + "to": "MAINT" + } + ], + "posts_retried_same_key": 0, + "confirmed_messages": 12686, + "history_messages": 12686, + "lost_confirmed": 0, + "duplicate_ids": 0, + "duplicate_texts": 0, + "timeline": [ + { + "t": 0, + "ok": 208, + "err": 0, + "instances": { + "d0874e4353c2": 105, + "84a23f8de677": 103 + }, + "versions": { + "4": 208 + } + }, + { + "t": 1, + "ok": 236, + "err": 0, + "instances": { + "84a23f8de677": 121, + "d0874e4353c2": 115 + }, + "versions": { + "4": 236 + } + }, + { + "t": 2, + "ok": 254, + "err": 0, + "instances": { + "84a23f8de677": 128, + "d0874e4353c2": 126 + }, + "versions": { + "4": 254 + } + }, + { + "t": 3, + "ok": 328, + "err": 0, + "instances": { + "84a23f8de677": 162, + "d0874e4353c2": 166 + }, + "versions": { + "4": 328 + } + }, + { + "t": 4, + "ok": 289, + "err": 0, + "instances": { + "84a23f8de677": 142, + "d0874e4353c2": 147 + }, + "versions": { + "4": 289 + } + }, + { + "t": 5, + "ok": 265, + "err": 0, + "instances": { + "84a23f8de677": 130, + "d0874e4353c2": 135 + }, + "versions": { + "4": 265 + } + }, + { + "t": 6, + "ok": 335, + "err": 0, + "instances": { + "84a23f8de677": 169, + "d0874e4353c2": 166 + }, + "versions": { + "4": 335 + } + }, + { + "t": 7, + "ok": 165, + "err": 0, + "instances": { + "d0874e4353c2": 77, + "84a23f8de677": 88 + }, + "versions": { + "4": 165 + } + }, + { + "t": 8, + "ok": 333, + "err": 0, + "instances": { + "84a23f8de677": 161, + "d0874e4353c2": 172 + }, + "versions": { + "4": 333 + } + }, + { + "t": 9, + "ok": 305, + "err": 0, + "instances": { + "84a23f8de677": 152, + "d0874e4353c2": 153 + }, + "versions": { + "4": 305 + } + }, + { + "t": 10, + "ok": 142, + "err": 0, + "instances": { + "84a23f8de677": 71, + "d0874e4353c2": 71 + }, + "versions": { + "4": 142 + } + }, + { + "t": 11, + "ok": 309, + "err": 0, + "instances": { + "84a23f8de677": 161, + "d0874e4353c2": 148 + }, + "versions": { + "4": 309 + } + }, + { + "t": 12, + "ok": 310, + "err": 0, + "instances": { + "d0874e4353c2": 161, + "84a23f8de677": 149 + }, + "versions": { + "4": 310 + } + }, + { + "t": 13, + "ok": 244, + "err": 0, + "instances": { + "84a23f8de677": 125, + "d0874e4353c2": 119 + }, + "versions": { + "4": 244 + } + }, + { + "t": 14, + "ok": 354, + "err": 0, + "instances": { + "84a23f8de677": 177, + "d0874e4353c2": 177 + }, + "versions": { + "4": 354 + } + }, + { + "t": 15, + "ok": 318, + "err": 0, + "instances": { + "d0874e4353c2": 156, + "84a23f8de677": 162 + }, + "versions": { + "4": 318 + } + }, + { + "t": 16, + "ok": 253, + "err": 0, + "instances": { + "d0874e4353c2": 119, + "84a23f8de677": 112, + "c93cc5e61399": 22 + }, + "versions": { + "4": 231, + "5": 22 + } + }, + { + "t": 17, + "ok": 712, + "err": 0, + "instances": { + "d0874e4353c2": 238, + "84a23f8de677": 238, + "c93cc5e61399": 236 + }, + "versions": { + "4": 476, + "5": 236 + } + }, + { + "t": 18, + "ok": 476, + "err": 0, + "instances": { + "c93cc5e61399": 163, + "84a23f8de677": 159, + "d0874e4353c2": 154 + }, + "versions": { + "5": 163, + "4": 313 + } + }, + { + "t": 19, + "ok": 491, + "err": 0, + "instances": { + "84a23f8de677": 163, + "d0874e4353c2": 165, + "c93cc5e61399": 163 + }, + "versions": { + "4": 328, + "5": 163 + } + }, + { + "t": 20, + "ok": 609, + "err": 0, + "instances": { + "d0874e4353c2": 203, + "84a23f8de677": 204, + "c93cc5e61399": 202 + }, + "versions": { + "4": 407, + "5": 202 + } + }, + { + "t": 21, + "ok": 329, + "err": 0, + "instances": { + "d0874e4353c2": 113, + "84a23f8de677": 106, + "c93cc5e61399": 110 + }, + "versions": { + "4": 219, + "5": 110 + } + }, + { + "t": 22, + "ok": 663, + "err": 0, + "instances": { + "84a23f8de677": 222, + "d0874e4353c2": 221, + "c93cc5e61399": 220 + }, + "versions": { + "4": 443, + "5": 220 + } + }, + { + "t": 23, + "ok": 334, + "err": 0, + "instances": { + "c93cc5e61399": 150, + "d0874e4353c2": 29, + "84a23f8de677": 155 + }, + "versions": { + "5": 150, + "4": 184 + } + }, + { + "t": 24, + "ok": 301, + "err": 0, + "instances": { + "c93cc5e61399": 152, + "84a23f8de677": 149 + }, + "versions": { + "5": 152, + "4": 149 + } + }, + { + "t": 25, + "ok": 305, + "err": 0, + "instances": { + "84a23f8de677": 156, + "c93cc5e61399": 149 + }, + "versions": { + "4": 156, + "5": 149 + } + }, + { + "t": 26, + "ok": 311, + "err": 0, + "instances": { + "c93cc5e61399": 157, + "84a23f8de677": 154 + }, + "versions": { + "5": 157, + "4": 154 + } + }, + { + "t": 27, + "ok": 224, + "err": 0, + "instances": { + "c93cc5e61399": 113, + "84a23f8de677": 111 + }, + "versions": { + "5": 113, + "4": 111 + } + }, + { + "t": 28, + "ok": 672, + "err": 0, + "instances": { + "c93cc5e61399": 231, + "84a23f8de677": 229, + "15adb5912f40": 212 + }, + "versions": { + "5": 443, + "4": 229 + } + }, + { + "t": 29, + "ok": 658, + "err": 0, + "instances": { + "84a23f8de677": 222, + "15adb5912f40": 221, + "c93cc5e61399": 215 + }, + "versions": { + "4": 222, + "5": 436 + } + }, + { + "t": 30, + "ok": 625, + "err": 0, + "instances": { + "c93cc5e61399": 214, + "15adb5912f40": 207, + "84a23f8de677": 204 + }, + "versions": { + "5": 421, + "4": 204 + } + }, + { + "t": 31, + "ok": 330, + "err": 0, + "instances": { + "c93cc5e61399": 110, + "84a23f8de677": 113, + "15adb5912f40": 107 + }, + "versions": { + "5": 217, + "4": 113 + } + }, + { + "t": 32, + "ok": 475, + "err": 0, + "instances": { + "c93cc5e61399": 154, + "84a23f8de677": 159, + "15adb5912f40": 162 + }, + "versions": { + "5": 316, + "4": 159 + } + }, + { + "t": 33, + "ok": 462, + "err": 0, + "instances": { + "84a23f8de677": 83, + "15adb5912f40": 186, + "c93cc5e61399": 193 + }, + "versions": { + "4": 83, + "5": 379 + } + }, + { + "t": 34, + "ok": 398, + "err": 0, + "instances": { + "15adb5912f40": 196, + "c93cc5e61399": 202 + }, + "versions": { + "5": 398 + } + }, + { + "t": 35, + "ok": 341, + "err": 0, + "instances": { + "15adb5912f40": 173, + "c93cc5e61399": 168 + }, + "versions": { + "5": 341 + } + }, + { + "t": 36, + "ok": 300, + "err": 0, + "instances": { + "15adb5912f40": 149, + "c93cc5e61399": 151 + }, + "versions": { + "5": 300 + } + }, + { + "t": 37, + "ok": 96, + "err": 0, + "instances": { + "15adb5912f40": 48, + "c93cc5e61399": 48 + }, + "versions": { + "5": 96 + } + }, + { + "t": 38, + "ok": 195, + "err": 0, + "instances": { + "c93cc5e61399": 92, + "15adb5912f40": 103 + }, + "versions": { + "5": 195 + } + }, + { + "t": 39, + "ok": 358, + "err": 0, + "instances": { + "c93cc5e61399": 181, + "15adb5912f40": 177 + }, + "versions": { + "5": 358 + } + }, + { + "t": 40, + "ok": 327, + "err": 0, + "instances": { + "c93cc5e61399": 163, + "15adb5912f40": 164 + }, + "versions": { + "5": 327 + } + }, + { + "t": 41, + "ok": 374, + "err": 0, + "instances": { + "c93cc5e61399": 191, + "15adb5912f40": 183 + }, + "versions": { + "5": 374 + } + }, + { + "t": 42, + "ok": 350, + "err": 0, + "instances": { + "15adb5912f40": 177, + "c93cc5e61399": 173 + }, + "versions": { + "5": 350 + } + }, + { + "t": 43, + "ok": 118, + "err": 0, + "instances": { + "15adb5912f40": 62, + "c93cc5e61399": 56 + }, + "versions": { + "5": 118 + } + }, + { + "t": 44, + "ok": 301, + "err": 0, + "instances": { + "c93cc5e61399": 151, + "15adb5912f40": 150 + }, + "versions": { + "5": 301 + } + }, + { + "t": 45, + "ok": 396, + "err": 0, + "instances": { + "c93cc5e61399": 204, + "15adb5912f40": 192 + }, + "versions": { + "5": 396 + } + }, + { + "t": 46, + "ok": 311, + "err": 0, + "instances": { + "15adb5912f40": 163, + "c93cc5e61399": 148 + }, + "versions": { + "5": 311 + } + }, + { + "t": 47, + "ok": 292, + "err": 0, + "instances": { + "c93cc5e61399": 146, + "15adb5912f40": 146 + }, + "versions": { + "5": 292 + } + }, + { + "t": 48, + "ok": 333, + "err": 0, + "instances": { + "c93cc5e61399": 173, + "15adb5912f40": 160 + }, + "versions": { + "5": 333 + } + }, + { + "t": 49, + "ok": 201, + "err": 0, + "instances": { + "15adb5912f40": 106, + "c93cc5e61399": 95 + }, + "versions": { + "5": 201 + } + }, + { + "t": 50, + "ok": 394, + "err": 0, + "instances": { + "c93cc5e61399": 199, + "15adb5912f40": 195 + }, + "versions": { + "5": 394 + } + }, + { + "t": 51, + "ok": 353, + "err": 0, + "instances": { + "c93cc5e61399": 179, + "15adb5912f40": 174 + }, + "versions": { + "5": 353 + } + }, + { + "t": 52, + "ok": 326, + "err": 0, + "instances": { + "15adb5912f40": 163, + "c93cc5e61399": 163 + }, + "versions": { + "5": 326 + } + }, + { + "t": 53, + "ok": 345, + "err": 0, + "instances": { + "15adb5912f40": 172, + "c93cc5e61399": 173 + }, + "versions": { + "5": 345 + } + }, + { + "t": 54, + "ok": 240, + "err": 0, + "instances": { + "15adb5912f40": 123, + "c93cc5e61399": 117 + }, + "versions": { + "5": 240 + } + }, + { + "t": 55, + "ok": 334, + "err": 0, + "instances": { + "c93cc5e61399": 168, + "15adb5912f40": 166 + }, + "versions": { + "5": 334 + } + }, + { + "t": 56, + "ok": 360, + "err": 0, + "instances": { + "15adb5912f40": 178, + "c93cc5e61399": 182 + }, + "versions": { + "5": 360 + } + }, + { + "t": 57, + "ok": 370, + "err": 0, + "instances": { + "15adb5912f40": 186, + "c93cc5e61399": 184 + }, + "versions": { + "5": 370 + } + }, + { + "t": 58, + "ok": 373, + "err": 0, + "instances": { + "c93cc5e61399": 189, + "15adb5912f40": 184 + }, + "versions": { + "5": 373 + } + }, + { + "t": 59, + "ok": 363, + "err": 0, + "instances": { + "15adb5912f40": 187, + "c93cc5e61399": 176 + }, + "versions": { + "5": 363 + } + }, + { + "t": 60, + "ok": 262, + "err": 0, + "instances": { + "c93cc5e61399": 129, + "15adb5912f40": 133 + }, + "versions": { + "5": 262 + } + }, + { + "t": 61, + "ok": 344, + "err": 0, + "instances": { + "c93cc5e61399": 172, + "15adb5912f40": 172 + }, + "versions": { + "5": 344 + } + }, + { + "t": 62, + "ok": 322, + "err": 0, + "instances": { + "c93cc5e61399": 167, + "15adb5912f40": 155 + }, + "versions": { + "5": 322 + } + }, + { + "t": 63, + "ok": 343, + "err": 0, + "instances": { + "15adb5912f40": 171, + "c93cc5e61399": 172 + }, + "versions": { + "5": 343 + } + }, + { + "t": 64, + "ok": 307, + "err": 0, + "instances": { + "15adb5912f40": 154, + "c93cc5e61399": 153 + }, + "versions": { + "5": 307 + } + }, + { + "t": 65, + "ok": 248, + "err": 0, + "instances": { + "c93cc5e61399": 122, + "15adb5912f40": 126 + }, + "versions": { + "5": 248 + } + }, + { + "t": 66, + "ok": 354, + "err": 0, + "instances": { + "c93cc5e61399": 179, + "15adb5912f40": 175 + }, + "versions": { + "5": 354 + } + }, + { + "t": 67, + "ok": 340, + "err": 0, + "instances": { + "15adb5912f40": 171, + "c93cc5e61399": 169 + }, + "versions": { + "5": 340 + } + }, + { + "t": 68, + "ok": 357, + "err": 0, + "instances": { + "15adb5912f40": 176, + "c93cc5e61399": 181 + }, + "versions": { + "5": 357 + } + }, + { + "t": 69, + "ok": 260, + "err": 0, + "instances": { + "15adb5912f40": 133, + "c93cc5e61399": 127 + }, + "versions": { + "5": 260 + } + }, + { + "t": 70, + "ok": 325, + "err": 0, + "instances": { + "c93cc5e61399": 164, + "15adb5912f40": 161 + }, + "versions": { + "5": 325 + } + }, + { + "t": 71, + "ok": 265, + "err": 0, + "instances": { + "15adb5912f40": 133, + "c93cc5e61399": 132 + }, + "versions": { + "5": 265 + } + }, + { + "t": 72, + "ok": 273, + "err": 0, + "instances": { + "15adb5912f40": 141, + "c93cc5e61399": 132 + }, + "versions": { + "5": 273 + } + }, + { + "t": 73, + "ok": 247, + "err": 0, + "instances": { + "c93cc5e61399": 126, + "15adb5912f40": 121 + }, + "versions": { + "5": 247 + } + }, + { + "t": 74, + "ok": 339, + "err": 0, + "instances": { + "c93cc5e61399": 166, + "15adb5912f40": 173 + }, + "versions": { + "5": 339 + } + }, + { + "t": 75, + "ok": 8, + "err": 0, + "instances": { + "c93cc5e61399": 8 + }, + "versions": { + "5": 8 + } + } + ], + "pass": true +} diff --git a/evidence/pre-submit-rolling-update.txt b/evidence/pre-submit-rolling-update.txt new file mode 100644 index 00000000..2a3a9851 --- /dev/null +++ b/evidence/pre-submit-rolling-update.txt @@ -0,0 +1,74 @@ +{ + "label": "Проверка перед сдачей 2026-10-29: rolling v4→v5", + "concurrency": 8, + "duration_s": 75.0, + "request_timeout_s": 2.0, + "action": { + "command": "scripts/rolling-update.sh 5", + "started_s": 10.017, + "finished_s": 36.172, + "exit_code": 0 + }, + "baseline_ok_rps": 278.9, + "overall_ok_rps": 338.2, + "requests_ok": 25368, + "errors_total": 0, + "error_rate": 0.0, + "errors_by_kind": {}, + "error_window_s": null, + "recovery_s": 0.0, + "post_action_ok_rps": 312.8, + "capacity_ratio": 1.12, + "latency_ok_ms": { + "p50": 9.7, + "p95": 81.3, + "p99": 104.6 + }, + "target_instance": null, + "target_last_seen_s": null, + "lb_events": [ + { + "t": 6.94, + "server": "api3", + "addr": "172.19.0.6:8080", + "from": "MAINT", + "to": "UP" + }, + { + "t": 13.28, + "server": "api1", + "addr": "172.19.0.2:8080", + "from": "UP", + "to": "DOWN" + }, + { + "t": 18.21, + "server": "api1", + "addr": "172.19.0.2:8080", + "from": "DOWN", + "to": "UP" + }, + { + "t": 23.44, + "server": "api2", + "addr": "172.19.0.3:8080", + "from": "UP", + "to": "DOWN" + }, + { + "t": 27.94, + "server": "api2", + "addr": "", + "from": "DOWN", + "to": "MAINT" + } + ], + "posts_retried_same_key": 0, + "confirmed_messages": 12686, + "history_messages": 12686, + "lost_confirmed": 0, + "duplicate_ids": 0, + "duplicate_texts": 0, + "pass": true +} +PASS diff --git a/evidence/pre-submit-script-errors.txt b/evidence/pre-submit-script-errors.txt new file mode 100644 index 00000000..acca0800 --- /dev/null +++ b/evidence/pre-submit-script-errors.txt @@ -0,0 +1,2 @@ +PASS: start-all.sh propagates Docker exit 42 and does not report success. +PASS: rolling-update.sh stops on failed migration before replacing replicas or updating .env. diff --git a/evidence/pre-submit-smoke.txt b/evidence/pre-submit-smoke.txt new file mode 100644 index 00000000..88517e6f --- /dev/null +++ b/evidence/pre-submit-smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8080" +PASS: lab3 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/rolling-update.json b/evidence/rolling-update.json new file mode 100644 index 00000000..7a77d34e --- /dev/null +++ b/evidence/rolling-update.json @@ -0,0 +1,1020 @@ +{ + "label": "rolling update v4", + "concurrency": 8, + "duration_s": 75.0, + "request_timeout_s": 2.0, + "action": { + "command": "scripts/rolling-update.sh 4", + "started_s": 10.025, + "finished_s": 34.09, + "exit_code": 0 + }, + "baseline_ok_rps": 278.7, + "overall_ok_rps": 333.5, + "requests_ok": 25013, + "errors_total": 0, + "error_rate": 0.0, + "errors_by_kind": {}, + "error_window_s": null, + "recovery_s": 0.0, + "post_action_ok_rps": 291.3, + "capacity_ratio": 1.05, + "latency_ok_ms": { + "p50": 8.8, + "p95": 84.3, + "p99": 100.1 + }, + "target_instance": null, + "target_last_seen_s": null, + "lb_events": [ + { + "t": 4.04, + "server": "api3", + "addr": "172.19.0.6:8080", + "from": "MAINT", + "to": "UP" + }, + { + "t": 11.17, + "server": "api1", + "addr": "172.19.0.4:8080", + "from": "UP", + "to": "DOWN" + }, + { + "t": 15.67, + "server": "api1", + "addr": "172.19.0.4:8080", + "from": "DOWN", + "to": "UP" + }, + { + "t": 21.8, + "server": "api2", + "addr": "172.19.0.3:8080", + "from": "UP", + "to": "DOWN" + }, + { + "t": 26.08, + "server": "api2", + "addr": "", + "from": "DOWN", + "to": "MAINT" + } + ], + "posts_retried_same_key": 0, + "confirmed_messages": 12510, + "history_messages": 12510, + "lost_confirmed": 0, + "duplicate_ids": 0, + "duplicate_texts": 0, + "timeline": [ + { + "t": 0, + "ok": 150, + "err": 0, + "instances": { + "832acbc47567": 73, + "617f40442335": 77 + }, + "versions": { + "3": 150 + } + }, + { + "t": 1, + "ok": 317, + "err": 0, + "instances": { + "832acbc47567": 159, + "617f40442335": 158 + }, + "versions": { + "3": 317 + } + }, + { + "t": 2, + "ok": 231, + "err": 0, + "instances": { + "832acbc47567": 116, + "617f40442335": 115 + }, + "versions": { + "3": 231 + } + }, + { + "t": 3, + "ok": 200, + "err": 0, + "instances": { + "832acbc47567": 99, + "617f40442335": 101 + }, + "versions": { + "3": 200 + } + }, + { + "t": 4, + "ok": 332, + "err": 0, + "instances": { + "832acbc47567": 170, + "617f40442335": 162 + }, + "versions": { + "3": 332 + } + }, + { + "t": 5, + "ok": 323, + "err": 0, + "instances": { + "832acbc47567": 162, + "617f40442335": 161 + }, + "versions": { + "3": 323 + } + }, + { + "t": 6, + "ok": 276, + "err": 0, + "instances": { + "832acbc47567": 137, + "617f40442335": 139 + }, + "versions": { + "3": 276 + } + }, + { + "t": 7, + "ok": 329, + "err": 0, + "instances": { + "617f40442335": 166, + "832acbc47567": 163 + }, + "versions": { + "3": 329 + } + }, + { + "t": 8, + "ok": 176, + "err": 0, + "instances": { + "617f40442335": 88, + "832acbc47567": 88 + }, + "versions": { + "3": 176 + } + }, + { + "t": 9, + "ok": 324, + "err": 0, + "instances": { + "832acbc47567": 159, + "617f40442335": 165 + }, + "versions": { + "3": 324 + } + }, + { + "t": 10, + "ok": 331, + "err": 0, + "instances": { + "832acbc47567": 170, + "617f40442335": 161 + }, + "versions": { + "3": 331 + } + }, + { + "t": 11, + "ok": 304, + "err": 0, + "instances": { + "617f40442335": 154, + "832acbc47567": 150 + }, + "versions": { + "3": 304 + } + }, + { + "t": 12, + "ok": 302, + "err": 0, + "instances": { + "832acbc47567": 150, + "617f40442335": 152 + }, + "versions": { + "3": 302 + } + }, + { + "t": 13, + "ok": 262, + "err": 0, + "instances": { + "617f40442335": 129, + "832acbc47567": 133 + }, + "versions": { + "3": 262 + } + }, + { + "t": 14, + "ok": 460, + "err": 0, + "instances": { + "617f40442335": 165, + "832acbc47567": 165, + "265523c62e7d": 130 + }, + "versions": { + "3": 330, + "4": 130 + } + }, + { + "t": 15, + "ok": 664, + "err": 0, + "instances": { + "265523c62e7d": 223, + "617f40442335": 223, + "832acbc47567": 218 + }, + "versions": { + "4": 223, + "3": 441 + } + }, + { + "t": 16, + "ok": 672, + "err": 0, + "instances": { + "832acbc47567": 223, + "265523c62e7d": 225, + "617f40442335": 224 + }, + "versions": { + "3": 447, + "4": 225 + } + }, + { + "t": 17, + "ok": 648, + "err": 0, + "instances": { + "617f40442335": 216, + "265523c62e7d": 215, + "832acbc47567": 217 + }, + "versions": { + "3": 433, + "4": 215 + } + }, + { + "t": 18, + "ok": 486, + "err": 0, + "instances": { + "832acbc47567": 166, + "617f40442335": 162, + "265523c62e7d": 158 + }, + "versions": { + "3": 328, + "4": 158 + } + }, + { + "t": 19, + "ok": 403, + "err": 0, + "instances": { + "265523c62e7d": 137, + "832acbc47567": 133, + "617f40442335": 133 + }, + "versions": { + "4": 137, + "3": 266 + } + }, + { + "t": 20, + "ok": 654, + "err": 0, + "instances": { + "832acbc47567": 218, + "265523c62e7d": 219, + "617f40442335": 217 + }, + "versions": { + "3": 435, + "4": 219 + } + }, + { + "t": 21, + "ok": 363, + "err": 0, + "instances": { + "617f40442335": 178, + "265523c62e7d": 182, + "832acbc47567": 3 + }, + "versions": { + "3": 181, + "4": 182 + } + }, + { + "t": 22, + "ok": 314, + "err": 0, + "instances": { + "265523c62e7d": 155, + "617f40442335": 159 + }, + "versions": { + "4": 155, + "3": 159 + } + }, + { + "t": 23, + "ok": 310, + "err": 0, + "instances": { + "265523c62e7d": 154, + "617f40442335": 156 + }, + "versions": { + "4": 154, + "3": 156 + } + }, + { + "t": 24, + "ok": 193, + "err": 0, + "instances": { + "265523c62e7d": 100, + "617f40442335": 93 + }, + "versions": { + "4": 100, + "3": 93 + } + }, + { + "t": 25, + "ok": 393, + "err": 0, + "instances": { + "617f40442335": 152, + "265523c62e7d": 146, + "f8ef1bf014c5": 95 + }, + "versions": { + "3": 152, + "4": 241 + } + }, + { + "t": 26, + "ok": 635, + "err": 0, + "instances": { + "617f40442335": 212, + "265523c62e7d": 212, + "f8ef1bf014c5": 211 + }, + "versions": { + "3": 212, + "4": 423 + } + }, + { + "t": 27, + "ok": 721, + "err": 0, + "instances": { + "617f40442335": 239, + "265523c62e7d": 241, + "f8ef1bf014c5": 241 + }, + "versions": { + "3": 239, + "4": 482 + } + }, + { + "t": 28, + "ok": 598, + "err": 0, + "instances": { + "617f40442335": 202, + "f8ef1bf014c5": 200, + "265523c62e7d": 196 + }, + "versions": { + "3": 202, + "4": 396 + } + }, + { + "t": 29, + "ok": 373, + "err": 0, + "instances": { + "265523c62e7d": 123, + "f8ef1bf014c5": 125, + "617f40442335": 125 + }, + "versions": { + "4": 248, + "3": 125 + } + }, + { + "t": 30, + "ok": 265, + "err": 0, + "instances": { + "617f40442335": 86, + "265523c62e7d": 93, + "f8ef1bf014c5": 86 + }, + "versions": { + "3": 86, + "4": 179 + } + }, + { + "t": 31, + "ok": 701, + "err": 0, + "instances": { + "f8ef1bf014c5": 248, + "617f40442335": 207, + "265523c62e7d": 246 + }, + "versions": { + "4": 494, + "3": 207 + } + }, + { + "t": 32, + "ok": 338, + "err": 0, + "instances": { + "265523c62e7d": 172, + "f8ef1bf014c5": 166 + }, + "versions": { + "4": 338 + } + }, + { + "t": 33, + "ok": 322, + "err": 0, + "instances": { + "f8ef1bf014c5": 162, + "265523c62e7d": 160 + }, + "versions": { + "4": 322 + } + }, + { + "t": 34, + "ok": 235, + "err": 0, + "instances": { + "f8ef1bf014c5": 117, + "265523c62e7d": 118 + }, + "versions": { + "4": 235 + } + }, + { + "t": 35, + "ok": 141, + "err": 0, + "instances": { + "265523c62e7d": 66, + "f8ef1bf014c5": 75 + }, + "versions": { + "4": 141 + } + }, + { + "t": 36, + "ok": 313, + "err": 0, + "instances": { + "265523c62e7d": 157, + "f8ef1bf014c5": 156 + }, + "versions": { + "4": 313 + } + }, + { + "t": 37, + "ok": 323, + "err": 0, + "instances": { + "265523c62e7d": 161, + "f8ef1bf014c5": 162 + }, + "versions": { + "4": 323 + } + }, + { + "t": 38, + "ok": 353, + "err": 0, + "instances": { + "265523c62e7d": 181, + "f8ef1bf014c5": 172 + }, + "versions": { + "4": 353 + } + }, + { + "t": 39, + "ok": 337, + "err": 0, + "instances": { + "265523c62e7d": 169, + "f8ef1bf014c5": 168 + }, + "versions": { + "4": 337 + } + }, + { + "t": 40, + "ok": 217, + "err": 0, + "instances": { + "f8ef1bf014c5": 110, + "265523c62e7d": 107 + }, + "versions": { + "4": 217 + } + }, + { + "t": 41, + "ok": 239, + "err": 0, + "instances": { + "f8ef1bf014c5": 119, + "265523c62e7d": 120 + }, + "versions": { + "4": 239 + } + }, + { + "t": 42, + "ok": 269, + "err": 0, + "instances": { + "265523c62e7d": 136, + "f8ef1bf014c5": 133 + }, + "versions": { + "4": 269 + } + }, + { + "t": 43, + "ok": 348, + "err": 0, + "instances": { + "f8ef1bf014c5": 175, + "265523c62e7d": 173 + }, + "versions": { + "4": 348 + } + }, + { + "t": 44, + "ok": 342, + "err": 0, + "instances": { + "f8ef1bf014c5": 170, + "265523c62e7d": 172 + }, + "versions": { + "4": 342 + } + }, + { + "t": 45, + "ok": 323, + "err": 0, + "instances": { + "f8ef1bf014c5": 162, + "265523c62e7d": 161 + }, + "versions": { + "4": 323 + } + }, + { + "t": 46, + "ok": 235, + "err": 0, + "instances": { + "f8ef1bf014c5": 122, + "265523c62e7d": 113 + }, + "versions": { + "4": 235 + } + }, + { + "t": 47, + "ok": 313, + "err": 0, + "instances": { + "265523c62e7d": 161, + "f8ef1bf014c5": 152 + }, + "versions": { + "4": 313 + } + }, + { + "t": 48, + "ok": 328, + "err": 0, + "instances": { + "265523c62e7d": 158, + "f8ef1bf014c5": 170 + }, + "versions": { + "4": 328 + } + }, + { + "t": 49, + "ok": 360, + "err": 0, + "instances": { + "265523c62e7d": 185, + "f8ef1bf014c5": 175 + }, + "versions": { + "4": 360 + } + }, + { + "t": 50, + "ok": 349, + "err": 0, + "instances": { + "f8ef1bf014c5": 174, + "265523c62e7d": 175 + }, + "versions": { + "4": 349 + } + }, + { + "t": 51, + "ok": 334, + "err": 0, + "instances": { + "f8ef1bf014c5": 167, + "265523c62e7d": 167 + }, + "versions": { + "4": 334 + } + }, + { + "t": 52, + "ok": 179, + "err": 0, + "instances": { + "265523c62e7d": 90, + "f8ef1bf014c5": 89 + }, + "versions": { + "4": 179 + } + }, + { + "t": 53, + "ok": 348, + "err": 0, + "instances": { + "f8ef1bf014c5": 174, + "265523c62e7d": 174 + }, + "versions": { + "4": 348 + } + }, + { + "t": 54, + "ok": 294, + "err": 0, + "instances": { + "f8ef1bf014c5": 149, + "265523c62e7d": 145 + }, + "versions": { + "4": 294 + } + }, + { + "t": 55, + "ok": 278, + "err": 0, + "instances": { + "f8ef1bf014c5": 137, + "265523c62e7d": 141 + }, + "versions": { + "4": 278 + } + }, + { + "t": 56, + "ok": 305, + "err": 0, + "instances": { + "265523c62e7d": 151, + "f8ef1bf014c5": 154 + }, + "versions": { + "4": 305 + } + }, + { + "t": 57, + "ok": 215, + "err": 0, + "instances": { + "f8ef1bf014c5": 109, + "265523c62e7d": 106 + }, + "versions": { + "4": 215 + } + }, + { + "t": 58, + "ok": 223, + "err": 0, + "instances": { + "f8ef1bf014c5": 114, + "265523c62e7d": 109 + }, + "versions": { + "4": 223 + } + }, + { + "t": 59, + "ok": 283, + "err": 0, + "instances": { + "265523c62e7d": 142, + "f8ef1bf014c5": 141 + }, + "versions": { + "4": 283 + } + }, + { + "t": 60, + "ok": 289, + "err": 0, + "instances": { + "265523c62e7d": 144, + "f8ef1bf014c5": 145 + }, + "versions": { + "4": 289 + } + }, + { + "t": 61, + "ok": 309, + "err": 0, + "instances": { + "f8ef1bf014c5": 155, + "265523c62e7d": 154 + }, + "versions": { + "4": 309 + } + }, + { + "t": 62, + "ok": 290, + "err": 0, + "instances": { + "265523c62e7d": 146, + "f8ef1bf014c5": 144 + }, + "versions": { + "4": 290 + } + }, + { + "t": 63, + "ok": 182, + "err": 0, + "instances": { + "f8ef1bf014c5": 90, + "265523c62e7d": 92 + }, + "versions": { + "4": 182 + } + }, + { + "t": 64, + "ok": 298, + "err": 0, + "instances": { + "f8ef1bf014c5": 150, + "265523c62e7d": 148 + }, + "versions": { + "4": 298 + } + }, + { + "t": 65, + "ok": 284, + "err": 0, + "instances": { + "265523c62e7d": 142, + "f8ef1bf014c5": 142 + }, + "versions": { + "4": 284 + } + }, + { + "t": 66, + "ok": 310, + "err": 0, + "instances": { + "265523c62e7d": 157, + "f8ef1bf014c5": 153 + }, + "versions": { + "4": 310 + } + }, + { + "t": 67, + "ok": 281, + "err": 0, + "instances": { + "265523c62e7d": 144, + "f8ef1bf014c5": 137 + }, + "versions": { + "4": 281 + } + }, + { + "t": 68, + "ok": 247, + "err": 0, + "instances": { + "f8ef1bf014c5": 124, + "265523c62e7d": 123 + }, + "versions": { + "4": 247 + } + }, + { + "t": 69, + "ok": 233, + "err": 0, + "instances": { + "f8ef1bf014c5": 116, + "265523c62e7d": 117 + }, + "versions": { + "4": 233 + } + }, + { + "t": 70, + "ok": 307, + "err": 0, + "instances": { + "f8ef1bf014c5": 155, + "265523c62e7d": 152 + }, + "versions": { + "4": 307 + } + }, + { + "t": 71, + "ok": 278, + "err": 0, + "instances": { + "f8ef1bf014c5": 139, + "265523c62e7d": 139 + }, + "versions": { + "4": 278 + } + }, + { + "t": 72, + "ok": 357, + "err": 0, + "instances": { + "f8ef1bf014c5": 182, + "265523c62e7d": 175 + }, + "versions": { + "4": 357 + } + }, + { + "t": 73, + "ok": 296, + "err": 0, + "instances": { + "f8ef1bf014c5": 149, + "265523c62e7d": 147 + }, + "versions": { + "4": 296 + } + }, + { + "t": 74, + "ok": 190, + "err": 0, + "instances": { + "265523c62e7d": 96, + "f8ef1bf014c5": 94 + }, + "versions": { + "4": 190 + } + }, + { + "t": 75, + "ok": 8, + "err": 0, + "instances": { + "265523c62e7d": 6, + "f8ef1bf014c5": 2 + }, + "versions": { + "4": 8 + } + } + ], + "pass": true +} diff --git a/evidence/rolling-update.txt b/evidence/rolling-update.txt new file mode 100644 index 00000000..bad3b3ef --- /dev/null +++ b/evidence/rolling-update.txt @@ -0,0 +1,20 @@ +## before 2026-10-24T14:58:33Z +mtusi-lab3-api-1 832acbc47567 Up About a minute (healthy) +mtusi-lab3-api-2 617f40442335 Up About a minute (healthy) +{"action": {"command": "scripts/rolling-update.sh 4", "started_s": 10.025, "finished_s": 34.09, "exit_code": 0}, "baseline_ok_rps": 278.7, "overall_ok_rps": 333.5, "post_action_ok_rps": 291.3, "requests_ok": 25013, "errors_total": 0, "latency_ok_ms": {"p50": 8.8, "p95": 84.3, "p99": 100.1}, "lb_events": [{"t": 4.04, "server": "api3", "addr": "172.19.0.6:8080", "from": "MAINT", "to": "UP"}, {"t": 11.17, "server": "api1", "addr": "172.19.0.4:8080", "from": "UP", "to": "DOWN"}, {"t": 15.67, "server": "api1", "addr": "172.19.0.4:8080", "from": "DOWN", "to": "UP"}, {"t": 21.8, "server": "api2", "addr": "172.19.0.3:8080", "from": "UP", "to": "DOWN"}, {"t": 26.08, "server": "api2", "addr": "", "from": "DOWN", "to": "MAINT"}], "confirmed_messages": 12510, "lost_confirmed": 0, "duplicate_texts": 0, "pass": true} +## action log +2026-10-24T14:58:44Z build version 4 + api Built +2026-10-24T14:58:46Z migrate (once) +2026-10-24 14:58:47,269 INFO migrations done; applied now: nothing +2026-10-24T14:58:47Z replacing 2 replicas +2026-10-24T14:58:54Z up mtusi-lab3-api-3 version=4 ip=172.19.0.6 UP in LB (UP slots: 4) +2026-10-24T14:58:57Z gone mtusi-lab3-api-1 (graceful SIGTERM) +2026-10-24T14:59:04Z up mtusi-lab3-api-4 version=4 ip=172.19.0.4 UP in LB (UP slots: 4) +2026-10-24T14:59:08Z gone mtusi-lab3-api-2 (graceful SIGTERM) +2026-10-24T14:59:08Z done: mtusi-lab3-api-3 mtusi-lab3-api-4 +## after 2026-10-24T14:59:51Z +mtusi-lab3-api-3 265523c62e7d Up About a minute (healthy) +mtusi-lab3-api-4 f8ef1bf014c5 Up 53 seconds (healthy) +/mtusi-lab3-api-3 APP_VERSION=4 +/mtusi-lab3-api-4 APP_VERSION=4 diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 00000000..88517e6f --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8080" +PASS: lab3 public API scenario; infrastructure and grading evidence remain separate. diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg new file mode 100644 index 00000000..a364ef41 --- /dev/null +++ b/infra/haproxy/haproxy.cfg @@ -0,0 +1,98 @@ +# Lab3: единая точка входа перед API-репликами. +# +# Обнаружение реплик: DNS Docker (127.0.0.11) отдаёт по имени сервиса `api` адреса +# ВСЕХ его контейнеров; server-template создаёт до 8 слотов и заполняет их по DNS. +# Поэтому `docker compose up --scale api=N` не требует правки конфигурации. +# +# Readiness: активная проверка GET /health/ready каждую 1 с; 2 неудачи подряд -> DOWN, +# 2 успеха -> UP. Максимальное время обнаружения отказа: +# inter(1s) + timeout check(1s) + fastinter(0.5s) + timeout check(1s) ~= 3.5 с; +# ready=503 или refused без ожидания таймаута -> ~1.5 с. +# Sticky sessions НЕ используются: balance roundrobin без cookie/stick-table для backend +# (stick-table во frontend считает только частоту входов по IP, на выбор реплики не влияет). +# +# Перегрузка: maxconn 10 на реплику (= DB_POOL_SIZE) — лишние запросы ждут в очереди LB +# (timeout queue 5s), а не плодят потоки внутри Python-процесса. Переполнение -> 503 JSON. + +global + log stdout format raw local0 info + maxconn 4096 + +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 2s + hold other 2s + hold refused 2s + hold nx 2s + hold timeout 2s + hold obsolete 2s + accepted_payload_size 8192 + +defaults + mode http + log global + option httplog + option dontlognull + # Внутри одного Docker-host соединение устанавливается за доли мс: 500 мс хватает с запасом, + # а при внезапно исчезнувшей реплике запрос быстро уходит в retry на другую. + timeout connect 500ms + timeout client 30s + timeout server 10s + timeout http-request 10s + timeout http-keep-alive 5s + timeout queue 5s + timeout check 1s + # Повтор только если соединение с backend НЕ установлено (запрос точно не дошёл + # до приложения) — это безопасно даже для неидемпотентных POST. Повтор уходит + # на другую реплику (redispatch). Ответы/таймауты после отправки не повторяются. + retries 2 + retry-on conn-failure + option redispatch 1 + + # Ошибки, которые формирует сам HAProxy (нет живых реплик, обрыв backend, timeout, + # переполнение очереди), отдаются в общем JSON-формате ошибки контракта, а не HTML. + # Ответы приложения (в т.ч. его 503) эти правила не затрагивают. + unique-id-format %[uuid()] + http-error status 400 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" lf-string '{"error":{"code":"invalid_request","message":"Неверный запрос","request_id":"%ID"}}' + http-error status 408 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" lf-string '{"error":{"code":"invalid_request","message":"Запрос не получен вовремя","request_id":"%ID"}}' + http-error status 429 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" hdr Retry-After "10" lf-string '{"error":{"code":"rate_limited","message":"Слишком много запросов, повторите позже","request_id":"%ID"}}' + http-error status 500 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" lf-string '{"error":{"code":"internal_error","message":"Внутренняя ошибка сервера","request_id":"%ID"}}' + http-error status 502 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" hdr Retry-After "1" lf-string '{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"%ID"}}' + http-error status 503 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" hdr Retry-After "1" lf-string '{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"%ID"}}' + http-error status 504 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" hdr Retry-After "1" lf-string '{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"%ID"}}' + +frontend fe_api + bind :8080 + # X-Request-Id формирует само приложение; LB только пробрасывает адрес клиента. + option forwardfor + # Защита входа от перебора паролей и шторма scrypt: не более LOGIN_RATE_LIMIT + # попыток POST /auth/sessions за 10 с с одного IP, сверх — 429 rate_limited. + stick-table type ip size 100k expire 60s store http_req_rate(10s) + acl is_login method POST + acl is_login_path path /api/v1/auth/sessions + # Явно вычисляем unique-id до deny: иначе в ответе 429 request_id остаётся пустым. + http-request set-var(txn.request_id) unique-id + http-request track-sc0 src if is_login is_login_path + http-request deny deny_status 429 if is_login is_login_path { sc_http_req_rate(0) gt "${LOGIN_RATE_LIMIT}" } + default_backend be_api + +backend be_api + balance roundrobin + option httpchk + http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host lb + http-check expect status 200 + # on-marked-down shutdown-sessions НЕ используется: при штатной остановке реплика ещё + # дообслуживает начатые запросы (drain), и обрыв их сессий дал бы лишние 502. + default-server maxconn 10 check inter 1s fastinter 500ms downinter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr libc,none + server-template api 8 api:8080 + +# Статистика LB (только на 127.0.0.1 хоста): видно, какие реплики UP/DOWN. +frontend stats + bind :8404 + stats enable + stats uri /stats + stats refresh 2s + stats show-legends diff --git a/migrations/001_init.sql b/migrations/001_init.sql new file mode 100644 index 00000000..1bf8d91f --- /dev/null +++ b/migrations/001_init.sql @@ -0,0 +1,40 @@ +-- Lab2: начальная схема. Источник истины — PostgreSQL. +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL UNIQUE, + display_name text NOT NULL, + password_hash text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id), + user_id uuid NOT NULL REFERENCES users(id), + position integer NOT NULL, -- порядок участников как в запросе + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX chat_members_user_idx ON chat_members (user_id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + sender_id uuid NOT NULL REFERENCES users(id), + text text NOT NULL, + created_at timestamptz NOT NULL +); +-- Индекс под keyset-пагинацию истории: (created_at, id) внутри чата. +CREATE INDEX messages_chat_order_idx ON messages (chat_id, created_at, id); + +CREATE TABLE sessions ( + token_hash bytea PRIMARY KEY, -- SHA-256 от токена; сам токен не хранится + user_id uuid NOT NULL REFERENCES users(id), + created_at timestamptz NOT NULL, + expires_at timestamptz NOT NULL, + revoked_at timestamptz +); diff --git a/migrations/002_idempotency.sql b/migrations/002_idempotency.sql new file mode 100644 index 00000000..a46f46ab --- /dev/null +++ b/migrations/002_idempotency.sql @@ -0,0 +1,17 @@ +-- Lab3: общая (для всех реплик) идемпотентность POST сообщения. +-- Миграция только добавляет таблицу: код lab2 продолжает работать на новой схеме +-- (expand-only), поэтому её можно применить до замены реплик при rolling update. +-- +-- Область уникальности по контракту: пользователь + метод + путь чата + ключ. +-- Метод всегда POST, путь однозначно задаётся chat_id, поэтому ключ PK — (user_id, chat_id, idem_key). +CREATE TABLE idempotency_keys ( + user_id uuid NOT NULL REFERENCES users(id), + chat_id uuid NOT NULL REFERENCES chats(id), + idem_key text NOT NULL, + request_hash bytea NOT NULL, -- SHA-256 канонического JSON тела запроса + message_id uuid NOT NULL REFERENCES messages(id), + created_at timestamptz NOT NULL DEFAULT now(), + expires_at timestamptz NOT NULL, + PRIMARY KEY (user_id, chat_id, idem_key) +); +CREATE INDEX idempotency_keys_expires_idx ON idempotency_keys (expires_at); diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..150f747d --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +# Закреплённые версии; драйвер PostgreSQL для Python. +psycopg[binary]==3.2.3 +psycopg-pool==3.2.4 diff --git a/scripts/failover-each.sh b/scripts/failover-each.sh new file mode 100755 index 00000000..9b087786 --- /dev/null +++ b/scripts/failover-each.sh @@ -0,0 +1,50 @@ +#!/bin/sh +# Уровень 4: ПОСЛЕДОВАТЕЛЬНО останавливает КАЖДУЮ API-реплику под нагрузкой, +# восстанавливая предыдущую перед следующей. Режимы: +# stop — docker stop (SIGTERM -> graceful drain), штатная остановка/деплой; +# kill — docker kill (SIGKILL), внезапное падение процесса без drain. +# Результаты: evidence/failover--.json (+ .action.log). +# Использование: scripts/failover-each.sh [stop|kill] ... (по умолчанию: stop kill) +set -eu +cd "$(dirname "$0")/.." +MODES=${*:-stop kill} +CONCURRENCY=${CONCURRENCY:-8} +DURATION=${DURATION:-40} +mkdir -p evidence + +wait_all_up() { + # API-контейнеры healthy и HAProxy видит их все UP (rise 2 * inter 1s). + ./scripts/start-all.sh >/dev/null + n=$(docker compose ps -q api | wc -l | tr -d ' ') + for _ in $(seq 1 60); do + up=$(curl -s 'http://127.0.0.1:8404/stats;csv' | awk -F, '$1=="be_api" && $18=="UP"' | wc -l | tr -d ' ') + [ "$up" -ge "$n" ] && return 0 + sleep 1 + done + echo "HAProxy did not mark all $n api servers UP" >&2; return 1 +} + +wait_all_up +# Список фиксируется один раз: остановленная реплика пропала бы из `docker compose ps`. +NAMES=$(docker compose ps --format '{{.Name}}' api | sort) +for mode in $MODES; do + for name in $NAMES; do + wait_all_up + cid=$(docker inspect -f '{{.Id}}' "$name"); short=$(echo "$cid" | cut -c1-12) + case $mode in + stop) action="docker stop -t 20 $cid" ;; + kill) action="docker kill $cid" ;; + *) echo "unknown mode $mode" >&2; exit 2 ;; + esac + echo "== $mode $name ($short) $(date -u +%FT%TZ)" + out=evidence/failover-$mode-$name.json + python3 student-tests/failover_bench.py --label "$mode $name" \ + --concurrency "$CONCURRENCY" --duration "$DURATION" --action-at 10 \ + --action "$action" --target-instance "$short" \ + --action-log "${out%.json}.action.log" --output "$out" \ + | python3 -c 'import json,sys; t=sys.stdin.read(); s=json.loads(t[:t.rindex("}")+1]); print(json.dumps({k:s[k] for k in ("baseline_ok_rps","post_action_ok_rps","capacity_ratio","errors_total","errors_by_kind","error_window_s","recovery_s","target_last_seen_s","lb_events","lost_confirmed","duplicate_texts","pass")},ensure_ascii=False)); sys.exit(0 if s["pass"] else 1)' + echo "-- state after action:"; docker compose ps -a --format '{{.Name}} {{.Status}}' api + done +done +wait_all_up +echo "== restored: $(docker compose ps --format '{{.Name}} {{.Status}}' api | tr '\n' ';')" diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh new file mode 100755 index 00000000..eb58f550 --- /dev/null +++ b/scripts/init-secrets.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# Создаёт локальные секреты и .env для учебного стенда. Повторный запуск ничего не перезаписывает. +# Значения секретов не печатаются. +set -eu +cd "$(dirname "$0")/.." +umask 077 +mkdir -p secrets +chmod 700 secrets +if [ ! -s secrets/postgres_password ]; then + python3 -c 'import secrets; print(secrets.token_urlsafe(24))' > secrets/postgres_password + echo "created secrets/postgres_password" +fi +# Файл монтируется в контейнеры (uid 70 postgres, uid 10001 app) — нужен на чтение; +# от других пользователей хоста его закрывает каталог secrets/ с правами 700. +chmod 644 secrets/postgres_password +if [ ! -f .env ]; then + cp .env.example .env + echo "created .env from .env.example" +fi diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..184e633e --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# Перезапуск API (все реплики), LB и PostgreSQL с сохранением volume. +# Не выполняет down -v, не пересоздаёт БД и не повторяет seed. +set -eu +cd "$(dirname "$0")/.." +docker compose restart db +docker compose restart api lb diff --git a/scripts/rolling-update.sh b/scripts/rolling-update.sh new file mode 100755 index 00000000..60c48154 --- /dev/null +++ b/scripts/rolling-update.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# Поочерёдная замена API-реплик на новую версию образа без остановки сервиса. +# scripts/rolling-update.sh +# Порядок (expand -> replace): +# 1. собрать новый образ (тот же тег mtusi-messenger:lab3, build-arg APP_VERSION); +# 2. ОДИН раз применить миграции (job migrate). Допускаются только обратно совместимые +# (expand-only) миграции: старые реплики продолжают работать на новой схеме; +# 3. для каждой старой реплики: поднять +1 новую -> дождаться healthy и UP в HAProxy -> +# штатно остановить (SIGTERM, drain) и удалить старую. Число обслуживающих реплик +# не опускается ниже исходного. +# 4. записать APP_VERSION в .env, чтобы следующий `docker compose up` не пересоздал всё разом. +set -eu +cd "$(dirname "$0")/.." +VERSION=${1:?usage: rolling-update.sh } +export APP_VERSION="$VERSION" +ts() { date -u +%FT%TZ; } + +lb_up_count() { + curl -s 'http://127.0.0.1:8404/stats;csv' | awk -F, '$1=="be_api" && $18=="UP"' | wc -l | tr -d ' ' +} +# UP ли в HAProxy слот с адресом конкретного контейнера. Проверяем именно адрес, а не число +# UP-серверов: новый контейнер может получить IP только что удалённого, и счётчик обманет. +lb_has_up() { + curl -s 'http://127.0.0.1:8404/stats;csv' | awk -F, -v a="$1:8080" '$1=="be_api" && $18=="UP" && $74==a' | grep -q . +} + +echo "$(ts) build version $VERSION" +docker compose --env-file .env build api >/dev/null +echo "$(ts) migrate (once)" +docker compose --env-file .env run --rm --no-deps migrate + +OLD=$(docker compose ps -q api) +N=$(echo "$OLD" | wc -l | tr -d ' ') +echo "$(ts) replacing $N replicas" +for old in $OLD; do + before=$(docker compose ps -q api | sort) + docker compose --env-file .env up -d --no-deps --no-recreate --scale api=$((N + 1)) api >/dev/null 2>&1 + new=$(docker compose ps -q api | sort | grep -v -F "$before" | head -1) + [ -n "$new" ] || { echo "new replica was not created" >&2; exit 1; } + for _ in $(seq 1 60); do + [ "$(docker inspect -f '{{.State.Health.Status}}' "$new")" = healthy ] && break; sleep 1 + done + [ "$(docker inspect -f '{{.State.Health.Status}}' "$new")" = healthy ] || { echo "new replica not healthy" >&2; exit 1; } + ip=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$new") + for _ in $(seq 1 30); do lb_has_up "$ip" && break; sleep 0.5; done + lb_has_up "$ip" || { echo "HAProxy did not mark new replica $ip UP" >&2; exit 1; } + echo "$(ts) up $(docker inspect -f '{{.Name}}' "$new" | tr -d /) version=$(docker exec "$new" printenv APP_VERSION) ip=$ip UP in LB (UP slots: $(lb_up_count))" + name=$(docker inspect -f '{{.Name}}' "$old" | tr -d /) + docker stop -t 20 "$old" >/dev/null && docker rm "$old" >/dev/null + echo "$(ts) gone $name (graceful SIGTERM)" +done +if grep -q '^APP_VERSION=' .env; then + sed -i.bak "s/^APP_VERSION=.*/APP_VERSION=$VERSION/" .env && rm -f .env.bak +else + echo "APP_VERSION=$VERSION" >> .env +fi +echo "$(ts) done: $(docker compose ps --format '{{.Name}}' api | tr '\n' ' ')" diff --git a/scripts/start-all.sh b/scripts/start-all.sh new file mode 100755 index 00000000..bd70fb78 --- /dev/null +++ b/scripts/start-all.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# Восстанавливает остановленные API-реплики (после stop-one.sh / failover-each.sh) и ждёт готовности. +# --no-deps: БД и job миграций не трогаются; --no-recreate: те же контейнеры (тот же образ). +set -eu +cd "$(dirname "$0")/.." +docker compose up -d --no-deps --no-recreate --wait api +docker compose ps --format '{{.Name}} {{.Status}}' api diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 00000000..e9ef5239 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# Останавливает ОДНУ API-реплику, обслужившую тест, и оставляет её остановленной. +# TARGET_INSTANCE_ID = X-Instance-Id = hostname контейнера = короткий ID контейнера. +# DB, LB и volumes не трогаются. Восстановление: scripts/start-all.sh +set -eu +cd "$(dirname "$0")/.." +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" +case "$TARGET_INSTANCE_ID" in + *[!0-9a-f]*|'') echo "unexpected instance id format" >&2; exit 2 ;; +esac +# Проверяем, что это действительно контейнер сервиса api этого compose-проекта. +cid=$(docker ps -q --no-trunc \ + --filter "label=com.docker.compose.project=mtusi-lab3" \ + --filter "label=com.docker.compose.service=api" \ + | grep "^${TARGET_INSTANCE_ID}" || true) +[ -n "$cid" ] || { echo "no running api container for $TARGET_INSTANCE_ID" >&2; exit 3; } +name=$(docker inspect -f '{{.Name}}' "$cid") +echo "$(date -u +%FT%TZ) stopping api container ${name#/} (${TARGET_INSTANCE_ID})" >&2 +# SIGTERM -> graceful shutdown приложения (drain 3 с + дообслуживание), затем выход. +docker stop -t 20 "$cid" >/dev/null +echo "$(date -u +%FT%TZ) stopped ${name#/}" >&2 diff --git a/src/migrate.py b/src/migrate.py new file mode 100644 index 00000000..b5c66643 --- /dev/null +++ b/src/migrate.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +"""Однократное применение миграций (compose-сервис `migrate`). + +Запускается ОДИН раз до старта/замены API-реплик, а не каждой репликой. +Дополнительно миграции выполняются под pg_advisory_xact_lock: даже если +оператор случайно запустит job дважды параллельно, гонки не будет. +Каждый файл применяется в своей транзакции и фиксируется в schema_migrations. +""" +import logging +import sys + +from server import MIGRATIONS_DIR, STORE + +log = logging.getLogger("messenger.migrate") + + +def main(): + STORE.open() + try: + before = STORE.pending_migrations(MIGRATIONS_DIR) + STORE.migrate(MIGRATIONS_DIR) + log.info("migrations done; applied now: %s", ", ".join(before) or "nothing") + finally: + STORE.close() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/security.py b/src/security.py new file mode 100644 index 00000000..f9078acf --- /dev/null +++ b/src/security.py @@ -0,0 +1,53 @@ +"""Пароли (scrypt из стандартной библиотеки) и сессионные токены.""" +import base64 +import hashlib +import hmac +import os +import secrets + +# Параметры scrypt: N=2^15, r=8, p=1 (~32 МБ памяти и ~0.1 с на проверку). +SCRYPT_LOG_N = 15 +SCRYPT_R = 8 +SCRYPT_P = 1 +_MAXMEM = 128 * 1024 * 1024 + + +def _scrypt(password, salt, log_n, r, p): + return hashlib.scrypt(password.encode("utf-8"), salt=salt, n=2 ** log_n, r=r, p=p, + maxmem=_MAXMEM, dklen=32) + + +def hash_password(password): + """Возвращает строку scrypt$logN$r$p$salt$hash; plaintext нигде не хранится.""" + salt = os.urandom(16) + digest = _scrypt(password, salt, SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P) + return "scrypt$%d$%d$%d$%s$%s" % ( + SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P, + base64.b64encode(salt).decode(), base64.b64encode(digest).decode()) + + +def verify_password(password, stored): + try: + scheme, log_n, r, p, salt, digest = stored.split("$") + if scheme != "scrypt": + return False + expected = base64.b64decode(digest) + actual = _scrypt(password, base64.b64decode(salt), int(log_n), int(r), int(p)) + except (ValueError, TypeError): + return False + return hmac.compare_digest(actual, expected) # сравнение за постоянное время + + +# Хеш несуществующего пользователя: неверный логин тратит столько же времени, +# сколько неверный пароль, и не выдаёт, существует ли username. +DUMMY_HASH = hash_password(secrets.token_urlsafe(16)) + + +def new_token(): + """Непрозрачный случайный токен: 32 байта = 256 бит энтропии.""" + return secrets.token_urlsafe(32) + + +def token_hash(token): + """В БД лежит только SHA-256 токена: утечка таблицы не даёт готовых сессий.""" + return hashlib.sha256(token.encode("utf-8")).digest() diff --git a/src/server.py b/src/server.py new file mode 100644 index 00000000..73b1705c --- /dev/null +++ b/src/server.py @@ -0,0 +1,655 @@ +#!/usr/bin/env python3 +"""MTUSI Messenger, lab3: REST API для запуска несколькими репликами за балансировщиком. + +Из lab2: PostgreSQL как источник истины, сессии (Bearer) в PostgreSQL, scrypt. +Новое в lab3: + * каждый ответ содержит X-Instance-Id (стабилен на жизнь процесса); + * POST сообщения требует Idempotency-Key, идемпотентность общая через PostgreSQL; + * миграции НЕ применяются репликами: их однократно выполняет src/migrate.py; + * SIGTERM: readiness -> 503, пауза на исключение из LB, дообслуживание и выход; + * пароль БД читается из файла секрета (POSTGRES_PASSWORD_FILE / DATABASE_URL_FILE); + * не более PASSWORD_HASH_CONCURRENCY одновременных scrypt (защита от OOM при шторме входов); + * /health/ready смотрит на фоновую проверку БД со своим соединением, а не на пул запросов. +""" +import base64 +import binascii +import contextlib +import hashlib +import json +import logging +import os +import re +import signal +import socket +import sys +import threading +import time +import uuid +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + +import psycopg +from psycopg.conninfo import make_conninfo +from psycopg_pool import PoolTimeout + +import security +from store import Conflict, Store, UnknownMember, from_micros + +HOST = os.environ.get("APP_HOST", "0.0.0.0") +PORT = int(os.environ.get("APP_PORT", "8080")) +APP_ENV = os.environ.get("APP_ENV", "lab") +SESSION_TTL_SECONDS = int(os.environ.get("SESSION_TTL_SECONDS", "3600")) +IDEMPOTENCY_TTL_SECONDS = int(os.environ.get("IDEMPOTENCY_TTL_SECONDS", "86400")) +MIGRATIONS_DIR = os.environ.get("MIGRATIONS_DIR", str(Path(__file__).resolve().parents[1] / "migrations")) +DB_POOL_SIZE = int(os.environ.get("DB_POOL_SIZE", "10")) +DB_STATEMENT_TIMEOUT_MS = int(os.environ.get("DB_STATEMENT_TIMEOUT_MS", "5000")) +# Graceful shutdown: сколько секунд после SIGTERM продолжаем обслуживать запросы с ready=503, +# чтобы LB успел исключить реплику (>= inter * fall проверки HAProxy), и сколько ждём in-flight. +DRAIN_SECONDS = float(os.environ.get("DRAIN_SECONDS", "3")) +SHUTDOWN_TIMEOUT_SECONDS = float(os.environ.get("SHUTDOWN_TIMEOUT_SECONDS", "10")) +# Таймаут сокета клиента: медленный/зависший клиент не держит поток бесконечно. +CLIENT_SOCKET_TIMEOUT_SECONDS = float(os.environ.get("CLIENT_SOCKET_TIMEOUT_SECONDS", "30")) +# Alias реплики. По умолчанию hostname контейнера (= короткий ID контейнера Docker), +# что позволяет stop-one.sh однозначно найти контейнер по X-Instance-Id. +INSTANCE_ID = os.environ.get("INSTANCE_ID") or socket.gethostname() +# Версия образа (build-arg APP_VERSION): видна в X-App-Version, нужна для проверки rolling update. +APP_VERSION = os.environ.get("APP_VERSION", "dev") +MAX_BODY_BYTES = 1024 * 1024 +# scrypt берёт ~32 MiB на проверку пароля (128 * r * N), лимит реплики 256 MiB. +# Без ограничения ~7 одновременных входов дают OOM-kill (проверено: evidence/before-fix). +# Больше 2 параллельных хешей на 0.5 CPU пропускную способность всё равно не увеличивает. +PASSWORD_HASH_CONCURRENCY = int(os.environ.get("PASSWORD_HASH_CONCURRENCY", "2")) +# Сколько запрос ждёт свободный слот scrypt, прежде чем получить 503 + Retry-After. +# Коротко: ожидающие входы не должны занимать слоты LB (maxconn) у обычных запросов. +PASSWORD_HASH_WAIT_SECONDS = float(os.environ.get("PASSWORD_HASH_WAIT_SECONDS", "0.5")) +# Readiness по БД: фоновый поток со СВОИМ соединением (не из пула запросов) пингует БД +# раз в DB_HEALTH_INTERVAL_SECONDS; реплика «готова», если последний успех не старше +# READY_STALE_SECONDS. Так проверка готовности не конкурирует с трафиком за пул. +DB_HEALTH_INTERVAL_SECONDS = float(os.environ.get("DB_HEALTH_INTERVAL_SECONDS", "1")) +READY_STALE_SECONDS = float(os.environ.get("READY_STALE_SECONDS", "3")) + +USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$") +IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$") +DEFAULT_LIMIT = 50 +BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"' +BEARER_CHALLENGE = 'Bearer realm="messenger"' + +logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") +log = logging.getLogger("messenger") + + +def _secret(name): + """Значение из NAME_FILE (Docker secret) либо из NAME; файл предпочтительнее.""" + path = os.environ.get(name + "_FILE") + if path: + with open(path, encoding="utf-8") as f: + return f.read().strip() + return os.environ.get(name, "") + + +def database_conninfo(): + """DATABASE_URL(_FILE) либо набор POSTGRES_*; пароль — только из секрета/окружения.""" + options = "-c statement_timeout=%d" % DB_STATEMENT_TIMEOUT_MS + url = _secret("DATABASE_URL") + if url: + return make_conninfo(url, connect_timeout=3, options=options) + return make_conninfo( + host=os.environ.get("POSTGRES_HOST", "localhost"), + port=os.environ.get("POSTGRES_PORT", "5432"), + dbname=os.environ.get("POSTGRES_DB", "messenger"), + user=os.environ.get("POSTGRES_USER", "messenger"), + password=_secret("POSTGRES_PASSWORD"), + connect_timeout=3, + options=options, + ) + + +class DbHealth: + """Фоновая проверка PostgreSQL для /health/ready. + + Отдельное соединение вне пула: при исчерпанном пуле (перегрузка) readiness не ждёт + PoolTimeout и не роняет все реплики в DOWN одновременно. Зависание БД/сети тоже + видно: если успешного пинга нет дольше stale_after, реплика не готова.""" + + def __init__(self, conninfo, interval, stale_after): + self.conninfo = conninfo + self.interval = interval + self.stale_after = stale_after + self.last_ok = None # time.monotonic() последнего успешного SELECT 1 + self._stop = threading.Event() + self._thread = None + + def start(self): + self._thread = threading.Thread(target=self._loop, name="db-health", daemon=True) + self._thread.start() + + def stop(self): + self._stop.set() + + def ok(self): + last = self.last_ok + return last is not None and time.monotonic() - last <= self.stale_after + + def _loop(self): + conn, healthy = None, None + while not self._stop.is_set(): + try: + if conn is None or conn.closed: + conn = psycopg.connect(self.conninfo, autocommit=True) + conn.execute("SELECT 1") + self.last_ok = time.monotonic() + if healthy is not True: + log.info("db health: ok") + healthy = True + except Exception as exc: + if healthy is not False: + log.warning("db health: failing (%s)", type(exc).__name__) + healthy = False + if conn is not None: + try: + conn.close() + except Exception: + pass + conn = None + self._stop.wait(self.interval) + if conn is not None: + conn.close() + + +DB_CONNINFO = database_conninfo() +STORE = Store(DB_CONNINFO, pool_size=DB_POOL_SIZE) +DB_HEALTH = DbHealth(DB_CONNINFO, DB_HEALTH_INTERVAL_SECONDS, READY_STALE_SECONDS) +DRAINING = threading.Event() # выставляется по SIGTERM +_INFLIGHT = 0 +_INFLIGHT_LOCK = threading.Lock() +_HASH_SLOTS = threading.BoundedSemaphore(PASSWORD_HASH_CONCURRENCY) + + +# -------------------------------------------------------------------------- +# Ошибки API +# -------------------------------------------------------------------------- +class ApiError(Exception): + def __init__(self, status, code, message, headers=None): + super().__init__(message) + self.status = status + self.code = code + self.message = message + self.headers = headers or {} + + +def bad_request(message="Неверный запрос"): + return ApiError(400, "invalid_request", message) + + +def unauthorized(challenge=BEARER_CHALLENGE): + # Одинаковый ответ для любых причин: не раскрываем, что именно не так. + return ApiError(401, "unauthorized", "Требуется действительная аутентификация", + {"WWW-Authenticate": challenge}) + + +def not_found(): + return ApiError(404, "not_found", "Объект не найден") + + +@contextlib.contextmanager +def password_hash_slot(): + """Ограничивает число одновременных scrypt (память!). Нет слота за + PASSWORD_HASH_WAIT_SECONDS — честный 503 с Retry-After, а не OOM всей реплики.""" + if not _HASH_SLOTS.acquire(timeout=PASSWORD_HASH_WAIT_SECONDS): + raise ApiError(503, "unavailable", "Сервис перегружен, повторите запрос позже", + {"Retry-After": "1"}) + try: + yield + finally: + _HASH_SLOTS.release() + + +# -------------------------------------------------------------------------- +# Валидация +# -------------------------------------------------------------------------- +def parse_uuid(value): + try: + return str(uuid.UUID(value)) + except (ValueError, TypeError, AttributeError): + return None + + +def require_object(body, allowed, required): + if not isinstance(body, dict): + raise bad_request("Тело запроса должно быть JSON-объектом") + if set(body) - set(allowed): + raise bad_request("Лишние поля в запросе") + if any(k not in body for k in required): + raise bad_request("Не хватает обязательных полей") + + +def require_text(value, field, max_len, min_len=1): + if not isinstance(value, str): + raise bad_request("Поле %s должно быть строкой" % field) + if not value.strip(): + raise bad_request("Поле %s не должно быть пустым" % field) + if "\x00" in value: + raise bad_request("Поле %s содержит недопустимый символ" % field) + if not min_len <= len(value) <= max_len: # len() считает Unicode code points + raise bad_request("Поле %s имеет недопустимую длину" % field) + return value + + +def encode_cursor(kind, scope, key): + raw = json.dumps({"k": kind, "s": scope, "t": key[0], "i": key[1]}, separators=(",", ":")) + return base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=") + + +def decode_cursor(cursor, kind, scope): + try: + padded = cursor + "=" * (-len(cursor) % 4) + data = json.loads(base64.urlsafe_b64decode(padded.encode("ascii"))) + if data["k"] != kind or data["s"] != scope: + raise ValueError + t, i = data["t"], parse_uuid(data["i"]) + if not isinstance(t, int) or isinstance(t, bool) or i is None or abs(t) > 10 ** 17: + raise ValueError + from_micros(t) # Проверяем границы datetime до передачи курсора в Store. + return (t, i) + except (ValueError, KeyError, TypeError, UnicodeError, binascii.Error, OverflowError): + raise bad_request("Неверный cursor") + + +def page_params(query): + def single(name): + values = query.get(name) + if values is None: + return None + if len(values) != 1: + raise bad_request("Параметр %s указан несколько раз" % name) + return values[0] + + limit_raw = single("limit") + if limit_raw is None: + limit = DEFAULT_LIMIT + else: + if not re.fullmatch(r"[0-9]{1,3}", limit_raw) or not 1 <= int(limit_raw) <= 100: + raise bad_request("limit должен быть целым от 1 до 100") + limit = int(limit_raw) + cursor = single("cursor") + if cursor == "": + raise bad_request("Неверный cursor") + return limit, cursor + + +# -------------------------------------------------------------------------- +# Обработчики +# -------------------------------------------------------------------------- +def h_live(req): + return 200, {"status": "ok"} + + +def h_ready(req): + # После SIGTERM реплика сообщает LB, что новые запросы ей слать не нужно. + if DRAINING.is_set(): + raise ApiError(503, "unavailable", "Реплика останавливается") + # Критичная зависимость одна — PostgreSQL. Без неё обслуживать запросы нельзя. + # Состояние берётся из фоновой проверки (DbHealth), а не из пула запросов. + if not DB_HEALTH.ok(): + raise ApiError(503, "unavailable", "Сервис временно недоступен") + return 200, {"status": "ok"} + + +def h_create_user(req): + body = req.json_body() + fields = ("username", "display_name", "password") + require_object(body, fields, fields) + username = body["username"] + if not isinstance(username, str) or not USERNAME_RE.fullmatch(username): + raise bad_request("username должен соответствовать [a-z0-9_]{3,32}") + display_name = require_text(body["display_name"], "display_name", 100) + password = require_text(body["password"], "password", 128, min_len=12) + with password_hash_slot(): + password_hash = security.hash_password(password) + try: + return 201, STORE.create_user(username, display_name, password_hash) + except Conflict: + raise ApiError(409, "conflict", "Имя пользователя уже занято") + + +def h_create_session(req): + """Вход: только Authorization: Basic, без JSON body.""" + header = req.headers.get("Authorization", "") + scheme, _, encoded = header.partition(" ") + failure = unauthorized(BASIC_CHALLENGE) + if scheme.lower() != "basic": + raise failure + try: + decoded = base64.b64decode(encoded.strip(), validate=True).decode("utf-8") + except (binascii.Error, ValueError, UnicodeError): + raise failure + username, sep, password = decoded.partition(":") # двоеточие в пароле допустимо + if not sep: + raise failure + user, stored_hash = (None, None) + if USERNAME_RE.fullmatch(username): + user, stored_hash = STORE.get_credentials(username) + # Проверяем scrypt всегда (для неизвестного логина — с фиктивным хешем): + # время ответа не выдаёт, существует ли пользователь. + with password_hash_slot(): + ok = security.verify_password(password, stored_hash or security.DUMMY_HASH) + if user is None or not ok: + raise failure + token = security.new_token() + expires_at = STORE.create_session(user["id"], security.token_hash(token), SESSION_TTL_SECONDS) + return 201, {"token": token, "token_type": "Bearer", "expires_at": expires_at, "user": user} + + +def h_delete_session(req): + req.current_user() + STORE.revoke_session(req.token_hash) + return 204, None + + +def h_me(req): + return 200, req.current_user() + + +def h_create_chat(req): + user = req.current_user() + body = req.json_body() + require_object(body, ("title", "member_ids"), ("title", "member_ids")) + title = require_text(body["title"], "title", 100) + members = body["member_ids"] + if not isinstance(members, list) or not 1 <= len(members) <= 100: + raise bad_request("member_ids должен быть списком из 1–100 UUID") + normalized = [] + for m in members: + mid = parse_uuid(m) if isinstance(m, str) else None + if mid is None: + raise bad_request("member_ids должен содержать UUID-строки") + normalized.append(mid) + if len(set(normalized)) != len(normalized): + raise bad_request("Дубликаты в member_ids") + if user["id"] not in normalized: + raise bad_request("Создатель должен входить в member_ids") + try: + return 201, STORE.create_chat(title, normalized) + except UnknownMember: + raise bad_request("Неизвестный участник чата") + + +def h_list_chats(req): + user = req.current_user() + limit, cursor = page_params(req.query) + after = decode_cursor(cursor, "chats", user["id"]) if cursor else None + items, last = STORE.list_chats(user["id"], after, limit) + return 200, {"items": items, "next_cursor": encode_cursor("chats", user["id"], last) if last else None} + + +def _chat_or_404(user, chat_id): + chat = STORE.get_chat_for(user["id"], chat_id) + if chat is None: + raise not_found() + return chat + + +def h_get_chat(req, chat_id): + user = req.current_user() + return 200, _chat_or_404(user, req.path_uuid(chat_id)) + + +def request_fingerprint(text): + """SHA-256 канонического представления тела: порядок ключей JSON не важен. + attachment_ids (с lab4) по умолчанию [] — отсутствие поля и [] семантически равны.""" + canonical = json.dumps({"attachment_ids": [], "text": text}, sort_keys=True, + separators=(",", ":"), ensure_ascii=False) + return hashlib.sha256(canonical.encode("utf-8")).digest() + + +def h_create_message(req, chat_id): + # Порядок: сессия -> доступ к чату -> тело -> ключ. Повтор с ключом снова проверяет + # действительность сессии и членство, поэтому отозванный токен не получит старый ответ. + user = req.current_user() + cid = req.path_uuid(chat_id) + _chat_or_404(user, cid) # посторонний получает 404 + body = req.json_body() + require_object(body, ("text",), ("text",)) + text = require_text(body["text"], "text", 4000) + key = req.headers.get("Idempotency-Key") + if key is None or not IDEMPOTENCY_KEY_RE.fullmatch(key): + raise bad_request("Требуется Idempotency-Key: [A-Za-z0-9._:-]{1,128}") + try: + result = STORE.add_message(user["id"], cid, text, key, request_fingerprint(text), + IDEMPOTENCY_TTL_SECONDS) + except Conflict: + raise ApiError(409, "conflict", "Idempotency-Key уже использован с другим сообщением") + if result is None: + raise not_found() + message, replayed = result + if replayed: + req.extra_headers["Idempotency-Replayed"] = "true" + return 201, message + + +def h_list_messages(req, chat_id): + user = req.current_user() + cid = req.path_uuid(chat_id) + _chat_or_404(user, cid) + limit, cursor = page_params(req.query) + after = decode_cursor(cursor, "messages", cid) if cursor else None + items, last = STORE.list_messages(cid, after, limit) + return 200, {"items": items, "next_cursor": encode_cursor("messages", cid, last) if last else None} + + +ROUTES = [ + ("GET", re.compile(r"^/health/live$"), h_live), + ("GET", re.compile(r"^/health/ready$"), h_ready), + ("POST", re.compile(r"^/api/v1/users$"), h_create_user), + ("GET", re.compile(r"^/api/v1/users/me$"), h_me), + ("POST", re.compile(r"^/api/v1/auth/sessions$"), h_create_session), + ("DELETE", re.compile(r"^/api/v1/auth/sessions/current$"), h_delete_session), + ("POST", re.compile(r"^/api/v1/chats$"), h_create_chat), + ("GET", re.compile(r"^/api/v1/chats$"), h_list_chats), + ("GET", re.compile(r"^/api/v1/chats/([^/]+)$"), h_get_chat), + ("POST", re.compile(r"^/api/v1/chats/([^/]+)/messages$"), h_create_message), + ("GET", re.compile(r"^/api/v1/chats/([^/]+)/messages$"), h_list_messages), +] + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + server_version = "mtusi-messenger/3.0" + sys_version = "" + timeout = CLIENT_SOCKET_TIMEOUT_SECONDS + + def json_body(self): + ctype = (self.headers.get("Content-Type") or "").split(";")[0].strip().lower() + if ctype != "application/json": + raise ApiError(415, "unsupported_media_type", "Ожидается Content-Type: application/json") + try: + return json.loads(self._body.decode("utf-8")) + except (UnicodeDecodeError, ValueError): + raise bad_request("Некорректный JSON") + + def current_user(self): + """Только Bearer-токен действующей сессии. Basic и X-User-Id доступа не дают.""" + scheme, _, token = self.headers.get("Authorization", "").partition(" ") + token = token.strip() + if scheme.lower() != "bearer" or not token: + raise unauthorized() + self.token_hash = security.token_hash(token) + user = STORE.get_session_user(self.token_hash) + if user is None: + raise unauthorized() + return user + + def path_uuid(self, value): + parsed = parse_uuid(value) + if parsed is None: + raise bad_request("Неверный UUID в пути") + return parsed + + def _read_body(self): + length = self.headers.get("Content-Length") + if length is None: + return b"" + try: + n = int(length) + except ValueError: + raise bad_request("Неверный Content-Length") + if n < 0: + raise bad_request("Неверный Content-Length") + if n > MAX_BODY_BYTES: + self.close_connection = True + raise ApiError(413, "payload_too_large", "Тело запроса слишком большое") + return self.rfile.read(n) + + def _dispatch(self, method): + global _INFLIGHT + with _INFLIGHT_LOCK: + _INFLIGHT += 1 + try: + self._handle(method) + finally: + with _INFLIGHT_LOCK: + _INFLIGHT -= 1 + + def _handle(self, method): + self.request_id = uuid.uuid4().hex + self.extra_headers = {} + started = time.monotonic() + parts = urlsplit(self.path) + path = parts.path + headers = {} + try: + self._body = self._read_body() + self.query = parse_qs(parts.query, keep_blank_values=True) + for m, pattern, func in ROUTES: + match = pattern.match(path) + if match and m == method: + status, payload = func(self, *match.groups()) + break + else: + raise not_found() + headers = self.extra_headers + except ApiError as err: + status, payload, headers = err.status, self._error(err.code, err.message), err.headers + except (psycopg.OperationalError, PoolTimeout): + # БД недоступна: честный 503, а не «успех» или 500. + log.warning("database unavailable request_id=%s", self.request_id) + status, payload = 503, self._error("unavailable", "Сервис временно недоступен") + except Exception: + log.exception("unhandled error request_id=%s", self.request_id) + status, payload = 500, self._error("internal_error", "Внутренняя ошибка сервера") + self._send(status, payload, headers) + # В лог не попадают тела запросов, пароли, токены и тексты сообщений. + log.info("%s %s -> %d %.1fms request_id=%s", method, path, status, + (time.monotonic() - started) * 1000, self.request_id) + + def _error(self, code, message): + return {"error": {"code": code, "message": message, "request_id": self.request_id}} + + def _send(self, status, payload, headers): + self.send_response(status) + self.send_header("X-Request-Id", self.request_id) + self.send_header("X-Instance-Id", INSTANCE_ID) + self.send_header("X-App-Version", APP_VERSION) + if DRAINING.is_set(): + # При остановке закрываем keep-alive: следующий запрос LB уйдёт на живую реплику. + self.close_connection = True + self.send_header("Connection", "close") + for name, value in headers.items(): + self.send_header(name, value) + if payload is None: # 204: без тела + self.end_headers() + return + data = json.dumps(payload, ensure_ascii=False).encode("utf-8") + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + self._dispatch("GET") + + def do_POST(self): + self._dispatch("POST") + + def do_PUT(self): + self._dispatch("PUT") + + def do_PATCH(self): + self._dispatch("PATCH") + + def do_DELETE(self): + self._dispatch("DELETE") + + def log_message(self, fmt, *args): + pass + + +class Server(ThreadingHTTPServer): + request_queue_size = 1024 + daemon_threads = True + + +def wait_for_schema(timeout_seconds=120): + """Реплика не применяет миграции (это делает отдельный однократный job migrate), + а только ждёт, пока схема БД дойдёт до версии, которую знает этот образ.""" + deadline = time.monotonic() + timeout_seconds + while True: + pending = STORE.pending_migrations(MIGRATIONS_DIR) + if not pending: + return + if time.monotonic() > deadline: + raise SystemExit("schema is not migrated: %s" % ", ".join(pending)) + log.info("waiting for migrations: %s", ", ".join(pending)) + time.sleep(1) + + +def wait_inflight(deadline): + while time.monotonic() < deadline: + with _INFLIGHT_LOCK: + if _INFLIGHT == 0: + return 0 + time.sleep(0.05) + with _INFLIGHT_LOCK: + return _INFLIGHT + + +def graceful_stop(server): + """SIGTERM: 1) ready=503 и Connection: close; 2) DRAIN_SECONDS продолжаем обслуживать, + пока HAProxy не исключит реплику; 3) перестаём принимать соединения; + 4) ждём завершения начатых запросов (не дольше SHUTDOWN_TIMEOUT_SECONDS).""" + DRAINING.set() + log.info("draining: readiness=503 for %.1fs", DRAIN_SECONDS) + time.sleep(DRAIN_SECONDS) + server.shutdown() + left = wait_inflight(time.monotonic() + SHUTDOWN_TIMEOUT_SECONDS) + log.info("listener closed, unfinished requests: %d", left) + + +def main(): + STORE.open() + wait_for_schema() + DB_HEALTH.start() + server = Server((HOST, PORT), Handler) + + def stop(signum, frame): + if DRAINING.is_set(): + return + log.info("signal %d received, graceful shutdown", signum) + threading.Thread(target=graceful_stop, args=(server,), daemon=True).start() + + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGINT, stop) + log.info("listening on %s:%d instance=%s version=%s env=%s session_ttl=%ds", HOST, PORT, + INSTANCE_ID, APP_VERSION, APP_ENV, SESSION_TTL_SECONDS) + server.serve_forever() + # serve_forever вернулся из graceful_stop: дождёмся, пока он доведёт in-flight до нуля. + wait_inflight(time.monotonic() + SHUTDOWN_TIMEOUT_SECONDS) + server.server_close() + DB_HEALTH.stop() + STORE.close() + log.info("stopped") + + +if __name__ == "__main__": + main() diff --git a/src/store.py b/src/store.py new file mode 100644 index 00000000..12db4d3e --- /dev/null +++ b/src/store.py @@ -0,0 +1,296 @@ +"""Работа с PostgreSQL: пользователи, чаты, сообщения, сессии. + +Источник истины — база данных. В памяти процесса состояния нет, поэтому +перезапуск API (и самой БД с сохранённым volume) не теряет данные. +""" +import datetime as dt +import logging +import time +import uuid +from pathlib import Path + +import psycopg +from psycopg.rows import dict_row +from psycopg_pool import ConnectionPool + +log = logging.getLogger("messenger.store") + +EPOCH = dt.datetime(1970, 1, 1, tzinfo=dt.timezone.utc) +MIGRATIONS_LOCK_ID = 727001 # произвольный номер advisory-блокировки для миграций + + +class Conflict(Exception): + pass + + +class UnknownMember(Exception): + pass + + +def format_ts(value): + """datetime -> RFC 3339 UTC с микросекундами и суффиксом Z.""" + return value.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ") + + +def to_micros(value): + delta = value - EPOCH + return (delta.days * 86400 + delta.seconds) * 1_000_000 + delta.microseconds + + +def from_micros(micros): + return EPOCH + dt.timedelta(microseconds=micros) + + +def _user(row): + # Пароль/hash и сессионные данные никогда не входят в User. + return { + "id": str(row["id"]), + "username": row["username"], + "display_name": row["display_name"], + "created_at": format_ts(row["created_at"]), + } + + +def _chat(row): + return { + "id": str(row["id"]), + "title": row["title"], + "member_ids": [str(m) for m in row["member_ids"]], + "created_at": format_ts(row["created_at"]), + } + + +def _message(row): + return { + "id": str(row["id"]), + "chat_id": str(row["chat_id"]), + "sender_id": str(row["sender_id"]), + "text": row["text"], + "created_at": format_ts(row["created_at"]), + } + + +CHAT_COLUMNS = """c.id, c.title, c.created_at, + (SELECT array_agg(m.user_id ORDER BY m.position) FROM chat_members m WHERE m.chat_id = c.id) AS member_ids""" + + +class Store: + def __init__(self, conninfo, pool_size=10, pool_timeout=3): + # check: перед выдачей соединение проверяется. После перезапуска PostgreSQL + # «мёртвые» соединения отбрасываются, и запрос не получает ложный 503. + self.pool = ConnectionPool( + conninfo, min_size=1, max_size=pool_size, timeout=pool_timeout, + kwargs={"row_factory": dict_row}, open=False, + check=ConnectionPool.check_connection) + + # --- запуск --- + def open(self, wait_seconds=60): + """Ждём готовности БД (она может стартовать дольше API) и открываем пул.""" + self.pool.open() + deadline = time.monotonic() + wait_seconds + while True: + try: + with self.pool.connection() as conn: + conn.execute("SELECT 1") + return + except Exception as exc: + if time.monotonic() > deadline: + raise + log.info("database is not ready yet (%s), retrying", type(exc).__name__) + time.sleep(1) + + def close(self): + self.pool.close() + + def migrate(self, directory): + """Применяет *.sql по порядку имён; каждая миграция — одна транзакция, один раз.""" + files = sorted(Path(directory).glob("*.sql")) + with self.pool.connection() as conn: + # Advisory-блокировка (сессионная): параллельный повторный запуск job не устроит гонку. + conn.autocommit = True + conn.execute("SELECT pg_advisory_lock(%s)", (MIGRATIONS_LOCK_ID,)) + try: + conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations ( + version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())""") + done = {r["version"] for r in conn.execute("SELECT version FROM schema_migrations")} + for path in files: + if path.name in done: + continue + # Миграция и её отметка — одна транзакция: либо целиком, либо никак. + with conn.transaction(): + conn.execute(path.read_text(encoding="utf-8")) + conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (path.name,)) + log.info("migration applied: %s", path.name) + finally: + conn.execute("SELECT pg_advisory_unlock(%s)", (MIGRATIONS_LOCK_ID,)) + conn.autocommit = False + + def pending_migrations(self, directory): + """Миграции из каталога образа, ещё не применённые к БД (API их НЕ применяет).""" + files = sorted(p.name for p in Path(directory).glob("*.sql")) + with self.pool.connection() as conn: + exists = conn.execute("SELECT to_regclass('schema_migrations') IS NOT NULL AS ok").fetchone()["ok"] + done = {r["version"] for r in conn.execute("SELECT version FROM schema_migrations")} if exists else set() + return [f for f in files if f not in done] + + def ping(self): + with self.pool.connection() as conn: + conn.execute("SELECT 1") + + # --- пользователи --- + def create_user(self, username, display_name, password_hash): + try: + with self.pool.connection() as conn: + row = conn.execute( + """INSERT INTO users (id, username, display_name, password_hash, created_at) + VALUES (%s, %s, %s, %s, clock_timestamp()) + RETURNING id, username, display_name, created_at""", + (uuid.uuid4(), username, display_name, password_hash)).fetchone() + except psycopg.errors.UniqueViolation: + # Уникальность гарантирует сама БД — гонка двух регистраций безопасна. + raise Conflict() + return _user(row) + + def get_credentials(self, username): + with self.pool.connection() as conn: + row = conn.execute( + "SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s", + (username,)).fetchone() + if row is None: + return None, None + return _user(row), row["password_hash"] + + # --- сессии --- + def create_session(self, user_id, token_hash, ttl_seconds): + with self.pool.connection() as conn: + row = conn.execute( + """INSERT INTO sessions (token_hash, user_id, created_at, expires_at) + VALUES (%s, %s, now(), now() + make_interval(secs => %s)) + RETURNING expires_at""", + (token_hash, user_id, ttl_seconds)).fetchone() + return format_ts(row["expires_at"]) + + def get_session_user(self, token_hash): + """Пользователь действующей сессии или None (неизвестна/истекла/отозвана).""" + with self.pool.connection() as conn: + row = conn.execute( + """SELECT u.id, u.username, u.display_name, u.created_at + FROM sessions s JOIN users u ON u.id = s.user_id + WHERE s.token_hash = %s AND s.revoked_at IS NULL AND s.expires_at > now()""", + (token_hash,)).fetchone() + return _user(row) if row else None + + def revoke_session(self, token_hash): + with self.pool.connection() as conn: + conn.execute( + "UPDATE sessions SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL", + (token_hash,)) + + # --- чаты --- + def create_chat(self, title, member_ids): + """Чат и его участники создаются в одной транзакции (атомарно).""" + chat_id = uuid.uuid4() + with self.pool.connection() as conn: + found = conn.execute( + "SELECT count(*) AS n FROM users WHERE id = ANY(%s::uuid[])", (member_ids,)).fetchone()["n"] + if found != len(member_ids): + raise UnknownMember() + conn.execute( + "INSERT INTO chats (id, title, created_at) VALUES (%s, %s, clock_timestamp())", + (chat_id, title)) + with conn.cursor() as cur: + cur.executemany( + "INSERT INTO chat_members (chat_id, user_id, position) VALUES (%s, %s, %s)", + [(chat_id, m, i) for i, m in enumerate(member_ids)]) + row = conn.execute("SELECT " + CHAT_COLUMNS + " FROM chats c WHERE c.id = %s", (chat_id,)).fetchone() + return _chat(row) + + def get_chat_for(self, user_id, chat_id): + """Чат, если пользователь — участник; иначе None (чужой и несуществующий неразличимы).""" + with self.pool.connection() as conn: + row = conn.execute( + "SELECT " + CHAT_COLUMNS + """ FROM chats c + WHERE c.id = %s AND EXISTS ( + SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = %s)""", + (chat_id, user_id)).fetchone() + return _chat(row) if row else None + + def list_chats(self, user_id, after, limit): + params = [user_id] + where = "" + if after: + where = "AND (c.created_at, c.id) > (%s, %s::uuid)" + params += [from_micros(after[0]), after[1]] + params.append(limit + 1) # +1 запись: узнаём, есть ли следующая страница + with self.pool.connection() as conn: + rows = conn.execute( + "SELECT " + CHAT_COLUMNS + """ FROM chats c + JOIN chat_members me ON me.chat_id = c.id AND me.user_id = %s + WHERE true """ + where + " ORDER BY c.created_at, c.id LIMIT %s", params).fetchall() + return self._page(rows, limit, _chat) + + # --- сообщения --- + def add_message(self, user_id, chat_id, text, idem_key, request_hash, idem_ttl_seconds): + """Идемпотентная отправка. Возвращает (message, replayed) или None, если чата нет/он чужой. + + Всё в ОДНОЙ транзакции: проверка доступа, поиск ключа, вставка сообщения и запись + ключа. Либо фиксируется и сообщение, и ключ, либо ничего (транзиентная ошибка + не запоминается как результат — клиент повторит с тем же ключом). + Конкурентные запросы с одним ключом через разные реплики сериализуются + блокировкой строки чата (FOR UPDATE), второй после COMMIT первого видит ключ. + PK таблицы ключей — страховка: даже без блокировки дубль не зафиксируется. + """ + with self.pool.connection() as conn: + # FOR UPDATE по строке чата: вставки в один чат идут по очереди, поэтому + # created_at растёт в порядке фиксации и keyset-курсор не пропускает записи. + allowed = conn.execute( + """SELECT 1 FROM chats c WHERE c.id = %s AND EXISTS ( + SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = %s) + FOR UPDATE OF c""", (chat_id, user_id)).fetchone() + if allowed is None: + return None + existing = conn.execute( + """SELECT k.request_hash, k.expires_at > now() AS alive, + m.id, m.chat_id, m.sender_id, m.text, m.created_at + FROM idempotency_keys k JOIN messages m ON m.id = k.message_id + WHERE k.user_id = %s AND k.chat_id = %s AND k.idem_key = %s""", + (user_id, chat_id, idem_key)).fetchone() + if existing is not None: + if existing["alive"]: + if bytes(existing["request_hash"]) != request_hash: + raise Conflict() + return _message(existing), True + # Ключ старше TTL (24 ч) — освобождаем его и обрабатываем как новый. + conn.execute( + "DELETE FROM idempotency_keys WHERE user_id = %s AND chat_id = %s AND idem_key = %s", + (user_id, chat_id, idem_key)) + row = conn.execute( + """INSERT INTO messages (id, chat_id, sender_id, text, created_at) + VALUES (%s, %s, %s, %s, clock_timestamp()) + RETURNING id, chat_id, sender_id, text, created_at""", + (uuid.uuid4(), chat_id, user_id, text)).fetchone() + conn.execute( + """INSERT INTO idempotency_keys (user_id, chat_id, idem_key, request_hash, message_id, expires_at) + VALUES (%s, %s, %s, %s, %s, now() + make_interval(secs => %s))""", + (user_id, chat_id, idem_key, request_hash, row["id"], idem_ttl_seconds)) + return _message(row), False + + def list_messages(self, chat_id, after, limit): + params = [chat_id] + where = "" + if after: + where = "AND (created_at, id) > (%s, %s::uuid)" + params += [from_micros(after[0]), after[1]] + params.append(limit + 1) + with self.pool.connection() as conn: + rows = conn.execute( + "SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = %s " + + where + " ORDER BY created_at, id LIMIT %s", params).fetchall() + return self._page(rows, limit, _message) + + @staticmethod + def _page(rows, limit, convert): + has_more = len(rows) > limit + rows = rows[:limit] + last = (to_micros(rows[-1]["created_at"]), str(rows[-1]["id"])) if rows and has_more else None + return [convert(r) for r in rows], last diff --git a/student-tests/cursor_validation.py b/student-tests/cursor_validation.py new file mode 100644 index 00000000..25a9801f --- /dev/null +++ b/student-tests/cursor_validation.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Проверка диапазона дат cursor: некорректная дата должна давать 400, а не 500.""" +import base64 +import json +import sys +import uuid +from pathlib import Path +from urllib.parse import quote + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) +from client import Client, arguments, run + + +def main(): + args = arguments(__doc__) + client = Client(args.base_url, ca_file=args.ca_file) + alice, _bob, _eve, chat = client.bootstrap() + checks = 0 + for kind, scope, path in ( + ("messages", chat["id"], "/api/v1/chats/" + chat["id"] + "/messages"), + ("chats", alice["id"], "/api/v1/chats"), + ): + for timestamp, expected in ((-10**17, 400), (-62135596800000001, 400), (0, 200)): + payload = {"k": kind, "s": scope, "t": timestamp, "i": str(uuid.uuid4())} + cursor = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=") + client.call("GET", path + "?cursor=" + quote(cursor, safe=""), expected, actor=alice) + checks += 1 + print("PASS: %d cursor date boundary checks; invalid dates return 400." % checks) + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/failover_bench.py b/student-tests/failover_bench.py new file mode 100644 index 00000000..87ffd2a4 --- /dev/null +++ b/student-tests/failover_bench.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +"""Отказ/замена API-реплики ПОД НАГРУЗКОЙ: RPS, ошибки, время обнаружения и восстановления (lab3, уровень 4). + +Что делает: + * CONCURRENCY потоков в closed-loop шлют смесь запросов через LB: POST сообщения + (с Idempotency-Key) и GET истории (limit=20) в пропорции 1:1; + * после неуспешного/неопределённого POST поток повторяет ТОТ ЖЕ ключ и тело (как + требует контракт), поэтому подтверждённых дублей быть не должно; + * на секунде --action-at запускается --action (например, docker stop/kill контейнера + или scripts/rolling-update.sh), его stdout/stderr пишутся в отдельный лог; + * параллельно каждые 200 мс опрашивается CSV статистики HAProxy: фиксируются моменты + UP -> DOWN / DOWN -> UP серверов backend (время обнаружения отказа LB); + * в конце читается вся история чата (тем же токеном) и проверяется: все подтверждённые + сообщения на месте, дублей нет. + +Метрики (все времена — от старта action): + errors_total / error_rate — неуспешные попытки (HTTP != ожидаемого, timeout, разрыв); + error_window_s — от первой до последней ошибки после старта action; + recovery_s — конец окна ошибок (дальше все запросы успешны), 0 если ошибок нет; + post_action_ok_rps/capacity_ratio — успешный RPS после действия и его доля от базового; + lb_down_detected_s — когда HAProxy пометил сервер DOWN; + target_last_seen_s — последний ответ от остановленной реплики. + +Ограничения: closed-loop генератор (coordinated omission), клиент на том же хосте, что и +стенд; цифры RPS сравнимы только между прогонами этого же скрипта на этом же ноутбуке. +""" +import argparse +import csv +import io +import json +import shlex +import subprocess +import sys +import threading +import time +import urllib.error +import urllib.request +import uuid +from collections import Counter, defaultdict +from pathlib import Path +from urllib.parse import quote + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) +from client import Client # noqa: E402 + +TIMEOUT = 2.0 + + +def percentile(values, p): + if not values: + return None + s = sorted(values) + return round(s[min(len(s) - 1, int(round(p / 100 * (len(s) - 1))))] * 1000, 1) + + +class Bench: + def __init__(self, a): + self.a = a + self.base = a.base_url.rstrip("/") + self.lock = threading.Lock() + self.t0 = None + self.stop = threading.Event() + self.per_sec = defaultdict(lambda: {"ok": 0, "err": 0, "inst": Counter(), "ver": Counter()}) + self.errors = [] # (t, kind) + self.lat = [] # успешные задержки, с + self.confirmed = {} # message id -> text + self.retried_posts = 0 + self.lb_events = [] + self.inst_last_seen = {} + + def now(self): + return time.monotonic() - self.t0 + + def record(self, ok, dt, inst=None, ver=None, kind=None): + t = self.now() + with self.lock: + b = self.per_sec[int(t)] + if ok: + b["ok"] += 1 + self.lat.append(dt) + if inst: + b["inst"][inst] += 1 + self.inst_last_seen[inst] = t + if ver: + b["ver"][ver] += 1 + else: + b["err"] += 1 + self.errors.append((round(t, 3), kind)) + + def request(self, method, path, body=None, headers=None, expected=200): + h = {"Authorization": "Bearer " + self.token} + h.update(headers or {}) + data = None + if body is not None: + data = json.dumps(body).encode() + h["Content-Type"] = "application/json" + req = urllib.request.Request(self.base + path, data=data, method=method, headers=h) + start = time.monotonic() + try: + with urllib.request.urlopen(req, timeout=TIMEOUT) as r: + payload = json.loads(r.read()) + ok = r.status == expected + self.record(ok, time.monotonic() - start, r.headers.get("X-Instance-Id"), + r.headers.get("X-App-Version"), None if ok else "http_%d" % r.status) + return payload if ok else None + except urllib.error.HTTPError as e: + self.record(False, 0, kind="http_%d" % e.code) + except Exception as e: # noqa: BLE001 + self.record(False, 0, kind=type(e).__name__) + return None + + def worker(self, n): + chat_path = "/api/v1/chats/" + self.chat["id"] + "/messages" + key = text = None + i = 0 + while not self.stop.is_set(): + i += 1 + if i % 2: + if key is None: # новый логический запрос; после ошибки ключ НЕ меняется + key = "bench-%d-%s" % (n, uuid.uuid4().hex) + text = "Нагрузка " + key + else: + with self.lock: + self.retried_posts += 1 + msg = self.request("POST", chat_path, {"text": text}, {"Idempotency-Key": key}, 201) + if msg is not None: + with self.lock: + self.confirmed[msg["id"]] = msg["text"] + key = None + else: + self.request("GET", chat_path + "?limit=20") + + def poll_lb(self): + prev = {} + while not self.stop.is_set(): + try: + with urllib.request.urlopen(self.a.stats_url, timeout=1) as r: + rows = list(csv.reader(io.StringIO(r.read().decode().lstrip("# ")))) + head = rows[0] + ix = {k: head.index(k) for k in ("pxname", "svname", "status", "addr")} + for row in rows[1:]: + if len(row) <= ix["addr"] or row[ix["pxname"]] != "be_api" or row[ix["svname"]] == "BACKEND": + continue + sv, st, addr = row[ix["svname"]], row[ix["status"]].split(" ")[0], row[ix["addr"]] + if sv in prev and prev[sv] != (st, addr): + self.lb_events.append({"t": round(self.now(), 2), "server": sv, "addr": addr, + "from": prev[sv][0], "to": st}) + prev[sv] = (st, addr) + except Exception: # noqa: BLE001 — статистика вспомогательная + pass + time.sleep(0.2) + + def history(self): + c, path, items = self.client, "/api/v1/chats/" + self.chat["id"] + "/messages?limit=100", [] + while True: + page = c.call("GET", path, actor=self.alice, schema="MessagePage")["json"] + items += page["items"] + if page["next_cursor"] is None: + return items + path = "/api/v1/chats/" + self.chat["id"] + "/messages?limit=100&cursor=" + quote(page["next_cursor"], safe="") + + def run(self): + a = self.a + self.client = Client(self.base, timeout=10) + self.alice, _bob, _eve, self.chat = self.client.bootstrap() + self.token = self.alice["token"] + self.t0 = time.monotonic() + threads = [threading.Thread(target=self.worker, args=(n,), daemon=True) for n in range(a.concurrency)] + threads.append(threading.Thread(target=self.poll_lb, daemon=True)) + for t in threads: + t.start() + time.sleep(a.action_at) + action = {"command": a.action, "started_s": round(self.now(), 3)} + log = open(a.action_log, "w", encoding="utf-8") if a.action_log else subprocess.DEVNULL + proc = subprocess.Popen(shlex.split(a.action), stdout=log, stderr=subprocess.STDOUT) + rc = proc.wait(timeout=a.duration) + action.update(finished_s=round(self.now(), 3), exit_code=rc) + remaining = a.duration - self.now() + if remaining > 0: + time.sleep(remaining) + self.stop.set() + for t in threads: + t.join(timeout=TIMEOUT + 1) + return self.summarize(action) + + def summarize(self, action): + a, t_act = self.a, action["started_s"] + secs = sorted(self.per_sec) + base = [self.per_sec[s]["ok"] for s in secs if 1 <= s < int(t_act)] # 1-я секунда — прогрев + baseline = sum(base) / len(base) if base else 0 + after = [(round(t - t_act, 3), k) for t, k in self.errors if t >= t_act] + # Восстановление = конец окна ошибок: после этого момента все запросы до конца + # прогона успешны. Если ошибок не было — 0. Мощность после отказа меряем отдельно: + # при меньшем числе реплик RPS законно ниже (лимиты CPU на реплику). + recovery = after[-1][0] if after else 0.0 + tail_secs = [s for s in secs if int(action.get("finished_s", t_act)) + 2 <= s < a.duration - 1] + post = [self.per_sec[s]["ok"] for s in tail_secs] + post_rps = sum(post) / len(post) if post else 0 + writes_after = any(self.per_sec[s]["ok"] > 0 for s in tail_secs) + target = a.target_instance + hist = self.history() + ids = [m["id"] for m in hist] + texts = [m["text"] for m in hist] + lost = [i for i in self.confirmed if i not in set(ids)] + timeline = [{"t": s, "ok": self.per_sec[s]["ok"], "err": self.per_sec[s]["err"], + "instances": dict(self.per_sec[s]["inst"]), "versions": dict(self.per_sec[s]["ver"])} + for s in secs] + total_ok = sum(b["ok"] for b in self.per_sec.values()) + total_err = len(self.errors) + summary = { + "label": a.label, + "concurrency": a.concurrency, "duration_s": a.duration, "request_timeout_s": TIMEOUT, + "action": action, + "baseline_ok_rps": round(baseline, 1), + "overall_ok_rps": round(total_ok / a.duration, 1), + "requests_ok": total_ok, "errors_total": total_err, + "error_rate": round(total_err / max(1, total_ok + total_err), 5), + "errors_by_kind": dict(Counter(k for _, k in self.errors)), + "error_window_s": [after[0][0], after[-1][0]] if after else None, + "recovery_s": recovery, + "post_action_ok_rps": round(post_rps, 1), + "capacity_ratio": round(post_rps / baseline, 2) if baseline else None, + "latency_ok_ms": {"p50": percentile(self.lat, 50), "p95": percentile(self.lat, 95), + "p99": percentile(self.lat, 99)}, + "target_instance": target, + "target_last_seen_s": (round(self.inst_last_seen[target] - t_act, 3) + if target in self.inst_last_seen else None), + "lb_events": [dict(e, t=round(e["t"] - t_act, 2)) for e in self.lb_events], + "posts_retried_same_key": self.retried_posts, + "confirmed_messages": len(self.confirmed), + "history_messages": len(hist), "lost_confirmed": len(lost), + "duplicate_ids": len(ids) - len(set(ids)), "duplicate_texts": len(texts) - len(set(texts)), + "timeline": timeline, + } + summary["pass"] = (summary["lost_confirmed"] == 0 and summary["duplicate_ids"] == 0 + and summary["duplicate_texts"] == 0 and action["exit_code"] == 0 + and writes_after and recovery <= 10) + return summary + + +def main(): + p = argparse.ArgumentParser(description="Отказ/замена реплики под нагрузкой") + p.add_argument("--base-url", default="http://localhost:8080") + p.add_argument("--stats-url", default="http://127.0.0.1:8404/stats;csv") + p.add_argument("--concurrency", type=int, default=8) + p.add_argument("--duration", type=float, default=40) + p.add_argument("--action-at", type=float, default=10) + p.add_argument("--action", required=True, help="команда без shell, например 'docker stop -t 20 '") + p.add_argument("--action-log") + p.add_argument("--target-instance", help="X-Instance-Id реплики, которую останавливает action") + p.add_argument("--label", default="") + p.add_argument("--output") + a = p.parse_args() + s = Bench(a).run() + brief = {k: v for k, v in s.items() if k != "timeline"} + print(json.dumps(brief, ensure_ascii=False, indent=2)) + if a.output: + Path(a.output).write_text(json.dumps(s, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print("PASS" if s["pass"] else "FAIL") + return 0 if s["pass"] else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/student-tests/idempotency_concurrency.py b/student-tests/idempotency_concurrency.py new file mode 100644 index 00000000..882d2333 --- /dev/null +++ b/student-tests/idempotency_concurrency.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Конкурентная идемпотентность через разные реплики (lab3, уровни 3–4). + +Сценарий на каждый раунд: + A) PARALLEL запросов одновременно отправляют ОДИН И ТОТ ЖЕ ключ и одинаковое тело. + Ожидаем: все 201, у всех один и тот же Message.id, ответы пришли от >=2 реплик, + в истории ровно одно сообщение с этим текстом. + B) Тот же ключ, но половина запросов с другим телом. Ожидаем: побеждает ровно одно + тело; запросы с ним — 201 и один id, запросы с другим телом — 409; дублей нет. + +Каждый запрос — отдельное TCP-соединение, поэтому HAProxy (roundrobin) раскладывает их +по репликам. Токены только в памяти; синтетические пользователи создаются заново. + + python3 student-tests/idempotency_concurrency.py --rounds 20 --parallel 16 +""" +import argparse +import json +import sys +import threading +import urllib.error +import urllib.request +import uuid +from collections import Counter +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) +from client import Client # noqa: E402 (публичный клиент тестов: bootstrap пользователей/чата) + + +def post(base, token, chat_id, key, text, barrier, out, idx): + data = json.dumps({"text": text}).encode() + req = urllib.request.Request( + base + "/api/v1/chats/" + chat_id + "/messages", data=data, method="POST", + headers={"Authorization": "Bearer " + token, "Content-Type": "application/json", + "Idempotency-Key": key, "Connection": "close"}) + barrier.wait() + try: + with urllib.request.urlopen(req, timeout=10) as r: + out[idx] = (r.status, json.loads(r.read()), r.headers.get("X-Instance-Id"), text) + except urllib.error.HTTPError as e: + out[idx] = (e.code, None, e.headers.get("X-Instance-Id"), text) + except Exception as e: # noqa: BLE001 — считаем любую сетевую ошибку + out[idx] = (0, repr(e), None, text) + + +def burst(base, token, chat_id, key, texts): + barrier = threading.Barrier(len(texts)) + out = [None] * len(texts) + threads = [threading.Thread(target=post, args=(base, token, chat_id, key, t, barrier, out, i)) + for i, t in enumerate(texts)] + for t in threads: + t.start() + for t in threads: + t.join() + return out + + +def history_texts(c, actor, chat): + from urllib.parse import quote + texts, path = [], "/api/v1/chats/" + chat["id"] + "/messages?limit=100" + while True: + page = c.call("GET", path, actor=actor, schema="MessagePage")["json"] + texts += [m["text"] for m in page["items"]] + if page["next_cursor"] is None: + return texts + path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100&cursor=" + quote(page["next_cursor"], safe="") + + +def main(): + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument("--base-url", default="http://localhost:8080") + p.add_argument("--rounds", type=int, default=20) + p.add_argument("--parallel", type=int, default=16) + p.add_argument("--output") + a = p.parse_args() + base = a.base_url.rstrip("/") + c = Client(base) + alice, _bob, _eve, chat = c.bootstrap() + token = alice["token"] + problems, instances = [], Counter() + stats = {"same_body": Counter(), "conflicting_body": Counter()} + + for rnd in range(a.rounds): + # A) одинаковое тело + key, text = "same-" + uuid.uuid4().hex, "Конкурентный повтор " + uuid.uuid4().hex + res = burst(base, token, chat["id"], key, [text] * a.parallel) + stats["same_body"].update(str(r[0]) for r in res) + ids = {r[1]["id"] for r in res if r[0] == 201} + seen = {r[2] for r in res if r[2]} + instances.update(r[2] for r in res if r[2]) + if any(r[0] != 201 for r in res) or len(ids) != 1: + problems.append("round %d same-body: statuses=%s ids=%d" % (rnd, Counter(r[0] for r in res), len(ids))) + if len(seen) < 2: + problems.append("round %d: only %d replica(s) answered" % (rnd, len(seen))) + + # B) тот же ключ, два разных тела вперемешку + key = "mixed-" + uuid.uuid4().hex + t1, t2 = "Тело A " + key, "Тело B " + key + res = burst(base, token, chat["id"], key, [t1, t2] * (a.parallel // 2)) + stats["conflicting_body"].update(str(r[0]) for r in res) + winners = {r[3] for r in res if r[0] == 201} + ids = {r[1]["id"] for r in res if r[0] == 201} + bad = [r[0] for r in res if r[0] not in (201, 409)] + losers_ok = all(r[0] == 409 for r in res if r[3] not in winners) + if len(winners) != 1 or len(ids) != 1 or bad or not losers_ok: + problems.append("round %d mixed-body: winners=%d ids=%d bad=%s" % (rnd, len(winners), len(ids), bad)) + + texts = history_texts(c, alice, chat) + dupes = [t for t, n in Counter(texts).items() if n > 1] + if dupes: + problems.append("duplicated messages in history: %d" % len(dupes)) + summary = { + "rounds": a.rounds, "parallel_per_burst": a.parallel, + "requests_total": a.rounds * a.parallel * 2, + "status_counts": {k: dict(v) for k, v in stats.items()}, + "replicas_answered": len(instances), "requests_per_replica": sorted(instances.values()), + "messages_in_history": len(texts), "expected_messages": a.rounds * 2, + "duplicates": len(dupes), "problems": problems, + } + if len(texts) != a.rounds * 2: + problems.append("history has %d messages, expected %d" % (len(texts), a.rounds * 2)) + print(json.dumps(summary, ensure_ascii=False, indent=2)) + if a.output: + Path(a.output).write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print("PASS" if not problems else "FAIL") + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/student-tests/login_flood.py b/student-tests/login_flood.py new file mode 100644 index 00000000..eae87bef --- /dev/null +++ b/student-tests/login_flood.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +"""Шторм входов: много параллельных POST /auth/sessions с неверным паролем через LB. + +Зачем: scrypt (N=2^15, r=8) берёт ~32 MiB на одну проверку пароля, лимит API-реплики +256 MiB. Без ограничения параллельных проверок несколько одновременных входов +приводят к OOM-kill реплики. Скрипт показывает, переживают ли реплики такой шторм. + +Что измеряется: + * статусы ответов шторма (ожидаем 401 и, при перегрузке, 503 с Retry-After) и + ответы не в JSON-формате ошибки контракта (например HTML-страницы HAProxy); + * «жертва»: параллельный поток раз в 50 мс читает /users/me действующим токеном — + обычные пользователи не должны получать ошибки из-за шторма входов; + * состояние API-контейнеров до/после: OOMKilled, RestartCount, StartedAt. + +Пример: python3 student-tests/login_flood.py --parallel 24 --duration 20 --output evidence/login-flood.json +""" +import argparse +import base64 +import json +import subprocess +import threading +import time +import urllib.error +import urllib.request +import uuid +from collections import Counter + +TIMEOUT = 10.0 + + +def http(base, method, path, headers=None, body=None): + data = json.dumps(body).encode() if body is not None else None + h = dict(headers or {}) + if data is not None: + h["Content-Type"] = "application/json" + req = urllib.request.Request(base + path, data=data, method=method, headers=h) + try: + with urllib.request.urlopen(req, timeout=TIMEOUT) as r: + return r.status, r.headers, r.read() + except urllib.error.HTTPError as e: + return e.code, e.headers, e.read() + + +def is_contract_error(headers, raw): + if not (headers.get("Content-Type") or "").startswith("application/json"): + return False + try: + err = json.loads(raw)["error"] + return bool(err["code"] and err["message"] and err["request_id"]) + except (ValueError, KeyError, TypeError): + return False + + +def api_containers(): + ids = subprocess.run(["docker", "compose", "ps", "-a", "-q", "api"], capture_output=True, + text=True, check=True).stdout.split() + out = {} + for cid in ids: + info = json.loads(subprocess.run(["docker", "inspect", cid], capture_output=True, text=True, + check=True).stdout)[0] + out[info["Name"].lstrip("/")] = { + "status": info["State"]["Status"], "oom_killed": info["State"]["OOMKilled"], + "restart_count": info["RestartCount"], "started_at": info["State"]["StartedAt"]} + return out + + +def oom_events(since): + """Имена контейнеров, получивших OOM с момента since (unix time): флаг OOMKilled + сбрасывается после рестарта по restart-policy, поэтому смотрим события Docker.""" + out = subprocess.run(["docker", "events", "--since", str(int(since)), "--until", str(int(time.time()) + 1), + "--filter", "type=container", "--filter", "event=oom", + "--format", "{{.Actor.Attributes.name}}"], capture_output=True, text=True).stdout + return sorted(Counter(out.split()).items()) + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--base-url", default="http://localhost:8080") + p.add_argument("--parallel", type=int, default=24) + p.add_argument("--duration", type=float, default=20) + p.add_argument("--output") + a = p.parse_args() + base = a.base_url.rstrip("/") + + username = "flood_" + uuid.uuid4().hex[:10] + password = "correct-horse-" + uuid.uuid4().hex[:8] + st, _, _ = http(base, "POST", "/api/v1/users", + body={"username": username, "display_name": "Flood", "password": password}) + assert st == 201, st + basic = base64.b64encode(("%s:%s" % (username, password)).encode()).decode() + st, _, raw = http(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic}) + assert st == 201, st + token = json.loads(raw)["token"] + bad = base64.b64encode(("%s:wrong-password-123" % username).encode()).decode() + + before = api_containers() + wall0 = time.time() + stop = threading.Event() + lock = threading.Lock() + flood, victim = Counter(), Counter() + non_json_errors = Counter() + retry_after_503 = [0, 0] # [503 всего, из них с Retry-After] + + def record(counter, status, headers, raw): + with lock: + counter[str(status)] += 1 + if status >= 400 and not is_contract_error(headers, raw): + non_json_errors[str(status)] += 1 + if status == 503 and counter is flood: + retry_after_503[0] += 1 + retry_after_503[1] += bool(headers.get("Retry-After")) + + def flooder(): + while not stop.is_set(): + try: + record(flood, *http(base, "POST", "/api/v1/auth/sessions", + headers={"Authorization": "Basic " + bad})) + except Exception as exc: # обрыв соединения, timeout + with lock: + flood["exc:" + type(exc).__name__] += 1 + + def prober(): + while not stop.is_set(): + try: + record(victim, *http(base, "GET", "/api/v1/users/me", + headers={"Authorization": "Bearer " + token})) + except Exception as exc: + with lock: + victim["exc:" + type(exc).__name__] += 1 + time.sleep(0.05) + + threads = [threading.Thread(target=flooder, daemon=True) for _ in range(a.parallel)] + threads.append(threading.Thread(target=prober, daemon=True)) + t0 = time.monotonic() + for t in threads: + t.start() + time.sleep(a.duration) + stop.set() + for t in threads: + t.join(TIMEOUT + 1) + elapsed = time.monotonic() - t0 + time.sleep(3) # дать restart-policy отработать, если реплика упала + after = api_containers() + + restarted = [n for n in after if n in before and ( + after[n]["restart_count"] != before[n]["restart_count"] + or after[n]["started_at"] != before[n]["started_at"])] + victim_ok = victim.get("200", 0) + victim_total = sum(victim.values()) + summary = { + "parallel": a.parallel, "duration_s": round(elapsed, 1), + "flood_statuses": dict(flood), "flood_rps": round(sum(flood.values()) / elapsed, 1), + "flood_503_with_retry_after": "%d/%d" % (retry_after_503[1], retry_after_503[0]), + "victim_statuses": dict(victim), + "victim_error_rate": round(1 - victim_ok / victim_total, 4) if victim_total else None, + "non_contract_error_bodies": dict(non_json_errors), + "containers_before": before, "containers_after": after, + "oom_events": dict(oom_events(wall0)), + "restarted": restarted, + } + summary["pass"] = (not summary["oom_events"] and not restarted and victim_total > 0 + and victim_ok == victim_total and not non_json_errors) + text = json.dumps(summary, ensure_ascii=False, indent=2) + print(text) + if a.output: + with open(a.output, "w", encoding="utf-8") as f: + f.write(text + "\n") + return 0 if summary["pass"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) -- 2.54.0 From d16551de52f970d1e11f0ef2400fc75e5878805c Mon Sep 17 00:00:00 2001 From: yura Date: Thu, 29 Oct 2026 16:30:35 +0300 Subject: [PATCH 2/2] =?UTF-8?q?=D0=A3=D0=BA=D0=B0=D0=B7=D0=B0=D1=82=D1=8C?= =?UTF-8?q?=20=D1=81=D1=81=D1=8B=D0=BB=D0=BA=D1=83=20=D0=BD=D0=B0=20=D1=81?= =?UTF-8?q?=D0=B4=D0=B0=D1=87=D1=83=20=D0=BB=D0=B0=D0=B1=D0=BE=D1=80=D0=B0?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=BD=D0=BE=D0=B9=20=D0=BD=D0=B0=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- REPORT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/REPORT.md b/REPORT.md index 395f94ec..ccb9431c 100644 --- a/REPORT.md +++ b/REPORT.md @@ -2,7 +2,7 @@ - Автор, группа: Лазарев Юрий Сергеевич, БПИ2303 - Целевая оценка; выбранный трек 5, если нужен: **3**, трек 5 не заявлен -- Ветка решения: `codex/lab3-bpi2303-lazarev`; fork: [zemiles/mtusi2026lab3](https://gitea.privcloud.tech/zemiles/mtusi2026lab3). +- Commit/PR: [PR #66 — ЛР 3 — БПИ2303 — Лазарев — на 3](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab3/pulls/66); реализация `094039b`, ветка `codex/lab3-bpi2303-lazarev`, fork [zemiles/mtusi2026lab3](https://gitea.privcloud.tech/zemiles/mtusi2026lab3). - Использованные источники, библиотеки и помощь ИИ: Python 3.12 (стандартная библиотека: `http.server`, `hashlib`, `secrets`, `threading`), `psycopg[binary]==3.2.3`, `psycopg-pool==3.2.4`; образы `python:3.12.7-slim`, `postgres:16.4-alpine` (`sha256:5660c2cb…e64c`), `haproxy:3.0.5-alpine` (`sha256:43a2591a…e949`). Документация: Docker Compose (services, secrets, deploy.resources), HAProxy 3.0 Configuration Manual (`server-template`, `resolvers`, `http-check`, `retry-on`), PostgreSQL (row locks, advisory locks). Код перенесён из моей lab2 и доработан с помощью ИИ-ассистента (Claude); проверен и запущен автором. Дополнительная проверка и исправления перед публикацией 29.10.2026 выполнены с помощью ChatGPT/Codex. ## Запуск из чистого clone -- 2.54.0