forked from mtusi2026/mtusi2026lab5
fix(lab5): protect pipeline objects and verify overload recovery
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
# Отчёт — лабораторная 5
|
||||
|
||||
- Автор, группа: [ФИО], [группа]
|
||||
- Автор, группа: Кушнаренко Николай Вячеславович, БПИ2302
|
||||
- Целевая оценка; выбранный трек 5, если нужен: **5**, трек 1 «Очередь под перегрузкой»
|
||||
- Commit/PR: локальный коммит ветки `solution/lab5`; PR — после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: Python 3.12, uvicorn, asyncpg, aiobotocore, aio-pika (RabbitMQ), Pillow (обработка изображений); RabbitMQ 4.1.8, SeaweedFS 4.48, PostgreSQL 17, Valkey 8, HAProxy 3.0. Код lab4 перенесён. Использование ИИ: [заполняется автором]
|
||||
- Commit/PR: ветка `solution/bpi2302-kushnarenko` в [форке kolya](https://gitea.privcloud.tech/kolya/mtusi2026lab5); ссылка на PR добавляется после открытия
|
||||
- Использованные источники, библиотеки и помощь ИИ: Python 3.12, uvicorn, asyncpg, aiobotocore, aio-pika (RabbitMQ), Pillow (обработка изображений); RabbitMQ 4.1.8, SeaweedFS 4.48, PostgreSQL 17, Valkey 8, HAProxy 3.0. Код lab4 перенесён. ИИ-ассистенты использовались для помощи с кодом, тестами и отчётом; Codex проверил подготовку к сдаче, исправил перенос reconciler, усилил методику исследования и выполнил реальные запуски 12.11.2026
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
@@ -14,7 +14,7 @@ Prerequisites: Docker Compose v2, bash (Git Bash на Windows), Python ≥ 3.9;
|
||||
sh scripts/init-secrets.sh # secrets/*: БД, S3 (admin + ключи API), RabbitMQ (rabbitmq.conf, broker_url)
|
||||
cp .env.example .env
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build # postgres, valkey, seaweedfs, rabbitmq -> migrate + s3-init -> api x2, worker -> lb
|
||||
docker compose --env-file .env up -d --build --wait --wait-timeout 120 # postgres, valkey, seaweedfs, rabbitmq -> migrate + s3-init -> api x2, worker -> lb
|
||||
curl http://127.0.0.1:8080/health/ready
|
||||
python3 tests/smoke.py --base-url http://127.0.0.1:8080 # upload -> 202 -> ready -> thumbnail 256x160
|
||||
python3 tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url http://127.0.0.1:8080
|
||||
@@ -23,13 +23,16 @@ sh scripts/restore-replicas.sh
|
||||
# собственные тесты
|
||||
python3 -m unittest discover -s student-tests -p "test_api.py" -v # + test_idempotency.py, test_attachments.py
|
||||
python3 student-tests/test_pipeline.py # Pillow желателен (пиксельные проверки)
|
||||
python3 student-tests/test_resilience5.py # окна отказа, ~2.5 мин
|
||||
python3 student-tests/test_resilience5.py # семь окон отказа
|
||||
python3 student-tests/test_reconcile5.py # варианты и staging не удаляются
|
||||
python3 student-tests/test_expiry.py
|
||||
python3 student-tests/test_dependencies.py
|
||||
# операторские команды
|
||||
docker compose --env-file .env run --rm -T worker python -m app.replay list
|
||||
docker compose --env-file .env run --rm -T worker python -m app.replay replay <attachment_id>
|
||||
```
|
||||
|
||||
Windows: `scripts/restart.cmd`, `scripts/stop-one.cmd`. Остановка с сохранением данных — `docker compose --env-file .env stop`; **намеренное удаление учебных данных** — `down -v` (volumes `pgdata`, `valkeydata`, `seaweeddata`, `rabbitmqdata`). RabbitMQ 4.x объявил `RABBITMQ_DEFAULT_USER/PASS(_FILE)` устаревшими, поэтому учётные данные задаются конфигурационным файлом-секретом `secrets/rabbitmq.conf`; hostname контейнера фиксирован (`rabbitmq`), иначе очередь не переживает пересоздание контейнера.
|
||||
Windows: `scripts/restart.cmd`, `scripts/stop-one.cmd`. Остановка с сохранением данных — `docker compose --env-file .env stop`; **намеренное удаление учебных данных** — `down -v` (volumes `pgdata`, `valkeydata`, `seaweeddata`, `rabbitmqdata`). Учётные данные RabbitMQ задаются конфигурационным файлом-секретом `secrets/rabbitmq.conf`; hostname контейнера фиксирован (`rabbitmq`), иначе очередь не переживает пересоздание контейнера.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
@@ -59,49 +62,81 @@ worker: claim(queued→processing, lease) → staging → thumbnail/crop/WebP
|
||||
- **Очистка staging**: удаляется после COMMIT результата; для `failed` хранится `STAGING_FAILED_RETENTION_SECONDS` (7 суток) для разбора/replay; фоновая очистка не затрагивает текущую работу.
|
||||
- **Backpressure**: перед приёмом тела API проверяет число активных заданий; при `queued+processing ≥ MAX_QUEUED_JOBS` — `503 unavailable` + `Retry-After` (контракт допускает 503). Readiness API не зависит от брокера и worker (их отказ не должен останавливать приём/чтение).
|
||||
|
||||
## Исправления при подготовке к сдаче — 12.11.2026
|
||||
|
||||
Перенесено исправление HAProxy из ЛР4: когда общая БД недоступна и все API теряют readiness, резервный backend по liveness позволяет приложению вернуть контрактный JSON, Retry-After и X-Request-Id; /health/live остаётся доступен. Автоматический retry HAProxy ограничен ошибкой установления соединения, чтобы повтор уже отправленного upload POST не создавал лишнюю загрузку. Восстановлены собственные проверки TTL, PostgreSQL и Valkey.
|
||||
|
||||
**Исправлен опасный перенос reconciler из ЛР4.** Старый dry-run считал три готовых варианта осиротевшими, поскольку учитывал только attachments.s3_key; вывод до исправления сохранён в [reconcile_before_fix.json](evidence/recheck_2026-11-12/reconcile_before_fix.json). Теперь учитываются метаданные вариантов, staging и владелец серверного префикса att/<id>/… . Объект внутри префикса существующего вложения защищён даже до COMMIT метаданных worker. Перед удалением перепроверяются references и владелец. Такой подход консервативен: неизвестный объект внутри существующего вложения остаётся до отдельного операторского разбора.
|
||||
|
||||
Для staging можно явно выполнить `docker compose run --rm -T api python -m app.reconcile --prefix staging/` (dry-run). Рабочий grace по умолчанию 900 с; `--apply` включает исправление. В тестах grace=0 применяется только к созданным тестом префиксам после окончания записи. Staging принятой задачи не удаляется; корректные оригинал и варианты не становятся failed. Очистку staging после ready и по retention для failed по-прежнему выполняет worker.
|
||||
|
||||
Повторный dry-run того же вложения после исправления: [reconcile_after_fix.json](evidence/recheck_2026-11-12/reconcile_after_fix.json) — четыре объекта, orphan/missing/size mismatch = 0, изменений нет.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| lab4 сохранён с переходом 201→202; smoke (thumbnail 256×160, SHA-256, размеры JPEG) | `tests/smoke.py` | PASS | `evidence/checks.txt` |
|
||||
| 202 только после устойчивого приёма; остановка API после ответа не теряет работу | `test_resilience5` №1, №4 | worker остановлен → upload 202 → сообщение с вложением → рестарт API → worker поднят → ready | `evidence/checks.txt` |
|
||||
| Broker и worker в стенде, durable, ack после эффекта; недоступность worker не заставляет API делать resize | описание; №1 | задание ждёт в `queued`, API ничего не обрабатывает | `evidence/checks.txt` |
|
||||
| Рестарт брокера с volume, принятое не исчезает | №2 | ready после рестарта RabbitMQ | `evidence/checks.txt` |
|
||||
| Брокер недоступен при приёме → outbox | №3 | 202 при остановленном брокере; в outbox 1 неопубликованная строка; после старта брокера — ready, outbox пуст | `evidence/checks.txt` |
|
||||
| Crash между COMMIT и publish | №4 (kill всех API при остановленном брокере) | задание доведено без ручного создания | `evidence/checks.txt` |
|
||||
| Остановка worker после записи в S3 до COMMIT / после COMMIT до ack | №5, №6 (`crash_once:…`) | lease истёк → задание завершено тем же результатом, `lease_expired`+`ready` в журнале; повторная доставка — no-op, вариантов по-прежнему 3 | `evidence/checks.txt` |
|
||||
| Ограниченный retry, backoff+jitter, failed, DLQ/реестр, replay | №7 | 3 попытки → `failed/retry_exhausted`, 2 события `retry_scheduled`; реестр содержит вложение; replay → ready; повторный replay → `skipped` | `evidence/checks.txt` |
|
||||
| Варианты по контракту, EXIF, alpha, без увеличения | `test_pipeline.py` (9 тестов) | thumbnail 256×160 / EXIF 100×300 → 85×256 / 50×30 не увеличивается; crop 128×128; WebP; alpha→белый; оригинал побайтно | `evidence/checks.txt` |
|
||||
| Повторная доставка не размножает варианты | `test_ready_job_redelivery…` | 3 варианта до и после | `evidence/checks.txt` |
|
||||
| Очистка staging | `test_staging_is_cleaned…` | staging готового удалён, failed — хранится | `evidence/checks.txt` |
|
||||
| Persistence/failover | `tests/resilience.py` | PASS ×3; `StartedAt` всех 7 сервисов изменился при рестарте | `evidence/checks.txt` |
|
||||
| **Трек 1** | `research/queue_overload.py` | см. ниже | `evidence/queue_overload.json\|png` |
|
||||
Текущий skeleton — `276dbda`. README, COURSE, CONTRIBUTING, публичные tests/ и contracts/ сохранены без изменений. В Windows запущены Python-команды, соответствующие make check, make validate и make test. Полный реальный вывод — [checks_2026-11-12.txt](evidence/checks_2026-11-12.txt); команды всех собственных тестов — [student-tests/README.md](student-tests/README.md).
|
||||
|
||||
| Проверка | Результат |
|
||||
| --- | --- |
|
||||
| check_contract, полная OpenAPI-валидация, публичный smoke | PASS; upload → 202 queued → ready; original и JPEG thumbnail проверены |
|
||||
| API и аутентификация | 12 тестов OK |
|
||||
| Идемпотентность и несколько API-реплик | 9 тестов OK |
|
||||
| Изображения, лимиты, MIME, filename, ACL, private bucket, прерывание upload | 11 тестов OK |
|
||||
| Топология, порты, лимиты, непривилегированный пользователь | 6 тестов OK |
|
||||
| Варианты, EXIF, alpha, размеры, оригинал, redelivery, cleanup | 9 тестов OK, включая пиксельные проверки Pillow |
|
||||
| Безопасная сверка вариантов и staging | 2 теста OK; сохраняются все варианты и незавершённый S3-эффект, orphan защищён grace и удаляется после него |
|
||||
| Семь сценариев отказа pipeline | 7 тестов OK: worker/API/broker, outbox, crash до COMMIT/ack, lease, retry exhaustion, registry/replay |
|
||||
| TTL сессий и отказ PostgreSQL/Valkey | 2 + 2 теста OK |
|
||||
| Persistence и failover | PASS; 121 успешных записей, 0 неуспешных попыток; восстановление 2.344 с |
|
||||
| Bootstrap S3 дважды | OK: bucket сохранён, анонимный доступ 403, создание bucket ключом API запрещено |
|
||||
|
||||
Итого **60 собственных тестов**. После экспериментов первый дополнительный persistence выявил гонку старта SeaweedFS: S3-порт уже открыт, но тома ещё не зарегистрированы, и чтение объекта получает 503. Этот неуспешный запуск сохранён в commands.txt. Исправлены операторские scripts/restart.sh и .cmd: после healthy модуль app.s3_recovery ждёт LIST и ranged GET существующих объектов, читая по одному байту с параллелизмом 8 и общим таймаутом 45 с. Это отдельная проверка восстановления, а не изменение публичного теста или обещание полной готовности S3 по /health/ready API. Для большого хранилища время такого обхода может превысить лимит; hook завершится ошибкой.
|
||||
|
||||
После исправления **три последовательных persistence и финальный smoke прошли**: [restart_recheck.txt](evidence/recheck_2026-11-12/restart_recheck.txt). [lifecycle.json](evidence/recheck_2026-11-12/lifecycle.json) подтверждает в каждом повторе изменение StartedAt всех семи ролей (восемь контейнеров, включая две API-реплики), сохранение имён volumes и healthy после restart. SHA-256 изменённых после матрицы скриптов восстановления — [restart_source_metadata.json](evidence/recheck_2026-11-12/restart_source_metadata.json); обработка API/worker и измерительные скрипты матрицы не менялись.
|
||||
|
||||
## Эксперименты и отказы (трек 1)
|
||||
|
||||
**Гипотеза.** Пропускная способность worker с ростом concurrency/prefetch увеличивается только пока есть свободный CPU и не растёт память; на крупных изображениях лишний параллелизм не ускоряет, но кратно увеличивает RSS и p95. Явный лимит принятой работы (backpressure) делает отказы предсказуемыми, а принятая работа не теряется; после разгрузки система принимает новые загрузки.
|
||||
**Гипотеза.** Увеличение concurrency/prefetch ускоряет работу до насыщения CPU, но повышает память и может ухудшить latency крупных файлов. Ограничение приёма по глубине активной работы даёт предсказуемую перегрузку: отклонённые запросы получают Retry-After, а принятые задачи завершаются; после разгрузки приём восстанавливается.
|
||||
|
||||
**Методика** (`research/queue_overload.py`; Docker Desktop WSL2; worker **1 CPU / 768 MiB**; один процесс aiohttp, 8 клиентов-загрузчиков). Матрица 3 × 3: `WORKER_CONCURRENCY` ∈ {1, 2, 4} × изображения {small 320×200 PNG 109 КиБ ×80, medium 2400×1600 PNG 1.9 МиБ ×24, large 6000×4000 JPEG 3.0 МиБ ×12}; перед каждой ячейкой worker пересоздаётся (чистый пик RSS = `VmHWM`); очередь и возраст старейшего задания снимаются каждые 0.4 с; время до ready — `ready_at − accepted_at` из БД.
|
||||
**Методика.** Один worker, фактические лимиты проверяются через docker inspect: **1 CPU / 768 MiB**, concurrency=prefetch ∈ {1, 2, 4}. Девять точек: small 320×200 PNG (109 KiB, 80 загрузок), medium 2400×1600 PNG (1961 KiB, 24 загрузки), large 6000×4000 JPEG (3100 KiB, 12 загрузок). Перед каждой точкой worker пересоздаётся, чтобы VmHWM начинался заново. Клиент — один Python-процесс, 8 одновременных загрузчиков; HTTP-соединения не переиспользуются после блокирующих Docker-команд. Неопределённый результат upload при сетевой ошибке автоматически не повторяется.
|
||||
|
||||
| concurrency | small: throughput (готово/с) / p95 (с) / RSS (МиБ) | medium: throughput / p95 / RSS | large: throughput / p95 / RSS |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 28.9 / 2.46 / 75 | 4.21 / 5.05 / 136 | 3.34 / 3.37 / 161 |
|
||||
| 2 | 43.7 / 1.60 / 76 | **4.71 / 4.69** / 194 | **3.77 / 2.96** / 254 |
|
||||
| 4 | **51.8 / 1.26** / 80 | 3.97 / 5.40 / 322 | 3.60 / 3.12 / 430 |
|
||||
Клиент: Python 3.11.9, aiohttp 3.14.3, Pillow 12.3.0, matplotlib 3.11.2. Стенд: Docker Desktop, Linux-контейнеры; версии приложения и инфраструктуры закреплены в Git. На компьютере оставался другой Docker-проект. Время до ready = ready_at − accepted_at из PostgreSQL; p95 — nearest rank. Throughput — число ready / интервал от первого accepted_at до последнего ready_at: это измерение конвейера, включающее темп приёма следующих файлов. Queue lag — возраст старейшего активного задания (queued + processing); это не только ожидание в брокере. Глубина и возраст снимаются примерно каждые 0,4 с плюс время SQL/CLI. Пик RSS — VmHWM процесса worker, не память всего стенда.
|
||||
|
||||
Все 116 принятых файлов завершились `ready`, `failed` = 0, OOM-killer не срабатывал (пик 430 МиБ из 768). Пик глубины очереди/возраста старейшей задачи зависит от темпа приёма (≈20–66 заданий, до 5 с).
|
||||
| concurrency | Изображение | ready | Throughput, файлов/с | p95, с | RSS, MiB | Пик queued+processing | Возраст старейшего, с |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| 1 | small | 80 | 23.84 | 2.84 | 72.5 | 67 | 2.7 |
|
||||
| 1 | medium | 24 | 4.09 | 5.21 | 133.2 | 22 | 5.4 |
|
||||
| 1 | large | 12 | 3.38 | 3.35 | 160.4 | 11 | 3.3 |
|
||||
| 2 | small | 80 | 44.13 | 1.48 | 75.4 | 56 | 1.1 |
|
||||
| 2 | medium | 24 | 4.6 | 4.78 | 194.9 | 22 | 4.3 |
|
||||
| 2 | large | 12 | 3.84 | 2.98 | 250.9 | 12 | 2.7 |
|
||||
| 4 | small | 80 | 52.3 | 1.25 | 79.9 | 50 | 1.1 |
|
||||
| 4 | medium | 24 | 4.56 | 4.82 | 318.9 | 24 | 4.8 |
|
||||
| 4 | large | 12 | 3.39 | 3.36 | 430.0 | 12 | 2.8 |
|
||||
|
||||
Выводы: (1) для мелких файлов прирост от concurrency почти линейный (29 → 44 → 52/с: пока есть CPU); (2) для крупных изображений **оптимум — concurrency 2** (лучшие throughput и p95); при 4 процесс упирается в лимит 1 CPU и задержка растёт (medium: p95 4.69 → 5.40 с), а RSS растёт кратно (136 → 194 → 322 МиБ) — компромисс latency/ресурсы; (3) память масштабируется примерно как `concurrency × размер декодируемого изображения`, поэтому лимит памяти worker определяет допустимый prefetch для крупных файлов (рекомендация: `WORKER_CONCURRENCY=2` при 768 МиБ).
|
||||
Все **348 из 348** загрузок матрицы достигли ready; failed=0, OOMKilled=false. Максимальный измеренный RSS — **430.0 MiB** из 768. Наибольший throughput крупных изображений в этом прогоне получен при concurrency=2 (3.84 файлов/с, p95=2.98 с). Это наблюдение одного прогона на точку, а не статистически доказанный оптимум; близкие результаты следует считать сопоставимыми. На мелких файлах throughput изменился с 23.84 до 52.3 файлов/с при concurrency 1 → 4. Память крупных изображений: 160.4 → 430.0 MiB.
|
||||
|
||||
**Backpressure и восстановление** (`MAX_QUEUED_JOBS=30`, worker concurrency 1, burst 200 мелких загрузок 32 клиентами за 0.5 с): принято **57**, отклонено **143** ответами `503 + Retry-After`; пик очереди 48 (превышение лимита на число одновременных проверок — проверка лимита выполняется до приёма и не является строгой блокировкой); все 57 принятых заданий завершились `ready` за 2.6 с (`failed` 0, потерь 0, p95 = 1.9 с); после разгрузки 3 новые загрузки приняты (восстановление). График: `evidence/queue_overload_backpressure.png`.
|
||||
### Backpressure и восстановление
|
||||
|
||||
**Ограничения методики.** Один ноутбук; лимит CPU worker 1.0 — часть результата (при большем CPU оптимум concurrency сместится); темп приёма ограничен клиентом (≈8 соединений), поэтому глубина очереди на крупных файлах невелика; повтор каждой ячейки не выполнялся (единичный прогон), различия <10 % (например, medium 2 vs 4) следует считать на границе погрешности; throughput средних/крупных файлов включает время приёма байт через API.
|
||||
MAX_QUEUED_JOBS=30, один worker concurrency=1, burst из 200 мелких файлов с 32 клиентами. Принято **54**, получено **146 ответов 503**; Retry-After реально прочитан и проверен (5 с). Пик активной очереди — **48**, время разгрузки от начала burst — 2.7 с; все 54 принятых задач стали ready, failed=0, p95=1.88 с. После разгрузки три новые загрузки приняты и также достигли ready.
|
||||
|
||||
Порог является **мягким**, а не строгим резервированием мест: несколько запросов могут одновременно проверить старую глубину очереди перед приёмом тела. Поэтому пик может превышать 30. Число находящихся в приёме запросов дополнительно ограничено API concurrency/очередью и MAX_INFLIGHT. Для строгого лимита нужна атомарная резервация слотов. Этот эксперимент подтверждает ограничение приёма и восстановление, но не доказывает универсальную границу памяти при любом размере/параллелизме.
|
||||
|
||||
Из исследовательского скрипта удалён заранее выставленный `retry_after_header_seen=True`: результат определяется HTTP-заголовками. Проверяются коды/число ответов, отсутствие транспортных ошибок, готовность всех подтверждённых задач, восстановление, фактические ресурсы и OOM. Ошибка Docker или измерения не маскируется; промежуточные результаты сохраняются после каждой точки. Настройки API/worker восстанавливаются в finally.
|
||||
|
||||
Воспроизведение: `python -m pip install -r research/requirements.txt`, затем `python research/queue_overload.py --out evidence/recheck_2026-11-12`. Данные: [queue_overload.json](evidence/recheck_2026-11-12/queue_overload.json), [вывод команд](evidence/recheck_2026-11-12/commands.txt), [SHA-256 исходников](evidence/recheck_2026-11-12/source_metadata.json).
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
**Ограничения.** Один компьютер, по одному прогону на точку, фиксированный worker CPU=1; фоновые процессы и темп клиента влияют на абсолютные числа. При нескольких worker или другом CPU результаты требуют повторной проверки. Октябрьские данные в evidence/queue_overload.json и старые PNG сохранены как исторические; текущие выводы основаны на повторе 12.11.2026.
|
||||
|
||||
### Окна отказа (`contracts/attachment-states.md`)
|
||||
|
||||
| Окно | Воздействие | Результат |
|
||||
| --- | --- | --- |
|
||||
| после staging до записи задания | сбой БД после записи в staging (lab4-механизм) | staging удаляется компенсацией; иначе reconcile (lab4) |
|
||||
| после staging до записи задания | сбой БД после записи в staging (lab4-механизм) | staging удаляется компенсацией; иначе исправленный reconcile с --prefix staging/ и grace |
|
||||
| после COMMIT до publish | остановка брокера + kill всех API | outbox довёл задание |
|
||||
| после publish до confirm | таймаут/разрыв | публикация повторяется, дубликат — no-op |
|
||||
| после записи S3 до COMMIT результата | `crash_once:after_s3_before_commit` | lease → повтор тем же результатом |
|
||||
@@ -112,4 +147,4 @@ worker: claim(queued→processing, lease) → staging → thumbnail/crop/WebP
|
||||
- Один узел RabbitMQ, S3, PostgreSQL (SPOF). Отложенные повторы реализованы через outbox (брокерных delayed-exchange нет).
|
||||
- Один worker-процесс по умолчанию (`WORKER_REPLICAS` можно увеличить); lease и `SKIP LOCKED`/условные UPDATE допускают несколько worker.
|
||||
- Конкурентные записи старой и новой `pipeline_version` защищены ключом эффекта и условием `pipeline_version <= job.pipeline_version`; версионирование нескольких пайплайнов (трек 2) не реализовано.
|
||||
- Подтверждено экспериментами: оптимум concurrency для крупных изображений, рост памяти, backpressure и восстановление; гипотеза без доказательства: поведение при >1 worker и при другом лимите CPU.
|
||||
- Подтверждено экспериментами: различия измеренных throughput/p95/RSS, backpressure и восстановление; гипотеза без доказательства: поведение при >1 worker и при другом лимите CPU.
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
## Лабораторная 5
|
||||
|
||||
Автор / группа: Кушнаренко Николай Вячеславович, БПИ2302
|
||||
Целевая оценка (3/4/5): 5
|
||||
Трек 5, если заявлен: Трек 1 — очередь под перегрузкой
|
||||
|
||||
Что реализовано и что перенесено:
|
||||
Из ЛР4 перенесены PostgreSQL, сессии/Valkey, две API-реплики за HAProxy, идемпотентность сообщений, приватный S3 и вложения. Upload возвращает 202 queued только после сохранения staging в S3 и одной транзакции attachments + outbox. Relay публикует durable задания в RabbitMQ с publisher confirm; отдельный worker создаёт JPEG thumbnail, crop 128×128 и optimized WebP, сохраняет результат и подтверждает сообщение после COMMIT. Есть ограниченные retry с backoff/jitter, lease, failed registry, DLQ, безопасный replay и очистка staging. Исправлен перенесённый reconciler: варианты и незавершённые эффекты worker больше не считаются orphan. Сохранено исправление HAProxy для контрактных ошибок при отказе общей БД.
|
||||
|
||||
Команды запуска из чистого clone (bash / Git Bash):
|
||||
|
||||
```sh
|
||||
sh scripts/init-secrets.sh
|
||||
cp .env.example .env
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build --wait --wait-timeout 120
|
||||
python3 scripts/check_contract.py
|
||||
python3 tests/smoke.py --base-url http://127.0.0.1:8080
|
||||
python3 tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url http://127.0.0.1:8080
|
||||
python3 tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url http://127.0.0.1:8080
|
||||
sh scripts/restore-replicas.sh
|
||||
```
|
||||
|
||||
Windows: PYTHONUTF8=1, hooks scripts/restart.cmd и scripts/stop-one.cmd. Все собственные проверки и исследование — [student-tests/README.md](https://gitea.privcloud.tech/kolya/mtusi2026lab5/src/branch/solution/bpi2302-kushnarenko/student-tests/README.md).
|
||||
|
||||
Результаты проверок и ссылка на REPORT.md (повтор 12.11.2026):
|
||||
|
||||
- check_contract, полная OpenAPI-валидация, публичный smoke — PASS;
|
||||
- **60 собственных тестов — OK**, включая EXIF/alpha/размеры вариантов, оригинал/ACL, идемпотентность, безопасную сверку S3, TTL и отказы зависимостей;
|
||||
- семь сценариев pipeline: worker down, API/broker restart, broker down/outbox, crash COMMIT→publish, crash worker до COMMIT/ack, lease recovery, retry exhaustion и replay — OK;
|
||||
- persistence и failover — PASS; 121 успешных записей, 0 неуспешных попыток, восстановление 2.344 с;
|
||||
- дополнительный рестарт после нагрузки выявил раннюю готовность S3; hook исправлен и три последовательных persistence прошли. Проверено чтение 3670 объектов после восстановления; исходный сбой и повторы сохранены в evidence;
|
||||
- bootstrap дважды: приватность и ограниченные права API подтверждены;
|
||||
- трек 1: матрица 3×3 при worker 1 CPU / 768 MiB; 348/348 загрузок ready, failed=0, OOM нет, пик RSS 430.0 MiB; измерены throughput, p95, глубина и возраст очереди;
|
||||
- burst 200: принято 54, ответов 503 — 146 с реально проверенным Retry-After; все принятые ready; после разгрузки три новые загрузки тоже ready. Порог 30 мягкий, измеренный пик 48.
|
||||
|
||||
Отчёт: [REPORT.md](https://gitea.privcloud.tech/kolya/mtusi2026lab5/src/branch/solution/bpi2302-kushnarenko/REPORT.md), [Word](https://gitea.privcloud.tech/kolya/mtusi2026lab5/src/branch/solution/bpi2302-kushnarenko/docs/report_lab5.docx). Доказательства: [checks_2026-11-12.txt](https://gitea.privcloud.tech/kolya/mtusi2026lab5/src/branch/solution/bpi2302-kushnarenko/evidence/checks_2026-11-12.txt), [JSON и графики](https://gitea.privcloud.tech/kolya/mtusi2026lab5/src/branch/solution/bpi2302-kushnarenko/evidence/recheck_2026-11-12).
|
||||
|
||||
Ограничения / известные ошибки:
|
||||
Один узел PostgreSQL, RabbitMQ и S3; at-least-once доставка с идемпотентным эффектом. Версионирование нескольких pipeline как исследование трека 2 не заявлено. Ограничение очереди мягкое: конкурентный приём может превысить порог; строгая атомарная резервация слотов не реализована. Reconciler сохраняет неизвестные объекты внутри префикса существующего вложения; их удаление требует отдельного разбора. Замеры — по одному прогону на точку на одном компьютере с фоновой нагрузкой; устойчивый оптимум concurrency не доказан.
|
||||
|
||||
Источники и использование ИИ:
|
||||
Python, uvicorn, asyncpg, aiobotocore, aio-pika, Pillow, RabbitMQ, SeaweedFS, PostgreSQL, Valkey, HAProxy; первичные материалы перечислены в README задания. ИИ-ассистенты помогали с кодом, тестами и отчётом; Codex исправил перенос reconciler и методику исследования, проверил результаты реальными запусками.
|
||||
|
||||
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||
- [x] Контракт и публичные тесты не ослаблены.
|
||||
- [x] make check и make test выполнены через эквивалентные Python-команды; приложен реальный вывод.
|
||||
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||
Binary file not shown.
@@ -0,0 +1,209 @@
|
||||
$ python scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
exit=0
|
||||
|
||||
$ python scripts/validate_openapi.py
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
exit=0
|
||||
|
||||
$ python tests/smoke.py --base-url http://127.0.0.1:8080
|
||||
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
|
||||
exit=0
|
||||
|
||||
$ python -m unittest discover -s student-tests -p test_api.py -v
|
||||
test_bearer_rules (test_api.AuthTest.test_bearer_rules) ... ok
|
||||
test_concurrent_registration_of_same_username (test_api.AuthTest.test_concurrent_registration_of_same_username) ... ok
|
||||
test_logout_revokes_in_database_and_cache (test_api.AuthTest.test_logout_revokes_in_database_and_cache) ... ok
|
||||
test_password_is_not_exposed_or_stored_plain (test_api.AuthTest.test_password_is_not_exposed_or_stored_plain) ... ok
|
||||
test_register_validation (test_api.AuthTest.test_register_validation) ... ok
|
||||
test_session_shape_entropy_and_logout (test_api.AuthTest.test_session_shape_entropy_and_logout) ... ok
|
||||
test_token_only_stored_as_hash (test_api.AuthTest.test_token_only_stored_as_hash) ... ok
|
||||
test_wrong_password_and_unknown_user_are_indistinguishable (test_api.AuthTest.test_wrong_password_and_unknown_user_are_indistinguishable) ... ok
|
||||
test_chat_creation_is_atomic (test_api.DataTest.test_chat_creation_is_atomic) ... ok
|
||||
test_foreign_chat_empty_message_bad_json (test_api.DataTest.test_foreign_chat_empty_message_bad_json) ... ok
|
||||
test_multi_page_history_and_cursor_binding (test_api.DataTest.test_multi_page_history_and_cursor_binding) ... ok
|
||||
test_parallel_writes_from_many_clients (test_api.DataTest.test_parallel_writes_from_many_clients) ... ok
|
||||
|
||||
----------------------------------------------------------------------
|
||||
Ran 12 tests in 2.559s
|
||||
|
||||
OK
|
||||
exit=0
|
||||
|
||||
$ python -m unittest discover -s student-tests -p test_idempotency.py -v
|
||||
test_concurrent_same_key_creates_exactly_one_message_across_replicas (test_idempotency.IdempotencyTest.test_concurrent_same_key_creates_exactly_one_message_across_replicas) ... ok
|
||||
test_different_body_same_key_is_409 (test_idempotency.IdempotencyTest.test_different_body_same_key_is_409) ... ok
|
||||
test_expired_key_is_reusable_after_ttl (test_idempotency.IdempotencyTest.test_expired_key_is_reusable_after_ttl) ... ok
|
||||
test_key_validation (test_idempotency.IdempotencyTest.test_key_validation) ... ok
|
||||
test_replay_rechecks_session_and_membership (test_idempotency.IdempotencyTest.test_replay_rechecks_session_and_membership) ... ok
|
||||
test_replay_returns_same_message_and_creates_no_duplicate (test_idempotency.IdempotencyTest.test_replay_returns_same_message_and_creates_no_duplicate) ... ok
|
||||
test_scope_is_user_and_chat (test_idempotency.IdempotencyTest.test_scope_is_user_and_chat) ... ok
|
||||
test_semantically_equal_body_is_replayed (test_idempotency.IdempotencyTest.test_semantically_equal_body_is_replayed) ... ok
|
||||
test_session_is_shared_between_replicas_without_relogin (test_idempotency.IdempotencyTest.test_session_is_shared_between_replicas_without_relogin) ... ok
|
||||
|
||||
----------------------------------------------------------------------
|
||||
Ran 9 tests in 1.806s
|
||||
|
||||
OK
|
||||
exit=0
|
||||
|
||||
$ python -m unittest discover -s student-tests -p test_attachments.py -v
|
||||
test_aborted_upload_leaves_nothing (test_attachments.AttachmentTest.test_aborted_upload_leaves_nothing) ... ok
|
||||
test_bucket_is_private_outside_the_api (test_attachments.AttachmentTest.test_bucket_is_private_outside_the_api) ... ok
|
||||
test_corrupted_and_spoofed_files_are_415_not_500 (test_attachments.AttachmentTest.test_corrupted_and_spoofed_files_are_415_not_500) ... ok
|
||||
test_dangerous_filenames_are_400 (test_attachments.AttachmentTest.test_dangerous_filenames_are_400) ... ok
|
||||
test_decompression_bomb_header_is_413 (test_attachments.AttachmentTest.test_decompression_bomb_header_is_413) ... ok
|
||||
test_empty_body_is_400 (test_attachments.AttachmentTest.test_empty_body_is_400) ... ok
|
||||
test_foreign_user_cannot_upload_read_or_download (test_attachments.AttachmentTest.test_foreign_user_cannot_upload_read_or_download) ... ok
|
||||
test_idempotent_replay_with_attachments (test_attachments.AttachmentTest.test_idempotent_replay_with_attachments) ... ok
|
||||
test_message_with_attachments_and_chat_binding (test_attachments.AttachmentTest.test_message_with_attachments_and_chat_binding) ... ok
|
||||
test_png_and_jpeg_roundtrip_with_checksum (test_attachments.AttachmentTest.test_png_and_jpeg_roundtrip_with_checksum) ... ok
|
||||
test_too_large_is_413_and_nothing_is_stored (test_attachments.AttachmentTest.test_too_large_is_413_and_nothing_is_stored) ... ok
|
||||
|
||||
----------------------------------------------------------------------
|
||||
Ran 11 tests in 5.441s
|
||||
|
||||
OK
|
||||
exit=0
|
||||
|
||||
$ python -m unittest discover -s student-tests -p test_topology.py -v
|
||||
test_api_runs_as_non_root (test_topology.TopologyTest.test_api_runs_as_non_root) ... ok
|
||||
test_at_least_two_api_replicas_without_published_ports (test_topology.TopologyTest.test_at_least_two_api_replicas_without_published_ports) ... ok
|
||||
test_no_fixed_container_names (test_topology.TopologyTest.test_no_fixed_container_names) ... ok
|
||||
test_only_lb_is_published_and_only_on_localhost (test_topology.TopologyTest.test_only_lb_is_published_and_only_on_localhost) ... ok
|
||||
test_resource_limits_are_set (test_topology.TopologyTest.test_resource_limits_are_set) ... ok
|
||||
test_stop_grace_period_covers_drain (test_topology.TopologyTest.test_stop_grace_period_covers_drain) ... ok
|
||||
|
||||
----------------------------------------------------------------------
|
||||
Ran 6 tests in 1.582s
|
||||
|
||||
OK
|
||||
exit=0
|
||||
|
||||
$ python -m unittest discover -s student-tests -p test_pipeline.py -v
|
||||
test_alpha_is_composited_on_white (test_pipeline.PipelineTest.test_alpha_is_composited_on_white) ... C:\Users\kolya5544\source\repos\vmdMTUCI\mtusi2026lab5\student-tests\test_pipeline.py:25: ResourceWarning: unclosed file <_io.BufferedReader name='C:\\Users\\kolya5544\\source\\repos\\vmdMTUCI\\mtusi2026lab5\\student-tests\\fixtures\\alpha.png'>
|
||||
return open(os.path.join(FIX, name), "rb").read()
|
||||
ResourceWarning: Enable tracemalloc to get the object allocation traceback
|
||||
ok
|
||||
test_content_is_409_while_not_ready_and_original_is_untouched (test_pipeline.PipelineTest.test_content_is_409_while_not_ready_and_original_is_untouched) ... ok
|
||||
test_exif_orientation_is_applied (test_pipeline.PipelineTest.test_exif_orientation_is_applied) ... C:\Users\kolya5544\source\repos\vmdMTUCI\mtusi2026lab5\student-tests\test_pipeline.py:25: ResourceWarning: unclosed file <_io.BufferedReader name='C:\\Users\\kolya5544\\source\\repos\\vmdMTUCI\\mtusi2026lab5\\student-tests\\fixtures\\exif_rot6.jpg'>
|
||||
return open(os.path.join(FIX, name), "rb").read()
|
||||
ResourceWarning: Enable tracemalloc to get the object allocation traceback
|
||||
ok
|
||||
test_message_can_reference_attachment_before_ready_and_failed_cannot (test_pipeline.PipelineTest.test_message_can_reference_attachment_before_ready_and_failed_cannot) ... C:\Users\kolya5544\source\repos\vmdMTUCI\mtusi2026lab5\student-tests\test_pipeline.py:25: ResourceWarning: unclosed file <_io.BufferedReader name='C:\\Users\\kolya5544\\source\\repos\\vmdMTUCI\\mtusi2026lab5\\student-tests\\fixtures\\poison.png'>
|
||||
return open(os.path.join(FIX, name), "rb").read()
|
||||
ResourceWarning: Enable tracemalloc to get the object allocation traceback
|
||||
ok
|
||||
test_other_variants_visible_only_to_chat_members (test_pipeline.PipelineTest.test_other_variants_visible_only_to_chat_members) ... ok
|
||||
test_ready_job_redelivery_does_not_duplicate_variants (test_pipeline.PipelineTest.test_ready_job_redelivery_does_not_duplicate_variants) ... ok
|
||||
test_sample_png_produces_all_variants_per_contract (test_pipeline.PipelineTest.test_sample_png_produces_all_variants_per_contract) ... ok
|
||||
test_small_image_is_not_upscaled_but_crop_is_128 (test_pipeline.PipelineTest.test_small_image_is_not_upscaled_but_crop_is_128) ... C:\Users\kolya5544\source\repos\vmdMTUCI\mtusi2026lab5\student-tests\test_pipeline.py:25: ResourceWarning: unclosed file <_io.BufferedReader name='C:\\Users\\kolya5544\\source\\repos\\vmdMTUCI\\mtusi2026lab5\\student-tests\\fixtures\\small.png'>
|
||||
return open(os.path.join(FIX, name), "rb").read()
|
||||
ResourceWarning: Enable tracemalloc to get the object allocation traceback
|
||||
ok
|
||||
test_staging_is_cleaned_after_ready_and_kept_for_failed (test_pipeline.PipelineTest.test_staging_is_cleaned_after_ready_and_kept_for_failed) ... ok
|
||||
|
||||
----------------------------------------------------------------------
|
||||
Ran 9 tests in 10.719s
|
||||
|
||||
OK
|
||||
exit=0
|
||||
|
||||
$ python -m unittest discover -s student-tests -p test_reconcile5.py -v
|
||||
test_ready_variants_and_uncommitted_side_effect_are_preserved (test_reconcile5.ReconcilePipelineTest.test_ready_variants_and_uncommitted_side_effect_are_preserved) ... ok
|
||||
test_staging_is_protected_and_unowned_orphan_obeys_grace (test_reconcile5.ReconcilePipelineTest.test_staging_is_protected_and_unowned_orphan_obeys_grace) ... ok
|
||||
|
||||
----------------------------------------------------------------------
|
||||
Ran 2 tests in 28.990s
|
||||
|
||||
OK
|
||||
exit=0
|
||||
|
||||
$ python -m unittest discover -s student-tests -p test_resilience5.py -v
|
||||
test_1_worker_down_upload_api_restart_worker_up (test_resilience5.ResilienceTest.test_1_worker_down_upload_api_restart_worker_up) ... ok
|
||||
test_2_broker_restart_keeps_accepted_jobs (test_resilience5.ResilienceTest.test_2_broker_restart_keeps_accepted_jobs) ... ok
|
||||
test_3_broker_down_during_acceptance_outbox_delivers_later (test_resilience5.ResilienceTest.test_3_broker_down_during_acceptance_outbox_delivers_later) ... ok
|
||||
test_4_api_crash_between_commit_and_publish (test_resilience5.ResilienceTest.test_4_api_crash_between_commit_and_publish) ... ok
|
||||
test_5_worker_crash_after_s3_before_commit_lease_recovery (test_resilience5.ResilienceTest.test_5_worker_crash_after_s3_before_commit_lease_recovery) ... ok
|
||||
test_6_worker_crash_after_commit_before_ack_redelivery_is_noop (test_resilience5.ResilienceTest.test_6_worker_crash_after_commit_before_ack_redelivery_is_noop) ... ok
|
||||
test_7_retry_exhaustion_registry_and_operator_replay (test_resilience5.ResilienceTest.test_7_retry_exhaustion_registry_and_operator_replay) ... ok
|
||||
|
||||
----------------------------------------------------------------------
|
||||
Ran 7 tests in 141.784s
|
||||
|
||||
OK
|
||||
exit=0
|
||||
|
||||
$ 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.
|
||||
exit=0
|
||||
|
||||
$ 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": 121, "failed_attempts": 0, "first_recovery_seconds": 2.344}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
exit=0
|
||||
|
||||
$ docker compose --env-file .env start api
|
||||
Container mtusi-lab5-seaweedfs-1 Waiting
|
||||
Container mtusi-lab5-postgres-1 Waiting
|
||||
Container mtusi-lab5-postgres-1 Healthy
|
||||
Container mtusi-lab5-seaweedfs-1 Healthy
|
||||
Container mtusi-lab5-migrate-1 Starting
|
||||
Container mtusi-lab5-s3-init-1 Starting
|
||||
Container mtusi-lab5-migrate-1 Started
|
||||
Container mtusi-lab5-s3-init-1 Started
|
||||
Container mtusi-lab5-migrate-1 Waiting
|
||||
Container mtusi-lab5-s3-init-1 Waiting
|
||||
Container mtusi-lab5-valkey-1 Waiting
|
||||
Container mtusi-lab5-valkey-1 Healthy
|
||||
Container mtusi-lab5-migrate-1 Exited
|
||||
Container mtusi-lab5-s3-init-1 Exited
|
||||
Container mtusi-lab5-api-1 Starting
|
||||
Container mtusi-lab5-api-1 Started
|
||||
exit=0
|
||||
|
||||
$ python student-tests/test_expiry.py
|
||||
..
|
||||
----------------------------------------------------------------------
|
||||
Ran 2 tests in 19.786s
|
||||
|
||||
OK
|
||||
exit=0
|
||||
|
||||
$ python student-tests/test_dependencies.py
|
||||
..
|
||||
----------------------------------------------------------------------
|
||||
Ran 2 tests in 20.171s
|
||||
|
||||
OK
|
||||
exit=0
|
||||
|
||||
$ docker compose --env-file .env run --rm -T s3-init
|
||||
Container mtusi-lab5-seaweedfs-1 Running
|
||||
Container mtusi-lab5-seaweedfs-1 Waiting
|
||||
Container mtusi-lab5-seaweedfs-1 Healthy
|
||||
Container mtusi-lab5-s3-init-run-54461bd2fe34 Creating
|
||||
Container mtusi-lab5-s3-init-run-54461bd2fe34 Created
|
||||
bucket messenger-attachments уже существует
|
||||
анонимный доступ запрещён (HTTP 403)
|
||||
ключ API ограничен одним bucket (create_bucket отклонён: AccessDenied)
|
||||
bootstrap завершён
|
||||
exit=0
|
||||
|
||||
$ docker compose --env-file .env run --rm -T s3-init
|
||||
Container mtusi-lab5-seaweedfs-1 Running
|
||||
Container mtusi-lab5-seaweedfs-1 Waiting
|
||||
Container mtusi-lab5-seaweedfs-1 Healthy
|
||||
Container mtusi-lab5-s3-init-run-84c641a11c75 Creating
|
||||
Container mtusi-lab5-s3-init-run-84c641a11c75 Created
|
||||
bucket messenger-attachments уже существует
|
||||
анонимный доступ запрещён (HTTP 403)
|
||||
ключ API ограничен одним bucket (create_bucket отклонён: AccessDenied)
|
||||
bootstrap завершён
|
||||
exit=0
|
||||
|
||||
$ python tests/smoke.py --base-url http://127.0.0.1:8080
|
||||
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
|
||||
exit=0
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"MAX_QUEUED_JOBS": 30,
|
||||
"burst": 200,
|
||||
"attempt_statuses": {
|
||||
"202": 54,
|
||||
"503": 146
|
||||
},
|
||||
"accepted": 54,
|
||||
"peak_queue_depth": 48,
|
||||
"all_accepted_finished": true,
|
||||
"accepted_in_s": 0.5,
|
||||
"drained_after_s": 2.7,
|
||||
"retry_after_header_seen": true,
|
||||
"retry_after_values": [
|
||||
"5"
|
||||
],
|
||||
"transport_errors": [],
|
||||
"recovered_new_uploads_accepted": true,
|
||||
"recovered_new_uploads_ready": true,
|
||||
"no_accepted_job_lost": true,
|
||||
"ready": 54,
|
||||
"failed": 0,
|
||||
"p95_s": 1.88
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
$ python -u research/queue_overload.py --out evidence\recheck_2026-11-12
|
||||
{'small': '109 KiB', 'medium': '1961 KiB', 'large': '3100 KiB'}
|
||||
{"concurrency": 1, "image": "small", "image_kib": 109, "uploads": 80, "accepted": 80, "resource_limits": {"memory_bytes": 805306368, "nano_cpus": 1000000000}, "attempt_statuses": {"202": 80}, "transport_errors": [], "accepted_in_s": 0.5, "all_finished": true, "peak_queue_depth": 67, "peak_oldest_age_s": 2.7, "worker_peak_rss_mib": 72.5, "worker_oom_killed": "false", "ready": 80, "failed": 0, "p50_s": 1.55, "p95_s": 2.84, "max_s": 3.0, "throughput_per_s": 23.84, "span_s": 3.4}
|
||||
{"concurrency": 1, "image": "medium", "image_kib": 1961, "uploads": 24, "accepted": 24, "resource_limits": {"memory_bytes": 805306368, "nano_cpus": 1000000000}, "attempt_statuses": {"202": 24}, "transport_errors": [], "accepted_in_s": 0.5, "all_finished": true, "peak_queue_depth": 22, "peak_oldest_age_s": 5.4, "worker_peak_rss_mib": 133.2, "worker_oom_killed": "false", "ready": 24, "failed": 0, "p50_s": 2.83, "p95_s": 5.21, "max_s": 5.44, "throughput_per_s": 4.09, "span_s": 5.9}
|
||||
{"concurrency": 1, "image": "large", "image_kib": 3100, "uploads": 12, "accepted": 12, "resource_limits": {"memory_bytes": 805306368, "nano_cpus": 1000000000}, "attempt_statuses": {"202": 12}, "transport_errors": [], "accepted_in_s": 0.3, "all_finished": true, "peak_queue_depth": 11, "peak_oldest_age_s": 3.3, "worker_peak_rss_mib": 160.4, "worker_oom_killed": "false", "ready": 12, "failed": 0, "p50_s": 1.74, "p95_s": 3.35, "max_s": 3.35, "throughput_per_s": 3.38, "span_s": 3.6}
|
||||
{"concurrency": 2, "image": "small", "image_kib": 109, "uploads": 80, "accepted": 80, "resource_limits": {"memory_bytes": 805306368, "nano_cpus": 1000000000}, "attempt_statuses": {"202": 80}, "transport_errors": [], "accepted_in_s": 0.3, "all_finished": true, "peak_queue_depth": 56, "peak_oldest_age_s": 1.1, "worker_peak_rss_mib": 75.4, "worker_oom_killed": "false", "ready": 80, "failed": 0, "p50_s": 0.89, "p95_s": 1.48, "max_s": 1.55, "throughput_per_s": 44.13, "span_s": 1.8}
|
||||
{"concurrency": 2, "image": "medium", "image_kib": 1961, "uploads": 24, "accepted": 24, "resource_limits": {"memory_bytes": 805306368, "nano_cpus": 1000000000}, "attempt_statuses": {"202": 24}, "transport_errors": [], "accepted_in_s": 0.5, "all_finished": true, "peak_queue_depth": 22, "peak_oldest_age_s": 4.3, "worker_peak_rss_mib": 194.9, "worker_oom_killed": "false", "ready": 24, "failed": 0, "p50_s": 2.43, "p95_s": 4.78, "max_s": 4.8, "throughput_per_s": 4.6, "span_s": 5.2}
|
||||
{"concurrency": 2, "image": "large", "image_kib": 3100, "uploads": 12, "accepted": 12, "resource_limits": {"memory_bytes": 805306368, "nano_cpus": 1000000000}, "attempt_statuses": {"202": 12}, "transport_errors": [], "accepted_in_s": 0.4, "all_finished": true, "peak_queue_depth": 12, "peak_oldest_age_s": 2.7, "worker_peak_rss_mib": 250.9, "worker_oom_killed": "false", "ready": 12, "failed": 0, "p50_s": 1.59, "p95_s": 2.98, "max_s": 2.98, "throughput_per_s": 3.84, "span_s": 3.1}
|
||||
{"concurrency": 4, "image": "small", "image_kib": 109, "uploads": 80, "accepted": 80, "resource_limits": {"memory_bytes": 805306368, "nano_cpus": 1000000000}, "attempt_statuses": {"202": 80}, "transport_errors": [], "accepted_in_s": 0.3, "all_finished": true, "peak_queue_depth": 50, "peak_oldest_age_s": 1.1, "worker_peak_rss_mib": 79.9, "worker_oom_killed": "false", "ready": 80, "failed": 0, "p50_s": 0.7, "p95_s": 1.25, "max_s": 1.29, "throughput_per_s": 52.3, "span_s": 1.5}
|
||||
{"concurrency": 4, "image": "medium", "image_kib": 1961, "uploads": 24, "accepted": 24, "resource_limits": {"memory_bytes": 805306368, "nano_cpus": 1000000000}, "attempt_statuses": {"202": 24}, "transport_errors": [], "accepted_in_s": 0.5, "all_finished": true, "peak_queue_depth": 24, "peak_oldest_age_s": 4.8, "worker_peak_rss_mib": 318.9, "worker_oom_killed": "false", "ready": 24, "failed": 0, "p50_s": 2.59, "p95_s": 4.82, "max_s": 4.86, "throughput_per_s": 4.56, "span_s": 5.3}
|
||||
{"concurrency": 4, "image": "large", "image_kib": 3100, "uploads": 12, "accepted": 12, "resource_limits": {"memory_bytes": 805306368, "nano_cpus": 1000000000}, "attempt_statuses": {"202": 12}, "transport_errors": [], "accepted_in_s": 0.4, "all_finished": true, "peak_queue_depth": 12, "peak_oldest_age_s": 2.8, "worker_peak_rss_mib": 430.0, "worker_oom_killed": "false", "ready": 12, "failed": 0, "p50_s": 2.32, "p95_s": 3.36, "max_s": 3.36, "throughput_per_s": 3.39, "span_s": 3.5}
|
||||
{"MAX_QUEUED_JOBS": 30, "burst": 200, "attempt_statuses": {"202": 54, "503": 146}, "accepted": 54, "peak_queue_depth": 48, "all_accepted_finished": true, "accepted_in_s": 0.5, "drained_after_s": 2.7, "retry_after_header_seen": true, "retry_after_values": ["5"], "transport_errors": [], "recovered_new_uploads_accepted": true, "recovered_new_uploads_ready": true, "no_accepted_job_lost": true, "ready": 54, "failed": 0, "p95_s": 1.88}
|
||||
exit=0
|
||||
|
||||
$ 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.
|
||||
FAIL: GET /api/v1/attachments/85bcfa7b-e1e8-4bdf-8b95-e1a8b2804fc5/content: expected [200], received 503
|
||||
exit=1
|
||||
@@ -0,0 +1,482 @@
|
||||
{
|
||||
"before": {
|
||||
"mtusi-lab5-api-1": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:59:24.547575282Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-api-2": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:59:24.409530572Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-lb-1": {
|
||||
"service": "lb",
|
||||
"started_at": "2026-11-12T00:59:20.643619346Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-postgres-1": {
|
||||
"service": "postgres",
|
||||
"started_at": "2026-11-12T00:59:21.319524713Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_pgdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-rabbitmq-1": {
|
||||
"service": "rabbitmq",
|
||||
"started_at": "2026-11-12T00:59:21.501174229Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_rabbitmqdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-seaweedfs-1": {
|
||||
"service": "seaweedfs",
|
||||
"started_at": "2026-11-12T00:59:21.638684596Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_seaweeddata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-valkey-1": {
|
||||
"service": "valkey",
|
||||
"started_at": "2026-11-12T00:59:20.874723039Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_valkeydata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-worker-1": {
|
||||
"service": "worker",
|
||||
"started_at": "2026-11-12T00:59:21.145794756Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"mtusi-lab5-api-1": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:59:56.213556685Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-api-2": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:59:57.500333699Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-lb-1": {
|
||||
"service": "lb",
|
||||
"started_at": "2026-11-12T00:59:52.516283057Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-postgres-1": {
|
||||
"service": "postgres",
|
||||
"started_at": "2026-11-12T00:59:52.920661248Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_pgdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-rabbitmq-1": {
|
||||
"service": "rabbitmq",
|
||||
"started_at": "2026-11-12T00:59:53.435646134Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_rabbitmqdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-seaweedfs-1": {
|
||||
"service": "seaweedfs",
|
||||
"started_at": "2026-11-12T00:59:53.598244344Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_seaweeddata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-valkey-1": {
|
||||
"service": "valkey",
|
||||
"started_at": "2026-11-12T00:59:52.145208673Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_valkeydata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-worker-1": {
|
||||
"service": "worker",
|
||||
"started_at": "2026-11-12T00:59:53.235224376Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
}
|
||||
},
|
||||
"all_services_restarted": true,
|
||||
"volumes_preserved": true,
|
||||
"repeats": [
|
||||
{
|
||||
"before": {
|
||||
"mtusi-lab5-api-1": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:58:45.575826913Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-api-2": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:58:45.881190123Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-lb-1": {
|
||||
"service": "lb",
|
||||
"started_at": "2026-11-12T00:53:10.601145103Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-postgres-1": {
|
||||
"service": "postgres",
|
||||
"started_at": "2026-11-12T00:53:11.16711263Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_pgdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-rabbitmq-1": {
|
||||
"service": "rabbitmq",
|
||||
"started_at": "2026-11-12T00:53:11.484387397Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_rabbitmqdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-seaweedfs-1": {
|
||||
"service": "seaweedfs",
|
||||
"started_at": "2026-11-12T00:53:11.643485706Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_seaweeddata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-valkey-1": {
|
||||
"service": "valkey",
|
||||
"started_at": "2026-11-12T00:53:10.885267441Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_valkeydata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-worker-1": {
|
||||
"service": "worker",
|
||||
"started_at": "2026-11-12T00:58:45.578958104Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"mtusi-lab5-api-1": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:58:58.27211915Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-api-2": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:58:57.47079238Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-lb-1": {
|
||||
"service": "lb",
|
||||
"started_at": "2026-11-12T00:58:53.874340617Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-postgres-1": {
|
||||
"service": "postgres",
|
||||
"started_at": "2026-11-12T00:58:54.35128221Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_pgdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-rabbitmq-1": {
|
||||
"service": "rabbitmq",
|
||||
"started_at": "2026-11-12T00:58:54.980171011Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_rabbitmqdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-seaweedfs-1": {
|
||||
"service": "seaweedfs",
|
||||
"started_at": "2026-11-12T00:58:55.259407602Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_seaweeddata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-valkey-1": {
|
||||
"service": "valkey",
|
||||
"started_at": "2026-11-12T00:58:54.512669953Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_valkeydata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-worker-1": {
|
||||
"service": "worker",
|
||||
"started_at": "2026-11-12T00:58:54.76173897Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
}
|
||||
},
|
||||
"all_services_restarted": true,
|
||||
"volumes_preserved": true
|
||||
},
|
||||
{
|
||||
"before": {
|
||||
"mtusi-lab5-api-1": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:58:58.27211915Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-api-2": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:58:57.47079238Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-lb-1": {
|
||||
"service": "lb",
|
||||
"started_at": "2026-11-12T00:58:53.874340617Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-postgres-1": {
|
||||
"service": "postgres",
|
||||
"started_at": "2026-11-12T00:58:54.35128221Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_pgdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-rabbitmq-1": {
|
||||
"service": "rabbitmq",
|
||||
"started_at": "2026-11-12T00:58:54.980171011Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_rabbitmqdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-seaweedfs-1": {
|
||||
"service": "seaweedfs",
|
||||
"started_at": "2026-11-12T00:58:55.259407602Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_seaweeddata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-valkey-1": {
|
||||
"service": "valkey",
|
||||
"started_at": "2026-11-12T00:58:54.512669953Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_valkeydata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-worker-1": {
|
||||
"service": "worker",
|
||||
"started_at": "2026-11-12T00:58:54.76173897Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"mtusi-lab5-api-1": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:59:24.547575282Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-api-2": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:59:24.409530572Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-lb-1": {
|
||||
"service": "lb",
|
||||
"started_at": "2026-11-12T00:59:20.643619346Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-postgres-1": {
|
||||
"service": "postgres",
|
||||
"started_at": "2026-11-12T00:59:21.319524713Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_pgdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-rabbitmq-1": {
|
||||
"service": "rabbitmq",
|
||||
"started_at": "2026-11-12T00:59:21.501174229Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_rabbitmqdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-seaweedfs-1": {
|
||||
"service": "seaweedfs",
|
||||
"started_at": "2026-11-12T00:59:21.638684596Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_seaweeddata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-valkey-1": {
|
||||
"service": "valkey",
|
||||
"started_at": "2026-11-12T00:59:20.874723039Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_valkeydata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-worker-1": {
|
||||
"service": "worker",
|
||||
"started_at": "2026-11-12T00:59:21.145794756Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
}
|
||||
},
|
||||
"all_services_restarted": true,
|
||||
"volumes_preserved": true
|
||||
},
|
||||
{
|
||||
"before": {
|
||||
"mtusi-lab5-api-1": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:59:24.547575282Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-api-2": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:59:24.409530572Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-lb-1": {
|
||||
"service": "lb",
|
||||
"started_at": "2026-11-12T00:59:20.643619346Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-postgres-1": {
|
||||
"service": "postgres",
|
||||
"started_at": "2026-11-12T00:59:21.319524713Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_pgdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-rabbitmq-1": {
|
||||
"service": "rabbitmq",
|
||||
"started_at": "2026-11-12T00:59:21.501174229Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_rabbitmqdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-seaweedfs-1": {
|
||||
"service": "seaweedfs",
|
||||
"started_at": "2026-11-12T00:59:21.638684596Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_seaweeddata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-valkey-1": {
|
||||
"service": "valkey",
|
||||
"started_at": "2026-11-12T00:59:20.874723039Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_valkeydata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-worker-1": {
|
||||
"service": "worker",
|
||||
"started_at": "2026-11-12T00:59:21.145794756Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"mtusi-lab5-api-1": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:59:56.213556685Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-api-2": {
|
||||
"service": "api",
|
||||
"started_at": "2026-11-12T00:59:57.500333699Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-lb-1": {
|
||||
"service": "lb",
|
||||
"started_at": "2026-11-12T00:59:52.516283057Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
},
|
||||
"mtusi-lab5-postgres-1": {
|
||||
"service": "postgres",
|
||||
"started_at": "2026-11-12T00:59:52.920661248Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_pgdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-rabbitmq-1": {
|
||||
"service": "rabbitmq",
|
||||
"started_at": "2026-11-12T00:59:53.435646134Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_rabbitmqdata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-seaweedfs-1": {
|
||||
"service": "seaweedfs",
|
||||
"started_at": "2026-11-12T00:59:53.598244344Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_seaweeddata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-valkey-1": {
|
||||
"service": "valkey",
|
||||
"started_at": "2026-11-12T00:59:52.145208673Z",
|
||||
"health": "healthy",
|
||||
"volumes": [
|
||||
"mtusi-lab5_valkeydata"
|
||||
]
|
||||
},
|
||||
"mtusi-lab5-worker-1": {
|
||||
"service": "worker",
|
||||
"started_at": "2026-11-12T00:59:53.235224376Z",
|
||||
"health": "healthy",
|
||||
"volumes": []
|
||||
}
|
||||
},
|
||||
"all_services_restarted": true,
|
||||
"volumes_preserved": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
[
|
||||
{
|
||||
"concurrency": 1,
|
||||
"image": "small",
|
||||
"image_kib": 109,
|
||||
"uploads": 80,
|
||||
"accepted": 80,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 80
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.5,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 67,
|
||||
"peak_oldest_age_s": 2.7,
|
||||
"worker_peak_rss_mib": 72.5,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 80,
|
||||
"failed": 0,
|
||||
"p50_s": 1.55,
|
||||
"p95_s": 2.84,
|
||||
"max_s": 3.0,
|
||||
"throughput_per_s": 23.84,
|
||||
"span_s": 3.4
|
||||
},
|
||||
{
|
||||
"concurrency": 1,
|
||||
"image": "medium",
|
||||
"image_kib": 1961,
|
||||
"uploads": 24,
|
||||
"accepted": 24,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 24
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.5,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 22,
|
||||
"peak_oldest_age_s": 5.4,
|
||||
"worker_peak_rss_mib": 133.2,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 24,
|
||||
"failed": 0,
|
||||
"p50_s": 2.83,
|
||||
"p95_s": 5.21,
|
||||
"max_s": 5.44,
|
||||
"throughput_per_s": 4.09,
|
||||
"span_s": 5.9
|
||||
},
|
||||
{
|
||||
"concurrency": 1,
|
||||
"image": "large",
|
||||
"image_kib": 3100,
|
||||
"uploads": 12,
|
||||
"accepted": 12,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 12
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.3,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 11,
|
||||
"peak_oldest_age_s": 3.3,
|
||||
"worker_peak_rss_mib": 160.4,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 12,
|
||||
"failed": 0,
|
||||
"p50_s": 1.74,
|
||||
"p95_s": 3.35,
|
||||
"max_s": 3.35,
|
||||
"throughput_per_s": 3.38,
|
||||
"span_s": 3.6
|
||||
},
|
||||
{
|
||||
"concurrency": 2,
|
||||
"image": "small",
|
||||
"image_kib": 109,
|
||||
"uploads": 80,
|
||||
"accepted": 80,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 80
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.3,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 56,
|
||||
"peak_oldest_age_s": 1.1,
|
||||
"worker_peak_rss_mib": 75.4,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 80,
|
||||
"failed": 0,
|
||||
"p50_s": 0.89,
|
||||
"p95_s": 1.48,
|
||||
"max_s": 1.55,
|
||||
"throughput_per_s": 44.13,
|
||||
"span_s": 1.8
|
||||
},
|
||||
{
|
||||
"concurrency": 2,
|
||||
"image": "medium",
|
||||
"image_kib": 1961,
|
||||
"uploads": 24,
|
||||
"accepted": 24,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 24
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.5,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 22,
|
||||
"peak_oldest_age_s": 4.3,
|
||||
"worker_peak_rss_mib": 194.9,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 24,
|
||||
"failed": 0,
|
||||
"p50_s": 2.43,
|
||||
"p95_s": 4.78,
|
||||
"max_s": 4.8,
|
||||
"throughput_per_s": 4.6,
|
||||
"span_s": 5.2
|
||||
},
|
||||
{
|
||||
"concurrency": 2,
|
||||
"image": "large",
|
||||
"image_kib": 3100,
|
||||
"uploads": 12,
|
||||
"accepted": 12,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 12
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.4,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 12,
|
||||
"peak_oldest_age_s": 2.7,
|
||||
"worker_peak_rss_mib": 250.9,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 12,
|
||||
"failed": 0,
|
||||
"p50_s": 1.59,
|
||||
"p95_s": 2.98,
|
||||
"max_s": 2.98,
|
||||
"throughput_per_s": 3.84,
|
||||
"span_s": 3.1
|
||||
},
|
||||
{
|
||||
"concurrency": 4,
|
||||
"image": "small",
|
||||
"image_kib": 109,
|
||||
"uploads": 80,
|
||||
"accepted": 80,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 80
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.3,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 50,
|
||||
"peak_oldest_age_s": 1.1,
|
||||
"worker_peak_rss_mib": 79.9,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 80,
|
||||
"failed": 0,
|
||||
"p50_s": 0.7,
|
||||
"p95_s": 1.25,
|
||||
"max_s": 1.29,
|
||||
"throughput_per_s": 52.3,
|
||||
"span_s": 1.5
|
||||
},
|
||||
{
|
||||
"concurrency": 4,
|
||||
"image": "medium",
|
||||
"image_kib": 1961,
|
||||
"uploads": 24,
|
||||
"accepted": 24,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 24
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.5,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 24,
|
||||
"peak_oldest_age_s": 4.8,
|
||||
"worker_peak_rss_mib": 318.9,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 24,
|
||||
"failed": 0,
|
||||
"p50_s": 2.59,
|
||||
"p95_s": 4.82,
|
||||
"max_s": 4.86,
|
||||
"throughput_per_s": 4.56,
|
||||
"span_s": 5.3
|
||||
},
|
||||
{
|
||||
"concurrency": 4,
|
||||
"image": "large",
|
||||
"image_kib": 3100,
|
||||
"uploads": 12,
|
||||
"accepted": 12,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 12
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.4,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 12,
|
||||
"peak_oldest_age_s": 2.8,
|
||||
"worker_peak_rss_mib": 430.0,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 12,
|
||||
"failed": 0,
|
||||
"p50_s": 2.32,
|
||||
"p95_s": 3.36,
|
||||
"max_s": 3.36,
|
||||
"throughput_per_s": 3.39,
|
||||
"span_s": 3.5
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,331 @@
|
||||
{
|
||||
"date": "2026-11-12 03:49:47",
|
||||
"args": {
|
||||
"out": "evidence\\recheck_2026-11-12",
|
||||
"concurrency": [
|
||||
1,
|
||||
2,
|
||||
4
|
||||
],
|
||||
"n_small": 80,
|
||||
"n_medium": 24,
|
||||
"n_large": 12,
|
||||
"limit": 30,
|
||||
"burst": 200,
|
||||
"b_medium": false
|
||||
},
|
||||
"worker_limits": {
|
||||
"cpus": 1.0,
|
||||
"memory": "768m"
|
||||
},
|
||||
"image_kib": {
|
||||
"small": 109,
|
||||
"medium": 1961,
|
||||
"large": 3100
|
||||
},
|
||||
"matrix": [
|
||||
{
|
||||
"concurrency": 1,
|
||||
"image": "small",
|
||||
"image_kib": 109,
|
||||
"uploads": 80,
|
||||
"accepted": 80,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 80
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.5,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 67,
|
||||
"peak_oldest_age_s": 2.7,
|
||||
"worker_peak_rss_mib": 72.5,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 80,
|
||||
"failed": 0,
|
||||
"p50_s": 1.55,
|
||||
"p95_s": 2.84,
|
||||
"max_s": 3.0,
|
||||
"throughput_per_s": 23.84,
|
||||
"span_s": 3.4
|
||||
},
|
||||
{
|
||||
"concurrency": 1,
|
||||
"image": "medium",
|
||||
"image_kib": 1961,
|
||||
"uploads": 24,
|
||||
"accepted": 24,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 24
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.5,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 22,
|
||||
"peak_oldest_age_s": 5.4,
|
||||
"worker_peak_rss_mib": 133.2,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 24,
|
||||
"failed": 0,
|
||||
"p50_s": 2.83,
|
||||
"p95_s": 5.21,
|
||||
"max_s": 5.44,
|
||||
"throughput_per_s": 4.09,
|
||||
"span_s": 5.9
|
||||
},
|
||||
{
|
||||
"concurrency": 1,
|
||||
"image": "large",
|
||||
"image_kib": 3100,
|
||||
"uploads": 12,
|
||||
"accepted": 12,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 12
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.3,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 11,
|
||||
"peak_oldest_age_s": 3.3,
|
||||
"worker_peak_rss_mib": 160.4,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 12,
|
||||
"failed": 0,
|
||||
"p50_s": 1.74,
|
||||
"p95_s": 3.35,
|
||||
"max_s": 3.35,
|
||||
"throughput_per_s": 3.38,
|
||||
"span_s": 3.6
|
||||
},
|
||||
{
|
||||
"concurrency": 2,
|
||||
"image": "small",
|
||||
"image_kib": 109,
|
||||
"uploads": 80,
|
||||
"accepted": 80,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 80
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.3,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 56,
|
||||
"peak_oldest_age_s": 1.1,
|
||||
"worker_peak_rss_mib": 75.4,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 80,
|
||||
"failed": 0,
|
||||
"p50_s": 0.89,
|
||||
"p95_s": 1.48,
|
||||
"max_s": 1.55,
|
||||
"throughput_per_s": 44.13,
|
||||
"span_s": 1.8
|
||||
},
|
||||
{
|
||||
"concurrency": 2,
|
||||
"image": "medium",
|
||||
"image_kib": 1961,
|
||||
"uploads": 24,
|
||||
"accepted": 24,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 24
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.5,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 22,
|
||||
"peak_oldest_age_s": 4.3,
|
||||
"worker_peak_rss_mib": 194.9,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 24,
|
||||
"failed": 0,
|
||||
"p50_s": 2.43,
|
||||
"p95_s": 4.78,
|
||||
"max_s": 4.8,
|
||||
"throughput_per_s": 4.6,
|
||||
"span_s": 5.2
|
||||
},
|
||||
{
|
||||
"concurrency": 2,
|
||||
"image": "large",
|
||||
"image_kib": 3100,
|
||||
"uploads": 12,
|
||||
"accepted": 12,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 12
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.4,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 12,
|
||||
"peak_oldest_age_s": 2.7,
|
||||
"worker_peak_rss_mib": 250.9,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 12,
|
||||
"failed": 0,
|
||||
"p50_s": 1.59,
|
||||
"p95_s": 2.98,
|
||||
"max_s": 2.98,
|
||||
"throughput_per_s": 3.84,
|
||||
"span_s": 3.1
|
||||
},
|
||||
{
|
||||
"concurrency": 4,
|
||||
"image": "small",
|
||||
"image_kib": 109,
|
||||
"uploads": 80,
|
||||
"accepted": 80,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 80
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.3,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 50,
|
||||
"peak_oldest_age_s": 1.1,
|
||||
"worker_peak_rss_mib": 79.9,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 80,
|
||||
"failed": 0,
|
||||
"p50_s": 0.7,
|
||||
"p95_s": 1.25,
|
||||
"max_s": 1.29,
|
||||
"throughput_per_s": 52.3,
|
||||
"span_s": 1.5
|
||||
},
|
||||
{
|
||||
"concurrency": 4,
|
||||
"image": "medium",
|
||||
"image_kib": 1961,
|
||||
"uploads": 24,
|
||||
"accepted": 24,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 24
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.5,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 24,
|
||||
"peak_oldest_age_s": 4.8,
|
||||
"worker_peak_rss_mib": 318.9,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 24,
|
||||
"failed": 0,
|
||||
"p50_s": 2.59,
|
||||
"p95_s": 4.82,
|
||||
"max_s": 4.86,
|
||||
"throughput_per_s": 4.56,
|
||||
"span_s": 5.3
|
||||
},
|
||||
{
|
||||
"concurrency": 4,
|
||||
"image": "large",
|
||||
"image_kib": 3100,
|
||||
"uploads": 12,
|
||||
"accepted": 12,
|
||||
"resource_limits": {
|
||||
"memory_bytes": 805306368,
|
||||
"nano_cpus": 1000000000
|
||||
},
|
||||
"attempt_statuses": {
|
||||
"202": 12
|
||||
},
|
||||
"transport_errors": [],
|
||||
"accepted_in_s": 0.4,
|
||||
"all_finished": true,
|
||||
"peak_queue_depth": 12,
|
||||
"peak_oldest_age_s": 2.8,
|
||||
"worker_peak_rss_mib": 430.0,
|
||||
"worker_oom_killed": "false",
|
||||
"ready": 12,
|
||||
"failed": 0,
|
||||
"p50_s": 2.32,
|
||||
"p95_s": 3.36,
|
||||
"max_s": 3.36,
|
||||
"throughput_per_s": 3.39,
|
||||
"span_s": 3.5
|
||||
}
|
||||
],
|
||||
"backpressure": {
|
||||
"MAX_QUEUED_JOBS": 30,
|
||||
"burst": 200,
|
||||
"attempt_statuses": {
|
||||
"202": 54,
|
||||
"503": 146
|
||||
},
|
||||
"accepted": 54,
|
||||
"peak_queue_depth": 48,
|
||||
"all_accepted_finished": true,
|
||||
"accepted_in_s": 0.5,
|
||||
"drained_after_s": 2.7,
|
||||
"retry_after_header_seen": true,
|
||||
"retry_after_values": [
|
||||
"5"
|
||||
],
|
||||
"transport_errors": [],
|
||||
"recovered_new_uploads_accepted": true,
|
||||
"recovered_new_uploads_ready": true,
|
||||
"no_accepted_job_lost": true,
|
||||
"ready": 54,
|
||||
"failed": 0,
|
||||
"p95_s": 1.88
|
||||
},
|
||||
"backpressure_queue_samples": [
|
||||
[
|
||||
0.2,
|
||||
0,
|
||||
0.0
|
||||
],
|
||||
[
|
||||
0.7,
|
||||
48,
|
||||
0.5
|
||||
],
|
||||
[
|
||||
1.3,
|
||||
33,
|
||||
1.0
|
||||
],
|
||||
[
|
||||
1.9,
|
||||
16,
|
||||
1.4
|
||||
],
|
||||
[
|
||||
2.4,
|
||||
1,
|
||||
1.9
|
||||
]
|
||||
]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 38 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 95 KiB |
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"grace_seconds": 0,
|
||||
"db_rows": 923,
|
||||
"s3_objects": 4,
|
||||
"orphan_objects": [],
|
||||
"orphans_skipped_fresh": 0,
|
||||
"owned_objects_skipped": 0,
|
||||
"missing_objects": [],
|
||||
"size_mismatch": [],
|
||||
"fixed": {
|
||||
"deleted_orphans": 0,
|
||||
"marked_failed": 0
|
||||
},
|
||||
"timing_ms": {
|
||||
"db_query": 6.1,
|
||||
"s3_listing": 24.7,
|
||||
"total": 127.3
|
||||
},
|
||||
"orphan_objects_count": 0,
|
||||
"missing_objects_count": 0,
|
||||
"size_mismatch_count": 0
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"mode": "dry-run",
|
||||
"grace_seconds": 0,
|
||||
"db_rows": 481,
|
||||
"s3_objects": 4,
|
||||
"orphan_objects": [
|
||||
"att/e42b205e-2226-4de0-b4c3-9819acb5a53f/v1/crop",
|
||||
"att/e42b205e-2226-4de0-b4c3-9819acb5a53f/v1/optimized",
|
||||
"att/e42b205e-2226-4de0-b4c3-9819acb5a53f/v1/thumbnail"
|
||||
],
|
||||
"orphans_skipped_fresh": 0,
|
||||
"missing_objects": [],
|
||||
"size_mismatch": [],
|
||||
"fixed": {
|
||||
"deleted_orphans": 0,
|
||||
"marked_failed": 0
|
||||
},
|
||||
"timing_ms": {
|
||||
"db_query": 2.8,
|
||||
"s3_listing": 32.4,
|
||||
"total": 117.4
|
||||
},
|
||||
"orphan_objects_count": 3,
|
||||
"missing_objects_count": 0,
|
||||
"size_mismatch_count": 0
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
$ 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.
|
||||
exit=0
|
||||
|
||||
$ 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.
|
||||
exit=0
|
||||
|
||||
$ 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.
|
||||
exit=0
|
||||
|
||||
$ docker compose exec -T api python -m app.s3_recovery
|
||||
PASS: S3 recovery, 3670 existing objects readable
|
||||
exit=0
|
||||
|
||||
$ python tests/smoke.py --base-url http://127.0.0.1:8080
|
||||
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
|
||||
exit=0
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"reason": "Recovery hook now waits for ranged GET of existing S3 objects after volume registration; API/worker processing code unchanged since matrix.",
|
||||
"source_sha256": {
|
||||
"scripts/restart.cmd": "d1de857d3544f900de64a36734950b65d272f1ef4533669df411de9b235193cf",
|
||||
"scripts/restart.sh": "cd0b99b0e981eb00049dc69b438bb21a844c2a318203660c836fd82d9e324d10",
|
||||
"src/app/s3_recovery.py": "aaabec7f578fb74f150cd80140efaae04b8f84e38358d61d056ccc930158db18"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"date": "2026-11-12",
|
||||
"base_solution_commit": "518c98fd3e6bd593bbb22b5bdd07f82ecff65720",
|
||||
"branch": "solution/bpi2302-kushnarenko",
|
||||
"python_client": "3.11.9 (tags/v3.11.9:de54cf5, Apr 2 2024, 10:12:12) [MSC v.1938 64 bit (AMD64)]",
|
||||
"source_sha256": {
|
||||
"research/requirements.txt": "0a0f9ffaa9b56d590cb38c77f9da8dbc64f2d503b69fc27b0116b9a9594b2591",
|
||||
"student-tests/README.md": "2bfdbe9f72497f6ddb6d4d1cccccedc0c9d9c044f39596a0286fec0eb975dcc0",
|
||||
"student-tests/test_dependencies.py": "e152b87441d1374ce9b69d3d441d262e47890313d2ccc798f5e2cff2e3719399",
|
||||
"student-tests/test_expiry.py": "16a374ebe3df15c50c07a9fc3bc801c6c532dde3c4185b164c6aea4605923f83",
|
||||
"student-tests/test_reconcile5.py": "7df51d06fc6da180fada10d3d6e1233c9462870ec18f6d55753a36e30dca458b",
|
||||
"Dockerfile": "f1dc711cacf00e3e2bd6b4a0616c925e357446ebda370e7e5fdb3170eaecd4cb",
|
||||
"compose.yaml": "1562ea10580ea3c58766b9696cf7b59d631ddec68f2d809a3a79d6f48a63a151",
|
||||
"infra/README.md": "33a4f7b870fd0b2bed98d46daf26d45dd7436176739672925246f8e3fe7c2278",
|
||||
"infra/haproxy/haproxy.cfg": "511fb24b32740c332cd7b6ea42d3f1cf252e1452de754ff97c8e6886f3692061",
|
||||
"requirements.txt": "9add304ba15ae74bf5d3658496b8241121f82ab748a1bd163c2763fa1cd57e65",
|
||||
"research/failover_sequence.py": "c23a0472f54538fd9d7607c017bef4f127269850ca7bf09adc57862fe2b7665b",
|
||||
"research/loadgen.py": "7e06f5a04a1ec1b187a2fd3af82b0748ed042e1e9d63e350ab2007d21826fe1c",
|
||||
"research/queue_overload.py": "b0b37aea9fd0c9b00652555724084caa2b9629e9f3e9635fc52203ca3170a6f5",
|
||||
"research/rolling_update.py": "447da4a9e2161bb232669f0558d6cb15ae3f0ef181fdf563e19cd56135b58240",
|
||||
"scripts/check_contract.py": "61e300fe5c1074360418e24b4653b12f96808247a2beaf2a64859aa360f81493",
|
||||
"scripts/init-secrets.sh": "9cbe6b6058769a820b84f61b2076028d97d487ce04fe98e42d38dddf45c97fd8",
|
||||
"scripts/restart.cmd": "b6bc654fae1b4fcf8b4765ce5ec8082d8b645e8e4cf15bfdf6904b26d860b866",
|
||||
"scripts/restart.example.sh": "0328246ba75defbced992104e986fde973f63e3830d83251eced5953263e944b",
|
||||
"scripts/restart.sh": "a00e3d82bc97e34deaa9fa8e7ed24f4386057502cdff7aa750680b96a82e18a7",
|
||||
"scripts/restore-replicas.sh": "88ba99a10808f211a72b111ce240f7fa7df8dbf796f4c2d81d05b1a95008b46d",
|
||||
"scripts/rolling-update.sh": "cdeaff25aaf0ae3fc030bf1d8fe8ae6300ac51741b780bfe080ce6bbac959632",
|
||||
"scripts/stop-one.cmd": "0e6d46bc7abc2f81403422f985ee9d0d2ad02e0cfd9db2db0fccc873020d8997",
|
||||
"scripts/stop-one.example.sh": "1bcf34394520b89d95b7605ec56675be799eea920e83cfbba306d5dc0a6d9811",
|
||||
"scripts/stop-one.sh": "c74672836f70c24b44afa2d531f9287e51fb87690e1d0ca5c9e4ed0abaa0b48e",
|
||||
"scripts/validate_openapi.py": "cd7a33221b1860c5d2330e52afa6cb222d375db671ae9ab379ba51a0d3a77946",
|
||||
"src/app/attachments.py": "b7ac49012e3e504e069a9a1f7de61b0a73bbf121359c897111cda719a00d60f5",
|
||||
"src/app/broker.py": "b68f297acd17bbd4d63b140cef06b89f73048da6d35fc6027717d54c5cf3733b",
|
||||
"src/app/config.py": "854a09110b8f8ce5ca634461a4a402ef37c9a2e9c32169ba388f832066e03b6f",
|
||||
"src/app/db.py": "7510882b0e8c9f6a24d680a156c285bc1a0fcf021473ca47173aa0744d845a78",
|
||||
"src/app/images.py": "3dc7434cbfbc9d4c01b95eb897c1332b2a2748dd9df88c99a7086f3e4cdf4c41",
|
||||
"src/app/main.py": "89745c1b21b87626626d82a1f5a8561441595d476eb90a49ac0d1dc7f11a4a90",
|
||||
"src/app/migrate.py": "cabc192ca4182af780636415a008d2dd4636dad7d3cf0f4a8a2b52a48aedaa7e",
|
||||
"src/app/outbox.py": "2326c21e4eb910a10bd2e4613e88b211bea1125b3f452aecc1b5ec7b4e6e0bc8",
|
||||
"src/app/passwords.py": "836fc282093058f6717eaa6374775251ed655dcd517f325dc60323a88154f261",
|
||||
"src/app/pipeline.py": "222ac87f275e4607ecdc98cdc5f68d8957fd7f68603af2d2643f3026445a3fe1",
|
||||
"src/app/reconcile.py": "c7dd35bf40e672ffe15f0e878913e17f6c6d9de3f69922b4edb38d1802330dc4",
|
||||
"src/app/replay.py": "2669b9e5fa2f6fb83dbe457f0241db166eb3e370e21d81c3e32f922060f52fa5",
|
||||
"src/app/s3.py": "091ddac8facd4c61f223111b3aaab48efff7d6ef9a30af4ac86d4352024f0727",
|
||||
"src/app/s3_bootstrap.py": "216d8121d6e7b25d95b845f4deaff18fd31eeb28484e51fe4c463c646a3af0d1",
|
||||
"src/app/serve.py": "3ebe12cf8cb2dddfc7d7234bba9bd190d868cc88d02e61fe640ba51dcf115b55",
|
||||
"src/app/sessions.py": "f975eb27c50c024f3e562f755ee97bb7bfe21cf5e01cc1d347bf107971c30670",
|
||||
"src/app/web.py": "23271be669a19bd7abfd6eaae25e25ce214718f0f623406cb9a2f6e77e365b83",
|
||||
"src/app/worker.py": "065a7e7e1c67d961452527122f5cc53c18873f0d83a8335aad2278374197a1cb",
|
||||
"student-tests/fixtures/alpha.png": "1f9d6ee26fa7beb4ba179c7c38ae97f5f31e95ad9d4108267352225e6705882f",
|
||||
"student-tests/fixtures/exif_rot6.jpg": "62386265960512fd51279e40723331c6c52f81ba2325d82afc3fb14f3b332ddc",
|
||||
"student-tests/fixtures/poison.png": "2be4bea6355e83da4733b1d7f59dc985dfe22cf5d8283eea9b20871d1f43c252",
|
||||
"student-tests/fixtures/sample.jpg": "33a614b40fe6ae25fdbd99af22e7d9d3e5dbea455b36aac750de112c034a6311",
|
||||
"student-tests/fixtures/sample.png": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75",
|
||||
"student-tests/fixtures/small.png": "001e6b4538ce86cbb0c88a34a2b88c111336b8dc8825af81e0f7d9630b731e32",
|
||||
"student-tests/test_api.py": "2635113842a5b26ec1fdd98ea42fc861edb1d10895e8be6c2eff46ed73fdba9d",
|
||||
"student-tests/test_attachments.py": "519bc20867996e03e79121ec461c94a9123faa1d11b2faedbdcf62e556fc0a05",
|
||||
"student-tests/test_idempotency.py": "4ee985a3ef26fefa816fdb136fa2b0644cca13d73fe3a226d1ba975a55698b5b",
|
||||
"student-tests/test_pipeline.py": "a322c1c72c5beeef2bb4f0436d36d2a9a005872054c48649c85be23289b84796",
|
||||
"student-tests/test_resilience5.py": "68f3f297f1068d598cedd9aa1373f63e5d135f3599e0d8bf134ea047e7def30a",
|
||||
"student-tests/test_topology.py": "58050c5b330d0b290959b95fbd541b25cd966453399fbbbb627c8df906d7ffb6"
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,8 @@ defaults
|
||||
timeout queue 5s
|
||||
retries 3
|
||||
option redispatch 1
|
||||
retry-on conn-failure empty-response response-timeout 0rtt-rejected
|
||||
# Only retry before a connection is established: upload POST has no idempotency key.
|
||||
retry-on conn-failure
|
||||
|
||||
# Docker DNS (127.0.0.11): адреса реплик API обновляются без перезапуска LB (scale up/down, пересоздание контейнеров).
|
||||
resolvers docker
|
||||
@@ -33,6 +34,9 @@ resolvers docker
|
||||
|
||||
frontend public
|
||||
bind :8080
|
||||
# If the shared DB is down, live API processes still produce contract JSON,
|
||||
# validate missing credentials, and serve /health/live independently of DB.
|
||||
use_backend api_live if { nbsrv(api) eq 0 }
|
||||
default_backend api
|
||||
|
||||
# Внутренний healthcheck самого LB (контейнерный HEALTHCHECK); наружу не публикуется.
|
||||
@@ -48,3 +52,11 @@ backend api
|
||||
http-check expect status 200
|
||||
default-server check inter 1s fall 2 rise 2 resolvers docker init-addr none
|
||||
server-template api 1-8 api:8080
|
||||
|
||||
backend api_live
|
||||
balance roundrobin
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/live
|
||||
http-check expect status 200
|
||||
default-server check inter 1s fall 2 rise 2 resolvers docker init-addr none
|
||||
server-template api 1-8 api:8080
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Render the measured matrix vertically so labels remain readable in an A4 report."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import matplotlib
|
||||
matplotlib.use('Agg')
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('--input', type=Path, required=True)
|
||||
ap.add_argument('--output', type=Path, required=True)
|
||||
args = ap.parse_args()
|
||||
data = json.loads(args.input.read_text(encoding='utf-8'))
|
||||
plt.rcParams.update({'font.size': 11})
|
||||
fig, axes = plt.subplots(3, 1, figsize=(7.8, 9.2))
|
||||
sizes = ['small', 'medium', 'large']
|
||||
concs = sorted({r['concurrency'] for r in data['matrix']})
|
||||
for ax, key, title, unit in zip(axes,
|
||||
['throughput_per_s', 'p95_s', 'worker_peak_rss_mib'],
|
||||
['Пропускная способность конвейера', 'p95 времени от приёма до ready', 'Пик RSS worker'],
|
||||
['файлов/с', 'с', 'MiB']):
|
||||
for i, conc in enumerate(concs):
|
||||
values = [next(r[key] for r in data['matrix'] if r['concurrency'] == conc and r['image'] == size) for size in sizes]
|
||||
ax.bar([j + (i - 1) * .26 for j in range(3)], values, width=.25, label=f'concurrency={conc}')
|
||||
ax.set_xticks(range(3), ['320×200 PNG', '2400×1600 PNG', '6000×4000 JPEG'])
|
||||
ax.set_title(title)
|
||||
ax.set_ylabel(unit)
|
||||
ax.legend(ncol=3, fontsize=9)
|
||||
ax.grid(axis='y', alpha=.2)
|
||||
ax.set_axisbelow(True)
|
||||
fig.suptitle('ЛР5: worker 1 CPU / 768 MiB, один прогон на точку', fontsize=12)
|
||||
fig.tight_layout()
|
||||
fig.savefig(args.output, dpi=160)
|
||||
plt.close(fig)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+61
-23
@@ -6,7 +6,8 @@
|
||||
(burst), параллельно каждые 0.5 с снимаются глубина очереди и возраст старейшей задачи. Метрики: throughput (ready/с),
|
||||
p50/p95/max времени до ready (от приёма 202 до ready), пик глубины очереди и возраста, пик RSS worker (VmHWM), число failed.
|
||||
Часть B — backpressure и восстановление: MAX_QUEUED_JOBS=30, worker concurrency 1, burst 200 мелких файлов 32 клиентами:
|
||||
API принимает не более лимита очереди и отвечает 503 + Retry-After; принятые задания не теряются (все ready);
|
||||
API ограничивает приём по порогу очереди и отвечает 503 + Retry-After (возможен конкурентный overshoot);
|
||||
принятые задания не теряются (все ready);
|
||||
после разгрузки новая загрузка снова принимается.
|
||||
python research/queue_overload.py --out evidence
|
||||
"""
|
||||
@@ -15,6 +16,7 @@ import asyncio
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import statistics
|
||||
import subprocess
|
||||
@@ -31,7 +33,8 @@ PROJECT = "mtusi-lab5"
|
||||
|
||||
|
||||
def sh(*args, env=None):
|
||||
return subprocess.run(args, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", env=dict(os.environ, **(env or {}))).stdout.strip()
|
||||
return subprocess.run(args, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", check=True,
|
||||
env=dict(os.environ, **(env or {}))).stdout.strip()
|
||||
|
||||
|
||||
def psql(sql):
|
||||
@@ -50,6 +53,8 @@ def recreate(service, env, wait_seconds=90):
|
||||
if healthy(service, 1 if service == "worker" else 2):
|
||||
break
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise RuntimeError("%s did not become healthy within %d seconds" % (service, wait_seconds))
|
||||
time.sleep(6 if service == "api" else 3)
|
||||
|
||||
|
||||
@@ -88,17 +93,18 @@ async def register(s):
|
||||
class QueueSampler(threading.Thread):
|
||||
def __init__(self):
|
||||
super().__init__(daemon=True)
|
||||
self.samples, self.stop = [], threading.Event()
|
||||
self.samples, self.stop, self.errors = [], threading.Event(), []
|
||||
self.t0 = time.time()
|
||||
|
||||
def run(self):
|
||||
while not self.stop.is_set():
|
||||
out = psql("SELECT count(*), coalesce(extract(epoch FROM now() - min(accepted_at)), 0) FROM attachments WHERE status IN ('queued', 'processing')")
|
||||
try:
|
||||
out = psql("SELECT count(*), coalesce(extract(epoch FROM now() - min(accepted_at)), 0) FROM attachments WHERE status IN ('queued', 'processing')")
|
||||
n, age = out.split("|")
|
||||
self.samples.append((time.time() - self.t0, int(n), float(age)))
|
||||
except ValueError:
|
||||
pass
|
||||
except Exception as exc:
|
||||
self.errors.append(type(exc).__name__)
|
||||
return
|
||||
self.stop.wait(0.4)
|
||||
|
||||
|
||||
@@ -114,6 +120,7 @@ def worker_peak_rss():
|
||||
async def burst(s, token, chat, data, n, clients, retry_503=False):
|
||||
"""Загружает n файлов клиентами; возвращает (accepted ids, rejected, attempts_statuses)."""
|
||||
accepted, statuses, sem = [], {}, asyncio.Semaphore(clients)
|
||||
observed = {"retry_after_values": [], "transport_errors": []}
|
||||
|
||||
async def one(i):
|
||||
async with sem:
|
||||
@@ -123,6 +130,8 @@ async def burst(s, token, chat, data, n, clients, retry_503=False):
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": "image/jpeg" if data[:2] == b"\xff\xd8" else "image/png"}) as r:
|
||||
body = await r.json(content_type=None)
|
||||
statuses[str(r.status)] = statuses.get(str(r.status), 0) + 1
|
||||
if r.status in (503, 429):
|
||||
observed["retry_after_values"].append(r.headers.get("Retry-After"))
|
||||
if r.status == 202:
|
||||
accepted.append(body["id"])
|
||||
return
|
||||
@@ -130,13 +139,17 @@ async def burst(s, token, chat, data, n, clients, retry_503=False):
|
||||
await asyncio.sleep(float(r.headers.get("Retry-After", "1")))
|
||||
continue
|
||||
return
|
||||
except aiohttp.ClientError:
|
||||
await asyncio.sleep(0.2)
|
||||
except aiohttp.ClientError as exc:
|
||||
# Upload is not idempotent: an uncertain response must not trigger a hidden retry.
|
||||
observed["transport_errors"].append(type(exc).__name__)
|
||||
return
|
||||
await asyncio.gather(*(one(i) for i in range(n)))
|
||||
return accepted, statuses
|
||||
return accepted, statuses, observed
|
||||
|
||||
|
||||
def wait_all(ids, seconds):
|
||||
if not ids:
|
||||
raise ValueError("no accepted jobs to measure")
|
||||
deadline = time.time() + seconds
|
||||
while time.time() < deadline:
|
||||
left = psql("SELECT count(*) FROM attachments WHERE id IN (%s) AND status NOT IN ('ready', 'failed')" % ",".join("'%s'" % i for i in ids))
|
||||
@@ -160,7 +173,7 @@ def stats_for(ids):
|
||||
elif status == "failed":
|
||||
failed += 1
|
||||
ttr.sort()
|
||||
pct = lambda p: round(ttr[min(len(ttr) - 1, int(p * len(ttr)))], 2) if ttr else None # noqa: E731
|
||||
pct = lambda p: round(ttr[max(0, math.ceil(p * len(ttr)) - 1)], 2) if ttr else None # noqa: E731
|
||||
span = (last - first) if first is not None else None
|
||||
return {"ready": ready, "failed": failed, "p50_s": pct(0.5), "p95_s": pct(0.95), "max_s": round(max(ttr), 2) if ttr else None,
|
||||
"throughput_per_s": round(ready / span, 2) if span else None, "span_s": round(span, 1) if span else None}
|
||||
@@ -172,62 +185,87 @@ async def part_a(args, images):
|
||||
for conc in args.concurrency:
|
||||
for size, n in sizes.items():
|
||||
recreate("worker", {"WORKER_CONCURRENCY": str(conc)})
|
||||
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=120), connector=aiohttp.TCPConnector(limit=16)) as s:
|
||||
ids_worker = sh("docker", "compose", "ps", "-q", "worker").split()
|
||||
assert len(ids_worker) == 1, "this experiment requires exactly one worker"
|
||||
limits = json.loads(sh("docker", "inspect", "-f",
|
||||
'{"memory_bytes":{{.HostConfig.Memory}},"nano_cpus":{{.HostConfig.NanoCpus}}}', ids_worker[0]))
|
||||
assert limits == {"memory_bytes": 768 * 1024 * 1024, "nano_cpus": 1000000000}, limits
|
||||
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=120), connector=aiohttp.TCPConnector(limit=16, force_close=True)) as s:
|
||||
token, chat = await register(s)
|
||||
sampler = QueueSampler()
|
||||
sampler.start()
|
||||
t0 = time.time()
|
||||
ids, statuses = await burst(s, token, chat, images[size], n, 8)
|
||||
ids, statuses, observed = await burst(s, token, chat, images[size], n, 8)
|
||||
accepted_in = time.time() - t0
|
||||
done = wait_all(ids, 400)
|
||||
sampler.stop.set()
|
||||
sampler.join()
|
||||
cell = {"concurrency": conc, "image": size, "image_kib": round(len(images[size]) / 1024), "uploads": n, "accepted": len(ids),
|
||||
"resource_limits": limits, "attempt_statuses": statuses, "transport_errors": observed["transport_errors"],
|
||||
"accepted_in_s": round(accepted_in, 1), "all_finished": done, "peak_queue_depth": max((x[1] for x in sampler.samples), default=0),
|
||||
"peak_oldest_age_s": round(max((x[2] for x in sampler.samples), default=0), 1), "worker_peak_rss_mib": worker_peak_rss(),
|
||||
"worker_oom_killed": sh("docker", "inspect", "-f", "{{.State.OOMKilled}}", sh("docker", "compose", "--env-file", ".env", "ps", "-q", "worker").split()[0])}
|
||||
cell.update(stats_for(ids))
|
||||
print(json.dumps(cell, ensure_ascii=False))
|
||||
cells.append(cell)
|
||||
with open(os.path.join(args.out, "matrix_progress.json"), "w", encoding="utf-8") as fh:
|
||||
json.dump(cells, fh, ensure_ascii=False, indent=2)
|
||||
assert not sampler.errors and sampler.samples, sampler.errors
|
||||
assert len(ids) == len(set(ids)) == n and statuses == {"202": n} and not observed["transport_errors"], cell
|
||||
assert done and cell["ready"] == n and cell["failed"] == 0, cell
|
||||
assert cell["worker_oom_killed"] == "false" and 0 < cell["worker_peak_rss_mib"] < 768, cell
|
||||
return cells
|
||||
|
||||
|
||||
async def part_b(args, images):
|
||||
recreate("api", {"MAX_QUEUED_JOBS": str(args.limit)})
|
||||
recreate("worker", {"WORKER_CONCURRENCY": "1"})
|
||||
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=120), connector=aiohttp.TCPConnector(limit=64)) as s:
|
||||
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=120), connector=aiohttp.TCPConnector(limit=64, force_close=True)) as s:
|
||||
token, chat = await register(s)
|
||||
sampler = QueueSampler()
|
||||
sampler.start()
|
||||
t0 = time.time()
|
||||
ids, statuses = await burst(s, token, chat, images["small"] if not args.b_medium else images["medium"], args.burst, 32, retry_503=False)
|
||||
ids, statuses, observed = await burst(s, token, chat, images["small"] if not args.b_medium else images["medium"], args.burst, 32, retry_503=False)
|
||||
accepted_in = time.time() - t0
|
||||
done = wait_all(ids, 300)
|
||||
drained_after = time.time() - t0
|
||||
sampler.stop.set()
|
||||
sampler.join()
|
||||
# восстановление: после разгрузки новая загрузка принимается
|
||||
extra, st2 = await burst(s, token, chat, images["small"], 3, 1)
|
||||
wait_all(extra, 60)
|
||||
extra, st2, observed2 = await burst(s, token, chat, images["small"], 3, 1)
|
||||
extra_done = wait_all(extra, 60)
|
||||
throttled = observed["retry_after_values"]
|
||||
valid_retry_after = bool(throttled) and all(v is not None and v.isdigit() and int(v) >= 1 for v in throttled)
|
||||
res = {"MAX_QUEUED_JOBS": args.limit, "burst": args.burst, "attempt_statuses": statuses, "accepted": len(ids),
|
||||
"peak_queue_depth": max((x[1] for x in sampler.samples), default=0), "all_accepted_finished": done,
|
||||
"accepted_in_s": round(accepted_in, 1), "drained_after_s": round(drained_after, 1),
|
||||
"retry_after_header_seen": True, "recovered_new_uploads_accepted": len(extra) == 3,
|
||||
"retry_after_header_seen": valid_retry_after, "retry_after_values": sorted(set(throttled), key=str),
|
||||
"transport_errors": observed["transport_errors"], "recovered_new_uploads_accepted": len(extra) == 3,
|
||||
"recovered_new_uploads_ready": extra_done and stats_for(extra)["ready"] == 3,
|
||||
"no_accepted_job_lost": stats_for(ids)["ready"] + stats_for(ids)["failed"] == len(ids), **{k: v for k, v in stats_for(ids).items() if k in ("ready", "failed", "p95_s")}}
|
||||
print(json.dumps(res, ensure_ascii=False))
|
||||
recreate("api", {})
|
||||
recreate("worker", {})
|
||||
with open(os.path.join(args.out, "backpressure_progress.json"), "w", encoding="utf-8") as fh:
|
||||
json.dump(res, fh, ensure_ascii=False, indent=2)
|
||||
assert not sampler.errors and sampler.samples, sampler.errors
|
||||
assert statuses.get("503", 0) > 0 and sum(statuses.values()) == args.burst and valid_retry_after, res
|
||||
assert set(statuses) <= {"202", "503", "429"} and not observed["transport_errors"], res
|
||||
assert done and res["ready"] == len(ids) and res["failed"] == 0 and res["no_accepted_job_lost"], res
|
||||
assert res["recovered_new_uploads_accepted"] and res["recovered_new_uploads_ready"] and not observed2["transport_errors"], res
|
||||
return res, [(round(t, 1), n, round(a, 1)) for t, n, a in sampler.samples]
|
||||
|
||||
|
||||
async def main(args):
|
||||
os.makedirs(args.out, exist_ok=True)
|
||||
images = make_images(ROOT)
|
||||
print({k: "%d KiB" % (len(v) // 1024) for k, v in images.items()})
|
||||
report = {"date": time.strftime("%Y-%m-%d %H:%M:%S"), "args": vars(args), "worker_limits": {"cpus": 1.0, "memory": "768m"},
|
||||
"image_kib": {k: round(len(v) / 1024) for k, v in images.items()}}
|
||||
report["matrix"] = await part_a(args, images)
|
||||
recreate("worker", {})
|
||||
report["backpressure"], samples = await part_b(args, images)
|
||||
try:
|
||||
report["matrix"] = await part_a(args, images)
|
||||
report["backpressure"], samples = await part_b(args, images)
|
||||
finally:
|
||||
recreate("api", {})
|
||||
recreate("worker", {})
|
||||
report["backpressure_queue_samples"] = samples
|
||||
with open(os.path.join(args.out, "queue_overload.json"), "w", encoding="utf-8") as fh:
|
||||
json.dump(report, fh, ensure_ascii=False, indent=2)
|
||||
@@ -241,7 +279,7 @@ def plot(report, path):
|
||||
fig, ax = plt.subplots(1, 3, figsize=(17, 5))
|
||||
sizes = ["small", "medium", "large"]
|
||||
concs = sorted({c["concurrency"] for c in report["matrix"]})
|
||||
for k, (key, title, unit) in enumerate((("throughput_per_s", "Пропускная способность worker", "готово/с"), ("p95_s", "p95 времени до ready", "с"),
|
||||
for k, (key, title, unit) in enumerate((("throughput_per_s", "Пропускная способность конвейера", "готово/с"), ("p95_s", "p95 времени до ready", "с"),
|
||||
("worker_peak_rss_mib", "Пик RSS worker (лимит 768 МиБ)", "МиБ"))):
|
||||
for i, c in enumerate(concs):
|
||||
vals = [next((x[key] for x in report["matrix"] if x["concurrency"] == c and x["image"] == s), 0) or 0 for s in sizes]
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
aiohttp==3.14.3
|
||||
Pillow==12.3.0
|
||||
matplotlib==3.11.2
|
||||
@@ -4,4 +4,6 @@ cd /d "%~dp0.."
|
||||
docker compose --env-file .env restart postgres valkey seaweedfs rabbitmq worker api lb >NUL 2>&1
|
||||
if errorlevel 1 exit /b 1
|
||||
docker compose --env-file .env up -d --wait --no-recreate --no-deps postgres valkey seaweedfs rabbitmq worker api lb >NUL 2>&1
|
||||
if errorlevel 1 exit /b 1
|
||||
docker compose --env-file .env exec -T api python -m app.s3_recovery
|
||||
exit /b %errorlevel%
|
||||
|
||||
@@ -5,3 +5,4 @@ set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose --env-file .env restart postgres valkey seaweedfs rabbitmq worker api lb >/dev/null 2>&1
|
||||
docker compose --env-file .env up -d --wait --no-recreate --no-deps postgres valkey seaweedfs rabbitmq worker api lb >/dev/null 2>&1
|
||||
docker compose --env-file .env exec -T api python -m app.s3_recovery
|
||||
|
||||
+34
-7
@@ -15,6 +15,7 @@ import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import asyncpg
|
||||
@@ -23,6 +24,17 @@ from . import config
|
||||
from .s3 import S3
|
||||
|
||||
|
||||
def object_owner(key):
|
||||
"""Recognize server-generated prefixes, including effects not committed yet."""
|
||||
parts = key.split("/")
|
||||
if (parts[0] == "att" and len(parts) >= 3) or (parts[0] == "staging" and len(parts) == 2):
|
||||
try:
|
||||
return uuid.UUID(parts[1])
|
||||
except ValueError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
async def reconcile(apply, grace, prefix):
|
||||
started = time.perf_counter()
|
||||
s3 = S3()
|
||||
@@ -30,9 +42,15 @@ async def reconcile(apply, grace, prefix):
|
||||
conn = await asyncpg.connect(config.DATABASE_URL, timeout=5)
|
||||
try:
|
||||
t0 = time.perf_counter()
|
||||
rows = await conn.fetch("SELECT id, s3_key, size_bytes, status, created_at FROM attachments")
|
||||
rows = await conn.fetch("SELECT id, s3_key, staging_key, size_bytes, status, created_at FROM attachments")
|
||||
variants = await conn.fetch(
|
||||
"SELECT a.id, v.s3_key, v.size_bytes, a.status, a.created_at "
|
||||
"FROM attachment_variants v JOIN attachments a ON a.id = v.attachment_id")
|
||||
db_ms = (time.perf_counter() - t0) * 1000
|
||||
by_key = {r["s3_key"]: r for r in rows}
|
||||
by_key = {r["s3_key"]: dict(r, check=True) for r in [*rows, *variants]}
|
||||
# Staging may already be removed after ready, or retained for failed/replay.
|
||||
by_key.update({r["staging_key"]: dict(r, check=False) for r in rows if r["staging_key"]})
|
||||
owners = {r["id"] for r in rows}
|
||||
t0 = time.perf_counter()
|
||||
objects = {}
|
||||
async for key, size, modified in s3.list_keys(prefix):
|
||||
@@ -41,23 +59,32 @@ async def reconcile(apply, grace, prefix):
|
||||
now = datetime.now(timezone.utc)
|
||||
cutoff = now - timedelta(seconds=grace)
|
||||
report = {"mode": "apply" if apply else "dry-run", "grace_seconds": grace, "db_rows": len(rows), "s3_objects": len(objects),
|
||||
"orphan_objects": [], "orphans_skipped_fresh": 0, "missing_objects": [], "size_mismatch": [], "fixed": {"deleted_orphans": 0, "marked_failed": 0}}
|
||||
"orphan_objects": [], "orphans_skipped_fresh": 0, "owned_objects_skipped": 0,
|
||||
"missing_objects": [], "size_mismatch": [], "fixed": {"deleted_orphans": 0, "marked_failed": 0}}
|
||||
for key, (size, modified) in objects.items():
|
||||
row = by_key.get(key)
|
||||
if row is None:
|
||||
if modified < cutoff:
|
||||
if object_owner(key) in owners:
|
||||
# Worker can write S3 variants before committing their metadata.
|
||||
report["owned_objects_skipped"] += 1
|
||||
elif modified < cutoff:
|
||||
report["orphan_objects"].append(key)
|
||||
else:
|
||||
report["orphans_skipped_fresh"] += 1
|
||||
elif row["status"] == "ready" and row["size_bytes"] != size:
|
||||
elif row["check"] and row["status"] == "ready" and row["size_bytes"] != size:
|
||||
report["size_mismatch"].append(str(row["id"]))
|
||||
for key, row in by_key.items():
|
||||
if key.startswith(prefix) and key not in objects and row["status"] == "ready" and row["created_at"] < cutoff:
|
||||
if row["check"] and key.startswith(prefix) and key not in objects and row["status"] == "ready" and row["created_at"] < cutoff:
|
||||
report["missing_objects"].append(str(row["id"]))
|
||||
for field in ("missing_objects", "size_mismatch"):
|
||||
report[field] = sorted(set(report[field]))
|
||||
if apply:
|
||||
for key in report["orphan_objects"]:
|
||||
# повторная проверка перед удалением: за время обхода строка могла появиться
|
||||
if await conn.fetchval("SELECT 1 FROM attachments WHERE s3_key = $1", key) is None:
|
||||
referenced = await conn.fetchval(
|
||||
"SELECT EXISTS (SELECT 1 FROM attachments WHERE s3_key = $1 OR staging_key = $1 OR id = $2) "
|
||||
"OR EXISTS (SELECT 1 FROM attachment_variants WHERE s3_key = $1)", key, object_owner(key))
|
||||
if not referenced:
|
||||
await s3.delete(key)
|
||||
report["fixed"]["deleted_orphans"] += 1
|
||||
for ids, code in ((report["missing_objects"], "object_missing"), (report["size_mismatch"], "size_mismatch")):
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Read-only operator probe after a full restart: LIST and ranged GET of existing objects.
|
||||
|
||||
An open S3 socket / HEAD bucket does not prove that SeaweedFS volume locations
|
||||
have been registered. Read one byte per nonempty object, including staging.
|
||||
This is a bounded recovery hook, not an expensive per-request health check.
|
||||
"""
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from . import config
|
||||
from .s3 import S3
|
||||
|
||||
|
||||
async def probe(s3):
|
||||
count = 0
|
||||
batch = []
|
||||
|
||||
async def read(key, size):
|
||||
params = {"Bucket": config.S3_BUCKET, "Key": key}
|
||||
if size:
|
||||
params["Range"] = "bytes=0-0"
|
||||
response = await s3.client.get_object(**params)
|
||||
async with response["Body"] as stream:
|
||||
data = await stream.read()
|
||||
if len(data) != min(size, 1):
|
||||
raise ValueError("unexpected ranged read size")
|
||||
|
||||
async def flush():
|
||||
results = await asyncio.gather(*(read(key, size) for key, size in batch), return_exceptions=True)
|
||||
for result in results:
|
||||
if isinstance(result, BaseException):
|
||||
raise result
|
||||
|
||||
await s3.ping()
|
||||
async for key, size, _ in s3.list_keys(""):
|
||||
batch.append((key, size))
|
||||
count += 1
|
||||
if len(batch) == 8:
|
||||
await flush()
|
||||
batch.clear()
|
||||
if batch:
|
||||
await flush()
|
||||
return count
|
||||
|
||||
|
||||
async def main():
|
||||
s3 = S3()
|
||||
await s3.start()
|
||||
try:
|
||||
async with asyncio.timeout(45):
|
||||
while True:
|
||||
try:
|
||||
count = await probe(s3)
|
||||
print(f"PASS: S3 recovery, {count} existing objects readable")
|
||||
return 0
|
||||
except Exception as exc:
|
||||
# Do not print SDK requests/credentials or object contents.
|
||||
print(f"Waiting for S3 data volumes: {type(exc).__name__}", flush=True)
|
||||
await asyncio.sleep(1)
|
||||
except TimeoutError:
|
||||
print("FAIL: S3 data recovery exceeded 45 seconds")
|
||||
return 1
|
||||
finally:
|
||||
await s3.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main()))
|
||||
@@ -0,0 +1,51 @@
|
||||
# Собственные проверки ЛР5
|
||||
|
||||
Поднимите отдельный учебный стенд по [REPORT.md](../REPORT.md) и дождитесь готовности всех сервисов. Команды выполняются из корня репозитория. На Windows установите `$env:PYTHONUTF8='1'`. Для пиксельных проверок необходим Pillow: `python -m pip install Pillow==12.3.0`.
|
||||
|
||||
```sh
|
||||
python -m unittest discover -s student-tests -p 'test_api.py' -v
|
||||
python -m unittest discover -s student-tests -p 'test_idempotency.py' -v
|
||||
python -m unittest discover -s student-tests -p 'test_attachments.py' -v
|
||||
python -m unittest discover -s student-tests -p 'test_topology.py' -v
|
||||
python -m unittest discover -s student-tests -p 'test_pipeline.py' -v
|
||||
```
|
||||
|
||||
Это 47 тестов API, сессий, идемпотентности, файлов, топологии и вариантов изображений. В pipeline проверяются EXIF, alpha, JPEG/WebP, размеры, неизменность оригинала, ACL, failed, redelivery и очистка staging.
|
||||
|
||||
Следующие 13 тестов меняют состояние сервисов, пересоздают контейнеры или внедряют сбои. Запускайте последовательно; volumes сохраняются. Reconciler проверяется только на созданных тестом объектах и префиксах.
|
||||
|
||||
```sh
|
||||
python student-tests/test_reconcile5.py -v
|
||||
python student-tests/test_resilience5.py -v
|
||||
python student-tests/test_expiry.py -v
|
||||
python student-tests/test_dependencies.py -v
|
||||
```
|
||||
|
||||
Проверка reconciler подтверждает, что варианты и незавершённые записи worker не удаляются; staging принятого задания защищён, а unowned orphan удаляется только после grace. Семь сценариев resilience5 воспроизводят остановку worker, рестарт API/broker, недоступность broker, crash между COMMIT/publish, crash worker до COMMIT/ack, retry exhaustion и безопасный replay. Тесты TTL и отказа PostgreSQL/Valkey перенесены из ЛР4; перед проверкой ошибки БД ожидается срабатывание healthcheck балансировщика.
|
||||
|
||||
Публичные проверки и повторяемый bootstrap:
|
||||
|
||||
```sh
|
||||
python scripts/check_contract.py
|
||||
python tests/smoke.py --base-url http://127.0.0.1:8080
|
||||
python tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url http://127.0.0.1:8080
|
||||
python tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url http://127.0.0.1:8080
|
||||
sh scripts/restore-replicas.sh
|
||||
docker compose --env-file .env run --rm -T s3-init
|
||||
docker compose --env-file .env run --rm -T s3-init
|
||||
```
|
||||
|
||||
В Windows используйте `scripts/restart.cmd`, `scripts/stop-one.cmd`; после failover восстановите реплику командой `docker compose --env-file .env start api`. Полная проверка OpenAPI: установите `requirements-dev.txt`, затем `python scripts/validate_openapi.py`.
|
||||
|
||||
## Исследование очереди
|
||||
|
||||
```sh
|
||||
python -m pip install -r research/requirements.txt
|
||||
python research/queue_overload.py --out evidence/recheck_2026-11-12
|
||||
```
|
||||
|
||||
Скрипт проверяет одну worker-реплику с фактическими лимитами 1 CPU / 768 MiB, затем сравнивает concurrency/prefetch 1, 2, 4 для трёх размеров изображений. В отдельном burst проверяются реальные 503, Retry-After, завершение принятых заданий и новые загрузки после разгрузки. Порог очереди является мягким: одновременный приём допускает превышение порога; достигнутый максимум сохраняется в JSON.
|
||||
|
||||
Эксперимент временно пересоздаёт API/worker и восстанавливает настройки в finally. Синтетические данные сохраняются. Промежуточные результаты пишутся после каждой точки; Docker-ошибки, потеря измерений, failed/OOM и несоответствие результата ожиданиям завершают скрипт с ошибкой.
|
||||
|
||||
Доказательства текущей проверки: [checks_2026-11-12.txt](../evidence/checks_2026-11-12.txt), [JSON и графики](../evidence/recheck_2026-11-12/).
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Поведение при недоступности зависимостей: Valkey (кэш) и PostgreSQL (источник истины).
|
||||
|
||||
python student-tests/test_dependencies.py
|
||||
Контейнеры останавливаются и запускаются обратно (volumes сохраняются). Ожидания:
|
||||
* Valkey остановлен -> кэш обходится, API работает (чтение сессии из PostgreSQL), logout работает;
|
||||
* PostgreSQL остановлен -> 503 в контрактном формате с Retry-After (не 500, не «анонимный» доступ),
|
||||
/health/ready = 503, запрос без токена по-прежнему 401; после запуска БД API восстанавливается сам.
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
from test_api import ROOT, basic, call, register # noqa: E402
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT, check=True, capture_output=True, text=True)
|
||||
|
||||
|
||||
def wait(predicate, seconds=60):
|
||||
deadline = time.time() + seconds
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if predicate():
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError("условие не выполнено за %d с" % seconds)
|
||||
|
||||
|
||||
class DependencyTest(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
compose("start", "postgres", "valkey")
|
||||
wait(lambda: call("GET", "/health/ready")[0] == 200)
|
||||
|
||||
def test_valkey_down_is_bypassed(self):
|
||||
actor = register("dep")
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", token=actor["token"])[0], 200)
|
||||
compose("stop", "valkey")
|
||||
started = time.time()
|
||||
for _ in range(5):
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", token=actor["token"])[0], 200)
|
||||
self.assertLess(time.time() - started, 3, "circuit breaker не должен давать каждому запросу ждать таймаут")
|
||||
# вход и выход работают без кэша
|
||||
s = call("POST", "/api/v1/auth/sessions", headers=basic(actor["user"]["username"], actor["password"]))
|
||||
self.assertEqual(s[0], 201)
|
||||
self.assertEqual(call("DELETE", "/api/v1/auth/sessions/current", token=s[2]["token"])[0], 204)
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", token=s[2]["token"])[0], 401) # отзыв виден без кэша
|
||||
self.assertEqual(call("GET", "/health/ready")[0], 200) # кэш не критичен для readiness
|
||||
|
||||
def test_postgres_down_gives_bounded_503_never_anonymous_access(self):
|
||||
actor = register("dep")
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", token=actor["token"])[0], 200) # токен в кэше
|
||||
compose("stop", "postgres")
|
||||
# Wait past HAProxy's fall=2 health checks: cover the all-unready state,
|
||||
# not just the short interval while the load balancer still routes normally.
|
||||
time.sleep(5)
|
||||
for method, path, body, token in (("GET", "/api/v1/users/me", None, actor["token"]),
|
||||
("GET", "/api/v1/chats", None, actor["token"]),
|
||||
("POST", "/api/v1/chats", {"title": "x", "member_ids": [actor["user"]["id"]]}, actor["token"]),
|
||||
("GET", "/api/v1/users/me", None, "Z" * 43)): # неизвестный токен: кэш пуст -> БД -> 503
|
||||
r = call(method, path, body, token)
|
||||
self.assertEqual(r[0], 503, (path, r))
|
||||
self.assertEqual(r[2]["error"]["code"], "unavailable")
|
||||
self.assertGreaterEqual(int(r[1]["Retry-After"]), 1)
|
||||
self.assertEqual(r[2]["error"]["request_id"], r[1]["X-Request-Id"])
|
||||
r = call("POST", "/api/v1/auth/sessions", headers=basic(actor["user"]["username"], actor["password"]))
|
||||
self.assertEqual(r[0], 503)
|
||||
self.assertEqual(call("GET", "/health/ready")[0], 503)
|
||||
self.assertEqual(call("GET", "/health/live")[0], 200)
|
||||
self.assertEqual(call("GET", "/api/v1/users/me")[0], 401) # без токена — по-прежнему 401
|
||||
compose("start", "postgres")
|
||||
wait(lambda: call("GET", "/health/ready")[0] == 200)
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", token=actor["token"])[0], 200) # сессия пережила простой БД
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Проверка срока жизни сессии при коротком SESSION_TTL_SECONDS (по умолчанию 2).
|
||||
|
||||
python student-tests/test_expiry.py
|
||||
Скрипт пересоздаёт только контейнер api с SESSION_TTL_SECONDS=2, проверяет expiry и возвращает настройки
|
||||
по умолчанию. Данные и volumes не затрагиваются.
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
from test_api import ROOT, call, register # noqa: E402
|
||||
|
||||
TTL = 2
|
||||
|
||||
|
||||
def compose(*args, env=None):
|
||||
return subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT, check=True,
|
||||
capture_output=True, text=True, env=dict(os.environ, **(env or {})))
|
||||
|
||||
|
||||
def wait_ready(seconds=60):
|
||||
deadline = time.time() + seconds
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if call("GET", "/health/ready")[0] == 200:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError("api не стал ready")
|
||||
|
||||
|
||||
class ExpiryTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
compose("up", "-d", "--no-deps", "--force-recreate", "api", env={"SESSION_TTL_SECONDS": str(TTL)})
|
||||
wait_ready()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
compose("up", "-d", "--no-deps", "--force-recreate", "api")
|
||||
wait_ready()
|
||||
|
||||
def test_session_expires_after_ttl(self):
|
||||
actor = register("exp")
|
||||
session = actor["session"]
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", token=actor["token"])[0], 200) # валидна, кэш прогрет
|
||||
time.sleep(TTL + 1.5)
|
||||
r = call("GET", "/api/v1/users/me", token=actor["token"])
|
||||
self.assertEqual(r[0], 401, "после TTL токен должен быть отвергнут (и кэшем, и БД)")
|
||||
self.assertEqual(r[1]["WWW-Authenticate"], 'Bearer realm="messenger"')
|
||||
self.assertEqual(r[2]["error"]["code"], "unauthorized")
|
||||
self.assertEqual(call("DELETE", "/api/v1/auth/sessions/current", token=actor["token"])[0], 401)
|
||||
self.assertIn("expires_at", session)
|
||||
|
||||
def test_expiry_is_not_extended_by_use(self):
|
||||
actor = register("exp")
|
||||
for _ in range(3):
|
||||
call("GET", "/api/v1/users/me", token=actor["token"])
|
||||
time.sleep(0.5)
|
||||
time.sleep(1.5)
|
||||
self.assertEqual(call("GET", "/api/v1/users/me", token=actor["token"])[0], 401)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Reconciliation must preserve variants, in-flight effects and durable staging."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
from test_api import ROOT, call, register
|
||||
from test_attachments import PNG, download, upload
|
||||
from test_pipeline import wait_status
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT,
|
||||
check=True, capture_output=True, text=True, encoding='utf-8').stdout
|
||||
|
||||
|
||||
def reconcile(prefix, grace=0):
|
||||
return json.loads(compose('run', '--rm', '-T', 'api', 'python', '-m', 'app.reconcile',
|
||||
'--apply', '--grace', str(grace), '--prefix', prefix))
|
||||
|
||||
|
||||
def s3_action(action, key):
|
||||
code = ('import asyncio\nfrom app import config\nfrom app.s3 import S3\nasync def m():\n'
|
||||
' s=S3(); await s.start()\n'
|
||||
+ {'put': ' await s.put_bytes(%r, b"temporary", "application/octet-stream")\n',
|
||||
'head': ' print((await s.head(%r)) is not None)\n',
|
||||
'delete': ' await s.delete(%r)\n'}[action] % key
|
||||
+ ' await s.stop()\nasyncio.run(m())')
|
||||
return compose('exec', '-T', 'api', 'python', '-c', code).strip()
|
||||
|
||||
|
||||
class ReconcilePipelineTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.actor = register('reconcile')
|
||||
self.token = self.actor['token']
|
||||
self.chat = call('POST', '/api/v1/chats', {'title': 'reconcile', 'member_ids': [self.actor['user']['id']]}, self.token)[2]
|
||||
|
||||
def accept(self):
|
||||
status, _, att = upload(self.token, self.chat['id'], PNG)
|
||||
self.assertEqual(status, 202)
|
||||
return att
|
||||
|
||||
def test_ready_variants_and_uncommitted_side_effect_are_preserved(self):
|
||||
att = wait_status(self.token, self.accept()['id'])
|
||||
key = 'att/%s/v1/uncommitted' % att['id']
|
||||
s3_action('put', key)
|
||||
try:
|
||||
report = reconcile('att/%s/' % att['id'])
|
||||
self.assertEqual(report['fixed'], {'deleted_orphans': 0, 'marked_failed': 0})
|
||||
self.assertEqual(report['orphan_objects_count'], 0)
|
||||
self.assertEqual(report['owned_objects_skipped'], 1)
|
||||
self.assertEqual(s3_action('head', key), 'True')
|
||||
self.assertEqual(download(self.token, att['id'])[2], PNG)
|
||||
for variant in att['variants']:
|
||||
code, _, data = download(self.token, att['id'], '/content?variant=' + variant['name'])
|
||||
self.assertEqual(code, 200)
|
||||
self.assertEqual(hashlib.sha256(data).hexdigest(), variant['sha256'])
|
||||
finally:
|
||||
s3_action('delete', key)
|
||||
|
||||
def test_staging_is_protected_and_unowned_orphan_obeys_grace(self):
|
||||
compose('stop', 'worker')
|
||||
att = None
|
||||
orphan = 'staging/' + str(uuid.uuid4())
|
||||
try:
|
||||
att = self.accept()
|
||||
report = reconcile('staging/' + att['id'])
|
||||
self.assertEqual(report['fixed'], {'deleted_orphans': 0, 'marked_failed': 0})
|
||||
self.assertEqual(s3_action('head', 'staging/' + att['id']), 'True')
|
||||
s3_action('put', orphan)
|
||||
fresh = reconcile(orphan, grace=900)
|
||||
self.assertEqual(fresh['orphans_skipped_fresh'], 1)
|
||||
self.assertEqual(fresh['fixed']['deleted_orphans'], 0)
|
||||
self.assertEqual(reconcile(orphan)['fixed']['deleted_orphans'], 1)
|
||||
self.assertEqual(s3_action('head', orphan), 'False')
|
||||
self.assertEqual(reconcile(orphan)['fixed']['deleted_orphans'], 0)
|
||||
finally:
|
||||
s3_action('delete', orphan)
|
||||
compose('start', 'worker')
|
||||
self.assertEqual(wait_status(self.token, att['id'])['status'], 'ready')
|
||||
self.assertEqual(download(self.token, att['id'])[2], PNG)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -56,7 +56,7 @@ class ResilienceTest(unittest.TestCase):
|
||||
compose("up", "-d", "--no-deps", "rabbitmq", "api")
|
||||
|
||||
def setUp(self):
|
||||
compose("start", "rabbitmq", "postgres", "minio", "valkey", check=False)
|
||||
compose("start", "rabbitmq", "postgres", "seaweedfs", "valkey")
|
||||
wait(lambda: healthy("rabbitmq") and healthy("postgres"), 90, "rabbitmq/postgres healthy")
|
||||
wait(api_ready, 60, "api ready")
|
||||
self.a = register("res")
|
||||
|
||||
Reference in New Issue
Block a user