Лабораторная работа 6

This commit is contained in:
2026-11-13 01:27:57 +03:00
parent 470d9d6f1e
commit 2dbdcf898c
218 changed files with 22057 additions and 37 deletions
+257
View File
@@ -0,0 +1,257 @@
# Отчёт — лабораторная 5
- Автор, группа: Попов Константин Дмитриевич, группа БВТ2303
- Целевая оценка: **4**; трек 5 не заявляется
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: Python 3.12, FastAPI 0.115.6, Uvicorn 0.34.0, Pydantic 2.10.4, psycopg 3.2.3 + psycopg-pool 3.2.4, **redis-py 5.2.1 (Redis Streams)**, argon2-cffi 23.1.0, boto3 1.35.99, **Pillow 11.1.0 (JPEG/WebP, ImageOps.exif_transpose)**; PostgreSQL 16.4, Redis 7.4.1 (кэш сессий **и отдельный брокер**), HAProxy 2.8.30, SeaweedFS 4.50. Документация: Redis Streams (XADD, XREADGROUP, XACK, XAUTOCLAIM, XPENDING, XTRIM MINID), Redis persistence (AOF, `appendfsync always`), RabbitMQ reliability/confirms (различие publisher confirm и consumer ack), шаблон transactional outbox, AWS Architecture Blog «Exponential Backoff And Jitter», Pillow (draft, reduce/reducing_gap, сохранение JPEG/WebP), Python `multiprocessing` (forkserver) и `resource` (RLIMIT_AS/RLIMIT_CPU). Помощь ИИ (Claude) — при проектировании outbox/аренд/fencing, написании worker, тестов отказов и отчёта.
Минимум lab4 перенесён целиком (балансировщик, ≥2 реплики, сессии, идемпотентность, приватный S3, проверки изображений, сборщик БД↔S3). Единственное объявленное изменение API: `POST /chats/{id}/attachments` отвечает **202 queued** вместо 201 ready.
## Запуск из чистого clone
**Версии.** API и worker — один образ из `Dockerfile` (`python:3.12.7-slim-bookworm`); `postgres:16.4-alpine`; `redis:7.4.1-alpine` (два сервиса: `redis` — кэш сессий, `broker` — очередь); `haproxy:2.8.30-alpine`; `chrislusf/seaweedfs:4.50`. Нужны Docker Engine/Desktop с Compose v2 и Python 3.9+ на хосте (`scripts/ops.py` и тесты — только стандартная библиотека). Оркестрация — **Compose** (Swarm не используется).
```sh
$env:PYTHONUTF8 = "1"
# 1. Секреты (один раз; secrets/ в .gitignore, значения не печатаются) и .env
python scripts/init_secrets.py # lab5 добавляет secrets/broker_password и secrets/broker_url
cp .env.example .env # Windows: copy .env.example .env
# 2. Сборка и запуск:
# postgres, redis, broker -> migrate (001..005); s3 -> s3-init (bucket) -> api x2 + worker -> lb
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build
# 3. Готовность: 2 реплики healthy и UP в HAProxy, S3 реально пишет/читает, worker healthy
python scripts/ops.py wait
python scripts/ops.py wait-s3
python scripts/ops.py worker-start # идемпотентно: дождаться healthy worker
python scripts/ops.py ps
```
Всё то же одной командой: `make up` (= init_secrets + config + up --build + ожидания). Прогрев после первой сборки ~30–40 с.
```sh
# Публичные проверки
make check # офлайн, без сервера
make test # smoke lab5: 202 -> ready -> thumbnail 256x160
python tests/resilience.py --mode persistence --action-script scripts/restart.sh # Windows: scripts\restart.cmd
python tests/resilience.py --mode failover --action-script scripts/stop-one.sh # Windows: scripts\stop-one.cmd
python scripts/ops.py restore
# Собственные проверки lab5
make test-pipeline # варианты по фактическим байтам (7 тестов)
make test-worker-outage # сценарий защиты уровня 3 (останавливает/запускает worker, рестарт API и broker)
make test-pipeline-faults # 10 внедрённых отказов уровня 4 (~2–3 мин; worker временно пересоздаётся)
python student-tests/run_all.py --base-url http://localhost:8080 # lab2-4 (+ test_pipeline.py)
# Всё сразу с записью в evidence/ (~20 мин; только на учебном стенде)
python scripts/collect_evidence.py # или --quick (~10 мин)
```
**Операторские команды очереди** (выполняются в one-off контейнере образа worker, секреты не печатаются):
```sh
python scripts/ops.py jobs stats # задания по статусам, outbox, DLQ, длина/pending/lag потока
python scripts/ops.py jobs failed # реестр dead_letters
python scripts/ops.py jobs show <attachment_id> # задание + журнал событий (job_events)
python scripts/ops.py jobs replay <attachment_id> # явный replay failed (make replay ID=...)
python scripts/ops.py jobs replay --all-failed --error-code retry_exhausted --dry-run
python scripts/ops.py worker-stop | worker-start | worker-kill | api-restart | broker-restart
python scripts/ops.py reconcile [--apply] # сверка БД <-> S3 (staging/, final/, originals/)
```
**Остановка.** Безопасная (volumes `pgdata`, `s3data`, `brokerdata` сохраняются): `make down` или `docker compose --env-file .env --profile ttl --profile faults down`. **Намеренное удаление всех учебных данных:** `docker compose --env-file .env --profile ttl --profile faults down -v` (удаляет БД, бакет и очередь безвозвратно).
## Архитектура и решения
```
клиент ──HTTP──> HAProxy ──> API x2 ──[1] INSERT pending ─────────────────────────> PostgreSQL
├──[2] PUT staging/<random> (Content-MD5) ───────> S3 (SeaweedFS)
├──[3] COMMIT: queued + attachment_jobs + job_outbox ──> PostgreSQL
│ └─> 202 queued
└──[4] после ответа: relay XADD (fsync) ─────────> broker (Redis Streams)
│ XREADGROUP (prefetch 1)
worker (WORKER_CONCURRENCY consumer'ов) <───────────────────────────────────────────────┘
claim: аренда в PostgreSQL (lease_token, lease_until)
читает staging (ключ из БД) -> SHA-256 -> PUT final/<id>/original
подпроцесс (RLIMIT_AS, timeout): thumbnail/crop/optimized -> PUT final/<id>/p1/<variant>
COMMIT (fenced по lease_token): attachment_variants + state=ready ──> PostgreSQL
XACK ──> broker; DELETE staging (иначе — сборщик)
sweeper outbox + сборщик просроченных аренд: в каждой реплике API и в worker
```
**Источник истины** — PostgreSQL: состояние вложения, задание, outbox, результаты, журнал. S3 хранит байты (staging/ и final/), брокер — только транспорт уведомлений (может быть пересоздан из outbox/таблицы заданий). Брокер **не** входит в синхронный путь API: при его недоступности upload всё равно отвечает 202, строка ждёт в `job_outbox`; `/health/ready` от брокера не зависит.
### Что сохранено в момент 202
1. Все байты оригинала в приватном S3 `staging/<random>` (PUT с Content-MD5, SHA-256 в метаданных объекта и в БД). Ключ генерирует сервер, filename в ключ не попадает.
2. Метаданные вложения (`state=queued`, size, sha256, размеры, будущий конечный ключ).
3. Намерение обработать: строка `attachment_jobs` (job_id, attempt=1, max_attempts) и строка `job_outbox` с JSON-сообщением **в той же транзакции**.
Сообщение в брокере на момент 202 может ещё не существовать — это нормально: его гарантирует outbox, а не HTTP-запрос. Остановка API сразу после 202 работу не теряет (тест A).
### Состояния и окна отказа
Внутреннее `pending` (приём идёт) наружу не видно; публичные: `queued → processing → ready | failed`.
| Окно отказа | Что произойдёт | Где доказано |
| --- | --- | --- |
| после staging PUT до COMMIT задания | строка pending + staging-объект; клиенту ошибка (не 202). Сборщик через grace удаляет и строку, и объект | lab4 `test_attachment_consistency.py` (crash_after_s3_put теперь между staging и COMMIT) |
| после COMMIT до publish | строка outbox осталась; sweeper любого процесса публикует через `RELAY_FAST_PATH_GRACE_SECONDS` | `test_a` (api-fault-publish, `FAULT_INJECTION=crash_after_commit`) |
| после publish до подтверждения в outbox | XADD выполнен, DELETE строки — нет -> повторная публикация, дубль в брокере -> worker no-op | `test_b` (api-fault-dup, `crash_after_publish`) |
| после записи S3 до COMMIT результата | сообщение в PEL; перезапущенный consumer читает свой PEL, перехватывает свою аренду, перезаписывает **те же** байты, COMMIT | `test_c` (`fault-crash-after-effects`) |
| после COMMIT результата до ack | повторная доставка -> claim видит succeeded -> `redelivery_noop already_succeeded`, ack | `test_d` (`fault-crash-before-ack`) |
| worker завис дольше аренды | сборщик аренд -> attempt+1 через outbox -> другой consumer -> ready; проснувшийся старый результат отсечён fencing'ом (`lease_lost`) | `test_h` (`fault-slow`) |
### Брокер: Redis Streams как durable at-least-once очередь
Выбран Redis Streams (разрешён README): тот же закреплённый образ, что и для кэша, но **отдельный сервис** с другими гарантиями. Кэш сессий — без persistence и с LRU-вытеснением; объединять их нельзя.
- **Durability:** `--appendonly yes --appendfsync always` — Redis отвечает на XADD только после fsync AOF. Успешный XADD — наш **publisher confirm**: сообщение переживает рестарт/падение брокера с volume `brokerdata` (проверено в сценарии `worker_outage`: lag=1 до и после рестарта брокера). `--maxmemory-policy noeviction`: поток никогда не вытесняется; при переполнении XADD упадёт, строка останется в outbox.
- **Доставка at-least-once:** consumer group; XREADGROUP кладёт сообщение в PEL до XACK. **Consumer ack** worker делает только после COMMIT результата (или перехода в retry/failed) — это другая граница, чем confirm при публикации.
- **Упавший consumer:** имя consumer = `<hostname>-<поток>`; после `restart` контейнера hostname тот же, и consumer первым делом читает свой PEL (`XREADGROUP ... 0`). Если контейнер пересоздан, сообщения забирает любой живой consumer через `XAUTOCLAIM` после `JOB_CLAIM_IDLE_SECONDS` (75 с > аренды 60 с).
- **Prefetch/конкуренция:** каждый consumer-поток берёт `COUNT 1`, потоков `WORKER_CONCURRENCY=2`, контейнеров `WORKER_REPLICAS=1` -> одновременно в обработке не больше 2 сообщений.
- **Очистка потока:** `XTRIM MINID` до минимума из (самый старый pending, last-delivered-id+1) — удаляются только доставленные и подтверждённые записи.
- **Содержимое сообщения** — ровно `contracts/jobs.schema.json` (`schema_version, job_id, type, attachment_id, pipeline_version, attempt, created_at`): без байтов, credentials, URL и filename. Worker проверяет схему строго; мусор подтверждается и логируется (`test_j`); сообщение, доставленное больше `JOB_MAX_DELIVERIES` раз, переводит задание в `failed poison_message`.
### Transactional outbox
`job_outbox` пишется в одной транзакции с `attachment_jobs` и `state=queued`. Публикация:
- **быстрый путь** — после отправки 202 (FastAPI background task) API берёт свою строку `FOR UPDATE SKIP LOCKED`, делает XADD, удаляет строку, пишет событие `published`, COMMIT;
- **sweeper** — в каждой реплике API и в worker раз в `RELAY_POLL_INTERVAL_SECONDS` публикует строки с `available_at <= now()`. У свежей строки `available_at = now()+2 c`, чтобы не соревноваться с быстрым путём; у retry — время следующей попытки (так реализован отложенный повтор без delayed-очереди брокера).
`SKIP LOCKED` разносит строки между relay; несколько relay безопасны. Сбой между XADD и COMMIT relay даёт дубль — это и есть at-least-once, дубль гасит идемпотентный worker.
### Worker, идемпотентность и аренды
- **Ключ идемпотентности эффекта** — `(attachment_id, pipeline_version, variant)`: PRIMARY KEY `attachment_variants` + **детерминированные ключи S3** `final/<id>/original`, `final/<id>/p1/{thumbnail.jpg,crop.jpg,optimized.webp}`. Повтор пишет те же байты по тем же ключам (Pillow-вывод детерминирован при одной версии библиотек — проверено в `test_a`/`test_c` сравнением SHA-256 с эталонной загрузкой). `job_id` не меняется при redelivery и retry.
- **Аренда (lease)**: claim атомарно ставит `status=processing, lease_token=<uuid>, lease_owner=<consumer>, lease_until=now()+JOB_TIMEOUT_SECONDS` (`SELECT ... FOR UPDATE`). Захват разрешён только для текущей попытки и если задание queued, или аренда истекла, или аренда принадлежит этому же consumer (его прошлая инкарнация мертва: consumer обрабатывает одно сообщение за раз).
- **Fencing**: публикация результата, retry и failed выполняются с условием `lease_token = <мой> AND status='processing'`. Worker, у которого аренду отобрали, ничего не может изменить (`test_h`, событие `lease_lost`). `ready` никогда не откатывается в processing старым дублем; `attachments.pipeline_version` обновляется только если новая версия ≥ текущей.
- **Зависший vs долгий worker:** аренда (60 с) > максимальной длительности попытки (обработка ≤ 30 с + S3-дедлайны), это проверяется при старте конфигурации. Пока аренда не истекла, второй worker задание не возьмёт (`leased_by_other`, ack дубля). Истекла + `JOB_LEASE_GRACE_SECONDS` -> сборщик аренд переводит задание в queued attempt+1 через outbox. Healthcheck worker'а — heartbeat, который пишется, только пока **все** consumer-потоки проходят цикл.
- **Staging** удаляется worker'ом после COMMIT и XACK; если не удалось — сборщик (проход D) удалит staging у ready-вложений. Staging failed-вложений хранится `STAGING_RETENTION_SECONDS` (24 ч) для replay, затем удаляется (replay после этого отклоняется: нужен повторный upload). Текущую работу (queued/processing) сборщик не трогает.
### Варианты изображений (pipeline_version = 1)
| Вариант | Формат | Правило | Параметры |
| --- | --- | --- | --- |
| thumbnail | JPEG | вписан в 256×256, пропорции, без увеличения, округление вниз (мин. 1 px): 320×200 → 256×160 | quality 85, optimize, baseline, 4:2:0 |
| crop | JPEG | центрированный квадрат min(w,h) → 128×128 (маленькие увеличиваются) | quality 85 |
| optimized | WebP | вписан в 1280×1280 без увеличения | lossy, quality 80, method 4; уменьшение каждого маленького файла не обещается |
Общее: EXIF orientation применяется **до** расчёта размеров (400×100 c orientation=6 → thumbnail 64×256); прозрачность компонуется на белый (масштабирование RGBA в Pillow — с premultiplied alpha); **EXIF и XMP не копируются** (Pillow пишет их только при явной передаче), ICC-профиль сохраняется, чтобы не исказить цвет. Целочисленная арифметика размеров исключает ошибки округления float.
**Ограничения ресурсов worker** (недоверенный файл, даже прошедший проверки API):
| Ресурс | Ограничение | Поведение |
| --- | --- | --- |
| байты | staging-объект > `MAX_UPLOAD_BYTES` не читается; SHA-256 и размер сверяются с БД | failed `invalid_image` / `processing_failed` |
| пиксели | размеры из заголовка до декодирования, > `MAX_IMAGE_PIXELS` | failed `invalid_image` |
| память | обработка в отдельном процессе (forkserver) с `RLIMIT_AS = WORKER_IMAGE_MEMORY_MB` (1024) | MemoryError/смерть процесса → failed `resource_limit` |
| время | процесс убивается через `WORKER_IMAGE_TIMEOUT_SECONDS` (30), `RLIMIT_CPU` — страховка | временная ошибка `processing_timeout`, повтор ≤ JOB_MAX_ATTEMPTS |
JPEG декодируется сразу в уменьшенном масштабе (`draft`), поэтому 40 Мп JPEG — пик 46 MiB; худший случай 40 Мп RGBA PNG — **361 MiB** (было 518 MiB, пока альфа компоновалась до масштабирования; порядок операций изменён). Отсюда лимит контейнера worker 1280 MiB при 2 подпроцессах. Замер: `evidence/local/imaging_memory.txt`; проверка самих лимитов: `python -m src.imaging FILE --memory-mb 200` → `resource_limit`, `--timeout 0.3` → `timeout`.
### Retry, backoff, DLQ, replay
- **Классификация ошибок.** Временные: S3 недоступен/таймаут, таймаут обработки, внедрённый `injected_transient` → retry. Постоянные: битое/неподдерживаемое изображение, превышение пикселей/байт, лимит памяти, нет источника, несовпадение SHA-256 staging → сразу `failed` без повторов (`test_f`). Если недоступна сама БД, сообщение **не** подтверждается и вернётся из PEL — решение о retry без БД принять нельзя.
- **Backoff с jitter** («equal jitter»): `d = min(JOB_RETRY_MAX_SECONDS, JOB_RETRY_BASE_SECONDS·2^(attempt−1))`, задержка равномерно в `[d/2, d]` (нижняя граница гарантирует паузу, случайная часть разносит повторы многих заданий). Реализован через `job_outbox.available_at`: попытка не начнётся раньше (проверено по журналу в `test_e`).
- **Предел:** `JOB_MAX_ATTEMPTS=5`; затем `failed retry_exhausted`, запись в `dead_letters` (реестр failed/DLQ), событие в `job_events`.
- **Replay** — только явная команда оператора (`ops.py jobs replay`). Разрешён только для `failed`; успешное задание **не исполняется повторно** (`noop`, событие `replay_refused`); без staging-источника — отказ. Новая попытка: attempt+1, свежий бюджет попыток, `replay_count+1`, `dead_letters.replayed_at`, публикация через outbox (`test_g`).
### Роли и сервисы
| Роль | Сервис | Версия | Health/readiness | Volume | Сеть/порт | Credentials |
| --- | --- | --- | --- | --- | --- | --- |
| load_balancer | `lb` | haproxy:2.8.30-alpine | `/lb-health`; проверка `/health/ready` реплик | — | backend; 127.0.0.1:8080 (единственный публичный), 8404 stats | — |
| api ×2 | `api` | сборка из Dockerfile | `/health/ready` (PG + схема 005 + не drain) | нет (read-only rootfs, tmpfs /tmp) | backend, storage, queue; 8080 только внутри | secrets: database_url, cache_url, s3_*, broker_url |
| worker | `worker` | тот же образ | heartbeat-файл < 90 с | нет (read-only, tmpfs) | backend, storage, queue | secrets: database_url, s3_*, broker_url |
| broker | `broker` | redis:7.4.1-alpine, AOF always, noeviction | `redis-cli ping` | brokerdata | queue (internal) | secrets: broker_password |
| postgres | `postgres` | postgres:16.4-alpine | pg_isready | pgdata | backend | secrets: postgres_password |
| кэш сессий | `redis` | redis:7.4.1-alpine, без persistence | ping | — | backend | secrets: redis_password |
| s3 | `s3` | chrislusf/seaweedfs:4.50 | /healthz + прогрев `ops.py wait-s3` | s3data | storage (internal) | secrets: s3_config.json |
| bootstrap | `migrate`, `s3-init` | тот же образ | one-shot, идемпотентны | — | backend / storage | — |
Топология брокера (поток + группа) создаётся кодом идемпотентно (`XGROUP CREATE ... MKSTREAM`, BUSYGROUP = no-op).
### Переменные `.env.example` → реальная конфигурация
| Логическое имя (skeleton) | Реализация |
| --- | --- |
| `BROKER_URL_FILE` | `/run/secrets/broker_url` (создаёт `init_secrets.py`) |
| `WORKER_CONCURRENCY=2` | число consumer-потоков в контейнере worker (prefetch 1 на поток) |
| `JOB_MAX_ATTEMPTS=5` | `attachment_jobs.max_attempts` при создании задания |
| `JOB_TIMEOUT_SECONDS=60` | срок аренды; ≥ `WORKER_IMAGE_TIMEOUT_SECONDS + 20` (проверка при старте) |
| `STAGING_RETENTION_SECONDS=86400` | хранение staging failed-вложений (окно replay) |
| дополнительно | `JOB_LEASE_GRACE_SECONDS`, `JOB_CLAIM_IDLE_SECONDS`, `JOB_MAX_DELIVERIES`, `JOB_RETRY_BASE/MAX_SECONDS`, `WORKER_IMAGE_TIMEOUT_SECONDS`, `WORKER_IMAGE_MEMORY_MB`, `RELAY_*`, `BROKER_STREAM/GROUP`, `PIPELINE_VERSION`, `WORKER_REPLICAS` — описаны в `.env.example` |
### Что изменено относительно lab4
- `migrations/005_async_processing.sql`: состояния `queued/processing/failed`, `staging_key`, `error_code`, `pipeline_version`; таблицы `attachment_variants`, `attachment_jobs`, `job_outbox`, `dead_letters`, `job_events`.
- `src/main.py`: upload → staging + задание + outbox → **202**; content: 409 для queued/processing/failed, варианты; сообщение с failed-вложением → 409, с queued/processing — разрешено.
- Новые модули: `src/broker.py`, `src/outbox.py`, `src/jobs.py` (переходы состояний), `src/worker.py`, `src/imaging.py`, `src/jobs_admin.py`.
- `src/reconcile.py`: префиксы `staging/`, `final/`, `originals/` (lab4), проход D — очистка staging.
- `compose.yaml`: сервисы `broker`, `worker`, `api-fault-publish`, `api-fault-dup`, сеть `queue`; `compose.faults.yaml`.
- Тесты lab4, ожидавшие 201, переведены на 202 + ожидание ready (`test_attachments.py`, `test_attachment_consistency.py`, `s3_outage.py`, `upload_memory.py`). Публичные `tests/` и контракт не изменялись.
## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Публичный smoke | `make test` | `PASS: lab5 public API scenario` (202 → ready, оригинал, JPEG thumbnail 256×160) | evidence/local/smoke.txt |
| Минимум lab4 сохранён | `student-tests/run_all.py` через 2 реплики | 91 тест OK (33 skip — требуют сеть compose), race 100/100, persistence и failover PASS | evidence/local/student-tests.txt, persistence.txt, failover.txt |
| 3: 202 только после durable staging + задания | `test_pipeline.py`, `test_i`, `test_a` | 202 приходит до публикации, задача доходит до ready даже при падении API сразу после 202 | pipeline_and_attachments.txt, pipeline_faults.txt |
| 3: отдельные broker и worker, durable, at-least-once, ack после эффекта | compose: `broker` (AOF always) + `worker`; `test_c`, `test_d` | ack только после COMMIT; падение до ack → повторная доставка без дубля | compose.yaml, pipeline_faults_events.txt |
| 3: worker недоступен → API не делает resize | `make test-worker-outage` | worker остановлен: 202, GET queued, content 409, сообщения 201; после старта worker — ready | worker_outage.txt/.json |
| 3: состояния queued/processing/ready/failed, original неизменен, thumbnail по контракту | `test_pipeline.py` | SHA-256 оригинала совпадает; thumbnail 256×160 по SOF-заголовку JPEG | pipeline_and_attachments.txt |
| 3: ограниченный retry, failed с безопасным error_code, повтор не создаёт 2-й набор | `test_e`, `test_g`, `assert_single_result` | ровно 3 строки variants и 1 событие succeeded во всех сценариях; `retry_exhausted`/`invalid_image` | pipeline_faults.txt |
| 3: демонстрация worker stop → upload → рестарт API → рестарт broker → worker → ready | `make test-worker-outage` | lag=1 до и после рестарта брокера, ready через ~0.03 с после старта worker | worker_outage.txt |
| 4: crop 128 и WebP; лимиты bytes/pixels/time/memory | `test_pipeline.py`, `python -m src.imaging` | crop 128×128, WebP по RIFF-заголовку; EXIF удалён; orientation/alpha/малые исходники; `resource_limit`, `timeout` | pipeline_and_attachments.txt, imaging_memory.txt |
| 4: outbox, crash между COMMIT и publish | `test_a` (api-fault-publish) | `fault_injected` от api-fault-publish, `published` другим процессом, attempt=1, ready | pipeline_faults_events.txt |
| 4: backoff+jitter, постоянные/временные, DLQ, безопасный replay | `test_e`, `test_f`, `test_g` | интервалы в [d/2, d]; permanent без повторов; replay → ready; повторный replay → noop | pipeline_faults.txt |
| 4: остановка worker после записи объекта до ack | `test_c`, `test_d` | `lease_takeover` своим consumer после рестарта; те же SHA-256; `redelivery_noop already_succeeded` | worker_fault_log.txt |
| 4: lease для зависшего processing, ограниченная конкуренция, очистка staging | `test_h`, `test_i` | `lease_expired` → attempt 2 у другого consumer → ready; старый `lease_lost`; staging_key=NULL | pipeline_faults_events.txt |
## Эксперименты и отказы
Локальная песочница: 2 vCPU, 7 GiB RAM, Linux, Python 3.13 (в образе — 3.12.7), без лимитов cgroup. Набор: синтетические изображения (`tests/fixtures/sample.png` 320×200, генерируемые 40 Мп PNG/JPEG). Повторов: сценарии отказов — 1 полный прогон, все 10 PASS; задержка — 30 последовательных загрузок. Основной compose-стенд: Windows 10, 32GB, Ryzen 5 7500f; доказательства в `/evidence`.
| Измерение | Результат |
| --- | --- |
| upload → 202 (sample.png, 109 KiB) | p50 16 мс, p95 29 мс |
| upload → ready (опрос каждые 0.2 с) | p50 0.44 с, p95 0.45 с, max 0.45 с |
| пик RSS подпроцесса обработки | 23 MiB (320×200), 46 MiB (40 Мп JPEG), 361 MiB (40 Мп RGBA PNG) |
| время обработки 40 Мп | JPEG 0.2 с, RGBA PNG 1.8 с |
| Воздействие | Что ожидаем | Что наблюдали | Восстановление / потеря данных |
| --- | --- | --- | --- |
| worker остановлен, upload | 202 queued, content 409, остальной API работает | так и есть, сообщения 201 | ready после старта worker; потерь нет |
| рестарт API и broker (volumes целы) при неподтверждённой задаче | задача остаётся в потоке | lag=1 до и после | — / нет |
| API умер после COMMIT до XADD | sweeper другого процесса публикует | published другим actor через ~2 с | ≤ RELAY_FAST_PATH_GRACE + 1 с / нет |
| API умер после XADD до подтверждения outbox | дубль, no-op | `redelivery_noop already_succeeded` | — / нет, 1 набор вариантов |
| worker умер после записи S3 до COMMIT | свой PEL после рестарта, те же байты | `lease_takeover`, SHA-256 = эталон | ~1–2 с (рестарт процесса) / нет |
| worker умер после COMMIT до XACK | повторная доставка no-op | `redelivery_noop already_succeeded` | ~1–2 с / нет |
| worker «завис» дольше аренды | новая попытка, fencing старой | `lease_expired` → ready на attempt 2 → `lease_lost` | аренда + grace + ≤5 с / нет |
| временные ошибки ×2 | backoff+jitter, ready на 3-й | задержки 0.5–1 с и 1–2 с (base 1, cap 4 в стенде отказов) | — |
| временная ошибка всегда | failed retry_exhausted, DLQ, replay | 5 попыток → failed → replay → ready → replay ещё раз = noop | — |
| мусор в потоке | ack, worker жив | pending=0 | — |
## Ограничения и следующие шаги
- **Один Docker-host:** брокер, PostgreSQL и S3 — по одному экземпляру. Выдерживаются рестарты и падения процессов с сохранением volumes, но не потеря диска/хоста. Redis без репликации: при потере volume брокера неопубликованные строки outbox сохранятся, а уже опубликованные, но не обработанные задачи потребуют повторной публикации (`jobs replay` работает только для failed; для queued без сообщения нужен ручной requeue — сборщик аренд покрывает только processing).
- **At-least-once + идемпотентность ≠ exactly-once:** дубли сообщений и повторная запись тех же объектов S3 возможны и ожидаемы; уникален только опубликованный результат. Детерминизм байтов вариантов гарантирован в пределах одной версии Pillow/libjpeg/libwebp; при обновлении библиотек нужна новая `pipeline_version` (версионирование нескольких pipeline — трек 5, не заявлен).
- Fencing защищает БД, но не S3: «проснувшийся» старый worker может перезаписать объект варианта теми же (детерминированными) байтами после публикации результата.
- Классификация ошибок упрощена: таймаут обработки считается временным, поэтому «тяжёлый» файл может занять до 5 попыток по 30 с.
- Маркеры отказов в filename работают **только** при `WORKER_FAULTS=true` (`compose.faults.yaml`); в обычном стенде filename на обработку не влияет.
- Старые ready-вложения lab4 остаются без вариантов (запрос варианта → 404 по контракту); фоновой догенерации нет.
- HTTP без TLS — только локальный учебный стенд (TLS — lab7).
## Вопросы защиты — кратко
- **Publisher confirm vs consumer ack.** Confirm — брокер принял и сохранил сообщение (у нас: ответ XADD после fsync AOF), это граница «producer → брокер»; после него relay удаляет строку outbox. Ack (XACK) — consumer сообщает, что обработка устойчиво завершена (COMMIT результата/перевода в retry/failed), это граница «брокер → consumer»; до него сообщение остаётся в PEL и будет доставлено снова.
- **Что сохранено в момент 202?** Байты в S3 staging, метаданные, задание и outbox в одной транзакции PostgreSQL. Сообщения в брокере может ещё не быть — его гарантирует outbox.
- **Почему повторная доставка нормальна и где ключ идемпотентности?** At-least-once неизбежно даёт дубли (падение до ack, повтор publish). Ключ эффекта — `(attachment_id, pipeline_version, variant)`: PK `attachment_variants` + детерминированные ключи S3; задание — `job_id` (UNIQUE `(attachment_id, pipeline_version)`); повтор успешного — no-op с ack.
- **Как отличить зависший worker от долго работающего?** Аренда с заведомо большим сроком, чем максимальная попытка (жёсткий таймаут подпроцесса + дедлайны S3). Пока аренда действует — задание не отдаётся второму worker; после истечения + grace — новая попытка, а результат старой отсекается fencing-токеном. Heartbeat контейнера проверяет, что все consumer-потоки живы.
+5
View File
@@ -0,0 +1,5 @@
# Доказательства
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
+54
View File
@@ -0,0 +1,54 @@
# 2026-11-10 14:26:03 UTC
OK Контракт (offline) evidence/check.txt
OK Compose config evidence/check.txt
OK Стенд: контейнеры evidence/stand.txt
OK Стенд: реплики и статус в LB evidence/stand.txt
OK Стенд: лимиты CPU/RAM evidence/stand.txt
OK Стенд: опубликованные порты (только lb) evidence/stand.txt
OK Образ SeaweedFS (закреплённая версия) evidence/stand.txt
OK lab5: broker (Redis AOF) и worker evidence/stand.txt
OK lab5: конфигурация durability брокера evidence/stand.txt
OK S3 bootstrap: лог первого запуска s3-init evidence/s3_bootstrap.txt
OK S3 bootstrap: повторный запуск (идемпотентность) evidence/s3_bootstrap.txt
OK Публичный smoke evidence/smoke.txt
OK Собственные тесты (HTTP через LB, включая test_attachments.py) evidence/student-tests.txt
OK Тесты с доступом к БД (внутри compose-сети) evidence/student-tests.txt
OK Истечение сессии (api-short-ttl, TTL 2 с) evidence/student-tests.txt
OK Согласованность БД <-> S3, обрыв загрузки, внедрённые отказы (api-fault-*) evidence/consistency.txt
OK Сверка БД <-> S3 (dry-run) evidence/reconcile.txt
OK Приватный бакет вне API, права ключей, закрытые админ-порты evidence/s3_private.txt
OK На API нет хранилища оригиналов: read-only rootfs, только tmpfs, без volumes evidence/s3_private.txt
OK API: файлы в /tmp (tmpfs) после загрузок evidence/s3_private.txt
OK Пик памяти: 10 одновременных загрузок по 9.5 MiB evidence/upload_memory.txt
OK Пик памяти: 20 одновременных загрузок evidence/upload_memory.txt
OK Failover #1: реплики до evidence/failover.txt
OK Failover #1: make test-failover (вкл. скачивание файла через другую реплику) evidence/failover.txt
OK Failover #1: реплики после (остановлена именно цель теста) evidence/failover.txt
OK Failover #1: restore evidence/failover.txt
OK Failover #2: реплики до evidence/failover.txt
OK Failover #2: make test-failover (вкл. скачивание файла через другую реплику) evidence/failover.txt
OK Failover #2: реплики после (остановлена именно цель теста) evidence/failover.txt
OK Failover #2: restore evidence/failover.txt
OK Failover #3: реплики до evidence/failover.txt
OK Failover #3: make test-failover (вкл. скачивание файла через другую реплику) evidence/failover.txt
OK Failover #3: реплики после (остановлена именно цель теста) evidence/failover.txt
OK Failover #3: restore evidence/failover.txt
OK Серия отказов: каждая реплика, graceful stop evidence/failover_series.txt
OK Серия отказов: каждая реплика, SIGKILL evidence/failover_series.txt
OK Недоступность S3 и восстановление evidence/s3_outage.txt
OK Варианты изображений по фактическим байтам (test_pipeline.py) evidence/pipeline.txt
OK Сценарий защиты 3: worker остановлен -> 202 -> рестарт API и broker -> worker -> ready evidence/worker_outage.txt
OK Уровень 4: внедрённые отказы pipeline (outbox, crash до/после ack, retry, DLQ, replay, lease) evidence/pipeline_faults.txt
OK Очередь после сценариев: задания, outbox, DLQ, lag evidence/pipeline_faults.txt
OK Реестр failed (DLQ) evidence/pipeline_faults.txt
OK Worker: последние строки лога evidence/worker_log_sample.txt
OK Rolling update lab5 -> lab5.1 под нагрузкой evidence/rolling_update.txt
OK Rolling update обратно lab5.1 -> lab5 (откат) под нагрузкой evidence/rolling_update.txt
OK Реплики после обновлений evidence/rolling_update.txt
OK Persistence: контейнеры до evidence/persistence.txt
OK Persistence: make test-persistence (API + worker + PostgreSQL + Redis + broker + S3 + LB) evidence/persistence.txt
OK Persistence: контейнеры после (Status = Up N seconds) evidence/persistence.txt
OK Persistence: сверка БД <-> S3 после рестарта evidence/persistence.txt
OK Нагрузка 30 с, concurrency 8 evidence/load.txt
OK CPU/RAM после нагрузки evidence/load.txt
OK Лог LB (последние строки, без секретов) evidence/lb_log_sample.txt
+7
View File
@@ -0,0 +1,7 @@
# 2026-11-10 14:13:49 UTC | Контракт (offline) | exit 0 | 0.1s
$ python scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
# 2026-11-10 14:13:49 UTC | Compose config | exit 0 | 0.3s
$ docker compose --env-file .env config --quiet
+75
View File
@@ -0,0 +1,75 @@
# 2026-11-10 14:15:11 UTC | Согласованность БД <-> S3, обрыв загрузки, внедрённые отказы (api-fault-*) | exit 0 | 20.0s
$ python scripts/ops.py in-network consistency
Container messenger-lab5-redis-1 Running
Container messenger-lab5-api-1 Running
Container messenger-lab5-api-2 Running
Container messenger-lab5-postgres-1 Running
Container messenger-lab5-s3-1 Running
Container messenger-lab5-api-fault-s3-1 Creating
Container messenger-lab5-api-fault-db-1 Creating
Container messenger-lab5-api-fault-crash-1 Creating
Container messenger-lab5-api-fault-s3-1 Created
Container messenger-lab5-api-fault-db-1 Created
Container messenger-lab5-api-fault-crash-1 Created
Container messenger-lab5-s3-1 Waiting
Container messenger-lab5-postgres-1 Waiting
Container messenger-lab5-s3-1 Healthy
Container messenger-lab5-postgres-1 Healthy
Container messenger-lab5-s3-init-1 Starting
Container messenger-lab5-migrate-1 Starting
Container messenger-lab5-s3-init-1 Started
Container messenger-lab5-migrate-1 Started
Container messenger-lab5-migrate-1 Waiting
Container messenger-lab5-s3-init-1 Waiting
Container messenger-lab5-postgres-1 Waiting
Container messenger-lab5-redis-1 Waiting
Container messenger-lab5-redis-1 Healthy
Container messenger-lab5-postgres-1 Healthy
Container messenger-lab5-migrate-1 Exited
Container messenger-lab5-s3-init-1 Exited
Container messenger-lab5-api-1 Waiting
Container messenger-lab5-api-2 Waiting
Container messenger-lab5-api-1 Waiting
Container messenger-lab5-api-2 Waiting
Container messenger-lab5-api-1 Waiting
Container messenger-lab5-api-2 Waiting
Container messenger-lab5-api-1 Healthy
Container messenger-lab5-api-2 Healthy
Container messenger-lab5-api-1 Healthy
Container messenger-lab5-api-2 Healthy
Container messenger-lab5-api-fault-db-1 Starting
Container messenger-lab5-api-fault-s3-1 Starting
Container messenger-lab5-api-1 Healthy
Container messenger-lab5-api-2 Healthy
Container messenger-lab5-api-fault-crash-1 Starting
Container messenger-lab5-api-fault-db-1 Started
Container messenger-lab5-api-fault-s3-1 Started
Container messenger-lab5-api-fault-crash-1 Started
Container messenger-lab5-api-run-e891dd567ea2 Creating
Container messenger-lab5-api-run-e891dd567ea2 Created
ready: http://api-fault-s3:8080/health/ready
Container messenger-lab5-api-run-a25e14654677 Creating
Container messenger-lab5-api-run-a25e14654677 Created
ready: http://api-fault-db:8080/health/ready
Container messenger-lab5-api-run-53cacd2097d3 Creating
Container messenger-lab5-api-run-53cacd2097d3 Created
ready: http://api-fault-crash:8080/health/ready
Container messenger-lab5-api-run-66f13fe194f4 Creating
Container messenger-lab5-api-run-66f13fe194f4 Created
test_crash_between_put_and_commit_dry_run_then_apply_then_noop (test_attachment_consistency.AttachmentConsistencyTests.test_crash_between_put_and_commit_dry_run_then_apply_then_noop) ... /usr/local/lib/python3.12/site-packages/botocore/auth.py:424: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
datetime_now = datetime.datetime.utcnow()
ok
test_fresh_pending_is_kept (test_attachment_consistency.AttachmentConsistencyTests.test_fresh_pending_is_kept) ... ok
test_missing_object_is_reported_not_deleted (test_attachment_consistency.AttachmentConsistencyTests.test_missing_object_is_reported_not_deleted) ... ok
test_orphan_object_deleted_only_after_grace (test_attachment_consistency.AttachmentConsistencyTests.test_orphan_object_deleted_only_after_grace) ... ok
test_pending_cannot_be_attached (test_attachment_consistency.AttachmentConsistencyTests.test_pending_cannot_be_attached) ... ok
test_ready_and_referenced_are_never_collected (test_attachment_consistency.AttachmentConsistencyTests.test_ready_and_referenced_are_never_collected) ... ok
test_aborted_upload_leaves_no_row_and_no_object (test_attachment_consistency.UploadFailureTests.test_aborted_upload_leaves_no_row_and_no_object) ... ok
test_db_failure_after_put_returns_503_and_deletes_object (test_attachment_consistency.UploadFailureTests.test_db_failure_after_put_returns_503_and_deletes_object) ... ok
test_process_crash_after_put_is_collected_by_gc (test_attachment_consistency.UploadFailureTests.test_process_crash_after_put_is_collected_by_gc) ... ok
test_s3_put_failure_returns_503_and_compensates (test_attachment_consistency.UploadFailureTests.test_s3_put_failure_returns_503_and_compensates) ... ok
----------------------------------------------------------------------
Ran 10 tests in 4.594s
OK
+66
View File
@@ -0,0 +1,66 @@
# 2026-11-10 14:15:40 UTC | Failover #1: реплики до | exit 0 | 0.3s
$ python scripts/ops.py ps
X-Instance-Id container state health image lb lb_status
4b1faad0399c messenger-lab5-api-1 running healthy messenger-api:lab5 api1 UP
3a0e06f14a63 messenger-lab5-api-2 running healthy messenger-api:lab5 api2 UP
# 2026-11-10 14:16:30 UTC | Failover #1: make test-failover (вкл. скачивание файла через другую реплику) | exit 0 | 49.3s
$ python tests/resilience.py --mode failover --action-script scripts\stop-one.cmd --base-url http://127.0.0.1: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": 4.297}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
# 2026-11-10 14:16:30 UTC | Failover #1: реплики после (остановлена именно цель теста) | exit 0 | 0.3s
$ python scripts/ops.py ps
X-Instance-Id container state health image lb lb_status
4b1faad0399c messenger-lab5-api-1 running healthy messenger-api:lab5 api1 UP
3a0e06f14a63 messenger-lab5-api-2 exited unhealthy messenger-api:lab5 - -
# 2026-11-10 14:16:37 UTC | Failover #1: restore | exit 0 | 6.6s
$ python scripts/ops.py restore
2026-11-10T14:16:37.028Z restore: started ['messenger-lab5-api-2']; 2 replicas healthy and UP in LB after 6.5s
# 2026-11-10 14:16:37 UTC | Failover #2: реплики до | exit 0 | 0.3s
$ python scripts/ops.py ps
X-Instance-Id container state health image lb lb_status
4b1faad0399c messenger-lab5-api-1 running healthy messenger-api:lab5 api1 UP
3a0e06f14a63 messenger-lab5-api-2 running healthy messenger-api:lab5 api2 UP
# 2026-11-10 14:16:54 UTC | Failover #2: make test-failover (вкл. скачивание файла через другую реплику) | exit 0 | 16.8s
$ python tests/resilience.py --mode failover --action-script scripts\stop-one.cmd --base-url http://127.0.0.1:8080
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 122, "failed_attempts": 0, "first_recovery_seconds": 4.532}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
# 2026-11-10 14:16:54 UTC | Failover #2: реплики после (остановлена именно цель теста) | exit 0 | 0.3s
$ python scripts/ops.py ps
X-Instance-Id container state health image lb lb_status
4b1faad0399c messenger-lab5-api-1 running healthy messenger-api:lab5 api1 UP
3a0e06f14a63 messenger-lab5-api-2 exited unhealthy messenger-api:lab5 - -
# 2026-11-10 14:17:01 UTC | Failover #2: restore | exit 0 | 6.6s
$ python scripts/ops.py restore
2026-11-10T14:17:00.997Z restore: started ['messenger-lab5-api-2']; 2 replicas healthy and UP in LB after 6.5s
# 2026-11-10 14:17:01 UTC | Failover #3: реплики до | exit 0 | 0.3s
$ python scripts/ops.py ps
X-Instance-Id container state health image lb lb_status
4b1faad0399c messenger-lab5-api-1 running healthy messenger-api:lab5 api1 UP
3a0e06f14a63 messenger-lab5-api-2 running healthy messenger-api:lab5 api2 UP
# 2026-11-10 14:17:18 UTC | Failover #3: make test-failover (вкл. скачивание файла через другую реплику) | exit 0 | 17.0s
$ python tests/resilience.py --mode failover --action-script scripts\stop-one.cmd --base-url http://127.0.0.1:8080
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 123, "failed_attempts": 0, "first_recovery_seconds": 4.437}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
# 2026-11-10 14:17:18 UTC | Failover #3: реплики после (остановлена именно цель теста) | exit 0 | 0.3s
$ python scripts/ops.py ps
X-Instance-Id container state health image lb lb_status
4b1faad0399c messenger-lab5-api-1 exited unhealthy messenger-api:lab5 - -
3a0e06f14a63 messenger-lab5-api-2 running healthy messenger-api:lab5 api2 UP
# 2026-11-10 14:17:25 UTC | Failover #3: restore | exit 0 | 6.7s
$ python scripts/ops.py restore
2026-11-10T14:17:25.258Z restore: started ['messenger-lab5-api-1']; 2 replicas healthy and UP in LB after 6.6s
# остановленные публичным тестом реплики: ['3a0e06f14a63', '3a0e06f14a63', '4b1faad0399c']
+294
View File
@@ -0,0 +1,294 @@
{
"scenario": "stop each API replica in turn under load, restore before the next",
"load": {
"writers": 4,
"readers": 2,
"client_timeout_s": 2.0,
"write_retry": "same Idempotency-Key and body until 201"
},
"replicas": [
"3a0e06f14a63",
"4b1faad0399c"
],
"rounds": [
{
"target_instance": "3a0e06f14a63",
"mode": "stop",
"lb_up_before": [
"api1",
"api2"
],
"stop_hook_seconds": 4.47,
"lb_detect_down_seconds": 1.88,
"target_last_served_after_stop_seconds": 1.83,
"target_served_after_hook_returned": false,
"errors_during_outage": 0,
"error_kinds": [],
"error_window_seconds": 0.0,
"restore_hook_seconds": 6.72,
"lb_back_up_seconds": 0.95,
"target_back_in_rotation_seconds": 6.72,
"windows": {
"before": {
"from_s": 0,
"to_s": 5.0,
"requests": 1083,
"ok": 1083,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 216.6,
"write_ok_rps": 125.0,
"latency_ms_ok": {
"p50": 16.0,
"p95": 94.0,
"p99": 188.0
},
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
]
},
"outage_first_10s": {
"from_s": 5.0,
"to_s": 15.0,
"requests": 1238,
"ok": 1238,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 123.8,
"write_ok_rps": 74.0,
"latency_ms_ok": {
"p50": 31.0,
"p95": 109.0,
"p99": 188.0
},
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
]
},
"outage_rest": {
"from_s": 15.0,
"to_s": 20.0,
"requests": 531,
"ok": 531,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 106.2,
"write_ok_rps": 60.8,
"latency_ms_ok": {
"p50": 63.0,
"p95": 109.0,
"p99": 391.0
},
"instances": [
"4b1faad0399c"
]
},
"after_restore": {
"from_s": 20.0,
"to_s": 29.98,
"requests": 1831,
"ok": 1831,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 183.4,
"write_ok_rps": 110.1,
"latency_ms_ok": {
"p50": 16.0,
"p95": 94.0,
"p99": 171.0
},
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
]
}
},
"lb_timeline": [
[
0.0,
[
"api1",
"api2"
]
],
[
6.88,
[
"api1"
]
],
[
20.95,
[
"api1",
"api2"
]
],
[
21.92,
[
"api1"
]
],
[
24.47,
[
"api1",
"api2"
]
]
],
"data": {
"confirmed_writes": 2768,
"stored_messages": 2768,
"missing_or_altered": 0,
"duplicate_ids": 0,
"duplicate_texts": 0,
"same_key_retries": 0,
"ok": true
}
},
{
"target_instance": "4b1faad0399c",
"mode": "stop",
"lb_up_before": [
"api1",
"api2"
],
"stop_hook_seconds": 4.55,
"lb_detect_down_seconds": 2.05,
"target_last_served_after_stop_seconds": 1.97,
"target_served_after_hook_returned": false,
"errors_during_outage": 0,
"error_kinds": [],
"error_window_seconds": 0.0,
"restore_hook_seconds": 7.06,
"lb_back_up_seconds": 2.08,
"target_back_in_rotation_seconds": 7.06,
"windows": {
"before": {
"from_s": 0,
"to_s": 5.0,
"requests": 1346,
"ok": 1346,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 269.2,
"write_ok_rps": 160.4,
"latency_ms_ok": {
"p50": 16.0,
"p95": 78.0,
"p99": 109.0
},
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
]
},
"outage_first_10s": {
"from_s": 5.0,
"to_s": 15.0,
"requests": 1371,
"ok": 1371,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 137.1,
"write_ok_rps": 82.7,
"latency_ms_ok": {
"p50": 31.0,
"p95": 94.0,
"p99": 187.0
},
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
]
},
"outage_rest": {
"from_s": 15.0,
"to_s": 20.0,
"requests": 564,
"ok": 564,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 112.8,
"write_ok_rps": 66.8,
"latency_ms_ok": {
"p50": 62.0,
"p95": 109.0,
"p99": 188.0
},
"instances": [
"3a0e06f14a63"
]
},
"after_restore": {
"from_s": 20.0,
"to_s": 30.38,
"requests": 1657,
"ok": 1657,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 159.7,
"write_ok_rps": 90.8,
"latency_ms_ok": {
"p50": 16.0,
"p95": 94.0,
"p99": 188.0
},
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
]
}
},
"lb_timeline": [
[
0.0,
[
"api1",
"api2"
]
],
[
7.05,
[
"api2"
]
],
[
22.08,
[
"api1",
"api2"
]
],
[
23.05,
[
"api2"
]
],
[
25.51,
[
"api1",
"api2"
]
]
],
"data": {
"confirmed_writes": 2905,
"stored_messages": 2905,
"missing_or_altered": 0,
"duplicate_ids": 0,
"duplicate_texts": 0,
"same_key_retries": 0,
"ok": true
}
}
],
"pass": true
}
+17
View File
@@ -0,0 +1,17 @@
# 2026-11-10 14:18:28 UTC | Серия отказов: каждая реплика, graceful stop | exit 0 | 62.8s
$ python student-tests/failover_series.py --base-url http://127.0.0.1:8080 --output evidence/failover_series.json
replicas observed through LB: ['3a0e06f14a63', '4b1faad0399c']
-- stopping 3a0e06f14a63 (mode=stop) under load
hook 4.47s | LB DOWN after 1.88 s | errors 0 (-) | RPS before 216.6, outage 123.8, after restore 183.4 | p95 outage 109.0 ms | back in rotation 6.72 s | data ok=True
-- stopping 4b1faad0399c (mode=stop) under load
hook 4.55s | LB DOWN after 2.05 s | errors 0 (-) | RPS before 269.2, outage 137.1, after restore 159.7 | p95 outage 94.0 ms | back in rotation 7.06 s | data ok=True
PASS: every replica stopped and restored; confirmed data intact, no duplicates
# 2026-11-10 14:19:31 UTC | Серия отказов: каждая реплика, SIGKILL | exit 0 | 63.0s
$ python student-tests/failover_series.py --base-url http://127.0.0.1:8080 --mode kill --output evidence/failover_series_kill.json
replicas observed through LB: ['3a0e06f14a63', '4b1faad0399c']
-- stopping 3a0e06f14a63 (mode=kill) under load
hook 1.20s | LB DOWN after 2.39 s | errors 3 (502) | RPS before 280.4, outage 89.8, after restore 171.1 | p95 outage 110.0 ms | back in rotation 7.06 s | data ok=True
-- stopping 4b1faad0399c (mode=kill) under load
hook 0.83s | LB DOWN after 2.34 s | errors 6 (502) | RPS before 260.4, outage 89.4, after restore 156.0 | p95 outage 110.0 ms | back in rotation 7.28 s | data ok=True
PASS: every replica stopped and restored; confirmed data intact, no duplicates
@@ -0,0 +1,298 @@
{
"scenario": "stop each API replica in turn under load, restore before the next",
"load": {
"writers": 4,
"readers": 2,
"client_timeout_s": 2.0,
"write_retry": "same Idempotency-Key and body until 201"
},
"replicas": [
"3a0e06f14a63",
"4b1faad0399c"
],
"rounds": [
{
"target_instance": "3a0e06f14a63",
"mode": "kill",
"lb_up_before": [
"api1",
"api2"
],
"stop_hook_seconds": 1.2,
"lb_detect_down_seconds": 2.39,
"target_last_served_after_stop_seconds": 0.56,
"target_served_after_hook_returned": false,
"errors_during_outage": 3,
"error_kinds": [
"502"
],
"error_window_seconds": 0.64,
"restore_hook_seconds": 7.12,
"lb_back_up_seconds": 1.42,
"target_back_in_rotation_seconds": 7.06,
"windows": {
"before": {
"from_s": 0,
"to_s": 5.0,
"requests": 1402,
"ok": 1402,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 280.4,
"write_ok_rps": 161.4,
"latency_ms_ok": {
"p50": 16.0,
"p95": 78.0,
"p99": 94.0
},
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
]
},
"outage_first_10s": {
"from_s": 5.0,
"to_s": 15.0,
"requests": 901,
"ok": 898,
"errors": 3,
"error_ratio": 0.0033,
"ok_rps": 89.8,
"write_ok_rps": 52.6,
"latency_ms_ok": {
"p50": 32.0,
"p95": 110.0,
"p99": 1015.0
},
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
]
},
"outage_rest": {
"from_s": 15.0,
"to_s": 20.0,
"requests": 518,
"ok": 518,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 103.6,
"write_ok_rps": 60.8,
"latency_ms_ok": {
"p50": 78.0,
"p95": 110.0,
"p99": 187.0
},
"instances": [
"4b1faad0399c"
]
},
"after_restore": {
"from_s": 20.0,
"to_s": 30.44,
"requests": 1786,
"ok": 1786,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 171.1,
"write_ok_rps": 101.4,
"latency_ms_ok": {
"p50": 16.0,
"p95": 94.0,
"p99": 187.0
},
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
]
}
},
"lb_timeline": [
[
0.0,
[
"api1",
"api2"
]
],
[
7.39,
[
"api1"
]
],
[
21.42,
[
"api1",
"api2"
]
],
[
21.53,
[
"api1"
]
],
[
24.02,
[
"api1",
"api2"
]
]
],
"data": {
"confirmed_writes": 2698,
"stored_messages": 2698,
"missing_or_altered": 0,
"duplicate_ids": 0,
"duplicate_texts": 0,
"same_key_retries": 1,
"ok": true
}
},
{
"target_instance": "4b1faad0399c",
"mode": "kill",
"lb_up_before": [
"api1",
"api2"
],
"stop_hook_seconds": 0.83,
"lb_detect_down_seconds": 2.34,
"target_last_served_after_stop_seconds": 0.09,
"target_served_after_hook_returned": false,
"errors_during_outage": 6,
"error_kinds": [
"502"
],
"error_window_seconds": 0.28,
"restore_hook_seconds": 7.3,
"lb_back_up_seconds": 1.33,
"target_back_in_rotation_seconds": 7.28,
"windows": {
"before": {
"from_s": 0,
"to_s": 5.0,
"requests": 1302,
"ok": 1302,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 260.4,
"write_ok_rps": 153.2,
"latency_ms_ok": {
"p50": 16.0,
"p95": 78.0,
"p99": 125.0
},
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
]
},
"outage_first_10s": {
"from_s": 5.0,
"to_s": 15.0,
"requests": 900,
"ok": 894,
"errors": 6,
"error_ratio": 0.0067,
"ok_rps": 89.4,
"write_ok_rps": 52.5,
"latency_ms_ok": {
"p50": 32.0,
"p95": 110.0,
"p99": 1016.0
},
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
]
},
"outage_rest": {
"from_s": 15.0,
"to_s": 20.0,
"requests": 565,
"ok": 565,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 113.0,
"write_ok_rps": 66.6,
"latency_ms_ok": {
"p50": 62.0,
"p95": 109.0,
"p99": 187.0
},
"instances": [
"3a0e06f14a63"
]
},
"after_restore": {
"from_s": 20.0,
"to_s": 30.5,
"requests": 1638,
"ok": 1638,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 156.0,
"write_ok_rps": 92.5,
"latency_ms_ok": {
"p50": 16.0,
"p95": 109.0,
"p99": 188.0
},
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
]
}
},
"lb_timeline": [
[
0.0,
[
"api1",
"api2"
]
],
[
7.34,
[
"api2"
]
],
[
21.33,
[
"api1",
"api2"
]
],
[
22.2,
[
"api2"
]
],
[
24.74,
[
"api1",
"api2"
]
]
],
"data": {
"confirmed_writes": 2599,
"stored_messages": 2599,
"missing_or_altered": 0,
"duplicate_ids": 0,
"duplicate_texts": 0,
"same_key_retries": 4,
"ok": true
}
}
],
"pass": true
}
+22
View File
@@ -0,0 +1,22 @@
# 2026-11-10 14:14:03 UTC | одна сессия, 20 запросов GET /users/me через LB
1 200 X-Instance-Id=4b1faad0399c X-Request-Id=AC1400019A78-1F90-6AF326AB268-0BC1-0008
2 200 X-Instance-Id=3a0e06f14a63 X-Request-Id=AC1400019A88-1F90-6AF326AB27B-0BC2-0008
3 200 X-Instance-Id=4b1faad0399c X-Request-Id=AC1400019A8E-1F90-6AF326AB27F-0BC3-0008
4 200 X-Instance-Id=3a0e06f14a63 X-Request-Id=AC1400019A9C-1F90-6AF326AB282-0BC4-0008
5 200 X-Instance-Id=4b1faad0399c X-Request-Id=AC1400019AA4-1F90-6AF326AB296-0BC5-0008
6 200 X-Instance-Id=3a0e06f14a63 X-Request-Id=AC1400019AA8-1F90-6AF326AB2A5-0BC6-0008
7 200 X-Instance-Id=4b1faad0399c X-Request-Id=AC1400019AAA-1F90-6AF326AB2B4-0BC7-0008
8 200 X-Instance-Id=3a0e06f14a63 X-Request-Id=AC1400019AB0-1F90-6AF326AB2C4-0BC8-0008
9 200 X-Instance-Id=4b1faad0399c X-Request-Id=AC1400019ABA-1F90-6AF326AB2D3-0BC9-0008
10 200 X-Instance-Id=3a0e06f14a63 X-Request-Id=AC1400019ABE-1F90-6AF326AB2E2-0BCA-0008
11 200 X-Instance-Id=4b1faad0399c X-Request-Id=AC1400019ACC-1F90-6AF326AB2E5-0BCB-0008
12 200 X-Instance-Id=3a0e06f14a63 X-Request-Id=AC1400019ADC-1F90-6AF326AB2F2-0BCC-0008
13 200 X-Instance-Id=4b1faad0399c X-Request-Id=AC1400019ADE-1F90-6AF326AB300-0BCD-0008
14 200 X-Instance-Id=3a0e06f14a63 X-Request-Id=AC1400019AE4-1F90-6AF326AB303-0BCE-0008
15 200 X-Instance-Id=4b1faad0399c X-Request-Id=AC1400019AEA-1F90-6AF326AB305-0BCF-0008
16 200 X-Instance-Id=3a0e06f14a63 X-Request-Id=AC1400019AF6-1F90-6AF326AB320-0BD0-0008
17 200 X-Instance-Id=4b1faad0399c X-Request-Id=AC1400019B06-1F90-6AF326AB323-0BD1-0008
18 200 X-Instance-Id=3a0e06f14a63 X-Request-Id=AC1400019B0C-1F90-6AF326AB33F-0BD2-0008
19 200 X-Instance-Id=4b1faad0399c X-Request-Id=AC1400019B16-1F90-6AF326AB34E-0BD3-0008
20 200 X-Instance-Id=3a0e06f14a63 X-Request-Id=AC1400019B24-1F90-6AF326AB351-0BD4-0008
разных реплик: 2
+62
View File
@@ -0,0 +1,62 @@
# 2026-11-10 14:26:03 UTC | Лог LB (последние строки, без секретов) | exit 0 | 0.3s
$ docker compose --env-file .env logs --no-color --tail 60 lb
lb-1 | 172.20.0.1:36070 [10/Nov/2026:14:26:00.806] public api/api1 0/0/0/24/25 201 421 ---- 7/7/4/3/0 0/0 rid=AC1400018CE6-1F90-6AF32978326-1436-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36082 [10/Nov/2026:14:26:00.818] public api/api1 0/0/0/14/14 201 421 ---- 8/8/4/2/0 0/0 rid=AC1400018CF2-1F90-6AF32978332-1438-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36116 [10/Nov/2026:14:26:00.827] public api/api2 0/0/0/6/6 201 421 ---- 7/7/3/1/0 0/0 rid=AC1400018D14-1F90-6AF3297833B-143B-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36130 [10/Nov/2026:14:26:00.831] public api/api2 0/0/0/7/8 201 421 ---- 8/8/4/1/0 0/0 rid=AC1400018D22-1F90-6AF3297833F-143D-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36078 [10/Nov/2026:14:26:00.822] public api/api1 0/0/0/18/18 201 421 ---- 8/8/3/2/0 0/0 rid=AC1400018CEE-1F90-6AF3297832C-143A-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36104 [10/Nov/2026:14:26:00.838] public api/api2 0/0/0/6/6 201 421 ---- 8/8/4/1/0 0/0 rid=AC1400018D08-1F90-6AF32978338-143F-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36182 [10/Nov/2026:14:26:00.842] public api/api2 0/0/0/6/6 201 421 ---- 8/8/4/0/0 0/0 rid=AC1400018D56-1F90-6AF3297834A-1441-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36196 [10/Nov/2026:14:26:00.850] public api/api2 0/0/0/4/4 201 421 ---- 8/8/7/1/0 0/0 rid=AC1400018D64-1F90-6AF32978352-1443-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36122 [10/Nov/2026:14:26:00.854] public api/api2 0/0/0/6/6 201 421 ---- 8/8/7/1/0 0/0 rid=AC1400018D1A-1F90-6AF3297833D-1445-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36212 [10/Nov/2026:14:26:00.856] public api/api2 0/0/0/6/6 201 421 ---- 8/8/6/0/0 0/0 rid=AC1400018D74-1F90-6AF32978358-1447-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36224 [10/Nov/2026:14:26:00.884] public api/api2 0/0/0/6/6 201 421 ---- 8/8/7/0/0 0/0 rid=AC1400018D80-1F90-6AF3297835E-1449-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36118 [10/Nov/2026:14:26:00.828] public api/api1 0/0/0/76/76 201 421 ---- 8/8/6/6/0 0/0 rid=AC1400018D16-1F90-6AF3297833C-143C-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36156 [10/Nov/2026:14:26:00.834] public api/api1 0/0/0/78/78 201 421 ---- 8/8/6/6/0 0/0 rid=AC1400018D3C-1F90-6AF32978342-143E-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36276 [10/Nov/2026:14:26:00.914] public api/api2 0/0/0/6/6 201 421 ---- 8/8/7/0/0 0/0 rid=AC1400018DB4-1F90-6AF32978392-144B-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36190 [10/Nov/2026:14:26:00.846] public api/api1 0/0/0/77/77 201 421 ---- 8/8/7/6/0 0/0 rid=AC1400018D5E-1F90-6AF3297834E-1442-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36168 [10/Nov/2026:14:26:00.841] public api/api1 0/0/0/82/83 201 421 ---- 7/7/6/5/0 0/0 rid=AC1400018D48-1F90-6AF32978349-1440-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36166 [10/Nov/2026:14:26:00.854] public api/api1 0/0/0/72/73 201 421 ---- 8/8/7/5/0 0/0 rid=AC1400018D46-1F90-6AF32978343-1446-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36262 [10/Nov/2026:14:26:00.906] public api/api1 0/0/0/21/21 201 421 ---- 8/8/6/4/0 0/0 rid=AC1400018DA6-1F90-6AF3297838A-144A-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36238 [10/Nov/2026:14:26:00.864] public api/api1 0/0/0/64/64 201 421 ---- 7/7/5/3/0 0/0 rid=AC1400018D8E-1F90-6AF32978360-1448-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36146 [10/Nov/2026:14:26:00.853] public api/api1 0/0/1/74/75 201 421 ---- 6/6/5/3/0 0/0 rid=AC1400018D32-1F90-6AF32978340-1444-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36282 [10/Nov/2026:14:26:00.922] public api/api2 0/0/0/6/6 201 421 ---- 5/5/4/1/0 0/0 rid=AC1400018DBA-1F90-6AF3297839A-144D-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36250 [10/Nov/2026:14:26:00.915] public api/api1 0/0/0/14/15 201 421 ---- 5/5/3/2/0 0/0 rid=AC1400018D9A-1F90-6AF3297837C-144C-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36294 [10/Nov/2026:14:26:00.926] public api/api2 0/0/0/8/8 201 421 ---- 8/8/6/2/0 0/0 rid=AC1400018DC6-1F90-6AF3297839E-144F-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36324 [10/Nov/2026:14:26:00.930] public api/api2 0/0/0/10/10 201 421 ---- 8/8/6/2/0 0/0 rid=AC1400018DE4-1F90-6AF329783A2-1451-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36378 [10/Nov/2026:14:26:00.935] public api/api2 0/0/0/7/7 201 421 ---- 8/8/6/1/0 0/0 rid=AC1400018E1A-1F90-6AF329783A7-1455-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36336 [10/Nov/2026:14:26:00.931] public api/api2 0/0/0/12/12 201 421 ---- 7/7/5/0/0 0/0 rid=AC1400018DF0-1F90-6AF329783A3-1453-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36396 [10/Nov/2026:14:26:00.945] public api/api2 0/0/0/5/5 201 421 ---- 8/8/7/1/0 0/0 rid=AC1400018E2C-1F90-6AF329783B1-1457-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36362 [10/Nov/2026:14:26:00.945] public api/api2 0/0/0/7/7 201 421 ---- 8/8/7/0/0 0/0 rid=AC1400018E0A-1F90-6AF329783A4-1459-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36416 [10/Nov/2026:14:26:00.977] public api/api2 0/0/0/7/7 201 421 ---- 8/8/7/0/0 0/0 rid=AC1400018E40-1F90-6AF329783BA-145B-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36308 [10/Nov/2026:14:26:00.926] public api/api1 0/0/0/78/78 201 421 ---- 8/8/7/7/0 0/0 rid=AC1400018DD4-1F90-6AF3297839E-144E-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36320 [10/Nov/2026:14:26:00.928] public api/api1 0/0/0/77/78 201 421 ---- 8/8/6/6/0 0/0 rid=AC1400018DE0-1F90-6AF329783A0-1450-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36428 [10/Nov/2026:14:26:01.006] public api/api2 0/0/0/6/6 201 420 ---- 8/8/6/0/0 0/0 rid=AC1400018E4C-1F90-6AF3297906-145D-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36348 [10/Nov/2026:14:26:00.931] public api/api1 0/0/0/86/86 201 421 ---- 8/8/6/6/0 0/0 rid=AC1400018DFC-1F90-6AF329783A3-1452-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36342 [10/Nov/2026:14:26:00.930] public api/api1 0/0/0/88/88 201 421 ---- 8/8/5/5/0 0/0 rid=AC1400018DF6-1F90-6AF329783A2-1454-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36418 [10/Nov/2026:14:26:00.986] public api/api1 0/0/0/35/36 201 421 ---- 8/8/4/4/0 0/0 rid=AC1400018E42-1F90-6AF329783DA-145C-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36384 [10/Nov/2026:14:26:00.942] public api/api1 0/0/0/80/81 201 421 ---- 7/7/4/3/0 0/0 rid=AC1400018E20-1F90-6AF329783AE-1456-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36392 [10/Nov/2026:14:26:00.945] public api/api1 0/0/0/77/78 201 421 ---- 6/6/3/2/0 0/0 rid=AC1400018E28-1F90-6AF329783B1-1458-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36402 [10/Nov/2026:14:26:00.952] public api/api1 0/0/0/71/71 201 421 ---- 6/6/2/1/0 0/0 rid=AC1400018E32-1F90-6AF329783B8-145A-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36444 [10/Nov/2026:14:26:01.014] public api/api1 0/0/0/14/14 201 420 ---- 8/8/5/2/0 0/0 rid=AC1400018E5C-1F90-6AF329790E-145E-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36438 [10/Nov/2026:14:26:01.023] public api/api2 0/0/0/11/11 201 420 ---- 8/8/5/2/0 0/0 rid=AC1400018E56-1F90-6AF3297908-145F-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36496 [10/Nov/2026:14:26:01.025] public api/api2 0/0/0/11/11 201 420 ---- 8/8/5/2/0 0/0 rid=AC1400018E90-1F90-6AF3297919-1461-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36482 [10/Nov/2026:14:26:01.025] public api/api1 0/0/0/11/11 201 420 ---- 7/7/4/2/0 0/0 rid=AC1400018E82-1F90-6AF3297919-1462-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36488 [10/Nov/2026:14:26:01.025] public api/api2 0/0/0/12/12 201 420 ---- 6/6/3/1/0 0/0 rid=AC1400018E88-1F90-6AF3297919-1463-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36512 [10/Nov/2026:14:26:01.036] public api/api2 0/0/0/10/10 201 420 ---- 8/8/7/2/0 0/0 rid=AC1400018EA0-1F90-6AF3297924-1465-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36462 [10/Nov/2026:14:26:01.038] public api/api2 0/0/0/11/11 201 420 ---- 8/8/7/2/0 0/0 rid=AC1400018E6E-1F90-6AF3297915-1467-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36524 [10/Nov/2026:14:26:01.039] public api/api2 0/0/0/9/10 201 420 ---- 7/7/6/1/0 0/0 rid=AC1400018EAC-1F90-6AF3297927-1469-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36546 [10/Nov/2026:14:26:01.048] public api/api2 0/0/0/8/8 201 420 ---- 8/8/7/1/0 0/0 rid=AC1400018EC2-1F90-6AF3297930-146B-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36568 [10/Nov/2026:14:26:01.051] public api/api2 0/0/0/7/7 201 420 ---- 8/8/7/0/0 0/0 rid=AC1400018ED8-1F90-6AF3297933-146D-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36592 [10/Nov/2026:14:26:01.059] public api/api2 0/0/0/4/4 201 420 ---- 8/8/7/0/0 0/0 rid=AC1400018EF0-1F90-6AF329793B-146F-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36508 [10/Nov/2026:14:26:01.030] public api/api1 0/0/0/68/68 201 420 ---- 8/8/7/7/0 0/0 rid=AC1400018E9C-1F90-6AF329791E-1464-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36470 [10/Nov/2026:14:26:01.025] public api/api1 0/0/0/73/73 201 420 ---- 7/7/6/6/0 0/0 rid=AC1400018E76-1F90-6AF3297919-1460-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36612 [10/Nov/2026:14:26:01.100] public api/api2 0/0/0/5/6 201 420 ---- 8/8/7/0/0 0/0 rid=AC1400018F04-1F90-6AF3297964-1471-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36620 [10/Nov/2026:14:26:01.108] public api/api2 0/0/0/4/4 201 420 ---- 8/8/7/0/0 0/0 rid=AC1400018F0C-1F90-6AF329796C-1473-0008 inst=cec102b25e41 "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36618 [10/Nov/2026:14:26:01.100] public api/api1 0/0/0/17/17 201 420 ---- 7/7/6/6/0 0/0 rid=AC1400018F0A-1F90-6AF3297964-1472-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36584 [10/Nov/2026:14:26:01.057] public api/api1 0/0/0/61/61 201 420 ---- 6/6/5/5/0 0/0 rid=AC1400018EE8-1F90-6AF3297939-146E-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36536 [10/Nov/2026:14:26:01.040] public api/api1 0/0/0/81/81 201 420 ---- 5/5/4/4/0 0/0 rid=AC1400018EB8-1F90-6AF3297928-146A-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36516 [10/Nov/2026:14:26:01.039] public api/api1 0/0/0/83/83 201 420 ---- 4/4/3/3/0 0/0 rid=AC1400018EA4-1F90-6AF3297927-1468-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36452 [10/Nov/2026:14:26:01.038] public api/api1 0/0/1/84/85 201 420 ---- 3/3/2/2/0 0/0 rid=AC1400018E64-1F90-6AF3297913-1466-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36600 [10/Nov/2026:14:26:01.065] public api/api1 0/0/0/57/58 201 420 ---- 2/2/1/1/0 0/0 rid=AC1400018EF8-1F90-6AF3297941-1470-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
lb-1 | 172.20.0.1:36562 [10/Nov/2026:14:26:01.051] public api/api1 0/0/0/72/72 201 420 ---- 1/1/0/0/0 0/0 rid=AC1400018ED2-1F90-6AF3297933-146C-0008 inst=9adbb2f64abd "POST /api/v1/chats/2e3b890e-2af9-4acf-8c20-41d8ad16ad39/messages"
+17
View File
@@ -0,0 +1,17 @@
{
"lab": 5,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.094,
"concurrency": 8,
"successful_requests": 5150,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 171.13,
"successful_latency_ms": {
"p50": 31.0,
"p95": 110.0,
"p99": 188.0
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+31
View File
@@ -0,0 +1,31 @@
# 2026-11-10 14:26:01 UTC | Нагрузка 30 с, concurrency 8 | exit 0 | 30.5s
$ python tests/load.py --base-url http://127.0.0.1:8080 --duration 30 --concurrency 8 --output evidence/load.json
{
"lab": 5,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.094,
"concurrency": 8,
"successful_requests": 5150,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 171.13,
"successful_latency_ms": {
"p50": 31.0,
"p95": 110.0,
"p99": 188.0
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
# 2026-11-10 14:26:03 UTC | CPU/RAM после нагрузки | exit 0 | 2.2s
$ docker stats --no-stream --format table {{.Name}} {{.CPUPerc}} {{.MemUsage}} {{.MemPerc}}
NAME CPU % MEM USAGE / LIMIT MEM %
messenger-lab5-api-6 20.42% 95.3MiB / 320MiB 29.78%
messenger-lab5-api-5 19.69% 94.15MiB / 320MiB 29.42%
messenger-lab5-worker-1 0.13% 77.54MiB / 1.25GiB 6.06%
messenger-lab5-lb-1 0.34% 13.26MiB / 128MiB 10.36%
messenger-lab5-postgres-1 3.10% 71.41MiB / 512MiB 13.95%
messenger-lab5-redis-1 0.21% 4.559MiB / 96MiB 4.75%
messenger-lab5-s3-1 2.87% 99.73MiB / 512MiB 19.48%
messenger-lab5-broker-1 2.79% 8.617MiB / 320MiB 2.69%
+33
View File
@@ -0,0 +1,33 @@
# Локальный прогон (без Docker) — что это и чем НЕ является
Дата: 2026-11-09. Эти файлы получены при разработке в изолированной Linux-песочнице,
где **Docker Hub недоступен** (образы не скачиваются), поэтому compose-стенд там не
поднимался. Те же процессы запускались нативно:
| Роль | В compose.yaml | В локальном прогоне |
| --- | --- | --- |
| API x2 | `api` (образ из Dockerfile) | `python -m src.server` x2 (INSTANCE_ID=api1/api2) |
| LB | HAProxy 2.8.30 | 40-строчный round-robin TCP-прокси на asyncio (только для теста) |
| PostgreSQL | postgres:16.4-alpine | PostgreSQL 16 (системный) |
| Кэш сессий | redis:7.4.1-alpine | Redis 7.0.15, без persistence |
| Broker | redis:7.4.1-alpine, AOF `appendfsync always`, `noeviction` | Redis 7.0.15 с теми же флагами, отдельный dir |
| S3 | SeaweedFS 4.50 | moto 5.0.28 (S3-эмулятор, in-memory) |
| Worker | `worker` (`python -m src.worker`) | тот же модуль; «restart: unless-stopped» эмулирован циклом в shell |
Код приложения, миграции и тесты — те же, что в репозитории. Хуки рестарта/остановки
заменены локальными скриптами (kill/pg_ctl/redis SHUTDOWN), поэтому **доказательства
на compose-стенде нужно собрать самостоятельно**: `python scripts/collect_evidence.py`
(запишет evidence/*.txt и evidence/SUMMARY.txt). S3 в локальном persistence-прогоне
не перезапускался (moto хранит данные в памяти).
| Файл | Что внутри |
| --- | --- |
| smoke.txt, student-tests.txt | `make test` и `student-tests/run_all.py` через 2 реплики: 91 тест + race, PASS |
| pipeline_and_attachments.txt | test_pipeline.py (7) и адаптированный test_attachments.py (17), PASS |
| pipeline_faults.txt | test_pipeline_faults.py: 10 сценариев отказов уровня 4, PASS |
| pipeline_faults_events.txt | журнал job_events этих сценариев (доказательство *как* система восстановилась) |
| worker_fault_log.txt | строки лога worker: внедрённые падения и восстановление своего PEL |
| worker_outage.txt / .json | сценарий защиты уровня 3 (worker stop -> 202 -> рестарт API и broker -> ready) |
| persistence.txt, failover.txt | публичные tests/resilience.py (persistence: API+worker+PG+Redis+broker) |
| latency.json | 30 загрузок: 202 p50 16 мс; до ready p50 0.44 с (с шагом опроса 0.2 с) |
| imaging_memory.txt | пиковый RSS подпроцесса обработки: 40 Мп RGBA PNG — 361 MiB, 40 Мп JPEG — 46 MiB |
+4
View File
@@ -0,0 +1,4 @@
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 141, "failed_attempts": 0, "first_recovery_seconds": 0.115}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
EXIT=0
@@ -0,0 +1,5 @@
synthetic/big.jpg 626630 {'thumbnail': (256, 160), 'crop': (128, 128), 'optimized': (1280, 800)} 0.20s peak RSS 46 MiB
synthetic/big.png 165443 {'thumbnail': (256, 160), 'crop': (128, 128), 'optimized': (1280, 800)} 1.80s peak RSS 361 MiB
tests/fixtures/sample.png 111817 {'thumbnail': (256, 160), 'crop': (128, 128), 'optimized': (320, 200)} 0.05s peak RSS 23 MiB
synthetic/alpha.png 86 {'thumbnail': (50, 30), 'crop': (128, 128), 'optimized': (50, 30)} 0.04s peak RSS 23 MiB
synthetic/orient.jpg 1365 {'thumbnail': (64, 256), 'crop': (128, 128), 'optimized': (100, 400)} 0.04s peak RSS 23 MiB
+14
View File
@@ -0,0 +1,14 @@
{
"n": 30,
"file": "tests/fixtures/sample.png 320x200 109 KiB",
"upload_202_s": {
"p50": 0.016,
"p95": 0.029
},
"upload_to_ready_s": {
"p50": 0.435,
"p95": 0.449,
"max": 0.45
},
"note": "local sandbox, poll interval 0.2 s, 1 worker x 2 consumers"
}
+3
View File
@@ -0,0 +1,3 @@
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
EXIT=0
@@ -0,0 +1,11 @@
.......
----------------------------------------------------------------------
Ran 7 tests in 4.403s
OK
.................
----------------------------------------------------------------------
Ran 17 tests in 3.869s
OK
done
@@ -0,0 +1,18 @@
test_a_crash_between_commit_and_publish (test_pipeline_faults.PipelineFaultTests.test_a_crash_between_commit_and_publish) ... ok
test_b_crash_after_publish_duplicate_is_noop (test_pipeline_faults.PipelineFaultTests.test_b_crash_after_publish_duplicate_is_noop) ... ok
test_c_worker_crash_after_side_effects_before_commit (test_pipeline_faults.PipelineFaultTests.test_c_worker_crash_after_side_effects_before_commit) ... ok
test_d_worker_crash_after_commit_before_ack (test_pipeline_faults.PipelineFaultTests.test_d_worker_crash_after_commit_before_ack) ... ok
test_e_transient_errors_retry_with_backoff (test_pipeline_faults.PipelineFaultTests.test_e_transient_errors_retry_with_backoff) ... ok
test_f_permanent_error_fails_without_retry (test_pipeline_faults.PipelineFaultTests.test_f_permanent_error_fails_without_retry) ... ok
test_g_retry_exhausted_dlq_then_explicit_replay (test_pipeline_faults.PipelineFaultTests.test_g_retry_exhausted_dlq_then_explicit_replay) ... ok
test_h_hung_worker_lease_expires_and_is_fenced (test_pipeline_faults.PipelineFaultTests.test_h_hung_worker_lease_expires_and_is_fenced) ... ok
test_i_staging_removed_after_safe_commit (test_pipeline_faults.PipelineFaultTests.test_i_staging_removed_after_safe_commit) ... /home/claude/venv/lib/python3.13/site-packages/botocore/auth.py:424: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
datetime_now = datetime.datetime.utcnow()
ok
test_j_garbage_broker_message_is_acked (test_pipeline_faults.PipelineFaultTests.test_j_garbage_broker_message_is_acked) ... ok
----------------------------------------------------------------------
Ran 10 tests in 71.328s
OK
EXIT=0
@@ -0,0 +1,71 @@
filename | attempt | event | detail | actor
----------------------------------+---------+-----------------+---------------------------------------------------+-------------
a.png | 1 | accepted | | api
a.png | 1 | fault_injected | crash between COMMIT and publish | api:apipub
a.png | 1 | published | stream id 1794253144786-0 | api:apidup
a.png | 1 | claimed | | wf-1
a.png | 1 | succeeded | thumbnail,crop,optimized | wf-1
b.png | 1 | accepted | | api
b.png | 1 | fault_injected | crash after XADD before outbox commit | api:apidup
b.png | 1 | claimed | | wf-1
b.png | 1 | succeeded | thumbnail,crop,optimized | wf-1
b.png | 1 | published | stream id 1794253148012-0 | api:api1
b.png | 1 | redelivery_noop | already_succeeded | wf-0
fault-crash-after-effects.png | 1 | accepted | | api
fault-crash-after-effects.png | 1 | published | stream id 1794253148173-0 | api:api1
fault-crash-after-effects.png | 1 | claimed | | wf-1
fault-crash-after-effects.png | 1 | fault_injected | crash after S3 writes before COMMIT | wf-1
fault-crash-after-effects.png | 1 | lease_takeover | previous owner wf-1 | wf-1
fault-crash-after-effects.png | 1 | succeeded | thumbnail,crop,optimized | wf-1
fault-crash-before-ack.png | 1 | accepted | | api
fault-crash-before-ack.png | 1 | published | stream id 1794253150245-0 | api:api1
fault-crash-before-ack.png | 1 | claimed | | wf-0
fault-crash-before-ack.png | 1 | succeeded | thumbnail,crop,optimized | wf-0
fault-crash-before-ack.png | 1 | fault_injected | crash after COMMIT before XACK | wf-0
fault-crash-before-ack.png | 1 | redelivery_noop | already_succeeded | wf-0
fault-permanent.png | 1 | accepted | | api
fault-permanent.png | 1 | published | stream id 1794253155274-0 | api:api1
fault-permanent.png | 1 | claimed | | wf-1
fault-permanent.png | 1 | failed | invalid_image; injected permanent failure | wf-1
fault-slow.png | 1 | accepted | | api
fault-slow.png | 1 | published | stream id 1794253167381-0 | api:api1
fault-slow.png | 1 | claimed | | wf-1
fault-slow.png | 1 | lease_expired | owner wf-1; next attempt 2 in 0.51s | worker:wf
fault-slow.png | 1 | redelivery_noop | stale_attempt | wf-0
fault-slow.png | 2 | published | stream id 1794253198039-0 | worker:wf
fault-slow.png | 2 | claimed | | wf-0
fault-slow.png | 2 | succeeded | thumbnail,crop,optimized | wf-0
fault-slow.png | 1 | lease_lost | result not published: lease token no longer valid | wf-1
fault-transient-until-3.png | 1 | accepted | | api
fault-transient-until-3.png | 1 | published | stream id 1794253152182-0 | api:api1
fault-transient-until-3.png | 1 | claimed | | wf-1
fault-transient-until-3.png | 1 | retry_scheduled | injected_transient; next attempt 2 in 0.79s | wf-1
fault-transient-until-3.png | 2 | published | stream id 1794253153023-0 | api:api1
fault-transient-until-3.png | 2 | claimed | | wf-0
fault-transient-until-3.png | 2 | retry_scheduled | injected_transient; next attempt 3 in 1.90s | wf-0
fault-transient-until-3.png | 3 | published | stream id 1794253154959-0 | worker:wf
fault-transient-until-3.png | 3 | claimed | | wf-0
fault-transient-until-3.png | 3 | succeeded | thumbnail,crop,optimized | wf-0
fault-transient-until-replay.png | 1 | accepted | | api
fault-transient-until-replay.png | 1 | published | stream id 1794253155506-0 | api:api1
fault-transient-until-replay.png | 1 | claimed | | wf-0
fault-transient-until-replay.png | 1 | retry_scheduled | injected_transient; next attempt 2 in 0.54s | wf-0
fault-transient-until-replay.png | 2 | published | stream id 1794253156965-0 | worker:wf
fault-transient-until-replay.png | 2 | claimed | | wf-1
fault-transient-until-replay.png | 2 | retry_scheduled | injected_transient; next attempt 3 in 1.97s | wf-1
fault-transient-until-replay.png | 3 | published | stream id 1794253158970-0 | worker:wf
fault-transient-until-replay.png | 3 | claimed | | wf-1
fault-transient-until-replay.png | 3 | retry_scheduled | injected_transient; next attempt 4 in 3.54s | wf-1
fault-transient-until-replay.png | 4 | published | stream id 1794253162979-0 | worker:wf
fault-transient-until-replay.png | 4 | claimed | | wf-1
fault-transient-until-replay.png | 4 | retry_scheduled | injected_transient; next attempt 5 in 2.54s | wf-1
fault-transient-until-replay.png | 5 | published | stream id 1794253165987-0 | worker:wf
fault-transient-until-replay.png | 5 | claimed | | wf-1
fault-transient-until-replay.png | 5 | failed | retry_exhausted; injected_transient | wf-1
fault-transient-until-replay.png | 6 | replayed | operator replay; new attempt 6 | test:replay
fault-transient-until-replay.png | 6 | published | stream id 1794253166991-0 | worker:wf
fault-transient-until-replay.png | 6 | claimed | | wf-0
fault-transient-until-replay.png | 6 | succeeded | thumbnail,crop,optimized | wf-0
fault-transient-until-replay.png | 6 | replay_refused | already succeeded (no duplicate execution) | test:replay
(67 rows)
+1
View File
@@ -0,0 +1 @@
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
+111
View File
@@ -0,0 +1,111 @@
== API, auth, concurrency, idempotency tests (DB/expiry tests skip without their env)
test_chat_list_pagination (test_api.ApiBehaviorTests.test_chat_list_pagination) ... ok
test_cursor_from_other_chat_returns_400 (test_api.ApiBehaviorTests.test_cursor_from_other_chat_returns_400) ... ok
test_duplicate_username_returns_409 (test_api.ApiBehaviorTests.test_duplicate_username_returns_409) ... ok
test_empty_message_returns_400 (test_api.ApiBehaviorTests.test_empty_message_returns_400) ... ok
test_malformed_json_returns_400 (test_api.ApiBehaviorTests.test_malformed_json_returns_400) ... ok
test_naive_timestamp_cursor_returns_400 (test_api.ApiBehaviorTests.test_naive_timestamp_cursor_returns_400) ... ok
test_outsider_cannot_access_chat (test_api.ApiBehaviorTests.test_outsider_cannot_access_chat) ... ok
test_pagination_returns_all_messages_without_duplicates (test_api.ApiBehaviorTests.test_pagination_returns_all_messages_without_duplicates) ... ok
test_password_never_returned (test_api.ApiBehaviorTests.test_password_never_returned) ... ok
test_registration_without_password_returns_400 (test_api.ApiBehaviorTests.test_registration_without_password_returns_400) ... ok
test_sender_id_in_body_rejected (test_api.ApiBehaviorTests.test_sender_id_in_body_rejected) ... ok
test_short_password_returns_400 (test_api.ApiBehaviorTests.test_short_password_returns_400) ... ok
test_crash_between_put_and_commit_dry_run_then_apply_then_noop (test_attachment_consistency.AttachmentConsistencyTests.test_crash_between_put_and_commit_dry_run_then_apply_then_noop) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_fresh_pending_is_kept (test_attachment_consistency.AttachmentConsistencyTests.test_fresh_pending_is_kept) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_missing_object_is_reported_not_deleted (test_attachment_consistency.AttachmentConsistencyTests.test_missing_object_is_reported_not_deleted) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_orphan_object_deleted_only_after_grace (test_attachment_consistency.AttachmentConsistencyTests.test_orphan_object_deleted_only_after_grace) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_pending_cannot_be_attached (test_attachment_consistency.AttachmentConsistencyTests.test_pending_cannot_be_attached) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_ready_and_referenced_are_never_collected (test_attachment_consistency.AttachmentConsistencyTests.test_ready_and_referenced_are_never_collected) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_aborted_upload_leaves_no_row_and_no_object (test_attachment_consistency.UploadFailureTests.test_aborted_upload_leaves_no_row_and_no_object) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_db_failure_after_put_returns_503_and_deletes_object (test_attachment_consistency.UploadFailureTests.test_db_failure_after_put_returns_503_and_deletes_object) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_process_crash_after_put_is_collected_by_gc (test_attachment_consistency.UploadFailureTests.test_process_crash_after_put_is_collected_by_gc) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_s3_put_failure_returns_503_and_compensates (test_attachment_consistency.UploadFailureTests.test_s3_put_failure_returns_503_and_compensates) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_attachment_from_other_chat_is_404_and_nothing_saved (test_attachments.AttachmentTests.test_attachment_from_other_chat_is_404_and_nothing_saved) ... ok
test_content_type_with_parameters_is_accepted (test_attachments.AttachmentTests.test_content_type_with_parameters_is_accepted) ... ok
test_corrupted_images_are_415 (test_attachments.AttachmentTests.test_corrupted_images_are_415) ... ok
test_dangerous_filenames_are_400 (test_attachments.AttachmentTests.test_dangerous_filenames_are_400) ... ok
test_exactly_max_size_is_accepted (test_attachments.AttachmentTests.test_exactly_max_size_is_accepted) ... ok
test_idempotency_includes_attachment_ids (test_attachments.AttachmentTests.test_idempotency_includes_attachment_ids) ... ok
test_invalid_and_unknown_attachment_ids (test_attachments.AttachmentTests.test_invalid_and_unknown_attachment_ids) ... ok
test_jpeg_baseline_and_progressive (test_attachments.AttachmentTests.test_jpeg_baseline_and_progressive) ... ok
test_message_attachment_validation (test_attachments.AttachmentTests.test_message_attachment_validation) ... ok
test_message_with_attachments_visible_to_members (test_attachments.AttachmentTests.test_message_with_attachments_visible_to_members) ... ok
test_mime_spoofing_is_415 (test_attachments.AttachmentTests.test_mime_spoofing_is_415) ... ok
test_original_variant_and_unknown_variants (test_attachments.AttachmentTests.test_original_variant_and_unknown_variants) ... ok
test_outsider_and_unknown_chat_upload_404 (test_attachments.AttachmentTests.test_outsider_and_unknown_chat_upload_404) ... ok
test_png_roundtrip_member_reads_outsider_404 (test_attachments.AttachmentTests.test_png_roundtrip_member_reads_outsider_404) ... ok
test_too_large_chunked_without_content_length (test_attachments.AttachmentTests.test_too_large_chunked_without_content_length) ... ok
test_too_large_with_content_length (test_attachments.AttachmentTests.test_too_large_with_content_length) ... ok
test_too_many_pixels (test_attachments.AttachmentTests.test_too_many_pixels) ... ok
test_basic_on_business_endpoint_rejected (test_auth.AuthTests.test_basic_on_business_endpoint_rejected) ... ok
test_login_with_body_rejected (test_auth.AuthTests.test_login_with_body_rejected)
Контракт: вход — только заголовок Basic, без тела. Лишний ввод -> 400, сессии нет. ... ok
test_logout_revokes_only_current_session (test_auth.AuthTests.test_logout_revokes_only_current_session) ... ok
test_malformed_basic_headers (test_auth.AuthTests.test_malformed_basic_headers) ... ok
test_password_with_colon_and_unicode (test_auth.AuthTests.test_password_with_colon_and_unicode) ... ok
test_session_shape_and_token_entropy (test_auth.AuthTests.test_session_shape_and_token_entropy) ... ok
test_unknown_and_garbage_tokens (test_auth.AuthTests.test_unknown_and_garbage_tokens) ... ok
test_wrong_password_and_unknown_user_look_the_same (test_auth.AuthTests.test_wrong_password_and_unknown_user_look_the_same) ... ok
test_x_user_id_gives_no_access (test_auth.AuthTests.test_x_user_id_gives_no_access) ... ok
test_duplicate_and_missing_caller_rejected (test_concurrency.ChatRollbackTests.test_duplicate_and_missing_caller_rejected) ... ok
test_unknown_member_rolls_back_whole_chat (test_concurrency.ChatRollbackTests.test_unknown_member_rolls_back_whole_chat)
Чат вставляется первым, затем участники по порядку (сначала сам владелец). ... ok
test_same_username_parallel_registration (test_concurrency.RegistrationRaceTests.test_same_username_parallel_registration) ... ok
test_session_expires_even_when_cached (test_expiry.ExpiryTests.test_session_expires_even_when_cached) ... skipped 'set EXPIRY_BASE_URL to the short-TTL API instance'
test_auth_checked_before_key (test_idempotency.IdempotencyTests.test_auth_checked_before_key) ... ok
test_concurrent_same_key_across_replicas_creates_one_message (test_idempotency.IdempotencyTests.test_concurrent_same_key_across_replicas_creates_one_message) ...
24 parallel POSTs, one key -> 1 message; replicas: ['api1', 'api2']
ok
test_concurrent_same_key_different_bodies_one_winner (test_idempotency.IdempotencyTests.test_concurrent_same_key_different_bodies_one_winner) ... ok
test_failed_access_does_not_burn_key (test_idempotency.IdempotencyTests.test_failed_access_does_not_burn_key) ... ok
test_json_formatting_and_key_order_do_not_matter (test_idempotency.IdempotencyTests.test_json_formatting_and_key_order_do_not_matter) ... ok
test_key_survives_new_session_of_same_user (test_idempotency.IdempotencyTests.test_key_survives_new_session_of_same_user) ... ok
test_missing_or_invalid_key_is_400 (test_idempotency.IdempotencyTests.test_missing_or_invalid_key_is_400) ... ok
test_replay_rechecks_session (test_idempotency.IdempotencyTests.test_replay_rechecks_session) ... ok
test_scope_is_user_and_chat (test_idempotency.IdempotencyTests.test_scope_is_user_and_chat) ... ok
test_sequential_replay_and_conflict (test_idempotency.IdempotencyTests.test_sequential_replay_and_conflict) ... ok
test_exif_orientation_applied_and_stripped (test_pipeline.PipelineTests.test_exif_orientation_applied_and_stripped) ... ok
test_fixture_320x200 (test_pipeline.PipelineTests.test_fixture_320x200) ... ok
test_progressive_jpeg (test_pipeline.PipelineTests.test_progressive_jpeg) ... ok
test_result_is_stable_and_private (test_pipeline.PipelineTests.test_result_is_stable_and_private) ... ok
test_small_source_not_upscaled_except_crop (test_pipeline.PipelineTests.test_small_source_not_upscaled_except_crop) ... ok
test_transparency_on_white (test_pipeline.PipelineTests.test_transparency_on_white) ... ok
test_unknown_variant_is_400 (test_pipeline.PipelineTests.test_unknown_variant_is_400) ... ok
test_a_crash_between_commit_and_publish (test_pipeline_faults.PipelineFaultTests.test_a_crash_between_commit_and_publish) ... skipped 'needs API at http://127.0.0.1:8090 and DB/S3/broker env'
test_b_crash_after_publish_duplicate_is_noop (test_pipeline_faults.PipelineFaultTests.test_b_crash_after_publish_duplicate_is_noop) ... skipped 'needs API at http://127.0.0.1:8090 and DB/S3/broker env'
test_c_worker_crash_after_side_effects_before_commit (test_pipeline_faults.PipelineFaultTests.test_c_worker_crash_after_side_effects_before_commit) ... skipped 'needs API at http://127.0.0.1:8090 and DB/S3/broker env'
test_d_worker_crash_after_commit_before_ack (test_pipeline_faults.PipelineFaultTests.test_d_worker_crash_after_commit_before_ack) ... skipped 'needs API at http://127.0.0.1:8090 and DB/S3/broker env'
test_e_transient_errors_retry_with_backoff (test_pipeline_faults.PipelineFaultTests.test_e_transient_errors_retry_with_backoff) ... skipped 'needs API at http://127.0.0.1:8090 and DB/S3/broker env'
test_f_permanent_error_fails_without_retry (test_pipeline_faults.PipelineFaultTests.test_f_permanent_error_fails_without_retry) ... skipped 'needs API at http://127.0.0.1:8090 and DB/S3/broker env'
test_g_retry_exhausted_dlq_then_explicit_replay (test_pipeline_faults.PipelineFaultTests.test_g_retry_exhausted_dlq_then_explicit_replay) ... skipped 'needs API at http://127.0.0.1:8090 and DB/S3/broker env'
test_h_hung_worker_lease_expires_and_is_fenced (test_pipeline_faults.PipelineFaultTests.test_h_hung_worker_lease_expires_and_is_fenced) ... skipped 'needs API at http://127.0.0.1:8090 and DB/S3/broker env'
test_i_staging_removed_after_safe_commit (test_pipeline_faults.PipelineFaultTests.test_i_staging_removed_after_safe_commit) ... skipped 'needs API at http://127.0.0.1:8090 and DB/S3/broker env'
test_j_garbage_broker_message_is_acked (test_pipeline_faults.PipelineFaultTests.test_j_garbage_broker_message_is_acked) ... skipped 'needs API at http://127.0.0.1:8090 and DB/S3/broker env'
test_debt_survives_api_restart (test_session_cache.SessionRevocationCacheTests.test_debt_survives_api_restart)
Процесс, выполнивший logout, умер до восстановления связи — новый процесс не доверяет кэшу. ... skipped 'DATABASE_URL is not configured'
test_normal_logout_leaves_no_debt (test_session_cache.SessionRevocationCacheTests.test_normal_logout_leaves_no_debt) ... skipped 'DATABASE_URL is not configured'
test_revoked_token_rejected_after_partition_heals (test_session_cache.SessionRevocationCacheTests.test_revoked_token_rejected_after_partition_heals) ... skipped 'DATABASE_URL is not configured'
test_cleanup_runs_on_one_replica_at_a_time (test_storage_idempotency.StorageIdempotencyTests.test_cleanup_runs_on_one_replica_at_a_time) ... skipped 'DATABASE_URL is not configured'
test_conflict_on_different_body (test_storage_idempotency.StorageIdempotencyTests.test_conflict_on_different_body) ... skipped 'DATABASE_URL is not configured'
test_expired_key_can_be_reused_and_is_cleaned (test_storage_idempotency.StorageIdempotencyTests.test_expired_key_can_be_reused_and_is_cleaned) ... skipped 'DATABASE_URL is not configured'
test_failure_inside_transaction_stores_nothing (test_storage_idempotency.StorageIdempotencyTests.test_failure_inside_transaction_stores_nothing) ... skipped 'DATABASE_URL is not configured'
test_threads_same_key_single_insert (test_storage_idempotency.StorageIdempotencyTests.test_threads_same_key_single_insert) ... skipped 'DATABASE_URL is not configured'
test_failure_after_inserts_leaves_nothing (test_storage_rollback.StorageRollbackTests.test_failure_after_inserts_leaves_nothing) ... skipped 'DATABASE_URL is not configured'
test_migrations_are_idempotent (test_storage_rollback.StorageRollbackTests.test_migrations_are_idempotent) ... skipped 'DATABASE_URL is not configured'
test_no_orphan_chats_in_database (test_storage_rollback.StorageRollbackTests.test_no_orphan_chats_in_database) ... skipped 'DATABASE_URL is not configured'
test_passwords_stored_as_argon2id (test_storage_rollback.StorageRollbackTests.test_passwords_stored_as_argon2id) ... skipped 'DATABASE_URL is not configured'
----------------------------------------------------------------------
Ran 91 tests in 11.178s
OK (skipped=33)
== Concurrent write test
PASS: concurrent write test; 10 clients x 10 messages = 100 messages; no lost or duplicate messages
ALL STUDENT TESTS PASSED
EXIT=0
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
EXIT=0
@@ -0,0 +1,8 @@
2026-11-09 22:39:08,453 ERROR messenger.worker FAULT_INJECTION: worker exits after S3 writes before COMMIT (job 689dc4ad-bf5d-4d33-a7f4-d557aef94b2a)
22:39:08 wf exited (os._exit(70)); supervisor restarts it like docker restart: unless-stopped
2026-11-09 22:39:09,883 INFO messenger.worker wf-1: recovering own unacked message 1794253148173-0
2026-11-09 22:39:10,530 ERROR messenger.worker FAULT_INJECTION: worker exits after COMMIT before XACK (job 6746ae17-f4cc-48b1-9864-c6e80507c2bf)
22:39:10 wf exited (os._exit(70)); supervisor restarts it like docker restart: unless-stopped
2026-11-09 22:39:11,945 INFO messenger.worker wf-0: recovering own unacked message 1794253150245-0
2026-11-09 22:39:57,386 INFO messenger.worker wf-0: claimed idle message 1794253167381-0 (deliveries=2)
2026-11-09 22:40:12,653 WARNING messenger.worker wf-1: lease lost for job acf17aa8-ef8d-4338-8beb-bd9bab29be8b; result not published (fenced)
@@ -0,0 +1,80 @@
[
{
"seconds": 0.02,
"step": "worker stopped",
"t": 0.14
},
{
"status": 202,
"attachment_id": "3985fc73-5e47-411d-8d68-c44551e77cb9",
"attachment_status": "queued",
"step": "upload accepted",
"t": 0.15
},
{
"metadata_status": "queued",
"content_status": 409,
"message_with_attachment": 201,
"plain_message": 201,
"message_id": "d589ad3f-63a3-4258-a981-701a2a7bfb5e",
"step": "while worker is down",
"t": 3.17
},
{
"length": 1,
"lag": 1,
"pending": 0,
"jobs": {
"succeeded": 32,
"failed": 1,
"queued": 1
},
"outbox_rows": 0,
"step": "broker before restarts",
"t": 3.37
},
{
"seconds": 3.06,
"step": "api replicas restarted",
"t": 6.43
},
{
"seconds": 2.03,
"step": "broker restarted (volume kept)",
"t": 8.46
},
{
"metadata_status": "queued",
"length": 1,
"lag": 1,
"pending": 0,
"jobs": {
"succeeded": 32,
"failed": 1,
"queued": 1
},
"outbox_rows": 0,
"step": "after restarts",
"t": 10.66
},
{
"seconds": 3.01,
"step": "worker started",
"t": 13.67
},
{
"attachment_id": "3985fc73-5e47-411d-8d68-c44551e77cb9",
"variants": [
"thumbnail",
"crop",
"optimized"
],
"thumbnail_jpeg_size": [
256,
160
],
"original_sha256_ok": true,
"step": "ready",
"t": 13.7
}
]
@@ -0,0 +1,11 @@
{"seconds": 0.02, "step": "worker stopped", "t": 0.14}
{"status": 202, "attachment_id": "3985fc73-5e47-411d-8d68-c44551e77cb9", "attachment_status": "queued", "step": "upload accepted", "t": 0.15}
{"metadata_status": "queued", "content_status": 409, "message_with_attachment": 201, "plain_message": 201, "message_id": "d589ad3f-63a3-4258-a981-701a2a7bfb5e", "step": "while worker is down", "t": 3.17}
{"length": 1, "lag": 1, "pending": 0, "jobs": {"succeeded": 32, "failed": 1, "queued": 1}, "outbox_rows": 0, "step": "broker before restarts", "t": 3.37}
{"seconds": 3.06, "step": "api replicas restarted", "t": 6.43}
{"seconds": 2.03, "step": "broker restarted (volume kept)", "t": 8.46}
{"metadata_status": "queued", "length": 1, "lag": 1, "pending": 0, "jobs": {"succeeded": 32, "failed": 1, "queued": 1}, "outbox_rows": 0, "step": "after restarts", "t": 10.66}
{"seconds": 3.01, "step": "worker started", "t": 13.67}
{"attachment_id": "3985fc73-5e47-411d-8d68-c44551e77cb9", "variants": ["thumbnail", "crop", "optimized"], "thumbnail_jpeg_size": [256, 160], "original_sha256_ok": true, "step": "ready", "t": 13.7}
PASS: accepted job survived worker stop + API restart + broker restart and became ready
EXIT=0
+53
View File
@@ -0,0 +1,53 @@
# 2026-11-10 14:24:42 UTC | Persistence: контейнеры до | exit 0 | 0.3s
$ docker compose --env-file .env ps -a --format table {{.Name}} {{.Status}} {{.RunningFor}}
NAME STATUS CREATED
messenger-lab5-api-5 Up 33 seconds (healthy) 34 seconds ago
messenger-lab5-api-6 Up 22 seconds (healthy) 22 seconds ago
messenger-lab5-broker-1 Up 3 minutes (healthy) 39 minutes ago
messenger-lab5-lb-1 Up 24 minutes (healthy) 39 minutes ago
messenger-lab5-migrate-1 Exited (0) 3 minutes ago 39 minutes ago
messenger-lab5-postgres-1 Up 25 minutes (healthy) 39 minutes ago
messenger-lab5-redis-1 Up 25 minutes (healthy) 39 minutes ago
messenger-lab5-s3-1 Up 4 minutes (healthy) 39 minutes ago
messenger-lab5-s3-init-1 Exited (0) 3 minutes ago 39 minutes ago
messenger-lab5-worker-1 Up About a minute (healthy) About a minute ago
# 2026-11-10 14:25:27 UTC | Persistence: make test-persistence (API + worker + PostgreSQL + Redis + broker + S3 + LB) | exit 0 | 45.1s
$ python tests/resilience.py --mode persistence --action-script scripts\restart.cmd --base-url http://127.0.0.1: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.
# 2026-11-10 14:25:27 UTC | Persistence: контейнеры после (Status = Up N seconds) | exit 0 | 0.3s
$ docker compose --env-file .env ps -a --format table {{.Name}} {{.Status}} {{.RunningFor}}
NAME STATUS CREATED
messenger-lab5-api-5 Up 7 seconds (healthy) About a minute ago
messenger-lab5-api-6 Up 7 seconds (healthy) About a minute ago
messenger-lab5-broker-1 Up 37 seconds (healthy) 40 minutes ago
messenger-lab5-lb-1 Up Less than a second (health: starting) 40 minutes ago
messenger-lab5-migrate-1 Exited (0) 4 minutes ago 40 minutes ago
messenger-lab5-postgres-1 Up 37 seconds (healthy) 40 minutes ago
messenger-lab5-redis-1 Up 37 seconds (healthy) 40 minutes ago
messenger-lab5-s3-1 Up 27 seconds (healthy) 40 minutes ago
messenger-lab5-s3-init-1 Exited (0) 4 minutes ago 40 minutes ago
messenger-lab5-worker-1 Up 7 seconds (healthy) 2 minutes ago
# 2026-11-10 14:25:30 UTC | Persistence: сверка БД <-> S3 после рестарта | exit 0 | 2.9s
$ python scripts/ops.py reconcile
Container messenger-lab5-api-run-467cf1258171 Creating
Container messenger-lab5-api-run-467cf1258171 Created
{
"mode": "dry-run",
"grace_seconds": 900,
"stale_pending": 0,
"stale_pending_ids": [],
"staging_to_clean": 1,
"objects_listed": 640,
"orphan_objects": 0,
"orphan_objects_within_grace": 0,
"orphan_objects_sample": [],
"bucket_scan_seconds": 0.211,
"ready_rows": 637,
"missing_objects": 0,
"missing_object_ids": [],
"total_seconds": 0.229
}
+14
View File
@@ -0,0 +1,14 @@
# 2026-11-10 14:20:25 UTC | Варианты изображений по фактическим байтам (test_pipeline.py) | exit 0 | 6.6s
$ python -m unittest discover -s student-tests -p test_pipeline.py -v
test_exif_orientation_applied_and_stripped (test_pipeline.PipelineTests.test_exif_orientation_applied_and_stripped) ... ok
test_fixture_320x200 (test_pipeline.PipelineTests.test_fixture_320x200) ... ok
test_progressive_jpeg (test_pipeline.PipelineTests.test_progressive_jpeg) ... ok
test_result_is_stable_and_private (test_pipeline.PipelineTests.test_result_is_stable_and_private) ... ok
test_small_source_not_upscaled_except_crop (test_pipeline.PipelineTests.test_small_source_not_upscaled_except_crop) ... ok
test_transparency_on_white (test_pipeline.PipelineTests.test_transparency_on_white) ... ok
test_unknown_variant_is_400 (test_pipeline.PipelineTests.test_unknown_variant_is_400) ... ok
----------------------------------------------------------------------
Ran 7 tests in 6.481s
OK
+152
View File
@@ -0,0 +1,152 @@
# 2026-11-10 14:23:04 UTC | Уровень 4: внедрённые отказы pipeline (outbox, crash до/после ack, retry, DLQ, replay, lease) | exit 0 | 126.3s
$ python scripts/ops.py pipeline-faults
2026-11-10T14:20:58.422Z pipeline-faults: recreating worker with compose.faults.yaml
Container messenger-lab5-postgres-1 Running
Container messenger-lab5-s3-1 Running
Container messenger-lab5-api-1 Running
Container messenger-lab5-api-2 Running
Container messenger-lab5-redis-1 Running
Container messenger-lab5-api-fault-publish-1 Creating
Container messenger-lab5-api-fault-dup-1 Creating
Container messenger-lab5-api-fault-publish-1 Created
Container messenger-lab5-api-fault-dup-1 Created
Container messenger-lab5-s3-1 Waiting
Container messenger-lab5-postgres-1 Waiting
Container messenger-lab5-postgres-1 Healthy
Container messenger-lab5-migrate-1 Starting
Container messenger-lab5-s3-1 Healthy
Container messenger-lab5-s3-init-1 Starting
Container messenger-lab5-migrate-1 Started
Container messenger-lab5-s3-init-1 Started
Container messenger-lab5-migrate-1 Waiting
Container messenger-lab5-s3-init-1 Waiting
Container messenger-lab5-postgres-1 Waiting
Container messenger-lab5-redis-1 Waiting
Container messenger-lab5-redis-1 Healthy
Container messenger-lab5-postgres-1 Healthy
Container messenger-lab5-migrate-1 Exited
Container messenger-lab5-s3-init-1 Exited
Container messenger-lab5-api-1 Waiting
Container messenger-lab5-api-2 Waiting
Container messenger-lab5-api-1 Waiting
Container messenger-lab5-api-2 Waiting
Container messenger-lab5-api-1 Healthy
Container messenger-lab5-api-2 Healthy
Container messenger-lab5-api-fault-dup-1 Starting
Container messenger-lab5-api-1 Healthy
Container messenger-lab5-api-2 Healthy
Container messenger-lab5-api-fault-publish-1 Starting
Container messenger-lab5-api-fault-dup-1 Started
Container messenger-lab5-api-fault-publish-1 Started
Container messenger-lab5-api-run-f6d1d1271d68 Creating
Container messenger-lab5-api-run-f6d1d1271d68 Created
ready: http://api-fault-publish:8080/health/ready
Container messenger-lab5-api-run-0c827bfb627f Creating
Container messenger-lab5-api-run-0c827bfb627f Created
ready: http://api-fault-dup:8080/health/ready
Container messenger-lab5-api-run-6e712120049d Creating
Container messenger-lab5-api-run-6e712120049d Created
test_a_crash_between_commit_and_publish (test_pipeline_faults.PipelineFaultTests.test_a_crash_between_commit_and_publish) ... ok
test_b_crash_after_publish_duplicate_is_noop (test_pipeline_faults.PipelineFaultTests.test_b_crash_after_publish_duplicate_is_noop) ... ok
test_c_worker_crash_after_side_effects_before_commit (test_pipeline_faults.PipelineFaultTests.test_c_worker_crash_after_side_effects_before_commit) ... ok
test_d_worker_crash_after_commit_before_ack (test_pipeline_faults.PipelineFaultTests.test_d_worker_crash_after_commit_before_ack) ... ok
test_e_transient_errors_retry_with_backoff (test_pipeline_faults.PipelineFaultTests.test_e_transient_errors_retry_with_backoff) ... ok
test_f_permanent_error_fails_without_retry (test_pipeline_faults.PipelineFaultTests.test_f_permanent_error_fails_without_retry) ... ok
test_g_retry_exhausted_dlq_then_explicit_replay (test_pipeline_faults.PipelineFaultTests.test_g_retry_exhausted_dlq_then_explicit_replay) ... ok
test_h_hung_worker_lease_expires_and_is_fenced (test_pipeline_faults.PipelineFaultTests.test_h_hung_worker_lease_expires_and_is_fenced) ... ok
test_i_staging_removed_after_safe_commit (test_pipeline_faults.PipelineFaultTests.test_i_staging_removed_after_safe_commit) ... /usr/local/lib/python3.12/site-packages/botocore/auth.py:424: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
datetime_now = datetime.datetime.utcnow()
ok
test_j_garbage_broker_message_is_acked (test_pipeline_faults.PipelineFaultTests.test_j_garbage_broker_message_is_acked) ... ok
----------------------------------------------------------------------
Ran 10 tests in 90.529s
OK
2026-11-10T14:23:04.629Z pipeline-faults: worker restored to normal configuration
# 2026-11-10 14:23:06 UTC | Очередь после сценариев: задания, outbox, DLQ, lag | exit 0 | 1.7s
$ python scripts/ops.py jobs stats
Container messenger-lab5-worker-run-e232ea69a3ca Creating
Container messenger-lab5-worker-run-e232ea69a3ca Created
{
"jobs": {
"succeeded": 158,
"failed": 2
},
"attachments": {
"ready": 159,
"failed": 2
},
"outbox": {
"rows": 0,
"due": 0,
"oldest_age_s": 0.0
},
"dead_letters_unreplayed": 2,
"oldest_unfinished_job_age_s": 0.0,
"broker": {
"stream": "attachments.jobs",
"length": 4,
"groups": [
{
"name": "attachment-workers",
"consumers": 10,
"pending": 0,
"lag": 0,
"last_delivered_id": "1794320565944-0"
}
]
}
}
# 2026-11-10 14:23:07 UTC | Реестр failed (DLQ) | exit 0 | 1.6s
$ python scripts/ops.py jobs failed --limit 10
Container messenger-lab5-worker-run-85c598896740 Creating
Container messenger-lab5-worker-run-85c598896740 Created
[
{
"attachment_id": "9f72cadb-e186-43cb-8456-ee1d5f3bde45",
"job_id": "05c07c99-eda0-4dbe-b49e-98d1426f3933",
"error_code": "retry_exhausted",
"attempts": 5,
"failed_at": "2026-11-10 14:21:41.960496+00:00",
"replayed_at": "2026-11-10 14:21:42.086003+00:00",
"replay_count": 1,
"job_status": "succeeded",
"replayable": false
},
{
"attachment_id": "390e3a82-63cd-4a64-a50c-a200f68924c4",
"job_id": "bfe81165-4f51-445a-bf37-07e61e527985",
"error_code": "invalid_image",
"attempts": 1,
"failed_at": "2026-11-10 14:21:32.124484+00:00",
"replayed_at": null,
"replay_count": 0,
"job_status": "failed",
"replayable": true
},
{
"attachment_id": "5c05fbd5-77b0-4554-87bd-5b315aea3b82",
"job_id": "d9f58adb-d682-4d2f-a94c-16f2ce326ec7",
"error_code": "retry_exhausted",
"attempts": 5,
"failed_at": "2026-11-10 14:09:44.857997+00:00",
"replayed_at": "2026-11-10 14:09:44.981918+00:00",
"replay_count": 1,
"job_status": "succeeded",
"replayable": false
},
{
"attachment_id": "5a2d84b3-b13f-4c34-83e5-65f42b792752",
"job_id": "41cdf50b-cfd4-4a88-864c-f5a918948014",
"error_code": "invalid_image",
"attempts": 1,
"failed_at": "2026-11-10 14:09:34.398249+00:00",
"replayed_at": null,
"replay_count": 0,
"job_status": "failed",
"replayable": true
}
]
+20
View File
@@ -0,0 +1,20 @@
# 2026-11-10 14:15:14 UTC | Сверка БД <-> S3 (dry-run) | exit 0 | 2.5s
$ python scripts/ops.py reconcile
Container messenger-lab5-api-run-864f3258a8e5 Creating
Container messenger-lab5-api-run-864f3258a8e5 Created
{
"mode": "dry-run",
"grace_seconds": 900,
"stale_pending": 0,
"stale_pending_ids": [],
"staging_to_clean": 0,
"objects_listed": 266,
"orphan_objects": 0,
"orphan_objects_within_grace": 0,
"orphan_objects_sample": [],
"bucket_scan_seconds": 0.053,
"ready_rows": 265,
"missing_objects": 0,
"missing_object_ids": [],
"total_seconds": 0.066
}
+147
View File
@@ -0,0 +1,147 @@
{
"scenario": "rolling update of all API replicas under continuous load",
"update_command": "scripts/ops.py rolling-update",
"update_exit_code": 0,
"update_seconds": 29.78,
"replicas_before": [
"cb14462a28f6",
"cc4d20e47b36"
],
"replicas_after": [
"9adbb2f64abd",
"cec102b25e41"
],
"all_replaced": true,
"errors_during_update": 0,
"error_kinds": [],
"windows": {
"before": {
"from_s": 0,
"to_s": 5.0,
"requests": 1438,
"ok": 1438,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 287.6,
"write_ok_rps": 163.2,
"latency_ms_ok": {
"p50": 16.0,
"p95": 63.0,
"p99": 109.0
},
"instances": [
"cb14462a28f6",
"cc4d20e47b36"
]
},
"during_update": {
"from_s": 5.0,
"to_s": 34.78,
"requests": 8087,
"ok": 8087,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 271.5,
"write_ok_rps": 160.1,
"latency_ms_ok": {
"p50": 16.0,
"p95": 78.0,
"p99": 109.0
},
"instances": [
"9adbb2f64abd",
"cb14462a28f6",
"cc4d20e47b36",
"cec102b25e41"
]
},
"after": {
"from_s": 34.78,
"to_s": 42.83,
"requests": 1845,
"ok": 1845,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 229.3,
"write_ok_rps": 137.2,
"latency_ms_ok": {
"p50": 16.0,
"p95": 79.0,
"p99": 140.0
},
"instances": [
"9adbb2f64abd",
"cec102b25e41"
]
}
},
"lb_timeline": [
[
0.0,
[
"api1",
"api3"
]
],
[
11.92,
[
"api1",
"api2",
"api3"
]
],
[
12.66,
[
"api1",
"api3"
]
],
[
15.09,
[
"api1",
"api2",
"api3"
]
],
[
19.36,
[
"api1",
"api2"
]
],
[
26.97,
[
"api1",
"api2",
"api3"
]
],
[
30.62,
[
"api2",
"api3"
]
]
],
"data": {
"confirmed_writes": 6690,
"stored_messages": 6690,
"missing_or_altered": 0,
"duplicate_ids": 0,
"duplicate_texts": 0,
"same_key_retries": 0,
"ok": true
},
"load": {
"writers": 4,
"readers": 2,
"client_timeout_s": 2.0
},
"pass": true
}
+147
View File
@@ -0,0 +1,147 @@
{
"scenario": "rolling update of all API replicas under continuous load",
"update_command": "scripts/ops.py rolling-update",
"update_exit_code": 0,
"update_seconds": 31.98,
"replicas_before": [
"3a0e06f14a63",
"4b1faad0399c"
],
"replicas_after": [
"cb14462a28f6",
"cc4d20e47b36"
],
"all_replaced": true,
"errors_during_update": 0,
"error_kinds": [],
"windows": {
"before": {
"from_s": 0,
"to_s": 5.0,
"requests": 1190,
"ok": 1190,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 238.0,
"write_ok_rps": 141.0,
"latency_ms_ok": {
"p50": 16.0,
"p95": 78.0,
"p99": 109.0
},
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
]
},
"during_update": {
"from_s": 5.0,
"to_s": 36.98,
"requests": 7392,
"ok": 7392,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 231.1,
"write_ok_rps": 135.8,
"latency_ms_ok": {
"p50": 16.0,
"p95": 93.0,
"p99": 141.0
},
"instances": [
"3a0e06f14a63",
"4b1faad0399c",
"cb14462a28f6",
"cc4d20e47b36"
]
},
"after": {
"from_s": 36.98,
"to_s": 45.02,
"requests": 2038,
"ok": 2038,
"errors": 0,
"error_ratio": 0.0,
"ok_rps": 253.7,
"write_ok_rps": 150.0,
"latency_ms_ok": {
"p50": 16.0,
"p95": 78.0,
"p99": 109.0
},
"instances": [
"cb14462a28f6",
"cc4d20e47b36"
]
}
},
"lb_timeline": [
[
0.0,
[
"api1",
"api2"
]
],
[
14.41,
[
"api1",
"api2",
"api3"
]
],
[
15.08,
[
"api1",
"api2"
]
],
[
17.67,
[
"api1",
"api2",
"api3"
]
],
[
22.42,
[
"api2",
"api3"
]
],
[
30.97,
[
"api1",
"api2",
"api3"
]
],
[
33.14,
[
"api1",
"api3"
]
]
],
"data": {
"confirmed_writes": 6255,
"stored_messages": 6255,
"missing_or_altered": 0,
"duplicate_ids": 0,
"duplicate_texts": 0,
"same_key_retries": 0,
"ok": true
},
"load": {
"writers": 4,
"readers": 2,
"client_timeout_s": 2.0
},
"pass": true
}
+29
View File
@@ -0,0 +1,29 @@
# 2026-11-10 14:23:55 UTC | Rolling update lab5 -> lab5.1 под нагрузкой | exit 0 | 47.5s
$ python student-tests/rolling_update_load.py --base-url http://127.0.0.1:8080 --output evidence/rolling_update.json
replicas before: ['3a0e06f14a63', '4b1faad0399c']
2026-11-10T14:23:14.819Z rolling-update: start; replicas=2 old=['4b1faad0399c', '3a0e06f14a63']
2026-11-10T14:23:20.086Z rolling-update: images built in 5.3s (tag lab5.1)
2026-11-10T14:23:22.594Z rolling-update: migrations once in 2.5s: schema is up to date; nothing applied
2026-11-10T14:23:34.419Z rolling-update: step 1/2 new=cb14462a28f6 (messenger-api:lab5.1, ready+UP in 7.5s) replaced old=4b1faad0399c (graceful stop 4.1s)
2026-11-10T14:23:46.022Z rolling-update: step 2/2 new=cc4d20e47b36 (messenger-api:lab5.1, ready+UP in 7.0s) replaced old=3a0e06f14a63 (graceful stop 4.4s)
2026-11-10T14:23:46.260Z rolling-update: done in 31.8s; replicas now ['cb14462a28f6', 'cc4d20e47b36']
update 32.0s rc=0 | replicas ['3a0e06f14a63', '4b1faad0399c'] -> ['cb14462a28f6', 'cc4d20e47b36'] | errors during update 0 (-) | RPS before 238.0, during 231.1, after 253.7 | p95 during 93.0 ms | data ok=True
PASS: rolling update under load
# 2026-11-10 14:24:41 UTC | Rolling update обратно lab5.1 -> lab5 (откат) под нагрузкой | exit 0 | 45.9s
$ python student-tests/rolling_update_load.py --base-url http://127.0.0.1:8080 --output evidence/rolling_back.json
replicas before: ['cb14462a28f6', 'cc4d20e47b36']
2026-11-10T14:24:02.303Z rolling-update: start; replicas=2 old=['cb14462a28f6', 'cc4d20e47b36']
2026-11-10T14:24:05.202Z rolling-update: images built in 2.9s (tag lab5)
2026-11-10T14:24:07.607Z rolling-update: migrations once in 2.4s: schema is up to date; nothing applied
2026-11-10T14:24:19.412Z rolling-update: step 1/2 new=cec102b25e41 (messenger-api:lab5, ready+UP in 7.2s) replaced old=cb14462a28f6 (graceful stop 4.4s)
2026-11-10T14:24:31.138Z rolling-update: step 2/2 new=9adbb2f64abd (messenger-api:lab5, ready+UP in 7.1s) replaced old=cc4d20e47b36 (graceful stop 4.4s)
2026-11-10T14:24:31.579Z rolling-update: done in 29.5s; replicas now ['cec102b25e41', '9adbb2f64abd']
update 29.8s rc=0 | replicas ['cb14462a28f6', 'cc4d20e47b36'] -> ['9adbb2f64abd', 'cec102b25e41'] | errors during update 0 (-) | RPS before 287.6, during 271.5, after 229.3 | p95 during 78.0 ms | data ok=True
PASS: rolling update under load
# 2026-11-10 14:24:41 UTC | Реплики после обновлений | exit 0 | 0.3s
$ python scripts/ops.py ps
X-Instance-Id container state health image lb lb_status
cec102b25e41 messenger-lab5-api-5 running healthy messenger-api:lab5 api2 UP
9adbb2f64abd messenger-lab5-api-6 running healthy messenger-api:lab5 api3 UP
+225
View File
@@ -0,0 +1,225 @@
# 2026-11-10 14:13:53 UTC | S3 bootstrap: лог первого запуска s3-init | exit 0 | 0.3s
$ docker compose --env-file .env logs --no-color s3-init
s3-init-1 | {
s3-init-1 | "endpoint_host": "s3",
s3-init-1 | "bucket": "messenger-attachments",
s3-init-1 | "checks": [
s3-init-1 | {
s3-init-1 | "check": "api credentials: put/get own bucket",
s3-init-1 | "ok": true,
s3-init-1 | "detail": ""
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "anonymous GET object is denied",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "HTTP 403"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "anonymous list bucket is denied",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "HTTP 403"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "anonymous list buckets is denied",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "HTTP 403"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "api credentials cannot create buckets",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "AccessDenied"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "api credentials cannot delete the bucket",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "AccessDenied"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "SeaweedFS admin/UI ports are not reachable on the shared network",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "checked [9333, 8888, 8080, 19333, 18888]"
s3-init-1 | }
s3-init-1 | ],
s3-init-1 | "bucket_action": "created",
s3-init-1 | "ok": true
s3-init-1 | }
s3-init-1 | {
s3-init-1 | "endpoint_host": "s3",
s3-init-1 | "bucket": "messenger-attachments",
s3-init-1 | "checks": [
s3-init-1 | {
s3-init-1 | "check": "api credentials: put/get own bucket",
s3-init-1 | "ok": true,
s3-init-1 | "detail": ""
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "anonymous GET object is denied",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "HTTP 403"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "anonymous list bucket is denied",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "HTTP 403"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "anonymous list buckets is denied",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "HTTP 403"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "api credentials cannot create buckets",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "AccessDenied"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "api credentials cannot delete the bucket",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "AccessDenied"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "SeaweedFS admin/UI ports are not reachable on the shared network",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "checked [9333, 8888, 8080, 19333, 18888]"
s3-init-1 | }
s3-init-1 | ],
s3-init-1 | "bucket_action": "already exists (idempotent no-op)",
s3-init-1 | "ok": true
s3-init-1 | }
s3-init-1 | {
s3-init-1 | "endpoint_host": "s3",
s3-init-1 | "bucket": "messenger-attachments",
s3-init-1 | "checks": [
s3-init-1 | {
s3-init-1 | "check": "api credentials: put/get own bucket",
s3-init-1 | "ok": true,
s3-init-1 | "detail": ""
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "anonymous GET object is denied",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "HTTP 403"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "anonymous list bucket is denied",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "HTTP 403"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "anonymous list buckets is denied",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "HTTP 403"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "api credentials cannot create buckets",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "AccessDenied"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "api credentials cannot delete the bucket",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "AccessDenied"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "SeaweedFS admin/UI ports are not reachable on the shared network",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "checked [9333, 8888, 8080, 19333, 18888]"
s3-init-1 | }
s3-init-1 | ],
s3-init-1 | "bucket_action": "already exists (idempotent no-op)",
s3-init-1 | "ok": true
s3-init-1 | }
s3-init-1 | {
s3-init-1 | "endpoint_host": "s3",
s3-init-1 | "bucket": "messenger-attachments",
s3-init-1 | "checks": [
s3-init-1 | {
s3-init-1 | "check": "api credentials: put/get own bucket",
s3-init-1 | "ok": true,
s3-init-1 | "detail": ""
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "anonymous GET object is denied",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "HTTP 403"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "anonymous list bucket is denied",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "HTTP 403"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "anonymous list buckets is denied",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "HTTP 403"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "api credentials cannot create buckets",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "AccessDenied"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "api credentials cannot delete the bucket",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "AccessDenied"
s3-init-1 | },
s3-init-1 | {
s3-init-1 | "check": "SeaweedFS admin/UI ports are not reachable on the shared network",
s3-init-1 | "ok": true,
s3-init-1 | "detail": "checked [9333, 8888, 8080, 19333, 18888]"
s3-init-1 | }
s3-init-1 | ],
s3-init-1 | "bucket_action": "already exists (idempotent no-op)",
s3-init-1 | "ok": true
s3-init-1 | }
# 2026-11-10 14:14:03 UTC | S3 bootstrap: повторный запуск (идемпотентность) | exit 0 | 9.6s
$ docker compose --env-file .env run --rm -T s3-init
Container messenger-lab5-s3-1 Running
Container messenger-lab5-s3-1 Waiting
Container messenger-lab5-s3-1 Healthy
Container messenger-lab5-s3-init-run-ac08328e286f Creating
Container messenger-lab5-s3-init-run-ac08328e286f Created
{
"endpoint_host": "s3",
"bucket": "messenger-attachments",
"checks": [
{
"check": "api credentials: put/get own bucket",
"ok": true,
"detail": ""
},
{
"check": "anonymous GET object is denied",
"ok": true,
"detail": "HTTP 403"
},
{
"check": "anonymous list bucket is denied",
"ok": true,
"detail": "HTTP 403"
},
{
"check": "anonymous list buckets is denied",
"ok": true,
"detail": "HTTP 403"
},
{
"check": "api credentials cannot create buckets",
"ok": true,
"detail": "AccessDenied"
},
{
"check": "api credentials cannot delete the bucket",
"ok": true,
"detail": "AccessDenied"
},
{
"check": "SeaweedFS admin/UI ports are not reachable on the shared network",
"ok": true,
"detail": "checked [9333, 8888, 8080, 19333, 18888]"
}
],
"bucket_action": "already exists (idempotent no-op)",
"ok": true
}
+98
View File
@@ -0,0 +1,98 @@
{
"scenario": "S3 outage and recovery",
"max_fail_seconds": 15.0,
"s3_warmup_seconds": 19.66,
"checks": [
{
"check": "baseline upload 202 (lab5)",
"ok": true,
"detail": "202"
},
{
"check": "readiness stays 200 while S3 is down (S3 is not a readiness dependency)",
"ok": true,
"detail": "200"
},
{
"check": "text message 201 during S3 outage",
"ok": true,
"detail": "201"
},
{
"check": "history 200 during S3 outage",
"ok": true,
"detail": "200"
},
{
"check": "attachment metadata 200 (PostgreSQL only)",
"ok": true,
"detail": "200"
},
{
"check": "message referencing existing attachment 201",
"ok": true,
"detail": "201"
},
{
"check": "upload #1 -> 503 unavailable",
"ok": true,
"detail": "503 unavailable in 5.06s"
},
{
"check": "upload #1 failed fast (<= 15s)",
"ok": true,
"detail": "5.06s"
},
{
"check": "upload #1 has Retry-After",
"ok": true,
"detail": ""
},
{
"check": "upload #2 -> 503 unavailable",
"ok": true,
"detail": "503 unavailable in 5.33s"
},
{
"check": "upload #2 failed fast (<= 15s)",
"ok": true,
"detail": "5.33s"
},
{
"check": "upload #2 has Retry-After",
"ok": true,
"detail": ""
},
{
"check": "download -> 503 during outage",
"ok": true,
"detail": "503 in 5.01s"
},
{
"check": "download failed fast",
"ok": true,
"detail": "5.01s"
},
{
"check": "session still valid",
"ok": true,
"detail": "200"
},
{
"check": "S3 read/write warm-up after start",
"ok": true,
"detail": "19.66s"
},
{
"check": "old file downloads byte-for-byte after recovery",
"ok": true,
"detail": "200 0.02s"
},
{
"check": "new upload 202 after recovery (same token, no API restart)",
"ok": true,
"detail": "202"
}
],
"pass": true
}
+24
View File
@@ -0,0 +1,24 @@
# 2026-11-10 14:20:18 UTC | Недоступность S3 и восстановление | exit 0 | 47.3s
$ python student-tests/s3_outage.py --base-url http://127.0.0.1:8080 --output evidence/s3_outage.json
PASS baseline upload 202 (lab5) — 202
$ docker compose --env-file .env stop s3
PASS readiness stays 200 while S3 is down (S3 is not a readiness dependency) — 200
PASS text message 201 during S3 outage — 201
PASS history 200 during S3 outage — 200
PASS attachment metadata 200 (PostgreSQL only) — 200
PASS message referencing existing attachment 201 — 201
PASS upload #1 -> 503 unavailable — 503 unavailable in 5.06s
PASS upload #1 failed fast (<= 15s) — 5.06s
PASS upload #1 has Retry-After
PASS upload #2 -> 503 unavailable — 503 unavailable in 5.33s
PASS upload #2 failed fast (<= 15s) — 5.33s
PASS upload #2 has Retry-After
PASS download -> 503 during outage — 503 in 5.01s
PASS download failed fast — 5.01s
PASS session still valid — 200
$ docker compose --env-file .env start s3
$ C:\Users\mrend\AppData\Local\Programs\Python\Python312\python.exe scripts/ops.py wait-s3
PASS S3 read/write warm-up after start — 19.66s
PASS old file downloads byte-for-byte after recovery — 200 0.02s
PASS new upload 202 after recovery (same token, no API restart) — 202
PASS
+67
View File
@@ -0,0 +1,67 @@
# 2026-11-10 14:15:16 UTC | Приватный бакет вне API, права ключей, закрытые админ-порты | exit 0 | 2.6s
$ python scripts/ops.py s3-check
Container messenger-lab5-api-run-796deabd49b0 Creating
Container messenger-lab5-api-run-796deabd49b0 Created
{
"endpoint_host": "s3",
"bucket": "messenger-attachments",
"checks": [
{
"check": "api credentials: put/get own bucket",
"ok": true,
"detail": ""
},
{
"check": "anonymous GET object is denied",
"ok": true,
"detail": "HTTP 403"
},
{
"check": "anonymous list bucket is denied",
"ok": true,
"detail": "HTTP 403"
},
{
"check": "anonymous list buckets is denied",
"ok": true,
"detail": "HTTP 403"
},
{
"check": "api credentials cannot create buckets",
"ok": true,
"detail": "AccessDenied"
},
{
"check": "api credentials cannot delete the bucket",
"ok": true,
"detail": "AccessDenied"
},
{
"check": "SeaweedFS admin/UI ports are not reachable on the shared network",
"ok": true,
"detail": "checked [9333, 8888, 8080, 19333, 18888]"
},
{
"check": "anonymous GET of a real attachment object is denied",
"ok": true,
"detail": "HTTP 403"
},
{
"check": "same object is readable with API credentials and matches sha256",
"ok": true,
"detail": "111817 bytes"
}
],
"ok": true
}
# 2026-11-10 14:15:17 UTC | На API нет хранилища оригиналов: read-only rootfs, только tmpfs, без volumes | exit 0 | 0.5s
$ python scripts/ops.py api-fs
messenger-lab5-api-1 ReadonlyRootfs=True Tmpfs={'/tmp': 'size=16m'} Mounts=['bind:/run/secrets/broker_url', 'bind:/run/secrets/cache_url', 'bind:/run/secrets/database_url', 'bind:/run/secrets/s3_access_key_id', 'bind:/run/secrets/s3_secret_access_key']
messenger-lab5-api-2 ReadonlyRootfs=True Tmpfs={'/tmp': 'size=16m'} Mounts=['bind:/run/secrets/broker_url', 'bind:/run/secrets/cache_url', 'bind:/run/secrets/database_url', 'bind:/run/secrets/s3_access_key_id', 'bind:/run/secrets/s3_secret_access_key']
# 2026-11-10 14:15:17 UTC | API: файлы в /tmp (tmpfs) после загрузок | exit 0 | 0.3s
$ docker compose --env-file .env exec -T api sh -c df -h /tmp; echo files_in_tmp=$(find /tmp -type f | wc -l)
Filesystem Size Used Avail Use% Mounted on
tmpfs 16M 0 16M 0% /tmp
files_in_tmp=0
+3
View File
@@ -0,0 +1,3 @@
# 2026-11-10 14:14:05 UTC | Публичный smoke | exit 0 | 1.8s
$ python tests/smoke.py --base-url http://127.0.0.1:8080
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
+61
View File
@@ -0,0 +1,61 @@
# 2026-11-10 14:13:49 UTC | Стенд: контейнеры | exit 0 | 0.3s
$ docker compose --env-file .env ps -a
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
messenger-lab5-api-1 messenger-api:lab5 "python -m src.server" api 28 minutes ago Up 10 minutes (healthy) 8080/tcp
messenger-lab5-api-2 messenger-api:lab5 "python -m src.server" api 28 minutes ago Up 10 minutes (healthy) 8080/tcp
messenger-lab5-broker-1 redis:7.4.1-alpine "docker-entrypoint.s…" broker 28 minutes ago Up 9 minutes (healthy) 6379/tcp
messenger-lab5-lb-1 haproxy:2.8.30-alpine "docker-entrypoint.s…" lb 28 minutes ago Up 13 minutes (healthy) 127.0.0.1:8080->8080/tcp, 127.0.0.1:8404->8404/tcp
messenger-lab5-migrate-1 messenger-lab5-migrate "python -m src.migra…" migrate 28 minutes ago Exited (0) 4 minutes ago
messenger-lab5-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 28 minutes ago Up 14 minutes (healthy) 5432/tcp
messenger-lab5-redis-1 redis:7.4.1-alpine "docker-entrypoint.s…" redis 28 minutes ago Up 14 minutes (healthy) 6379/tcp
messenger-lab5-s3-1 chrislusf/seaweedfs:4.50 "/usr/bin/weed serve…" s3 28 minutes ago Up 14 minutes (healthy) 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
messenger-lab5-s3-init-1 messenger-lab5-s3-init "python -m src.s3_bo…" s3-init 28 minutes ago Exited (0) 4 minutes ago
messenger-lab5-worker-1 messenger-api:lab5 "python -m src.worker" worker 3 minutes ago Up 2 minutes (healthy) 8080/tcp
# 2026-11-10 14:13:50 UTC | Стенд: реплики и статус в LB | exit 0 | 0.3s
$ python scripts/ops.py ps
X-Instance-Id container state health image lb lb_status
4b1faad0399c messenger-lab5-api-1 running healthy messenger-api:lab5 api1 UP
3a0e06f14a63 messenger-lab5-api-2 running healthy messenger-api:lab5 api2 UP
# 2026-11-10 14:13:52 UTC | Стенд: лимиты CPU/RAM | exit 0 | 2.2s
$ docker stats --no-stream --format table {{.Name}} {{.CPUPerc}} {{.MemUsage}} {{.MemPerc}}
NAME CPU % MEM USAGE / LIMIT MEM %
messenger-lab5-worker-1 0.09% 76.75MiB / 1.25GiB 6.00%
messenger-lab5-lb-1 0.13% 12.85MiB / 128MiB 10.04%
messenger-lab5-api-1 0.38% 82.19MiB / 320MiB 25.68%
messenger-lab5-api-2 18.24% 77.13MiB / 320MiB 24.10%
messenger-lab5-postgres-1 3.64% 74.93MiB / 512MiB 14.63%
messenger-lab5-redis-1 0.27% 3.957MiB / 96MiB 4.12%
messenger-lab5-s3-1 2.99% 189.7MiB / 512MiB 37.06%
messenger-lab5-broker-1 0.29% 4.012MiB / 320MiB 1.25%
# 2026-11-10 14:13:52 UTC | Стенд: опубликованные порты (только lb) | exit 0 | 0.4s
$ docker compose --env-file .env ps --format table {{.Service}} {{.Ports}}
SERVICE PORTS
api 8080/tcp
api 8080/tcp
broker 6379/tcp
lb 127.0.0.1:8080->8080/tcp, 127.0.0.1:8404->8404/tcp
postgres 5432/tcp
redis 6379/tcp
s3 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
worker 8080/tcp
# 2026-11-10 14:13:53 UTC | Образ SeaweedFS (закреплённая версия) | exit 0 | 0.4s
$ docker compose --env-file .env images s3
CONTAINER REPOSITORY TAG PLATFORM IMAGE ID SIZE CREATED
messenger-lab5-s3-1 chrislusf/seaweedfs 4.50 linux/amd64 c2658820e763 734MB 2 weeks ago
# 2026-11-10 14:13:53 UTC | lab5: broker (Redis AOF) и worker | exit 0 | 0.3s
$ docker compose --env-file .env ps broker worker
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
messenger-lab5-broker-1 redis:7.4.1-alpine "docker-entrypoint.s…" broker 28 minutes ago Up 10 minutes (healthy) 6379/tcp
messenger-lab5-worker-1 messenger-api:lab5 "python -m src.worker" worker 3 minutes ago Up 2 minutes (healthy) 8080/tcp
# 2026-11-10 14:13:53 UTC | lab5: конфигурация durability брокера | exit 0 | 0.3s
$ docker compose --env-file .env exec -T broker sh -c REDISCLI_AUTH="$(tr -d '\r\n' < /run/secrets/broker_password)" redis-cli CONFIG GET appendfsync; REDISCLI_AUTH="$(tr -d '\r\n' < /run/secrets/broker_password)" redis-cli CONFIG GET maxmemory-policy
appendfsync
always
maxmemory-policy
noeviction
+185
View File
@@ -0,0 +1,185 @@
# 2026-11-10 14:14:27 UTC | Собственные тесты (HTTP через LB, включая test_attachments.py) | exit 0 | 21.7s
$ python student-tests/run_all.py --base-url http://127.0.0.1:8080
== API, auth, concurrency, idempotency tests (DB/expiry tests skip without their env)
test_chat_list_pagination (test_api.ApiBehaviorTests.test_chat_list_pagination) ... ok
test_cursor_from_other_chat_returns_400 (test_api.ApiBehaviorTests.test_cursor_from_other_chat_returns_400) ... ok
test_duplicate_username_returns_409 (test_api.ApiBehaviorTests.test_duplicate_username_returns_409) ... ok
test_empty_message_returns_400 (test_api.ApiBehaviorTests.test_empty_message_returns_400) ... ok
test_malformed_json_returns_400 (test_api.ApiBehaviorTests.test_malformed_json_returns_400) ... ok
test_naive_timestamp_cursor_returns_400 (test_api.ApiBehaviorTests.test_naive_timestamp_cursor_returns_400) ... ok
test_outsider_cannot_access_chat (test_api.ApiBehaviorTests.test_outsider_cannot_access_chat) ... ok
test_pagination_returns_all_messages_without_duplicates (test_api.ApiBehaviorTests.test_pagination_returns_all_messages_without_duplicates) ... ok
test_password_never_returned (test_api.ApiBehaviorTests.test_password_never_returned) ... ok
test_registration_without_password_returns_400 (test_api.ApiBehaviorTests.test_registration_without_password_returns_400) ... ok
test_sender_id_in_body_rejected (test_api.ApiBehaviorTests.test_sender_id_in_body_rejected) ... ok
test_short_password_returns_400 (test_api.ApiBehaviorTests.test_short_password_returns_400) ... ok
test_crash_between_put_and_commit_dry_run_then_apply_then_noop (test_attachment_consistency.AttachmentConsistencyTests.test_crash_between_put_and_commit_dry_run_then_apply_then_noop) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_fresh_pending_is_kept (test_attachment_consistency.AttachmentConsistencyTests.test_fresh_pending_is_kept) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_missing_object_is_reported_not_deleted (test_attachment_consistency.AttachmentConsistencyTests.test_missing_object_is_reported_not_deleted) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_orphan_object_deleted_only_after_grace (test_attachment_consistency.AttachmentConsistencyTests.test_orphan_object_deleted_only_after_grace) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_pending_cannot_be_attached (test_attachment_consistency.AttachmentConsistencyTests.test_pending_cannot_be_attached) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_ready_and_referenced_are_never_collected (test_attachment_consistency.AttachmentConsistencyTests.test_ready_and_referenced_are_never_collected) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_aborted_upload_leaves_no_row_and_no_object (test_attachment_consistency.UploadFailureTests.test_aborted_upload_leaves_no_row_and_no_object) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_db_failure_after_put_returns_503_and_deletes_object (test_attachment_consistency.UploadFailureTests.test_db_failure_after_put_returns_503_and_deletes_object) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_process_crash_after_put_is_collected_by_gc (test_attachment_consistency.UploadFailureTests.test_process_crash_after_put_is_collected_by_gc) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_s3_put_failure_returns_503_and_compensates (test_attachment_consistency.UploadFailureTests.test_s3_put_failure_returns_503_and_compensates) ... skipped 'DATABASE_URL and S3 settings are not configured'
test_attachment_from_other_chat_is_404_and_nothing_saved (test_attachments.AttachmentTests.test_attachment_from_other_chat_is_404_and_nothing_saved) ... ok
test_content_type_with_parameters_is_accepted (test_attachments.AttachmentTests.test_content_type_with_parameters_is_accepted) ... ok
test_corrupted_images_are_415 (test_attachments.AttachmentTests.test_corrupted_images_are_415) ... ok
test_dangerous_filenames_are_400 (test_attachments.AttachmentTests.test_dangerous_filenames_are_400) ... ok
test_exactly_max_size_is_accepted (test_attachments.AttachmentTests.test_exactly_max_size_is_accepted) ... ok
test_idempotency_includes_attachment_ids (test_attachments.AttachmentTests.test_idempotency_includes_attachment_ids) ... ok
test_invalid_and_unknown_attachment_ids (test_attachments.AttachmentTests.test_invalid_and_unknown_attachment_ids) ... ok
test_jpeg_baseline_and_progressive (test_attachments.AttachmentTests.test_jpeg_baseline_and_progressive) ... ok
test_message_attachment_validation (test_attachments.AttachmentTests.test_message_attachment_validation) ... ok
test_message_with_attachments_visible_to_members (test_attachments.AttachmentTests.test_message_with_attachments_visible_to_members) ... ok
test_mime_spoofing_is_415 (test_attachments.AttachmentTests.test_mime_spoofing_is_415) ... ok
test_original_variant_and_unknown_variants (test_attachments.AttachmentTests.test_original_variant_and_unknown_variants) ... ok
test_outsider_and_unknown_chat_upload_404 (test_attachments.AttachmentTests.test_outsider_and_unknown_chat_upload_404) ... ok
test_png_roundtrip_member_reads_outsider_404 (test_attachments.AttachmentTests.test_png_roundtrip_member_reads_outsider_404) ... ok
test_too_large_chunked_without_content_length (test_attachments.AttachmentTests.test_too_large_chunked_without_content_length) ... ok
test_too_large_with_content_length (test_attachments.AttachmentTests.test_too_large_with_content_length) ... ok
test_too_many_pixels (test_attachments.AttachmentTests.test_too_many_pixels) ... ok
test_basic_on_business_endpoint_rejected (test_auth.AuthTests.test_basic_on_business_endpoint_rejected) ... ok
test_login_with_body_rejected (test_auth.AuthTests.test_login_with_body_rejected)
Контракт: вход — только заголовок Basic, без тела. Лишний ввод -> 400, сессии нет. ... ok
test_logout_revokes_only_current_session (test_auth.AuthTests.test_logout_revokes_only_current_session) ... ok
test_malformed_basic_headers (test_auth.AuthTests.test_malformed_basic_headers) ... ok
test_password_with_colon_and_unicode (test_auth.AuthTests.test_password_with_colon_and_unicode) ... ok
test_session_shape_and_token_entropy (test_auth.AuthTests.test_session_shape_and_token_entropy) ... ok
test_unknown_and_garbage_tokens (test_auth.AuthTests.test_unknown_and_garbage_tokens) ... ok
test_wrong_password_and_unknown_user_look_the_same (test_auth.AuthTests.test_wrong_password_and_unknown_user_look_the_same) ... ok
test_x_user_id_gives_no_access (test_auth.AuthTests.test_x_user_id_gives_no_access) ... ok
test_duplicate_and_missing_caller_rejected (test_concurrency.ChatRollbackTests.test_duplicate_and_missing_caller_rejected) ... ok
test_unknown_member_rolls_back_whole_chat (test_concurrency.ChatRollbackTests.test_unknown_member_rolls_back_whole_chat)
Чат вставляется первым, затем участники по порядку (сначала сам владелец). ... ok
test_same_username_parallel_registration (test_concurrency.RegistrationRaceTests.test_same_username_parallel_registration) ... ok
test_session_expires_even_when_cached (test_expiry.ExpiryTests.test_session_expires_even_when_cached) ... skipped 'set EXPIRY_BASE_URL to the short-TTL API instance'
test_auth_checked_before_key (test_idempotency.IdempotencyTests.test_auth_checked_before_key) ... ok
test_concurrent_same_key_across_replicas_creates_one_message (test_idempotency.IdempotencyTests.test_concurrent_same_key_across_replicas_creates_one_message) ... ok
test_concurrent_same_key_different_bodies_one_winner (test_idempotency.IdempotencyTests.test_concurrent_same_key_different_bodies_one_winner) ... ok
test_failed_access_does_not_burn_key (test_idempotency.IdempotencyTests.test_failed_access_does_not_burn_key) ... ok
test_json_formatting_and_key_order_do_not_matter (test_idempotency.IdempotencyTests.test_json_formatting_and_key_order_do_not_matter) ... ok
test_key_survives_new_session_of_same_user (test_idempotency.IdempotencyTests.test_key_survives_new_session_of_same_user) ... ok
test_missing_or_invalid_key_is_400 (test_idempotency.IdempotencyTests.test_missing_or_invalid_key_is_400) ... ok
test_replay_rechecks_session (test_idempotency.IdempotencyTests.test_replay_rechecks_session) ... ok
test_scope_is_user_and_chat (test_idempotency.IdempotencyTests.test_scope_is_user_and_chat) ... ok
test_sequential_replay_and_conflict (test_idempotency.IdempotencyTests.test_sequential_replay_and_conflict) ... ok
test_exif_orientation_applied_and_stripped (test_pipeline.PipelineTests.test_exif_orientation_applied_and_stripped) ... ok
test_fixture_320x200 (test_pipeline.PipelineTests.test_fixture_320x200) ... ok
test_progressive_jpeg (test_pipeline.PipelineTests.test_progressive_jpeg) ... ok
test_result_is_stable_and_private (test_pipeline.PipelineTests.test_result_is_stable_and_private) ... ok
test_small_source_not_upscaled_except_crop (test_pipeline.PipelineTests.test_small_source_not_upscaled_except_crop) ... ok
test_transparency_on_white (test_pipeline.PipelineTests.test_transparency_on_white) ... ok
test_unknown_variant_is_400 (test_pipeline.PipelineTests.test_unknown_variant_is_400) ... ok
test_a_crash_between_commit_and_publish (test_pipeline_faults.PipelineFaultTests.test_a_crash_between_commit_and_publish) ... skipped 'needs API at http://127.0.0.1:8080 and DB/S3/broker env'
test_b_crash_after_publish_duplicate_is_noop (test_pipeline_faults.PipelineFaultTests.test_b_crash_after_publish_duplicate_is_noop) ... skipped 'needs API at http://127.0.0.1:8080 and DB/S3/broker env'
test_c_worker_crash_after_side_effects_before_commit (test_pipeline_faults.PipelineFaultTests.test_c_worker_crash_after_side_effects_before_commit) ... skipped 'needs API at http://127.0.0.1:8080 and DB/S3/broker env'
test_d_worker_crash_after_commit_before_ack (test_pipeline_faults.PipelineFaultTests.test_d_worker_crash_after_commit_before_ack) ... skipped 'needs API at http://127.0.0.1:8080 and DB/S3/broker env'
test_e_transient_errors_retry_with_backoff (test_pipeline_faults.PipelineFaultTests.test_e_transient_errors_retry_with_backoff) ... skipped 'needs API at http://127.0.0.1:8080 and DB/S3/broker env'
test_f_permanent_error_fails_without_retry (test_pipeline_faults.PipelineFaultTests.test_f_permanent_error_fails_without_retry) ... skipped 'needs API at http://127.0.0.1:8080 and DB/S3/broker env'
test_g_retry_exhausted_dlq_then_explicit_replay (test_pipeline_faults.PipelineFaultTests.test_g_retry_exhausted_dlq_then_explicit_replay) ... skipped 'needs API at http://127.0.0.1:8080 and DB/S3/broker env'
test_h_hung_worker_lease_expires_and_is_fenced (test_pipeline_faults.PipelineFaultTests.test_h_hung_worker_lease_expires_and_is_fenced) ... skipped 'needs API at http://127.0.0.1:8080 and DB/S3/broker env'
test_i_staging_removed_after_safe_commit (test_pipeline_faults.PipelineFaultTests.test_i_staging_removed_after_safe_commit) ... skipped 'needs API at http://127.0.0.1:8080 and DB/S3/broker env'
test_j_garbage_broker_message_is_acked (test_pipeline_faults.PipelineFaultTests.test_j_garbage_broker_message_is_acked) ... skipped 'needs API at http://127.0.0.1:8080 and DB/S3/broker env'
test_debt_survives_api_restart (test_session_cache.SessionRevocationCacheTests.test_debt_survives_api_restart)
Процесс, выполнивший logout, умер до восстановления связи — новый процесс не доверяет кэшу. ... skipped 'DATABASE_URL is not configured'
test_normal_logout_leaves_no_debt (test_session_cache.SessionRevocationCacheTests.test_normal_logout_leaves_no_debt) ... skipped 'DATABASE_URL is not configured'
test_revoked_token_rejected_after_partition_heals (test_session_cache.SessionRevocationCacheTests.test_revoked_token_rejected_after_partition_heals) ... skipped 'DATABASE_URL is not configured'
test_cleanup_runs_on_one_replica_at_a_time (test_storage_idempotency.StorageIdempotencyTests.test_cleanup_runs_on_one_replica_at_a_time) ... skipped 'DATABASE_URL is not configured'
test_conflict_on_different_body (test_storage_idempotency.StorageIdempotencyTests.test_conflict_on_different_body) ... skipped 'DATABASE_URL is not configured'
test_expired_key_can_be_reused_and_is_cleaned (test_storage_idempotency.StorageIdempotencyTests.test_expired_key_can_be_reused_and_is_cleaned) ... skipped 'DATABASE_URL is not configured'
test_failure_inside_transaction_stores_nothing (test_storage_idempotency.StorageIdempotencyTests.test_failure_inside_transaction_stores_nothing) ... skipped 'DATABASE_URL is not configured'
test_threads_same_key_single_insert (test_storage_idempotency.StorageIdempotencyTests.test_threads_same_key_single_insert) ... skipped 'DATABASE_URL is not configured'
test_failure_after_inserts_leaves_nothing (test_storage_rollback.StorageRollbackTests.test_failure_after_inserts_leaves_nothing) ... skipped 'DATABASE_URL is not configured'
test_migrations_are_idempotent (test_storage_rollback.StorageRollbackTests.test_migrations_are_idempotent) ... skipped 'DATABASE_URL is not configured'
test_no_orphan_chats_in_database (test_storage_rollback.StorageRollbackTests.test_no_orphan_chats_in_database) ... skipped 'DATABASE_URL is not configured'
test_passwords_stored_as_argon2id (test_storage_rollback.StorageRollbackTests.test_passwords_stored_as_argon2id) ... skipped 'DATABASE_URL is not configured'
----------------------------------------------------------------------
Ran 91 tests in 19.876s
OK (skipped=33)
24 parallel POSTs, one key -> 1 message; replicas: ['3a0e06f14a63', '4b1faad0399c']
== Concurrent write test
PASS: concurrent write test; 10 clients x 10 messages = 100 messages; no lost or duplicate messages
ALL STUDENT TESTS PASSED
# 2026-11-10 14:14:36 UTC | Тесты с доступом к БД (внутри compose-сети) | exit 0 | 8.8s
$ python scripts/ops.py in-network storage
Container messenger-lab5-api-run-87d6a97994de Creating
Container messenger-lab5-api-run-87d6a97994de Created
test_cleanup_runs_on_one_replica_at_a_time (test_storage_idempotency.StorageIdempotencyTests.test_cleanup_runs_on_one_replica_at_a_time) ... ok
test_conflict_on_different_body (test_storage_idempotency.StorageIdempotencyTests.test_conflict_on_different_body) ... ok
test_expired_key_can_be_reused_and_is_cleaned (test_storage_idempotency.StorageIdempotencyTests.test_expired_key_can_be_reused_and_is_cleaned) ... ok
test_failure_inside_transaction_stores_nothing (test_storage_idempotency.StorageIdempotencyTests.test_failure_inside_transaction_stores_nothing) ... ok
test_threads_same_key_single_insert (test_storage_idempotency.StorageIdempotencyTests.test_threads_same_key_single_insert) ... ok
test_failure_after_inserts_leaves_nothing (test_storage_rollback.StorageRollbackTests.test_failure_after_inserts_leaves_nothing) ... ok
test_migrations_are_idempotent (test_storage_rollback.StorageRollbackTests.test_migrations_are_idempotent) ... ok
test_no_orphan_chats_in_database (test_storage_rollback.StorageRollbackTests.test_no_orphan_chats_in_database) ... ok
test_passwords_stored_as_argon2id (test_storage_rollback.StorageRollbackTests.test_passwords_stored_as_argon2id) ... ok
----------------------------------------------------------------------
Ran 9 tests in 3.408s
OK
Container messenger-lab5-api-run-7049d7c00dfc Creating
Container messenger-lab5-api-run-7049d7c00dfc Created
test_debt_survives_api_restart (test_session_cache.SessionRevocationCacheTests.test_debt_survives_api_restart)
Процесс, выполнивший logout, умер до восстановления связи — новый процесс не доверяет кэшу. ... logout: cache invalidation deferred; positive cache disabled
ok
test_normal_logout_leaves_no_debt (test_session_cache.SessionRevocationCacheTests.test_normal_logout_leaves_no_debt) ... ok
test_revoked_token_rejected_after_partition_heals (test_session_cache.SessionRevocationCacheTests.test_revoked_token_rejected_after_partition_heals) ... logout: cache invalidation deferred; positive cache disabled
ok
----------------------------------------------------------------------
Ran 3 tests in 2.032s
OK
# 2026-11-10 14:14:51 UTC | Истечение сессии (api-short-ttl, TTL 2 с) | exit 0 | 15.7s
$ python scripts/ops.py in-network expiry
Container messenger-lab5-postgres-1 Running
Container messenger-lab5-s3-1 Running
Container messenger-lab5-api-1 Running
Container messenger-lab5-api-2 Running
Container messenger-lab5-redis-1 Running
Container messenger-lab5-api-short-ttl-1 Creating
Container messenger-lab5-api-short-ttl-1 Created
Container messenger-lab5-s3-1 Waiting
Container messenger-lab5-postgres-1 Waiting
Container messenger-lab5-s3-1 Healthy
Container messenger-lab5-postgres-1 Healthy
Container messenger-lab5-migrate-1 Starting
Container messenger-lab5-s3-init-1 Starting
Container messenger-lab5-migrate-1 Started
Container messenger-lab5-s3-init-1 Started
Container messenger-lab5-postgres-1 Waiting
Container messenger-lab5-redis-1 Waiting
Container messenger-lab5-migrate-1 Waiting
Container messenger-lab5-s3-init-1 Waiting
Container messenger-lab5-redis-1 Healthy
Container messenger-lab5-postgres-1 Healthy
Container messenger-lab5-migrate-1 Exited
Container messenger-lab5-s3-init-1 Exited
Container messenger-lab5-api-1 Waiting
Container messenger-lab5-api-2 Waiting
Container messenger-lab5-api-1 Healthy
Container messenger-lab5-api-2 Healthy
Container messenger-lab5-api-short-ttl-1 Starting
Container messenger-lab5-api-short-ttl-1 Started
Container messenger-lab5-api-run-f4cd12243eab Creating
Container messenger-lab5-api-run-f4cd12243eab Created
ready: http://api-short-ttl:8080/health/ready
Container messenger-lab5-api-run-249c8116f0a3 Creating
Container messenger-lab5-api-run-249c8116f0a3 Created
test_session_expires_even_when_cached (test_expiry.ExpiryTests.test_session_expires_even_when_cached) ... ok
----------------------------------------------------------------------
Ran 1 test in 3.743s
OK
+161
View File
@@ -0,0 +1,161 @@
# 2026-11-10 14:15:28 UTC | Пик памяти: 10 одновременных загрузок по 9.5 MiB | exit 0 | 11.3s
$ python student-tests/upload_memory.py --base-url http://127.0.0.1:8080 --concurrency 10 --rounds 3 --docker --label c=10, MAX_CONCURRENT_UPLOADS=4 --output evidence/upload_memory_c10.json
{
"label": "c=10, MAX_CONCURRENT_UPLOADS=4",
"date_utc": "2026-11-10T14:15:28Z",
"host": "Windows AMD64, 12 CPU",
"source": "docker stats + cgroup peak",
"concurrency": 10,
"rounds": 3,
"file_mib": 9.5,
"uploads": 30,
"statuses": {
"202": 30
},
"sha256_ok": 30,
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
],
"duration_s": 6.22,
"latency_201_s": {
"p50": 1.719,
"p95": 1.922,
"max": 2.5309999999990396,
"mean": 1.663
},
"memory": {
"messenger-lab5-worker-1": {
"baseline_mib": 76.3,
"peak_mib": 151.7,
"growth_mib": 75.4,
"samples": 5
},
"messenger-lab5-lb-1": {
"baseline_mib": 13.0,
"peak_mib": 30.2,
"growth_mib": 17.3,
"samples": 5
},
"messenger-lab5-api-1": {
"baseline_mib": 134.6,
"peak_mib": 153.6,
"growth_mib": 19.0,
"samples": 5
},
"messenger-lab5-api-2": {
"baseline_mib": 136.9,
"peak_mib": 152.8,
"growth_mib": 15.9,
"samples": 5
},
"messenger-lab5-postgres-1": {
"baseline_mib": 84.9,
"peak_mib": 86.6,
"growth_mib": 1.7,
"samples": 5
},
"messenger-lab5-redis-1": {
"baseline_mib": 4.7,
"peak_mib": 5.3,
"growth_mib": 0.6,
"samples": 5
},
"messenger-lab5-s3-1": {
"baseline_mib": 227.9,
"peak_mib": 303.6,
"growth_mib": 75.7,
"samples": 5
},
"messenger-lab5-broker-1": {
"baseline_mib": 4.2,
"peak_mib": 4.5,
"growth_mib": 0.4,
"samples": 5
}
},
"process_peak_rss_mib": {},
"cgroup_peak_mib_before": {},
"cgroup_peak_mib_after": {}
}
# 2026-11-10 14:15:40 UTC | Пик памяти: 20 одновременных загрузок | exit 0 | 11.5s
$ python student-tests/upload_memory.py --base-url http://127.0.0.1:8080 --concurrency 20 --rounds 2 --docker --label c=20, MAX_CONCURRENT_UPLOADS=4 --output evidence/upload_memory_c20.json
{
"label": "c=20, MAX_CONCURRENT_UPLOADS=4",
"date_utc": "2026-11-10T14:15:40Z",
"host": "Windows AMD64, 12 CPU",
"source": "docker stats + cgroup peak",
"concurrency": 20,
"rounds": 2,
"file_mib": 9.5,
"uploads": 40,
"statuses": {
"202": 40
},
"sha256_ok": 40,
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
],
"duration_s": 7.16,
"latency_201_s": {
"p50": 2.984,
"p95": 3.562,
"max": 3.577999999997701,
"mean": 2.695
},
"memory": {
"messenger-lab5-worker-1": {
"baseline_mib": 152.5,
"peak_mib": 152.5,
"growth_mib": 0.0,
"samples": 5
},
"messenger-lab5-lb-1": {
"baseline_mib": 73.6,
"peak_mib": 74.0,
"growth_mib": 0.4,
"samples": 5
},
"messenger-lab5-api-1": {
"baseline_mib": 155.9,
"peak_mib": 171.2,
"growth_mib": 15.3,
"samples": 5
},
"messenger-lab5-api-2": {
"baseline_mib": 168.7,
"peak_mib": 168.7,
"growth_mib": 0.0,
"samples": 5
},
"messenger-lab5-postgres-1": {
"baseline_mib": 86.3,
"peak_mib": 86.7,
"growth_mib": 0.4,
"samples": 5
},
"messenger-lab5-redis-1": {
"baseline_mib": 4.2,
"peak_mib": 5.1,
"growth_mib": 0.9,
"samples": 5
},
"messenger-lab5-s3-1": {
"baseline_mib": 348.9,
"peak_mib": 430.3,
"growth_mib": 81.4,
"samples": 5
},
"messenger-lab5-broker-1": {
"baseline_mib": 4.7,
"peak_mib": 5.3,
"growth_mib": 0.6,
"samples": 5
}
},
"process_peak_rss_mib": {},
"cgroup_peak_mib_before": {},
"cgroup_peak_mib_after": {}
}
+78
View File
@@ -0,0 +1,78 @@
{
"label": "c=10, MAX_CONCURRENT_UPLOADS=4",
"date_utc": "2026-11-10T14:15:28Z",
"host": "Windows AMD64, 12 CPU",
"source": "docker stats + cgroup peak",
"concurrency": 10,
"rounds": 3,
"file_mib": 9.5,
"uploads": 30,
"statuses": {
"202": 30
},
"sha256_ok": 30,
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
],
"duration_s": 6.22,
"latency_201_s": {
"p50": 1.719,
"p95": 1.922,
"max": 2.5309999999990396,
"mean": 1.663
},
"memory": {
"messenger-lab5-worker-1": {
"baseline_mib": 76.3,
"peak_mib": 151.7,
"growth_mib": 75.4,
"samples": 5
},
"messenger-lab5-lb-1": {
"baseline_mib": 13.0,
"peak_mib": 30.2,
"growth_mib": 17.3,
"samples": 5
},
"messenger-lab5-api-1": {
"baseline_mib": 134.6,
"peak_mib": 153.6,
"growth_mib": 19.0,
"samples": 5
},
"messenger-lab5-api-2": {
"baseline_mib": 136.9,
"peak_mib": 152.8,
"growth_mib": 15.9,
"samples": 5
},
"messenger-lab5-postgres-1": {
"baseline_mib": 84.9,
"peak_mib": 86.6,
"growth_mib": 1.7,
"samples": 5
},
"messenger-lab5-redis-1": {
"baseline_mib": 4.7,
"peak_mib": 5.3,
"growth_mib": 0.6,
"samples": 5
},
"messenger-lab5-s3-1": {
"baseline_mib": 227.9,
"peak_mib": 303.6,
"growth_mib": 75.7,
"samples": 5
},
"messenger-lab5-broker-1": {
"baseline_mib": 4.2,
"peak_mib": 4.5,
"growth_mib": 0.4,
"samples": 5
}
},
"process_peak_rss_mib": {},
"cgroup_peak_mib_before": {},
"cgroup_peak_mib_after": {}
}
+78
View File
@@ -0,0 +1,78 @@
{
"label": "c=20, MAX_CONCURRENT_UPLOADS=4",
"date_utc": "2026-11-10T14:15:40Z",
"host": "Windows AMD64, 12 CPU",
"source": "docker stats + cgroup peak",
"concurrency": 20,
"rounds": 2,
"file_mib": 9.5,
"uploads": 40,
"statuses": {
"202": 40
},
"sha256_ok": 40,
"instances": [
"3a0e06f14a63",
"4b1faad0399c"
],
"duration_s": 7.16,
"latency_201_s": {
"p50": 2.984,
"p95": 3.562,
"max": 3.577999999997701,
"mean": 2.695
},
"memory": {
"messenger-lab5-worker-1": {
"baseline_mib": 152.5,
"peak_mib": 152.5,
"growth_mib": 0.0,
"samples": 5
},
"messenger-lab5-lb-1": {
"baseline_mib": 73.6,
"peak_mib": 74.0,
"growth_mib": 0.4,
"samples": 5
},
"messenger-lab5-api-1": {
"baseline_mib": 155.9,
"peak_mib": 171.2,
"growth_mib": 15.3,
"samples": 5
},
"messenger-lab5-api-2": {
"baseline_mib": 168.7,
"peak_mib": 168.7,
"growth_mib": 0.0,
"samples": 5
},
"messenger-lab5-postgres-1": {
"baseline_mib": 86.3,
"peak_mib": 86.7,
"growth_mib": 0.4,
"samples": 5
},
"messenger-lab5-redis-1": {
"baseline_mib": 4.2,
"peak_mib": 5.1,
"growth_mib": 0.9,
"samples": 5
},
"messenger-lab5-s3-1": {
"baseline_mib": 348.9,
"peak_mib": 430.3,
"growth_mib": 81.4,
"samples": 5
},
"messenger-lab5-broker-1": {
"baseline_mib": 4.7,
"peak_mib": 5.3,
"growth_mib": 0.6,
"samples": 5
}
},
"process_peak_rss_mib": {},
"cgroup_peak_mib_before": {},
"cgroup_peak_mib_after": {}
}
+3
View File
@@ -0,0 +1,3 @@
# 2026-11-10 14:23:08 UTC | Worker: последние строки лога | exit 0 | 0.3s
$ docker compose --env-file .env logs --no-color --tail 80 worker
worker-1 | 2026-11-10 14:23:00,051 INFO messenger.worker worker 853a915daea3: concurrency=2 max_attempts=5 lease=60s claim_idle=75s image_timeout=30.0s image_memory=1024MiB retry=2.0..60.0s faults=off
+80
View File
@@ -0,0 +1,80 @@
[
{
"seconds": 2.06,
"step": "worker stopped",
"t": 2.42
},
{
"status": 202,
"attachment_id": "998f7ba6-a5ae-42ab-b965-8c3cb4be2d00",
"attachment_status": "queued",
"step": "upload accepted",
"t": 2.44
},
{
"metadata_status": "queued",
"content_status": 409,
"message_with_attachment": 201,
"plain_message": 201,
"message_id": "310e494b-eccf-49b1-9424-bfec99522d7b",
"step": "while worker is down",
"t": 5.53
},
{
"length": 9,
"lag": 1,
"pending": 0,
"jobs": {
"succeeded": 148,
"failed": 1,
"queued": 1
},
"outbox_rows": 0,
"step": "broker before restarts",
"t": 7.22
},
{
"seconds": 11.0,
"step": "api replicas restarted",
"t": 18.22
},
{
"seconds": 4.58,
"step": "broker restarted (volume kept)",
"t": 22.8
},
{
"metadata_status": "queued",
"length": 9,
"lag": 1,
"pending": 0,
"jobs": {
"succeeded": 148,
"failed": 1,
"queued": 1
},
"outbox_rows": 0,
"step": "after restarts",
"t": 26.67
},
{
"seconds": 6.41,
"step": "worker started",
"t": 33.08
},
{
"attachment_id": "998f7ba6-a5ae-42ab-b965-8c3cb4be2d00",
"variants": [
"thumbnail",
"crop",
"optimized"
],
"thumbnail_jpeg_size": [
256,
160
],
"original_sha256_ok": true,
"step": "ready",
"t": 33.12
}
]
+12
View File
@@ -0,0 +1,12 @@
# 2026-11-10 14:20:58 UTC | Сценарий защиты 3: worker остановлен -> 202 -> рестарт API и broker -> worker -> ready | exit 0 | 33.3s
$ python student-tests/worker_outage.py --base-url http://127.0.0.1:8080 --output evidence/worker_outage.json
{"seconds": 2.06, "step": "worker stopped", "t": 2.42}
{"status": 202, "attachment_id": "998f7ba6-a5ae-42ab-b965-8c3cb4be2d00", "attachment_status": "queued", "step": "upload accepted", "t": 2.44}
{"metadata_status": "queued", "content_status": 409, "message_with_attachment": 201, "plain_message": 201, "message_id": "310e494b-eccf-49b1-9424-bfec99522d7b", "step": "while worker is down", "t": 5.53}
{"length": 9, "lag": 1, "pending": 0, "jobs": {"succeeded": 148, "failed": 1, "queued": 1}, "outbox_rows": 0, "step": "broker before restarts", "t": 7.22}
{"seconds": 11.0, "step": "api replicas restarted", "t": 18.22}
{"seconds": 4.58, "step": "broker restarted (volume kept)", "t": 22.8}
{"metadata_status": "queued", "length": 9, "lag": 1, "pending": 0, "jobs": {"succeeded": 148, "failed": 1, "queued": 1}, "outbox_rows": 0, "step": "after restarts", "t": 26.67}
{"seconds": 6.41, "step": "worker started", "t": 33.08}
{"attachment_id": "998f7ba6-a5ae-42ab-b965-8c3cb4be2d00", "variants": ["thumbnail", "crop", "optimized"], "thumbnail_jpeg_size": [256, 160], "original_sha256_ok": true, "step": "ready", "t": 33.12}
PASS: accepted job survived worker stop + API restart + broker restart and became ready