Compare commits

10 Commits
Author SHA1 Message Date
Alexey Bodanyuk 77a50af326 lab5: доказательства из чистого clone, REPORT с результатами трека 2, текст PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

collect_evidence на новом clone (новые secrets, пустые volumes): make check/validate/test,
test-persistence, test-failover (обе реплики), сценарий защиты, свои тесты 377 passed,
матрица трека 2 12/12 без нарушений, аудит ok (522 объекта, SHA-256). Исправлен порядок
шагов сценария «reorder версий» (не запускать сервис с обычной конфигурацией между шагами).
2026-10-31 17:59:42 +03:00
Alexey BodanyukandClaude Opus 5.5 cf6e92957c docs: PIPELINE, DEFENSE, DATA_MODEL, WINDOWS для lab5; черновик REPORT
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:17:17 +03:00
Alexey Bodanyuk e453ee2312 трек 2: read-only аудит инвариантов I1-I7 и автоматическая матрица отказов
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

audit: БД только READ ONLY-транзакциями, S3 ключом auditor (Read+List): потерянная работа,
один эффект на версию, опубликованные объекты и SHA-256, монотонная версия, источник у
активной работы, посторонние объекты, попытки. pipeline_faults: дубль, reorder, crash relay
после confirm, crash worker до/после побочного эффекта и после COMMIT, временные ошибки,
два worker, устаревшая версия (v2 медленная, v3 быстрая; дубль v1), reorder версий в очереди,
зависший worker (docker pause).
2026-10-31 17:17:16 +03:00
Alexey BodanyukandClaude Opus 5.5 a3fa7713fa тесты: ждать обновления счётчиков rabbitmqctl; collect_evidence и CI для lab5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:02:24 +03:00
Alexey Bodanyuk 962adbe03b lab5 уровень 4: jobctl (реестр failed, replay, reprocess), тесты окон отказа и demo
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

jobctl: replay только failed с живым источником (новое задание replay_of + аудит),
reprocess только ready и только более новой версии; решения под той же блокировкой
строки, что и уборка. test_pipeline_flow: все окна отказа attachment-states.md, retry с
jitter, retry_exhausted -> replay, постоянные ошибки, лимиты памяти/времени, DLQ, зависший
worker (docker pause), graceful stop, prefetch, уборка vs replay, кейсы из рецензий.
2026-10-31 16:48:26 +03:00
Alexey Bodanyuk 1d37fd0dab fix: relay/worker переподключаются после рестарта брокера; heartbeat AMQP 10 с
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Найдено тестом «брокер остановлен -> upload 202 -> брокер вернулся»: aio-pika не выставляет
is_closed при закрытии соединения сервером, worker оставался без consumer, а healthcheck
показывал healthy; relay падал на ChannelInvalidStateError. Теперь потеря соединения
отслеживается через close_callbacks, heartbeat-файл пишется только при живом consumer,
любая ошибка публикации оставляет строки в outbox. Внедрённые падения worker срабатывают
один раз на задание. Внутренняя пометка staging не меняет публичный updated_at.
2026-10-31 16:48:26 +03:00
Alexey Bodanyuk aef6eb1d4c тесты lab4 переведены на 202 + worker; unit-тесты pipeline; кейсы рецензий как 415
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

PNG с фильтром строки 5/0xff, IDAT не zlib, JPEG из 27 байт, SOS с компонентом не из SOF:
415 при загрузке. 40 Мпикс проходит до ready в лимите памяти worker.
2026-10-31 16:12:52 +03:00
Alexey Bodanyuk bc32a50967 lab5: RabbitMQ, relay и worker в стенде; reconciler lab4 убран
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

broker: RabbitMQ 4.3.7 (тег+digest), quorum queue + DLX/DLQ из definitions, пользователи
relay (только publish в exchange) и worker (только consume), без management UI и портов.
relay: outbox -> publish с publisher confirm, reaper истёкших lease, страховка от потерянных
сообщений. worker: claim + heartbeat lease, варианты, публикация с fencing, ack после COMMIT,
graceful stop, уборка staging и мусора попыток. S3: два bucket и четыре identity
(admin, api, worker, auditor) с проверкой модели доступа в s3-init. Отдельная сеть queue.
Reconciler lab4 (трек прошлой лабы) удалён: его роль выполняет уборка по журналу попыток.
2026-10-31 16:12:52 +03:00
Alexey Bodanyuk 655f264104 lab5 API: upload 202 queued через staging + задание + outbox одной транзакцией
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Порядок: pending-намерение -> PUT в приватный staging bucket -> COMMIT queued + jobs + outbox
-> 202. Проверки 413/415 lab4 остаются синхронными. GET видит queued/processing/failed,
content: 409 до ready, варианты thumbnail/crop/optimized; к сообщению можно прикрепить
queued/processing, failed -> 409. API не связан с брокером.
2026-10-31 16:12:52 +03:00
Alexey Bodanyuk a633949919 lab5: схема 0005 (jobs, outbox, попытки, варианты, аудит) и модули pipeline
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Миграция только добавляет: статусы pending/queued/processing/ready/failed, staging-ключ,
published_version, jobs с lease и токеном попытки, job_attempts с заранее известными
ключами, attachment_variants (PK = ключ эффекта), outbox, job_events, view failed_jobs,
post_message_v3. CHECK attachments_active_has_source: у queued/processing всегда есть источник.
pipeline.py — версии 1/2/3 и геометрия по контракту; imaging.py — варианты в дочернем
процессе (RLIMIT_AS, таймаут, лимит пикселей); jobs.py — все переходы заданий одной
транзакцией с fencing по токену; broker.py — топология и строгая схема сообщения.
Зависимости: aio-pika 9.6.2, pillow 12.3.0 (lock с хешами).
2026-10-31 16:12:51 +03:00
65 changed files with 6301 additions and 1374 deletions
+34 -2
View File
@@ -24,6 +24,8 @@ S3_REGION=us-east-1
S3_BUCKET=messenger-attachments
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
# Lab 5: private staging bucket for originals accepted before 202 (API: Write; worker: Read+Write).
S3_STAGING_BUCKET=messenger-staging
# Contract limits (may be lowered, never raised above 10485760 / 40000000).
MAX_UPLOAD_BYTES=10485760
MAX_IMAGE_PIXELS=40000000
@@ -38,8 +40,33 @@ S3_TIMEOUT_SECONDS=3
# Janitor: 'pending' intents older than this are failed uploads (object + row removed).
PENDING_GRACE_SECONDS=900
JANITOR_INTERVAL_SECONDS=60
# Level 4 failure experiments only (after_s3_put, after_ready_commit); keep empty.
FAULT_POINTS=
# Lab 5: broker credentials are files too (relay and worker get their OWN RabbitMQ user/URL;
# secrets/broker_url_relay|worker are mounted as /run/secrets/broker_url). The API has none.
BROKER_URL_FILE=/run/secrets/broker_url
# Jobs processed at once by one worker = RabbitMQ prefetch; image child processes at once.
WORKER_CONCURRENCY=2
WORKER_REPLICAS=1
# Managed attempts (claims) per job, then failed/retry_exhausted; backoff = full jitter.
JOB_MAX_ATTEMPTS=5
JOB_RETRY_BASE_SECONDS=2
JOB_RETRY_MAX_SECONDS=60
# One attempt: hard time limit (child process killed) and the lease renewed by its heartbeat.
JOB_TIMEOUT_SECONDS=60
JOB_LEASE_SECONDS=30
# Address-space limit of the image child process (RLIMIT_AS).
IMAGE_MAX_MEMORY_MB=768
# Staging copy of a FAILED attachment is kept this long for a replay (ready: deleted at once).
STAGING_RETENTION_SECONDS=86400
# Objects of attempts that never published are deleted this long after the attempt ended.
ORPHAN_GRACE_SECONDS=600
# Queued job without a claim for this long gets a new outbox row (lost-message guard).
QUEUED_REPUBLISH_SECONDS=300
# Pipeline version of new uploads (track 2: versions 1, 2, 3 in src/messenger/pipeline.py).
PIPELINE_VERSION=1
# Failure experiments only, per service (see src/messenger/config.py FAULT_POINTS); keep empty.
API_FAULT_POINTS=
RELAY_FAULT_POINTS=
WORKER_FAULT_POINTS=
# Additional settings of this implementation (defaults shown; all optional):
LOG_LEVEL=info
DB_POOL_MIN=1
@@ -60,6 +87,11 @@ PG_CPUS=2.0
PG_MEMORY=1g
VALKEY_CPUS=0.5
LB_CPUS=1.0
BROKER_CPUS=1.0
BROKER_MEMORY=512m
WORKER_CPUS=2.0
WORKER_MEMORY=1536m
RELAY_CPUS=0.5
PG_MAX_CONNECTIONS=100
# Host ports of the load balancer (published on 127.0.0.1 only; API replicas publish nothing)
APP_PUBLISH_PORT=8080
+8 -6
View File
@@ -1,4 +1,4 @@
name: Application (lab4)
name: Application (lab5)
on: [push, pull_request]
permissions:
contents: read
@@ -13,26 +13,28 @@ jobs:
python-version: '3.13'
- name: Synthetic secrets and env (CI only, never committed)
run: python scripts/init_secrets.py && cp .env.example .env
- name: Build, migrate once, bootstrap the S3 bucket, start 2 API replicas behind HAProxy
- name: Build, migrate once, bootstrap both S3 buckets, start broker, 2 API replicas, LB, relay, worker
run: docker compose --env-file .env up -d --build --wait
- name: Contract and public smoke
run: make check test PYTHON=python
- name: Persistence across restart of LB, API replicas, PostgreSQL, Valkey and S3
- name: Persistence across restart of LB, API replicas, relay, worker, PostgreSQL, Valkey, S3, RabbitMQ
run: make test-persistence ACTION_SCRIPT=scripts/restart.sh PYTHON=python
- name: Failover of the replica that served the test, then restore it
run: |
make test-failover ACTION_SCRIPT=scripts/stop-one.sh PYTHON=python
sh scripts/restore-api.sh && python scripts/lbctl.py wait-up 2
- name: Reconciler (track 2) dry-run on the stand - read-only report
run: docker compose run --rm reconciler
- name: Defense scenario - worker stopped, 202, 409, restart API and broker, ready
run: python -m pip install -q pillow==12.3.0 && python scripts/demo_pipeline.py
- name: Own tests (unit + stand; every failure is restored in finally)
run: |
python -m pip install --require-hashes --no-deps -r requirements.txt
python -m pip install -r requirements-test.txt
make student-test PYTHON=python
- name: Track 2 invariants (read-only audit of PostgreSQL and both buckets)
run: docker compose run --rm --no-deps auditor --verify-checksums
- name: Logs
if: always()
run: docker compose logs --tail 100 api lb s3 s3-init
run: docker compose logs --tail 100 api lb s3 s3-init broker relay worker
- name: Remove CI stand and its synthetic data
if: always()
run: docker compose down -v
+3 -2
View File
@@ -1,6 +1,7 @@
# syntax=docker/dockerfile:1
# Messenger API, lab 4 (replicas behind HAProxy, PostgreSQL + Valkey + S3). Built by compose.yaml
# (services api, migrate, s3-init, reconciler: one image, different commands).
# Messenger, lab 5 (API replicas behind HAProxy, PostgreSQL + Valkey + S3 + RabbitMQ). Built by
# compose.yaml (services api, migrate, s3-init, relay, worker, auditor, jobctl: one image, different
# commands; only the worker imports Pillow).
#
# Python is interpreted, so there is no separate compile stage; the image
# contains only the interpreter, locked dependencies and the source code.
+29 -18
View File
@@ -29,23 +29,23 @@ test-failover:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
# ---------------------------------------------------------------------------
# Student solution (lab 4, Python). On Windows: PowerShell/Git Bash with GNU make, public
# Student solution (lab 5, Python). On Windows: PowerShell/Git Bash with GNU make, public
# tests need PYTHONUTF8=1, and the hooks are started through scripts/*.cmd (Git Bash).
.PHONY: secrets up down logs ps migrate student-test unit-test explain lb-status restore rolling-update failover-series reconcile reconcile-apply bench-memory bench-reconcile
.PHONY: secrets up down logs ps migrate student-test unit-test explain lb-status restore rolling-update failover-series bench-memory worker-stop worker-start jobs failed audit track2
secrets:
$(PYTHON) scripts/init_secrets.py
# Build, apply migrations ONCE (service migrate), start API replicas and the LB, wait for healthy.
# Build, apply migrations ONCE (service migrate), start broker, API replicas, LB, relay and worker.
up: secrets
docker compose up -d --build --wait
# Safe stop: containers stop, named volumes (data) stay.
# Safe stop: containers stop, named volumes (data, queue) stay.
down:
docker compose down
logs:
docker compose logs --tail 50 api lb
docker compose logs --tail 50 api lb relay worker
ps:
docker compose ps -a
@@ -67,10 +67,32 @@ restore:
rolling-update:
sh scripts/rolling-update.sh
# Level 4: stop each replica in turn under load, measure RPS/errors/recovery (evidence/failover/).
# Lab 3: stop each replica in turn under load, measure RPS/errors/recovery (evidence/failover/).
failover-series:
$(PYTHON) bench/failover_series.py --output evidence/failover
# Lab 5 demo: stop the worker (uploads still get 202, content answers 409), start it again.
worker-stop:
docker compose stop worker
worker-start:
docker compose start worker
# Lab 5 operator view: jobs by state + outbox backlog; failed registry (replay: see REPORT.md).
jobs:
docker compose run --rm --no-deps jobctl stats
failed:
docker compose run --rm --no-deps jobctl list-failed
# Track 2: read-only check of the pipeline invariants over PostgreSQL and both buckets.
audit:
docker compose run --rm --no-deps auditor
# Track 2: automatic fault-injection matrix (duplicate, reorder, crashes, stale versions).
track2:
$(PYTHON) bench/pipeline_faults.py --output evidence/track2
# Own tests: unit + black-box against the running stand (needs requirements*.txt in a venv).
student-test:
$(PYTHON) -m pytest student-tests -v
@@ -81,17 +103,6 @@ unit-test:
explain:
$(PYTHON) scripts/explain_history.py --output evidence/explain-history.txt
# Track 2: reconciler of S3 objects vs attachment rows (dry-run by default, read-only).
reconcile:
docker compose run --rm reconciler
reconcile-apply:
docker compose run --rm reconciler --apply
# Level 4: peak RAM of the replicas under 16 simultaneous uploads (evidence/memory/).
# Lab 4: peak RAM of the replicas under 16 simultaneous uploads (evidence/memory/).
bench-memory:
$(PYTHON) bench/upload_memory.py --output evidence/memory
# Track 2: cost of one reconciler pass for 1k/10k/50k attachments (evidence/reconcile/).
bench-reconcile:
$(PYTHON) bench/reconcile_cost.py --output evidence/reconcile
+171 -17
View File
@@ -1,37 +1,191 @@
# Отчёт — лабораторная 5
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
- Автор, группа: Боданюк Алексей, БВТ2302
- Целевая оценка; трек 5: **5**, трек 2 «Доказанная идемпотентность pipeline»
- Commit/PR: ветка `solution/bvt2302-bodanyuk`; PR «ЛР 5 — БВТ2302 — Боданюк — на 5» (ссылка после публикации)
- Источники, библиотеки, ИИ: Python 3.13, Starlette, uvicorn, psycopg 3, redis-py, argon2-cffi, aiobotocore (из ЛР 2–4); новое: **aio-pika 9.6.2** (AMQP), **Pillow 12.3.0** (варианты, только в worker). Документация: [RabbitMQ reliability](https://www.rabbitmq.com/docs/reliability), [confirms](https://www.rabbitmq.com/docs/confirms), [quorum queues](https://www.rabbitmq.com/docs/quorum-queues), AWS «Exponential Backoff And Jitter». Код, тесты и документы написаны с помощью ИИ-ассистента (Claude); архитектурные решения разобраны и объяснимы автором (см. [docs/DEFENSE.md](docs/DEFENSE.md)).
## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
Версии (всё по тегу **и** digest, см. [compose.yaml](compose.yaml)): Python 3.13.16-slim-bookworm, PostgreSQL 18.6, Valkey 8.1.3, SeaweedFS 4.46, **RabbitMQ 4.3.7-alpine**, HAProxy 3.2.26. Python-пакеты — `requirements.txt` с sha256-хешами (`pip install --require-hashes --no-deps`).
Prerequisites: Docker с Compose v2, Python 3.12+, Git; на Windows — [docs/WINDOWS.md](docs/WINDOWS.md).
```sh
git clone <fork> mtusi2026lab5 && cd mtusi2026lab5 && git checkout solution/bvt2302-bodanyuk
python3 scripts/init_secrets.py # ./secrets: пароли БД/Valkey, 4 пары S3, пользователи RabbitMQ (хеши), URL брокера
cp .env.example .env
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build --wait # migrate и s3-init — один раз, exit 0; остальные healthy
make check test # Windows: $env:PYTHONUTF8="1"; make ... PYTHON=python
make test-persistence ACTION_SCRIPT=scripts/restart.sh
make test-failover ACTION_SCRIPT=scripts/stop-one.sh && make restore
python3 -m venv .venv && .venv/bin/pip install --require-hashes --no-deps -r requirements.txt && .venv/bin/pip install -r requirements-test.txt
.venv/bin/python scripts/demo_pipeline.py # сценарий защиты, шаги 2-3
.venv/bin/python -m pytest student-tests -v
.venv/bin/python bench/pipeline_faults.py --output evidence/track2
make audit # инварианты, read-only
```
Всё это одной командой на чистом clone: `python scripts/collect_evidence.py` (вывод — в `evidence/`). Действий оператора нет. Безопасная остановка: `docker compose down` (volumes остаются). Намеренное удаление учебных данных: `docker compose down -v` и удалить `./secrets`.
## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab4, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
```text
client ─▶ lb (HAProxy) ─▶ api ×2 ──▶ postgres (метаданные, jobs, outbox, попытки, аудит) [data]
├──▶ valkey (сессии) [data]
└──▶ s3: messenger-staging (Write) / messenger-attachments (Read) [storage]
relay ──▶ postgres (outbox, reaper) ──▶ broker (RabbitMQ, quorum queue + DLQ) [data, queue]
worker ◀── broker; ──▶ postgres; ──▶ s3 (Read/Write оба bucket) [data, storage, queue]
```
- **Источник истины — PostgreSQL**, включая работу: состояние, попытки, lease, время повтора, реестр failed. Брокер доставляет только `job_id`; ack — после COMMIT результата. Подробно — [docs/PIPELINE.md](docs/PIPELINE.md); схема — [docs/DATA_MODEL.md](docs/DATA_MODEL.md).
- **Транзакционные границы.** Upload: `pending` → PUT staging → **одна транзакция** `queued + jobs + outbox` → 202. Результат: **одна транзакция** `attachment_variants ×3 + attachments ready` с проверкой `lease_token` → ack.
- **API не связан с брокером** (нет сети `queue`, нет учётных данных). Недоступность worker/брокера не делает resize синхронным и не ломает upload.
- **Перенесено из lab4 без изменений** (коммит `5112be8`): API, сессии, идемпотентность сообщений, HAProxy с активной readiness, лимиты загрузки, PNG-валидатор и `djpeg -strict`, janitor `pending`, graceful shutdown, тесты.
- **Изменено:** upload 201 → 202; GET метаданных видит `queued/processing/failed`; `content` → 409 до ready, варианты `thumbnail/crop/optimized`; к сообщению можно прикрепить `queued/processing` (`post_message_v3`), `failed` → 409; S3 разделён на два bucket и четыре identity; restart-хук перезапускает и broker/relay/worker.
- **Убрано:** reconciler lab4 (трек прошлой лабы, не обязательный минимум). В lab5 мусор находится по журналу `job_attempts.planned_keys` без права List; аудит `messenger.audit` проверяет оба bucket read-only-ключом. Удаление файлов reconciler попало в коммит `a633949`, а не в `bc32a50`, где об этом сказано, — ошибка при разбиении коммитов, историю не переписывал.
- **Ограничения доступа.** S3: api — Write staging + Read final; worker — Read/Write оба; auditor — Read+List; admin — только `s3-init`. RabbitMQ: `relay` — только write в exchange `messenger.jobs`, `worker` — только read очереди, configure ни у кого; `guest` нет; management UI и Prometheus выключены. Проверяется `s3-init` при каждом старте и тестом `test_compose_policy_limits_ports_secrets_images`.
### Соответствие `.env.example`
| Переменная | Значение | Где |
| --- | --- | --- |
| `BROKER_URL_FILE` | `/run/secrets/broker_url` | relay и worker, у каждого свой пользователь RabbitMQ |
| `S3_STAGING_BUCKET` | `messenger-staging` | api, worker, s3-init, auditor |
| `WORKER_CONCURRENCY` | 2 | prefetch и число дочерних процессов worker |
| `JOB_MAX_ATTEMPTS` | 5 | claim-ов на задание (пишется в задание при создании) |
| `JOB_TIMEOUT_SECONDS` | 60 | потолок одной попытки (kill процесса, конец продления lease) |
| `JOB_LEASE_SECONDS` | 30 | lease, heartbeat каждые 10 с |
| `JOB_RETRY_BASE_SECONDS` / `_MAX_` | 2 / 60 | full jitter |
| `STAGING_RETENTION_SECONDS` | 86400 | хранение staging у `failed` для replay (у `ready` удаляется сразу) |
| `ORPHAN_GRACE_SECONDS` | 600 | удаление объектов неуспешных попыток |
| `IMAGE_MAX_MEMORY_MB` | 768 | RLIMIT_AS дочернего процесса |
| `PIPELINE_VERSION` | 1 | версия заданий новых загрузок (1, 2, 3 в `pipeline.py`) |
| `API_/RELAY_/WORKER_FAULT_POINTS` | пусто | внедрение отказов только для экспериментов |
| `MAX_UPLOAD_BYTES`, `MAX_IMAGE_PIXELS` | 10485760, 40000000 | API (до чтения тела) и worker (до скачивания/декодирования) |
## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
Все файлы — из прогона `scripts/collect_evidence.py` на **чистом clone** (новые secrets, пустые volumes), см. раздел «Финальный прогон».
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл |
| --- | --- | --- | --- |
| Публичный smoke | `make check validate test` | PASS ×3: 202 → ready, JPEG 256×160 | [make-check-validate-test.txt](evidence/make-check-validate-test.txt) |
| **3:** минимум lab4 сохранён, 201 → 202 | `pytest student-tests` (test_api, test_attachments, test_idempotency, test_balancing, test_sessions, test_failures) | 377 passed; 415 на все кейсы рецензий (PNG фильтр 5/0xff, IDAT не zlib, JPEG 27 байт, SOS не из SOF) | [student-tests.txt](evidence/student-tests.txt) |
| **3:** 202 только после устойчивого приёма; остановка API не теряет | test_consistency (`after_s3_put`, `after_enqueue_commit`), demo | окно «после staging» — невидимый `pending`, убран janitor; после COMMIT — ready | student-tests.txt |
| **3:** отдельные broker и worker, durable, ack после эффекта | compose, `rabbitmqctl list_queues`; `test_worker_crash_after_commit…` | quorum queue durable; redelivery → `noop_finished` | [clean-clone.txt](evidence/clean-clone.txt), student-tests.txt |
| **3:** worker недоступен → API не делает resize | `test_worker_stopped…`, demo | 202 queued, content 409, сообщения 201 | [demo-pipeline.txt](evidence/demo-pipeline.txt) |
| **3:** состояния queued/processing/ready/failed, thumbnail по контракту | test_pipeline_flow (`check_variants`) | реальные размеры через Pillow, sha256 = метаданные, оригинал побайтно | student-tests.txt |
| **3:** ограниченный retry, failed + error_code; повтор не плодит варианты | `test_retry_exhausted…`, `test_duplicate…` | 5 попыток → `retry_exhausted`; дубли → 1 набор | student-tests.txt |
| **3:** демонстрация stop worker → 202 → сообщение → restart API (+broker) → ready | `scripts/demo_pipeline.py` | очередь `messages=1` до и после рестарта брокера, ready, одна попытка | demo-pipeline.txt |
| Persistence / failover (публичные) | `make test-persistence`, `make test-failover` | PASS, состояния контейнеров до/после | [test-persistence.txt](evidence/test-persistence.txt), [test-failover.txt](evidence/test-failover.txt) |
| **4:** crop 128 и WebP 1280, параметры | unit test_pipeline + check_variants | геометрия, EXIF, alpha, без метаданных — [PIPELINE.md](docs/PIPELINE.md#варианты) | student-tests.txt |
| **4:** лимиты bytes/пикселей/времени/памяти worker | `test_memory_and_time_limits_of_the_worker`, `test_exactly_40_megapixels…` | 40 Мпикс при 200 МБ → `image_too_large`; 3 с → `processing_timeout`; 40 Мпикс в 768 МБ → ready | student-tests.txt |
| **4:** outbox; crash между COMMIT и publish | `test_broker_down…`, `test_relay_down…`, `test_crash_after_publish…` | строка outbox ждёт, публикуется без ручных действий | student-tests.txt |
| **4:** backoff с jitter, постоянные/временные | `test_transient_errors…`, `test_permanent_error…` | задержки в `[0, base·2^(n−1)]`, invalid_image — 1 попытка | student-tests.txt |
| **4:** DLQ/реестр failed, безопасный replay | `jobctl list-failed/replay`, `test_bad_message…` | replay → ready; replay готового → `already_ready`; плохое сообщение → DLQ | student-tests.txt |
| **4:** crash после записи объекта до ack | `test_worker_crash_after_s3_write…`, `…after_commit…` | один опубликованный набор, мусор попытки 1 удалён | student-tests.txt |
| **4:** lease зависшего processing, prefetch, очистка staging | `test_hung_worker…` (docker pause), `test_concurrency…`, `test_queued_staging…`, `test_cleanup_racing…` | попытки `[abandoned, succeeded]`; ≤2 processing; staging `queued` не удаляется, CHECK отвергает | student-tests.txt |
| **5, трек 2** | `bench/pipeline_faults.py`, `make audit` | 12/12 сценариев, 0 нарушений, аудит ok | [evidence/track2/](evidence/track2/), [track2-runs.txt](evidence/track2-runs.txt) |
## Эксперименты и отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
### Трек 2: доказанная идемпотентность versioned pipeline
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
**Гипотеза.** При at-least-once доставке, дублях и переупорядочивании сообщений, crash worker до/после побочного эффекта и устаревших заданиях старой версии pipeline: (H1) ни одна принятая 202 работа не теряется; (H2) каждый эффект `(attachment, version, variant)` опубликован ровно один раз; (H3) опубликованная версия только растёт, `ready` не откатывается; (H4) мусор прерванных попыток удаляется, опубликованное не удаляется никогда.
**Механизм.** Ключ эффекта — PK `attachment_variants`; ключи объектов включают токен попытки; fencing `lease_token` при каждом COMMIT; монотонный `published_version`; claim по состоянию задания в БД; уборка только по `planned_keys` неуспешных попыток под блокировкой.
**Методика** ([bench/pipeline_faults.py](bench/pipeline_faults.py)). Для каждого сценария пересоздаётся один сервис с `FAULT_POINTS` (реальные пути кода, реальный `os._exit`, реальный `docker pause`), N загрузок через LB, затем читаются факты из PostgreSQL и S3 (List auditor-ключом), а в конце аудит `I1–I7` с проверкой SHA-256 всех опубликованных объектов по всему стенду.
| Сценарий | Внедрение |
| --- | --- |
| baseline | — |
| дубль | relay публикует каждое сообщение дважды |
| дубль + reorder | дважды и в обратном порядке пачки |
| crash relay после confirm до отметки | `os._exit` relay |
| crash worker до побочного эффекта | `os._exit` после claim |
| crash worker после S3 до COMMIT | `os._exit` после PUT объектов |
| crash worker после COMMIT до ack | `os._exit` после COMMIT |
| временные ошибки | 2 неудачные попытки |
| 2 worker + дубль | конкурирующие потребители |
| устаревшая версия | reprocess v2 (медленный) и v3 одновременно; затем вручную опубликованный дубль задания v1 |
| reorder версий в очереди | v2 и v3 в outbox, relay публикует в обратном порядке, 1 worker |
| зависший worker | 2 worker, `docker pause` владельца lease |
**Результаты** (чистый clone, 2026-10-31 14:48–14:57 UTC, 5 загрузок на «плоский» сценарий; [summary.txt](evidence/track2/summary.txt), подробно — [summary.json](evidence/track2/summary.json)):
| Сценарий | Загрузок | ready | claim-ов | Нарушений | Последовательность событий задания |
| --- | --- | --- | --- | --- | --- |
| baseline | 5 | 5 | 5 | 0 | created › claimed › succeeded |
| дубль publish | 5 | 5 | 5 | 0 | то же: второе сообщение — `noop_finished` |
| дубль + обратный порядок | 5 | 5 | 5 | 0 | то же |
| crash relay после confirm | 5 | 5 | 5 | 0 | created › claimed › fault_injected › succeeded |
| crash worker после claim | 5 | 5 | 14 | 0 | claimed › fault_injected › lease_expired › claimed › succeeded (*) |
| crash worker после S3, до COMMIT | 5 | 5 | 10 | 0 | claimed › fault_injected › lease_expired › claimed › succeeded |
| crash worker после COMMIT, до ack | 5 | 5 | 5 | 0 | claimed › succeeded › fault_injected (redelivery = no-op) |
| 2 временные ошибки | 5 | 5 | 15 | 0 | 3 claim-а на загрузку, ровно как задано |
| 2 worker + дубль | 5 | 5 | 5 | 0 | один claim при конкурирующих потребителях |
| устаревшая версия | 1 | — | — | 0 | v1 succeeded, v2 (медленная) **superseded** при COMMIT, v3 succeeded; статус всё время `ready`; ручной дубль задания v1 — no-op |
| reorder версий в очереди | 1 | — | 2 | 0 | v3 опубликована первой, v2 **superseded при claim** без работы |
| зависший worker (`docker pause`) | 1 | — | 2 | 0 | claimed › lease_expired › claimed › succeeded; ожившая попытка fenced |
| **аудит всего стенда после матрицы** | | | | **0** | `ok=True`, 522 опубликованных объекта, SHA-256 сверены, `final=523` (+sentinel) |
(*) claim-ов больше, чем 2 на загрузку: `os._exit` при одном задании убивает **весь процесс**, а с ним и соседнюю попытку другого задания (prefetch 2). Ей тоже приходится ждать истечения lease. Это и есть «crash до побочного эффекта»: лишние claim-ы ничего не публикуют, и ни в одном сценарии нет второго набора вариантов или объектов (столбец «Нарушений» — проверки H2/H4 по БД и S3).
**Вывод.** H1–H4 подтверждены на всех 12 сценариях: 0 нарушений по сценарным проверкам и по аудиту I1–I7. Время до ready при отказах определяется lease (6 с в эксперименте) + интервалом reaper (5 с): 15–22 с против ~2 с без отказов.
**Ограничения эксперимента.** Один прогон матрицы на 5 загрузок (плюс прогоны тех же сценариев в `student-tests` и отладочный прогон на 3 загрузки — тоже 0 нарушений). Это доказательство на конечном наборе чередований, а не формальная верификация. Отказы внедряются в заранее выбранных точках кода, а не в случайные моменты. Один Docker-хост.
**Почему это не exactly-once.** Доставка остаётся at-least-once: в сценариях дубля в очереди физически два сообщения, а у зависшего worker вычисление выполнялось дважды (попытки `abandoned` и `succeeded`). Exactly-once — только у **видимого эффекта**, за счёт ключа эффекта, fencing и монотонной версии. Чего нет: (1) защиты от двух независимых **сред** с разными БД; (2) гарантии при потере диска одного Docker-хоста (quorum queue и PostgreSQL на одном узле); (3) удаления опубликованных вариантов старых версий — они остаются (rollback-кандидаты), удаляются только неопубликованные.
### Отказы
| Воздействие | Что ожидаем | Что наблюдали | Восстановление / потеря |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
| worker остановлен, upload | 202, content 409, сообщения работают | так и есть | после старта worker → ready, 0 потерь |
| restart API + broker с volumes | сообщение остаётся в quorum queue | `messages=1` до и после | 0 потерь |
| broker остановлен | upload 202, outbox ждёт | `published=False`, текст работает | relay публикует после возврата брокера |
| relay остановлен | outbox ждёт | так и есть | ready после старта |
| crash relay после confirm | дубль в очереди | один claim, один набор | 0 дублей эффекта |
| crash worker после claim / S3 / COMMIT | lease → reaper → попытка 2; либо no-op | `[abandoned, succeeded]`; мусор удалён | lease 6 с в тесте (30 с по умолчанию) + ≤5 с reaper |
| docker pause worker с lease | второй worker публикует, первый fenced | так и есть | ≤ lease + 5 с + AMQP heartbeat |
| 5× временная ошибка | `failed/retry_exhausted` → replay → ready | так и есть | replay оператора |
| уборка vs replay (пауза в уборке) | staging не удалён | ready, staging удалён только после ready | — |
| S3 остановлен/заморожен (lab4) | readiness 503, upload 503 < 8 с, текст работает | так и есть | файлы целы |
**Дефекты, найденные в ходе работы и исправленные:**
1. После рестарта брокера worker оставался без consumer, а healthcheck показывал healthy; relay падал на `ChannelInvalidStateError`. Причина: aio-pika не выставляет `is_closed` при закрытии соединения сервером. Исправлено (`1d37fd0`): `close_callbacks`, heartbeat-файл только при живом consumer.
2. Внедрённый crash worker срабатывал на каждой попытке, а не один раз на задание. Исправлено там же.
3. Аудит ошибочно требовал объект staging у `pending` (PUT мог не пройти). Исправлен инвариант I5.
### Окружение и лимиты
Ноутбук: AMD Ryzen 5 3400G (4 ядра / 8 потоков), 29,9 ГБ RAM, Windows 10 Enterprise 19045, Docker Desktop 29.8.0 (VM: 8 CPU, 15,7 ГБ). Лимиты контейнеров (фактические, `docker inspect` в clean-clone.txt): api 1 CPU / 512m ×2, worker 2 CPU / 1536m (без swap), broker 1 CPU / 512m, relay 0,5 / 256m, postgres 2 / 1g, s3 1 / 1g, valkey 0,5 / 256m, lb 1 / 128m, migrate/s3-init 0,5 / 256m, auditor 1 / 256m, jobctl 0,5 / 128m. Нагрузочных выводов о производительности в этой лабе не делается (трек 2 — про корректность); `tests/load.py` приложен как контроль регрессии lab3.
## Финальный прогон
`python scripts/collect_evidence.py` в **новой папке** (`git clone` ветки, commit `cf6e929`): новые secrets, пустые volumes (стенд разработки удалён `down -v`), образы приложения собраны заново (слои базовых образов из кэша Docker). Все шаги `exit 0`:
| Файл | Что внутри |
| --- | --- |
| [clean-clone.txt](evidence/clean-clone.txt) | init_secrets, `compose config`, `up --build --wait`, migrate (0001–0005), s3-init (вердикты прав), пользователи и права RabbitMQ, очереди, **лимиты `docker inspect`**, версии |
| [make-check-validate-test.txt](evidence/make-check-validate-test.txt) | `make check` PASS, `make validate` PASS, `make test` PASS lab5 |
| [test-persistence.txt](evidence/test-persistence.txt) | PASS; состояния контейнеров до/после (новые pid у lb, api, relay, worker, postgres, valkey, s3, broker) |
| [test-failover.txt](evidence/test-failover.txt) | PASS дважды, остановлены обе реплики по очереди |
| [demo-pipeline.txt](evidence/demo-pipeline.txt) | сценарий защиты шаги 2–3, очередь `messages=1` до и после рестарта брокера, ready, JPEG 256×160 |
| [student-tests.txt](evidence/student-tests.txt) | **377 passed, 4 skipped** (skipped — unit-тесты `djpeg`, которого нет на Windows-хосте; те же случаи проходят против стенда), 25 мин |
| [track2-runs.txt](evidence/track2-runs.txt), [track2/](evidence/track2/) | матрица трека 2, аудит `--verify-checksums`, `jobctl stats` (outbox пуст), `tests/load.py` |
| [load.json](evidence/load.json) | контроль регрессии lab3: 183 успешных RPS, 0 ошибок, p95 44 мс (4 клиента, 30 с; не сравнивается с lab3 — другой стенд) |
Свап: у api и worker `memswap = memory` (без swap). У инфраструктурных контейнеров остался умолчательный swap Docker (= 2 × memory) — видно в `docker inspect`, для выводов этой лабы не важно.
## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
- Один Docker-хост: quorum queue на одном узле (без репликации), PostgreSQL один. «Устойчиво» = переживает рестарт процессов/контейнеров с volumes.
- SeaweedFS подтверждает PUT без явного fsync каждой записи; потеря питания хоста — вне модели угроз.
- Опубликованные варианты старых версий не удаляются; квоты на число версий нет.
- Колонки карантина lab4 (`lost_at`) сохранены, но ничем не выставляются (reconciler удалён).
- Объект, записанный замороженной попыткой **после** её уборки (пауза дольше `ORPHAN_GRACE_SECONDS`), станет мусором; аудит покажет его как `leaked_object`. Это не потеря: опубликованное не задевается.
- Следующие шаги: трассировка (`traceparent` в сообщении уже предусмотрен схемой) — lab6.
+309
View File
@@ -0,0 +1,309 @@
#!/usr/bin/env python3
"""Track 2 experiment: proven idempotency of the versioned pipeline under injected faults.
Hypothesis. With at-least-once delivery, duplicated and reordered messages, crashes of the worker
before/after its side effects and stale jobs of an older pipeline version:
H1 no accepted (202) work is lost - every upload ends ready (or failed with a code, never stuck);
H2 every effect (attachment, pipeline_version, variant) is published exactly once - one set of
variant rows written by ONE successful attempt, one set of objects in the bucket;
H3 the published version only grows - an older job never overwrites a newer result, `ready`
never goes back to queued/processing;
H4 objects of interrupted attempts are garbage that the cleanup removes; nothing published is
ever deleted.
Method. For every scenario the affected service (relay/worker) is recreated with FAULT_POINTS of
the scenario (the real code paths, real crashes = os._exit of the process, real `docker pause`),
N uploads go through the LB, then the scenario-specific facts are read from PostgreSQL and S3 and
the read-only invariant audit (messenger.audit, I1-I7, with SHA-256 of every published object)
runs over the WHOLE stand. The normal configuration is restored after each scenario.
python bench/pipeline_faults.py --output evidence/track2 [--uploads 5]
"""
from __future__ import annotations
import argparse
import datetime as dt
import json
import platform
import statistics
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "student-tests"))
import imagegen # noqa: E402
from conftest import (Api, attachment_row, compose, events_of, jobctl, psql, s3_keys, service_with_env, # noqa: E402
wait_healthy)
FAST = {"JOB_LEASE_SECONDS": "6", "ORPHAN_GRACE_SECONDS": "3", "CLEANUP_INTERVAL_SECONDS": "1"}
def now() -> str:
return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def wait(condition, timeout: float, what: str):
deadline = time.monotonic() + timeout
while True:
value = condition()
if value:
return value
if time.monotonic() > deadline:
raise AssertionError(what)
time.sleep(0.5)
def facts(attachment_id: str, objects: set[str]) -> dict:
row = attachment_row(attachment_id)
out = psql("SELECT json_build_object("
"'claims', (SELECT count(*) FROM job_attempts a JOIN jobs j ON j.id = a.job_id WHERE j.attachment_id = '{0}'), "
"'succeeded_attempts', (SELECT count(*) FROM job_attempts a JOIN jobs j ON j.id = a.job_id "
" WHERE j.attachment_id = '{0}' AND a.outcome = 'succeeded'), "
"'variant_rows', (SELECT count(*) FROM attachment_variants WHERE attachment_id = '{0}'), "
"'versions', (SELECT coalesce(json_agg(DISTINCT pipeline_version), '[]') FROM attachment_variants "
" WHERE attachment_id = '{0}'), "
"'job_states', (SELECT coalesce(json_agg(state || ':v' || pipeline_version ORDER BY created_at), '[]') "
" FROM jobs WHERE attachment_id = '{0}'), "
"'uncleaned_failed_attempts', (SELECT count(*) FROM job_attempts a JOIN jobs j ON j.id = a.job_id "
" WHERE j.attachment_id = '{0}' AND a.outcome <> 'succeeded' AND a.objects_cleaned_at IS NULL))"
.format(attachment_id))
f = json.loads(out)
f.update(status=row["status"], published_version=row["published_version"], staging_state=row["staging_state"],
objects=len([k for k in objects if k.startswith(f"a/{attachment_id}/")]))
f["events"] = [e["event"] for e in events_of(attachment_id)]
return f
def audit() -> dict:
r = compose("run", "--rm", "--no-deps", "-T", "auditor", "--verify-checksums", check=False, timeout=600)
report = json.loads(r.stdout)
return {"ok": report["ok"], "violations": report["violations"], "notes": len(report["notes"]),
"objects": report["objects"]}
class Run:
def __init__(self, api: Api, uploads: int):
self.api = api
self.n = uploads
self.alice, self.bob = api.user("t2a"), api.user("t2b")
self.chat = api.chat(self.alice, self.bob)
def upload_many(self, n: int | None = None) -> list[dict]:
return [self.api.upload(self.alice, self.chat, imagegen.png(60 + i, 40, noise=True)).json()
for i in range(n or self.n)]
def finish(self, atts: list[dict], timeout: float = 180) -> tuple[list[dict], list[float]]:
started = time.monotonic()
took = []
for a in atts:
self.api.wait_status(self.bob, a["id"], timeout=timeout)
took.append(round(time.monotonic() - started, 2))
return atts, took
def expect_one_effect(f: dict, version: int = 1) -> list[str]:
"""H1 + H2 for a plain upload of pipeline `version`."""
problems = []
if f["status"] != "ready":
problems.append(f"status {f['status']}")
if f["succeeded_attempts"] != 1 or f["variant_rows"] != 3 or f["published_version"] != version:
problems.append(f"effect {f['succeeded_attempts']} attempts/{f['variant_rows']} rows/v{f['published_version']}")
if f["objects"] != 4: # original + thumbnail + crop + optimized, cleanup done
problems.append(f"{f['objects']} objects in the bucket")
return problems
def plain_scenario(run: Run, name: str, service: str, env: dict, *, scale: int | None = None,
cleanup_wait: bool = True) -> dict:
with service_with_env(service, scale=scale, **env):
atts, took = run.finish(run.upload_many())
if cleanup_wait: # garbage of interrupted attempts: cleaned after ORPHAN_GRACE_SECONDS
try:
wait(lambda: all(json.loads(psql(
"SELECT json_build_object('n', count(*)) FROM job_attempts a JOIN jobs j ON j.id = a.job_id "
f"WHERE j.attachment_id = '{a['id']}' AND a.outcome <> 'succeeded' "
"AND a.objects_cleaned_at IS NULL"))["n"] == 0 for a in atts), 60, "cleanup")
except AssertionError:
pass # reported below as uncleaned attempts
objects = s3_keys("a/")
per = [facts(a["id"], objects) for a in atts]
problems = {a["id"]: p for a, f in zip(atts, per) if (p := expect_one_effect(f))}
return {"scenario": name, "faults": {service: env}, "uploads": len(atts),
"ready": sum(f["status"] == "ready" for f in per), "claims_total": sum(f["claims"] for f in per),
"max_claims": max(f["claims"] for f in per), "time_to_ready_s": {"p50": statistics.median(took),
"max": max(took)},
"event_sequences": sorted({" > ".join(f["events"]) for f in per}), "problems": problems}
def versions_scenario(run: Run) -> dict:
"""Stale job after a newer version: v2 (slow) and v3 run at the same time; v3 publishes first,
v2 finishes later and must end superseded without touching the published v3 result."""
att = run.upload_many(1)[0]
run.api.wait_status(run.bob, att["id"], "ready")
observed = set()
with service_with_env("worker", WORKER_FAULT_POINTS="slow=10,slow_pipeline=2"):
jobctl("reprocess", att["id"], "--pipeline", "2", "--operator", "track2", "--reason", "new encoder")
wait(lambda: "processing:v2" in facts(att["id"], set())["job_states"], 60, "v2 not claimed")
jobctl("reprocess", att["id"], "--pipeline", "3", "--operator", "track2", "--reason", "newer encoder")
deadline = time.monotonic() + 120
while time.monotonic() < deadline:
meta = run.api.attachment(run.bob, att["id"])
observed.add(meta["status"])
states = facts(att["id"], set())["job_states"]
if not any(s.startswith(("queued", "processing")) for s in states):
break
time.sleep(0.3)
final = run.api.attachment(run.bob, att["id"])
f = facts(att["id"], s3_keys("a/"))
thumb_v3 = psql(f"SELECT encode(sha256, 'hex') FROM attachment_variants WHERE attachment_id = '{att['id']}' "
"AND pipeline_version = 3 AND name = 'thumbnail'")
problems = []
if f["job_states"] != ["succeeded:v1", "superseded:v2", "succeeded:v3"]:
problems.append(f"job states {f['job_states']}")
if f["published_version"] != 3 or observed != {"ready"}:
problems.append(f"published v{f['published_version']}, statuses seen {sorted(observed)}")
if next(v["sha256"] for v in final["variants"] if v["name"] == "thumbnail") != thumb_v3:
problems.append("published thumbnail is not the v3 one")
# Stale duplicate of the FIRST job, published by hand with the relay's broker user: a no-op.
job_v1 = psql(f"SELECT id FROM jobs WHERE attachment_id = '{att['id']}' AND pipeline_version = 1")
script = ("import asyncio, aio_pika, datetime as d\n"
"from messenger import broker\n"
"async def m():\n"
" c = await aio_pika.connect(open('/run/secrets/broker_url').read().strip())\n"
" ch = await c.channel(publisher_confirms=True)\n"
" ex = await ch.get_exchange(broker.EXCHANGE, ensure=False)\n"
f" body = broker.encode('{job_v1}', '{att['id']}', 1, 1, d.datetime.now(d.timezone.utc))\n"
" await ex.publish(aio_pika.Message(body), routing_key=broker.ROUTING_KEY)\n"
" await c.close()\n"
"asyncio.run(m())\n")
compose("exec", "-T", "relay", "python", "-c", script)
time.sleep(3)
after = run.api.attachment(run.bob, att["id"])
if after != final:
problems.append("stale v1 message changed the attachment")
return {"scenario": "stale_version_and_reorder", "uploads": 1, "statuses_seen_during_reprocess": sorted(observed),
"job_states": f["job_states"], "published_version": f["published_version"],
"variant_rows_by_version": f["variant_rows"], "objects": f["objects"],
"events": f["events"], "problems": problems}
def queued_reorder_scenario(run: Run) -> dict:
"""Both newer versions wait in the outbox; the relay publishes them in REVERSE order and one worker
takes them one by one: v3 is published first, v2 is then superseded at its claim (no work)."""
att = run.upload_many(1)[0]
run.api.wait_status(run.bob, att["id"], "ready")
# The worker stays stopped until it is recreated with concurrency 1 (no normal start in between).
# Worker and relay stay stopped until each is recreated with the scenario's settings: no normal
# start in between that would consume/publish the jobs in the ordinary order.
compose("stop", "worker", "relay")
try:
jobctl("reprocess", att["id"], "--pipeline", "2", "--operator", "track2", "--reason", "v2")
jobctl("reprocess", att["id"], "--pipeline", "3", "--operator", "track2", "--reason", "v3")
with service_with_env("relay", RELAY_FAULT_POINTS="reverse_order"):
wait(lambda: psql("SELECT count(*) FROM outbox o JOIN jobs j ON j.id = o.job_id WHERE j.attachment_id = "
f"'{att['id']}' AND j.pipeline_version > 1 AND o.published_at IS NOT NULL") == "2",
30, "both reprocess jobs not published") # in one relay batch: v3 first, then v2
with service_with_env("worker", WORKER_CONCURRENCY="1"):
wait(lambda: not any(s.startswith(("queued", "processing"))
for s in facts(att["id"], set())["job_states"]), 120, "reprocess jobs did not finish")
finally:
compose("start", "worker", "relay")
wait_healthy("worker", "relay")
f = facts(att["id"], s3_keys("a/"))
problems = []
if f["job_states"] != ["succeeded:v1", "superseded:v2", "succeeded:v3"] or f["published_version"] != 3:
problems.append(f"{f['job_states']} published v{f['published_version']}")
if f["claims"] != 2: # v1 and v3 only: v2 was superseded before any work
problems.append(f"{f['claims']} claims")
return {"scenario": "reordered_versions_in_queue", "job_states": f["job_states"], "claims": f["claims"],
"published_version": f["published_version"], "events": f["events"], "problems": problems}
def hung_worker_scenario(run: Run) -> dict:
with service_with_env("worker", scale=2, WORKER_FAULT_POINTS="slow=8", **FAST):
att = run.upload_many(1)[0]
owner = wait(lambda: psql(f"SELECT lease_owner FROM jobs WHERE attachment_id = '{att['id']}' "
"AND state = 'processing'"), 30, "not claimed")
ids = compose("ps", "-q", "worker").stdout.split()
names = dict(line.split() for line in subprocess.run(
["docker", "inspect", "-f", "{{.Config.Hostname}} {{.Id}}", *ids], capture_output=True, text=True,
check=True).stdout.splitlines())
subprocess.run(["docker", "pause", names[owner]], check=True)
try:
run.api.wait_status(run.bob, att["id"], "ready", timeout=150)
published = psql(f"SELECT string_agg(object_key, ',' ORDER BY object_key) FROM attachment_variants "
f"WHERE attachment_id = '{att['id']}'")
finally:
subprocess.run(["docker", "unpause", names[owner]], check=True)
time.sleep(15)
again = psql(f"SELECT string_agg(object_key, ',' ORDER BY object_key) FROM attachment_variants "
f"WHERE attachment_id = '{att['id']}'")
wait(lambda: json.loads(psql("SELECT json_build_object('n', count(*)) FROM job_attempts a JOIN jobs j "
f"ON j.id = a.job_id WHERE j.attachment_id = '{att['id']}' AND a.outcome <> "
"'succeeded' AND a.objects_cleaned_at IS NULL"))["n"] == 0, 60, "cleanup")
f = facts(att["id"], s3_keys("a/"))
problems = expect_one_effect(f)
if published != again:
problems.append("the resumed (fenced) attempt changed the published result")
return {"scenario": "hung_worker_docker_pause", "frozen": owner, "claims": f["claims"], "events": f["events"],
"problems": problems}
def main() -> int:
p = argparse.ArgumentParser()
p.add_argument("--output", default="evidence/track2")
p.add_argument("--uploads", type=int, default=5)
args = p.parse_args()
out = ROOT / args.output
out.mkdir(parents=True, exist_ok=True)
api = Api()
run = Run(api, args.uploads)
started = now()
results = []
plan = [
("baseline_no_faults", "worker", {}),
("duplicate_publish", "relay", {"RELAY_FAULT_POINTS": "duplicate_publish"}),
("duplicate_and_reverse_order", "relay", {"RELAY_FAULT_POINTS": "duplicate_publish,reverse_order"}),
("relay_crash_after_confirm_before_mark", "relay", {"RELAY_FAULT_POINTS": "crash_after_publish"}),
("worker_crash_before_side_effect", "worker", {"WORKER_FAULT_POINTS": "crash_after_claim", **FAST}),
("worker_crash_after_s3_before_commit", "worker", {"WORKER_FAULT_POINTS": "crash_after_s3_write", **FAST}),
("worker_crash_after_commit_before_ack", "worker", {"WORKER_FAULT_POINTS": "crash_after_commit", **FAST}),
("transient_errors_then_success", "worker", {"WORKER_FAULT_POINTS": "transient_error=2",
"JOB_RETRY_BASE_SECONDS": "0.5", **FAST}),
]
for name, service, env in plan:
print(f"[{now()}] {name}", flush=True)
results.append(plain_scenario(run, name, service, env))
print(f"[{now()}] two_workers_duplicate_publish", flush=True)
with service_with_env("relay", RELAY_FAULT_POINTS="duplicate_publish"):
results.append(plain_scenario(run, "two_workers_duplicate_publish", "worker", {}, scale=2))
for scenario in (versions_scenario, queued_reorder_scenario, hung_worker_scenario):
print(f"[{now()}] {scenario.__name__}", flush=True)
results.append(scenario(run))
wait_healthy("worker", "relay")
report = audit()
summary = {
"experiment": "track 2: idempotency of the versioned pipeline under injected faults",
"started": started, "finished": now(),
"host": {"os": platform.platform(), "python": platform.python_version()},
"uploads_per_plain_scenario": args.uploads,
"scenarios": results,
"audit_after_all": report,
"violations": sum(len(r["problems"]) for r in results) + len(report["violations"]),
}
(out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=1), encoding="utf-8")
lines = [f"{'scenario':45} {'uploads':>7} {'ready':>5} {'claims':>6} problems"]
for r in results:
lines.append(f"{r['scenario']:45} {r.get('uploads', 1):>7} {r.get('ready', '-'):>5} "
f"{r.get('claims_total', r.get('claims', '-')):>6} {len(r['problems'])}")
lines.append(f"audit after all scenarios: ok={report['ok']} violations={len(report['violations'])} "
f"objects={report['objects']}")
(out / "summary.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")
print("\n".join(lines))
return 0 if summary["violations"] == 0 else 1
if __name__ == "__main__":
sys.exit(main())
-156
View File
@@ -1,156 +0,0 @@
#!/usr/bin/env python3
"""Track 2 experiment: cost of one reconciler pass as a function of the number of attachments.
Hypothesis: a pass is O(N) with ~N/1000 S3 list requests + N/1000 DB pages and constant memory
(merge-join of two key-ordered streams); --verify-checksums adds reading every byte (O(total size)).
Method: synthetic, CONSISTENT attachments (row 'ready' + 1 KiB object with the matching size and
SHA-256, filename 'bench-reconcile') are added in steps up to the largest N; after each step the
reconciler runs in dry-run 3 times (median reported), plus page-size and checksum variants.
Everything synthetic is deleted at the end (objects first, then rows).
python bench/reconcile_cost.py --steps 1000 10000 50000 --output evidence/reconcile
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import platform
import statistics
import subprocess
import sys
import time
import uuid
from pathlib import Path
import httpx2 as httpx
ROOT = Path(__file__).resolve().parents[1]
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
PASSWORD = "Bench-password-Ω-12345"
OBJECT = bytes(range(256)) * 4 # 1 KiB, the same content for every object
SHA = hashlib.sha256(OBJECT).hexdigest()
PUT_SCRIPT = """
import asyncio, sys
from messenger.config import Settings, s3_settings
from messenger.storage import Storage
DATA = bytes(range(256)) * 4
async def main():
s = Storage(Settings(host='', port=0, env='lab', log_level='info', shutdown_timeout=0, max_body_bytes=1024, **s3_settings()))
await s.open()
keys = sys.stdin.read().split()
sem = asyncio.Semaphore(32)
async def one(k):
async with sem:
await s.{op}(k{args})
await asyncio.gather(*(one(k) for k in keys))
await s.close()
print(len(keys))
asyncio.run(main())
"""
def compose(*args: str, stdin: str | None = None, timeout: float = 1800, check: bool = True) -> subprocess.CompletedProcess:
return subprocess.run(["docker", "compose", *args], cwd=ROOT, input=stdin, capture_output=True, text=True,
encoding="utf-8", timeout=timeout, check=check)
def psql(sql: str) -> str:
"""SQL through stdin: a 5000-row INSERT does not fit into a Windows command line (32 KiB)."""
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-v",
"ON_ERROR_STOP=1", "-f", "-", stdin=sql).stdout.strip()
def s3_bulk(op: str, keys: list[str]) -> None:
script = PUT_SCRIPT.replace("{op}", op).replace("{args}", ", DATA, 'image/png', {}" if op == "put" else "")
compose("run", "--rm", "--no-deps", "-T", "--entrypoint", "python", "reconciler", "-c", script, stdin="\n".join(keys))
def owner_and_chat() -> tuple[str, str]:
import base64
c = httpx.Client(base_url=BASE, timeout=30)
name = "rc_" + uuid.uuid4().hex[:10]
c.post("/api/v1/users", json={"username": name, "display_name": "bench", "password": PASSWORD}).raise_for_status()
token = c.post("/api/v1/auth/sessions", headers={
"Authorization": "Basic " + base64.b64encode(f"{name}:{PASSWORD}".encode()).decode()}).json()["token"]
me = c.get("/api/v1/users/me", headers={"Authorization": "Bearer " + token}).json()
chat = c.post("/api/v1/chats", headers={"Authorization": "Bearer " + token},
json={"title": "bench", "member_ids": [me["id"]]}).json()
return me["id"], chat["id"]
def add(n: int, owner: str, chat: str) -> None:
keys = ["o/" + uuid.uuid4().hex for _ in range(n)]
for i in range(0, n, 5000):
part = keys[i:i + 5000]
values = ",".join(f"('{uuid.uuid4()}','{k}')" for k in part)
psql("INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height, "
"object_key, status, created_at, updated_at) "
f"SELECT v.id::uuid, '{chat}', '{owner}', 'bench-reconcile', 'image/png', {len(OBJECT)}, "
f"decode('{SHA}', 'hex'), 1, 1, v.k, 'ready', clock_timestamp() - interval '2 hours', "
f"clock_timestamp() - interval '2 hours' FROM (VALUES {values}) AS v(id, k)")
s3_bulk("put", keys)
def reconcile(*args: str) -> dict:
out = compose("run", "--rm", "--no-deps", "-T", "reconciler", *args).stdout
return json.loads(out)
def measure(label: str, args: list[str], repeats: int) -> dict:
runs = [reconcile(*args) for _ in range(repeats)]
durations = [r["duration_seconds"] for r in runs]
last = runs[-1]
return {"label": label, "args": args, "runs": repeats, "duration_s_median": statistics.median(durations),
"duration_s_all": durations, "objects": last["scanned"]["objects"], "rows": last["scanned"]["rows"],
"findings": {k: v for k, v in last["findings"].items() if v}, "cost": last["cost"]}
def main() -> int:
p = argparse.ArgumentParser()
p.add_argument("--steps", type=int, nargs="+", default=[1000, 10000, 50000])
p.add_argument("--repeats", type=int, default=3)
p.add_argument("--output", default="evidence/reconcile")
args = p.parse_args()
out = ROOT / args.output
out.mkdir(parents=True, exist_ok=True)
owner, chat = owner_and_chat()
present = 0
results = []
steps = sorted(args.steps)
variant_step = steps[min(1, len(steps) - 1)]
try:
for target in sorted(args.steps):
started = time.perf_counter()
add(target - present, owner, chat)
present = target
print(f"populated {present} synthetic attachments in {time.perf_counter() - started:.1f} s", flush=True)
results.append({"synthetic": present, **measure("dry-run, page 1000", [], args.repeats)})
print(json.dumps(results[-1], ensure_ascii=False), flush=True)
if present == variant_step: # page-size and checksum variants at one size
for label, extra in (("dry-run, page 100", ["--page-size", "100"]),
("dry-run, --verify-checksums", ["--verify-checksums"])):
results.append({"synthetic": present, **measure(label, extra, args.repeats)})
print(json.dumps(results[-1], ensure_ascii=False), flush=True)
finally:
keys = psql("SELECT object_key FROM attachments WHERE filename = 'bench-reconcile' AND chat_id = "
f"'{chat}'").split()
if keys:
s3_bulk("delete", keys)
psql(f"DELETE FROM attachments WHERE filename = 'bench-reconcile' AND chat_id = '{chat}'")
print(f"removed {len(keys)} synthetic attachments", flush=True)
meta = {"date": time.strftime("%Y-%m-%d %H:%M:%S"), "host": platform.platform(), "cpus": os.cpu_count(),
"commit": subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, capture_output=True,
text=True).stdout.strip(),
"object_bytes": len(OBJECT), "reconciler_limits": "cpus 1.0, memory 256m (compose)",
"note": "the bucket/table also contain the attachments of earlier test runs (counted in objects/rows)"}
(out / "cost.json").write_text(json.dumps({"meta": meta, "results": results}, ensure_ascii=False, indent=1),
encoding="utf-8")
return 0
if __name__ == "__main__":
sys.exit(main())
-174
View File
@@ -1,174 +0,0 @@
#!/usr/bin/env python3
"""Track 2 evidence: inject faults on both sides, run the reconciler, keep every JSON report.
Scenario A (all fault kinds; the same as student-tests/test_reconcile.py, but the reports are saved):
S3 side: old orphan objects, object deleted under a USED ready row, object truncated under an
unused ready row, same-size corruption (found only with --verify-checksums);
DB side: stale intents (with / without object), quarantine mark on a healthy row;
fresh: orphan + intent younger than --grace.
Runs: dry-run (+ snapshot of both stores before/after) -> apply -> apply again -> restore of the
lost object from a "backup" -> apply (quarantine lifted).
Scenario B (interrupted apply): 2000 old orphans, S3 is paused while --apply deletes them ->
the run stops with an error, nothing else is damaged; the next run finishes the rest; the
third run finds nothing.
python bench/reconcile_faults.py --output evidence/reconcile
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
import threading
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "student-tests"))
import imagegen # noqa: E402
from conftest import (Api, attachment_row, compose, findings_by_key, psql, s3_delete, s3_exec, s3_keys, # noqa: E402
s3_put)
from test_reconcile import insert_intent, snapshot # noqa: E402
GRACE = ["--grace", "30", "--allow-small-grace"]
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
def reconcile(*args: str) -> tuple[int, dict]:
r = compose("run", "--rm", "--no-deps", "-T", "reconciler", "--samples", "1000", *args, check=False, timeout=600)
return r.returncode, json.loads(r.stdout)
def save(out: Path, name: str, data) -> None:
(out / name).write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
def ours(report: dict, keys: dict[str, str]) -> dict:
"""The findings of this scenario's keys only (the stand also holds other test data)."""
f = findings_by_key(report)
return {label: ({"kind": f[k]["kind"], "result": f[k]["result"], "used": f[k]["used"]} if k in f else None)
for label, k in keys.items()}
def scenario_a(out: Path) -> dict:
api = Api()
alice, bob = api.user("alice"), api.user("bob")
chat = api.chat(alice, bob)
up = {n: api.upload(alice, chat, imagegen.png(40 + i, 30, noise=True)).json() for i, n in enumerate("ABCDEF")}
data = {n: api.call("GET", f"/api/v1/attachments/{a['id']}/content", 200, token=alice["token"]).content
for n, a in up.items()}
key = {n: attachment_row(a["id"])["object_key"] for n, a in up.items()}
api.post_message(alice, chat, {"text": "used", "attachment_ids": [up["A"]["id"], up["C"]["id"], up["E"]["id"]]})
keys = {"healthy used A": key["A"], "healthy unused B": key["B"], "used, object deleted C": key["C"],
"unused, object truncated D": key["D"], "quarantined but healthy E": key["E"],
"same-size corruption F": key["F"]}
orphan = "o/" + uuid.uuid4().hex
stale_with, stale_without = "o/" + uuid.uuid4().hex, "o/" + uuid.uuid4().hex
s3_put(orphan, SAMPLE)
s3_put(stale_with, SAMPLE)
insert_intent(chat, alice, stale_with, SAMPLE, 600)
insert_intent(chat, alice, stale_without, SAMPLE, 600)
s3_delete(key["C"])
s3_put(key["D"], data["D"][: len(data["D"]) // 2])
s3_put(key["F"], data["F"][:200] + bytes([data["F"][200] ^ 1]) + data["F"][201:])
psql(f"UPDATE attachments SET lost_at = clock_timestamp(), lost_reason = 'missing_object' WHERE id = '{up['E']['id']}'")
keys.update({"old orphan object": orphan, "stale intent + object": stale_with, "stale intent, no object": stale_without})
time.sleep(32)
fresh_orphan, fresh_intent = "o/" + uuid.uuid4().hex, "o/" + uuid.uuid4().hex
s3_put(fresh_orphan, SAMPLE)
s3_put(fresh_intent, SAMPLE)
insert_intent(chat, alice, fresh_intent, SAMPLE, 0)
keys.update({"fresh orphan (in-flight)": fresh_orphan, "fresh intent (in-flight)": fresh_intent})
before = snapshot()
_, dry = reconcile("--verify-checksums", *GRACE)
after = snapshot()
_, apply1 = reconcile("--apply", "--verify-checksums", *GRACE)
_, apply2 = reconcile("--apply", "--verify-checksums", *GRACE)
s3_put(key["C"], data["C"]) # the lost object restored from a backup
_, apply3 = reconcile("--apply", "--verify-checksums", *GRACE)
for name, report in (("faults-1-dry-run.json", dry), ("faults-2-apply.json", apply1),
("faults-3-apply-again.json", apply2), ("faults-4-after-restore.json", apply3)):
save(out, name, report)
rows = {label: attachment_row(up[n]["id"]) for label, n in (("C", "C"), ("D", "D"), ("E", "E"), ("F", "F"), ("A", "A"), ("B", "B"))}
content = {n: api.client.get(f"/api/v1/attachments/{up[n]['id']}/content",
headers={"Authorization": "Bearer " + bob["token"]}).status_code for n in "ABCDEF"}
present = s3_keys()
summary = {
"dry_run_changed_nothing": before == after,
"per_key": {"dry-run": ours(dry, keys), "apply": ours(apply1, keys), "apply again": ours(apply2, keys),
"after restore of C": ours(apply3, keys)},
"objects_present_at_end (fresh items were older than --grace by the later runs)": {label: k in present for label, k in keys.items()},
"rows_after": {k: (v and {"status": v["status"], "lost_reason": v["lost_reason"]}) for k, v in rows.items()},
"content_status_after": content,
"durations_s": [dry["duration_seconds"], apply1["duration_seconds"], apply2["duration_seconds"],
apply3["duration_seconds"]],
}
print(json.dumps(summary, ensure_ascii=False, indent=1), flush=True)
return summary
def scenario_b(out: Path, count: int = 2000) -> dict:
keys = ["o/" + uuid.uuid4().hex for _ in range(count)]
s3_exec("ks = sys.stdin.read().split()\n"
"sem = asyncio.Semaphore(32)\n"
"async def one(k):\n"
" async with sem:\n"
" await s.put(k, b'orphan', 'image/png', {})\n"
"await asyncio.gather(*(one(k) for k in ks))", stdin="\n".join(keys))
time.sleep(32)
result: dict = {}
def run_apply() -> None:
result["code"], result["report"] = reconcile("--apply", "--max-orphan-fraction", "1", *GRACE)
t = threading.Thread(target=run_apply)
t.start()
# pause S3 as soon as deletions are under way (the reconciler is planning/listing first)
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
left = len(s3_keys() & set(keys))
if left < count:
break
time.sleep(0.2)
subprocess.run(["docker", "compose", "pause", "s3"], cwd=ROOT, check=True, capture_output=True)
t.join()
subprocess.run(["docker", "compose", "unpause", "s3"], cwd=ROOT, check=True, capture_output=True)
time.sleep(5) # let S3 settle after unpause before counting
left_after_interrupt = len(s3_keys() & set(keys))
code2, second = reconcile("--apply", "--max-orphan-fraction", "1", *GRACE)
code3, third = reconcile("--apply", *GRACE)
save(out, "interrupted-1-apply.json", result["report"])
save(out, "interrupted-2-rerun.json", second)
save(out, "interrupted-3-third.json", third)
summary = {
"orphans_injected": count,
"interrupted_run": {"exit_code": result["code"], "error": result["report"].get("error"),
"applied": result["report"]["actions"]["applied"]},
"orphans_left_after_interrupt": left_after_interrupt,
"rerun": {"exit_code": code2, "applied": second["actions"]["applied"], "error": second["error"]},
"third": {"exit_code": code3, "planned": third["actions"]["planned"]},
"orphans_left_at_end": len(s3_keys() & set(keys)),
}
print(json.dumps(summary, ensure_ascii=False, indent=1), flush=True)
return summary
def main() -> int:
p = argparse.ArgumentParser()
p.add_argument("--output", default="evidence/reconcile")
args = p.parse_args()
out = ROOT / args.output
out.mkdir(parents=True, exist_ok=True)
a = scenario_a(out)
b = scenario_b(out)
commit = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, capture_output=True, text=True).stdout.strip()
save(out, "faults-summary.json", {"date": time.strftime("%Y-%m-%d %H:%M:%S"), "commit": commit,
"grace_seconds": 30, "scenario_a": a, "scenario_b_interrupted": b})
return 0
if __name__ == "__main__":
sys.exit(main())
+225 -42
View File
@@ -1,15 +1,20 @@
# Lab 4 stand: client -> HAProxy (lb) -> API x N (one scalable service `api`)
# -> PostgreSQL (metadata, source of truth) + Valkey (sessions) + SeaweedFS S3 (bytes).
# Lab 5 stand: client -> HAProxy (lb) -> API x N (scalable service `api`)
# -> PostgreSQL (metadata, jobs, outbox: source of truth) + Valkey (sessions)
# + SeaweedFS S3 (staging bucket and final bucket, both private)
# relay : outbox in PostgreSQL -> RabbitMQ (publisher confirms) [service `relay`]
# broker : RabbitMQ 4.3, durable quorum queue + dead-letter queue [service `broker`]
# worker : RabbitMQ -> variants -> final bucket + PostgreSQL, then ack [service `worker`]
# From a clean clone (details and Windows notes: REPORT.md, docs/WINDOWS.md):
# python scripts/init_secrets.py # once: random local credentials into ./secrets (git-ignored)
# cp .env.example .env # optional overrides (API_REPLICAS, limits, ...)
# docker compose --env-file .env up -d --build --wait
# Order: postgres/valkey/s3 healthy -> migrate + s3-init (ONE run each, exit 0) -> api healthy -> lb.
# Order: postgres/valkey/s3/broker healthy -> migrate + s3-init (ONE run each, exit 0)
# -> api healthy -> lb; relay and worker start after migrate/s3-init.
# Images are pinned by version AND digest. Passwords/keys are passed only as secret files, and
# every service gets only the secrets it needs. Only the LB publishes ports (loopback only).
# Three networks: `edge` (lb <-> api), `data` (api/migrate/reconciler <-> postgres/valkey) and
# `storage` (api/s3-init/reconciler <-> s3); data and storage are internal (no route outside).
name: mtusi-lab4
# Networks: `edge` (lb <-> api); internal (no route outside): `data` (postgres/valkey),
# `storage` (s3), `queue` (broker). The API is NOT on `queue`: it never talks to the broker.
name: mtusi-lab5
x-api-env: &api-env
APP_ENV: ${APP_ENV:-lab}
@@ -29,10 +34,11 @@ x-api-env: &api-env
SHUTDOWN_TIMEOUT_SECONDS: ${SHUTDOWN_TIMEOUT_SECONDS:-8}
DOCS_ENABLED: ${DOCS_ENABLED:-true}
MESSAGE_WRITE_PATH: ${MESSAGE_WRITE_PATH:-function}
# Lab 4: S3 (the API's own Read+Write key pair, see infra/seaweedfs/start.sh) and upload limits.
# S3: the API's own key pair (Write staging + Read final, see infra/seaweedfs/start.sh).
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333}
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging}
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
S3_TIMEOUT_SECONDS: ${S3_TIMEOUT_SECONDS:-3}
@@ -46,8 +52,33 @@ x-api-env: &api-env
JPEG_MAX_MEMORY_MB: ${JPEG_MAX_MEMORY_MB:-256}
PENDING_GRACE_SECONDS: ${PENDING_GRACE_SECONDS:-900}
JANITOR_INTERVAL_SECONDS: ${JANITOR_INTERVAL_SECONDS:-60}
# Level 4 failure experiments only (compose.faults.yaml); empty = no injected failures.
FAULT_POINTS: ${FAULT_POINTS:-}
# Lab 5: pipeline version and attempt budget of the jobs created by uploads.
PIPELINE_VERSION: ${PIPELINE_VERSION:-1}
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
# Failure experiments only (student-tests, bench/); empty = no injected failures.
FAULT_POINTS: ${API_FAULT_POINTS:-}
# Settings of the pipeline shared by relay and worker (docs/PIPELINE.md).
x-pipeline-env: &pipeline-env
APP_ENV: ${APP_ENV:-lab}
LOG_LEVEL: ${LOG_LEVEL:-info}
DATABASE_URL_FILE: /run/secrets/database_url
BROKER_URL_FILE: /run/secrets/broker_url
DB_POOL_MAX: ${PIPELINE_DB_POOL_MAX:-6}
DB_TIMEOUT_SECONDS: ${DB_TIMEOUT_SECONDS:-3}
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333}
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging}
S3_TIMEOUT_SECONDS: ${S3_TIMEOUT_SECONDS:-3}
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-30}
JOB_RETRY_BASE_SECONDS: ${JOB_RETRY_BASE_SECONDS:-2}
JOB_RETRY_MAX_SECONDS: ${JOB_RETRY_MAX_SECONDS:-60}
QUEUED_REPUBLISH_SECONDS: ${QUEUED_REPUBLISH_SECONDS:-300}
services:
postgres:
@@ -102,15 +133,15 @@ services:
resources:
limits: {cpus: "${VALKEY_CPUS:-0.5}", memory: 256m}
# Lab 4: S3-compatible object storage (SeaweedFS: master + volume + filer + S3 gateway in one
# process). Bytes of the attachments live ONLY here, on the named volume s3data. Identities
# and exposure: infra/seaweedfs/start.sh. Not published on the host; its web UIs listen on
# 127.0.0.1 inside the container only.
# S3-compatible object storage (SeaweedFS: master + volume + filer + S3 gateway in one process).
# Bytes live ONLY here, on the named volume s3data: staging bucket (originals accepted before
# 202) and final bucket (published originals and variants). Identities: infra/seaweedfs/start.sh.
s3:
image: chrislusf/seaweedfs:4.46@sha256:08d516132314207d10c8e37cbffc1f32b147d870169688734cc61c6231625b62
entrypoint: ["/bin/sh", "/etc/seaweedfs/start.sh"]
environment:
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging}
# Go heap target below the container limit: the GC returns memory before the cgroup OOM.
GOMEMLIMIT: ${S3_GOMEMLIMIT:-600MiB}
secrets:
@@ -118,8 +149,10 @@ services:
- s3_admin_secret_access_key
- s3_api_access_key_id
- s3_api_secret_access_key
- s3_reconciler_access_key_id
- s3_reconciler_secret_access_key
- s3_worker_access_key_id
- s3_worker_secret_access_key
- s3_auditor_access_key_id
- s3_auditor_secret_access_key
volumes:
- ./infra/seaweedfs/start.sh:/etc/seaweedfs/start.sh:ro
- s3data:/data
@@ -137,6 +170,34 @@ services:
resources:
limits: {cpus: "${S3_CPUS:-1.0}", memory: "${S3_MEMORY:-1g}"}
# Lab 5: RabbitMQ. Topology (exchange, quorum queue, DLX/DLQ) and users come from definition
# files imported at boot (infra/rabbitmq, secrets/rabbitmq_users.json). Messages of the quorum
# queue live on the named volume rabbitmqdata. No management UI, no host port.
broker:
image: rabbitmq:4.3.7-alpine@sha256:b1f997f74103d08fc1f20a13890dc44fe6cfa51d528cf521b480ada988d3ffa5
hostname: broker # node name rabbit@broker: stable across container re-creation
secrets:
- source: rabbitmq_users
target: /etc/rabbitmq/definitions.d/users.json
volumes:
- ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/conf.d/20-lab5.conf:ro
- ./infra/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins:ro
- ./infra/rabbitmq/topology.json:/etc/rabbitmq/definitions.d/topology.json:ro
- rabbitmqdata:/var/lib/rabbitmq
healthcheck:
# The node runs and the AMQP listener accepts connections.
test: ["CMD-SHELL", "rabbitmq-diagnostics -q ping && rabbitmq-diagnostics -q check_port_connectivity"]
interval: 5s
timeout: 10s
retries: 30
start_period: 20s
stop_grace_period: 30s
restart: unless-stopped
networks: [queue]
deploy:
resources:
limits: {cpus: "${BROKER_CPUS:-1.0}", memory: "${BROKER_MEMORY:-512m}"}
# One-shot schema migration: runs ONCE per `up`, before any API replica starts
# (api depends_on service_completed_successfully). Replicas never migrate themselves.
migrate:
@@ -144,7 +205,7 @@ services:
context: .
args:
BUILD_REVISION: ${BUILD_REVISION:-dev}
image: ${API_IMAGE:-mtusi-messenger:lab4}
image: ${API_IMAGE:-mtusi-messenger:lab5}
command: ["python", "-m", "messenger.migrate"]
environment:
DATABASE_URL_FILE: /run/secrets/database_url
@@ -160,28 +221,33 @@ services:
resources:
limits: {cpus: "0.5", memory: 256m}
# One-shot, idempotent S3 bootstrap: bucket, sentinel object, verification of the access model
# (private bucket, least-privilege keys). The ONLY holder of the admin key pair besides s3.
# One-shot, idempotent S3 bootstrap: both buckets, sentinel object, verification of the access
# model (private buckets, least-privilege keys). The ONLY holder of the admin key pair besides s3.
s3-init:
image: ${API_IMAGE:-mtusi-messenger:lab4}
image: ${API_IMAGE:-mtusi-messenger:lab5}
command: ["python", "-m", "messenger.s3_bootstrap"]
environment:
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333}
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging}
S3_ADMIN_ACCESS_KEY_ID_FILE: /run/secrets/s3_admin_access_key_id
S3_ADMIN_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_admin_secret_access_key
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_api_access_key_id
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_api_secret_access_key
S3_RECONCILER_ACCESS_KEY_ID_FILE: /run/secrets/s3_reconciler_access_key_id
S3_RECONCILER_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_reconciler_secret_access_key
S3_WORKER_ACCESS_KEY_ID_FILE: /run/secrets/s3_worker_access_key_id
S3_WORKER_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_worker_secret_access_key
S3_AUDITOR_ACCESS_KEY_ID_FILE: /run/secrets/s3_auditor_access_key_id
S3_AUDITOR_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_auditor_secret_access_key
secrets:
- s3_admin_access_key_id
- s3_admin_secret_access_key
- s3_api_access_key_id
- s3_api_secret_access_key
- s3_reconciler_access_key_id
- s3_reconciler_secret_access_key
- s3_worker_access_key_id
- s3_worker_secret_access_key
- s3_auditor_access_key_id
- s3_auditor_secret_access_key
depends_on:
s3:
condition: service_healthy
@@ -200,7 +266,7 @@ services:
context: .
args:
BUILD_REVISION: ${BUILD_REVISION:-dev}
image: ${API_IMAGE:-mtusi-messenger:lab4}
image: ${API_IMAGE:-mtusi-messenger:lab5}
environment: *api-env
secrets:
- database_url
@@ -236,7 +302,7 @@ services:
replicas: ${API_REPLICAS:-2}
resources:
# 512m: UPLOAD_CONCURRENCY (4) x 10 MiB bodies + one djpeg (<= JPEG_MAX_MEMORY_MB) + runtime;
# measured in evidence/memory/ (bench/upload_memory.py).
# measured in lab 4 (bench/upload_memory.py). No resizing happens in the API.
limits: {cpus: "${API_CPUS:-1.0}", memory: "${API_MEMORY:-512m}"}
# No swap on top of the limit (Docker's default would allow as much swap again): the RAM bound
# of the experiments is a real bound, and running out of it is visible, not hidden in swap.
@@ -268,29 +334,112 @@ services:
resources:
limits: {cpus: "${LB_CPUS:-1.0}", memory: 128m}
# Track 2 (lab 4): reconciler of S3 objects vs PostgreSQL metadata. Not a daemon: started on
# demand, dry-run by default (read-only on both stores):
# docker compose run --rm reconciler # report only
# docker compose run --rm reconciler --apply # fix: orphans, stale intents, quarantine
reconciler:
# Lab 5: outbox relay + lease reaper (src/messenger/relay.py). One process; a second one would
# be safe (SKIP LOCKED) but is not needed. Database + broker only, no S3 keys.
relay:
image: ${API_IMAGE:-mtusi-messenger:lab5}
command: ["python", "-m", "messenger.relay"]
environment:
<<: *pipeline-env
RELAY_POLL_SECONDS: ${RELAY_POLL_SECONDS:-0.5}
FAULT_POINTS: ${RELAY_FAULT_POINTS:-}
secrets:
- database_url
- source: broker_url_relay
target: broker_url
healthcheck:
test: ["CMD", "python", "-m", "messenger.healthcheck", "--file", "/tmp/heartbeat", "--max-age", "30"]
interval: 5s
timeout: 3s
retries: 3
start_period: 10s
depends_on:
postgres:
condition: service_healthy
broker:
condition: service_healthy
migrate:
condition: service_completed_successfully
stop_grace_period: 10s
restart: unless-stopped
networks: [data, queue]
deploy:
resources:
limits: {cpus: "${RELAY_CPUS:-0.5}", memory: 256m}
# Lab 5: image worker (src/messenger/worker.py). Scalable (`--scale worker=2`): competing
# consumers of one queue; the database lease decides who works on a job.
worker:
image: ${API_IMAGE:-mtusi-messenger:lab5}
command: ["python", "-m", "messenger.worker"]
environment:
<<: *pipeline-env
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
WORKER_SHUTDOWN_SECONDS: ${WORKER_SHUTDOWN_SECONDS:-20}
IMAGE_MAX_MEMORY_MB: ${IMAGE_MAX_MEMORY_MB:-768}
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
ORPHAN_GRACE_SECONDS: ${ORPHAN_GRACE_SECONDS:-600}
CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-30}
FAULT_POINTS: ${WORKER_FAULT_POINTS:-}
secrets:
- database_url
- source: broker_url_worker
target: broker_url
- source: s3_worker_access_key_id
target: s3_access_key_id
- source: s3_worker_secret_access_key
target: s3_secret_access_key
healthcheck:
test: ["CMD", "python", "-m", "messenger.healthcheck", "--file", "/tmp/heartbeat", "--max-age", "30"]
interval: 5s
timeout: 3s
retries: 3
start_period: 10s
depends_on:
postgres:
condition: service_healthy
broker:
condition: service_healthy
s3:
condition: service_healthy
migrate:
condition: service_completed_successfully
s3-init:
condition: service_completed_successfully
stop_grace_period: 30s # > WORKER_SHUTDOWN_SECONDS (20 s) + release
restart: unless-stopped
networks: [data, storage, queue]
deploy:
replicas: ${WORKER_REPLICAS:-1}
resources:
# WORKER_CONCURRENCY (2) child processes x IMAGE_MAX_MEMORY_MB (768) address space + worker.
limits: {cpus: "${WORKER_CPUS:-2.0}", memory: "${WORKER_MEMORY:-1536m}"}
memswap_limit: ${WORKER_MEMORY:-1536m}
# Track 2: read-only checker of the pipeline invariants (database in read-only transactions,
# S3 auditor key: Read + List, no Write). On demand: docker compose run --rm auditor
auditor:
profiles: ["tools"]
image: ${API_IMAGE:-mtusi-messenger:lab4}
entrypoint: ["python", "-m", "messenger.reconcile"]
image: ${API_IMAGE:-mtusi-messenger:lab5}
entrypoint: ["python", "-m", "messenger.audit"]
command: []
environment:
DATABASE_URL_FILE: /run/secrets/database_url
DB_TIMEOUT_SECONDS: ${RECONCILE_DB_TIMEOUT_SECONDS:-10}
DB_TIMEOUT_SECONDS: ${AUDIT_DB_TIMEOUT_SECONDS:-30}
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333}
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_STAGING_BUCKET: ${S3_STAGING_BUCKET:-messenger-staging}
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
S3_TIMEOUT_SECONDS: ${S3_TIMEOUT_SECONDS:-3}
secrets:
- database_url
- source: s3_reconciler_access_key_id
- source: s3_auditor_access_key_id
target: s3_access_key_id
- source: s3_reconciler_secret_access_key
- source: s3_auditor_secret_access_key
target: s3_secret_access_key
depends_on:
postgres:
@@ -301,19 +450,43 @@ services:
networks: [data, storage]
deploy:
resources:
limits: {cpus: "${RECONCILER_CPUS:-1.0}", memory: 256m}
limits: {cpus: "1.0", memory: 256m}
# Operator CLI (replay of failed jobs, reprocess with a newer pipeline, failed registry):
# docker compose run --rm jobctl list-failed
# docker compose run --rm jobctl replay <attachment_id> --operator alice --reason "..."
jobctl:
profiles: ["tools"]
image: ${API_IMAGE:-mtusi-messenger:lab5}
entrypoint: ["python", "-m", "messenger.jobctl"]
command: []
environment:
DATABASE_URL_FILE: /run/secrets/database_url
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
secrets: [database_url]
depends_on:
postgres:
condition: service_healthy
restart: "no"
networks: [data]
deploy:
resources:
limits: {cpus: "0.5", memory: 128m}
networks:
edge:
data:
internal: true # no route outside: stores talk only to api/migrate
internal: true # no route outside: stores talk only to the services above
storage:
internal: true # S3 API reachable only by api, s3-init, reconciler
internal: true # S3 API reachable only by api, s3-init, worker, auditor
queue:
internal: true # broker reachable only by relay and worker
volumes:
pgdata:
valkeydata:
s3data:
rabbitmqdata:
secrets:
postgres_password:
@@ -332,7 +505,17 @@ secrets:
file: ./secrets/s3_api_access_key_id
s3_api_secret_access_key:
file: ./secrets/s3_api_secret_access_key
s3_reconciler_access_key_id:
file: ./secrets/s3_reconciler_access_key_id
s3_reconciler_secret_access_key:
file: ./secrets/s3_reconciler_secret_access_key
s3_worker_access_key_id:
file: ./secrets/s3_worker_access_key_id
s3_worker_secret_access_key:
file: ./secrets/s3_worker_secret_access_key
s3_auditor_access_key_id:
file: ./secrets/s3_auditor_access_key_id
s3_auditor_secret_access_key:
file: ./secrets/s3_auditor_secret_access_key
rabbitmq_users:
file: ./secrets/rabbitmq_users.json
broker_url_relay:
file: ./secrets/broker_url_relay
broker_url_worker:
file: ./secrets/broker_url_worker
+57
View File
@@ -0,0 +1,57 @@
# Модель данных lab5
Схема: [0001_init.sql](../migrations/0001_init.sql) (lab2), [0002_idempotency_keys.sql](../migrations/0002_idempotency_keys.sql) и [0003_post_message_function.sql](../migrations/0003_post_message_function.sql) (lab3), [0004_attachments.sql](../migrations/0004_attachments.sql) (lab4), [0005_pipeline.sql](../migrations/0005_pipeline.sql) (lab5: задания, outbox, попытки, варианты). Миграции применяет один раз отдельный сервис `migrate` до старта реплик API; миграции lab3–lab5 только добавляют объекты (0004 ослабляет `CHECK` длины текста, 0005 — `CHECK` статуса и ключа объекта), поэтому совместимы с работающей предыдущей версией. Байты вложений живут **только** в двух приватных bucket S3 (SeaweedFS): `messenger-staging` (оригинал до обработки) и `messenger-attachments` (опубликованный оригинал и варианты); в PostgreSQL — метаданные, задания и их история. Порядок записи и окна отказа — [PIPELINE.md](PIPELINE.md). Источник истины для пользователей, чатов, участников и сообщений — PostgreSQL 18. Для сессий источник истины — хранилище, выбранное через `SESSION_STORE`. По умолчанию это Valkey с AOF, его можно переключить на таблицу `sessions` в PostgreSQL.
## Таблицы и ограничения
| Таблица | Ключ | Ограничения | Зачем |
| --- | --- | --- | --- |
| `users` | `id uuid` | `UNIQUE (username)`, `CHECK` формата username, длина `display_name` | уникальность имени держит БД, а не код: гонку регистрации разрешает уникальный индекс |
| `chats` | `id uuid` | FK `created_by → users`, длина `title` | `last_message_at` — «часы» чата для упорядочивания сообщений |
| `chat_members` | `(chat_id, user_id)` | FK на `chats` и `users`, `UNIQUE (chat_id, position)` | `position` хранит порядок `member_ids`; `chat_created_at` — копия времени чата для keyset-списка чатов |
| `messages` | `id uuid` | FK `(chat_id, sender_id) → chat_members`, длина `text` | отправитель обязан быть участником — это гарантирует сама БД |
| `sessions` | `token_hash bytea` | FK `user_id → users`, длина хеша 32 байта | хранится SHA-256 токена; сам токен не хранится нигде |
| `idempotency_keys` | `(user_id, chat_id, key)` | FK на `users`, `chats`; `message_id → messages` (DEFERRABLE, `UNIQUE`); `CHECK` формата ключа и длины SHA-256 | общая для всех реплик идемпотентность отправки: ключ → отпечаток тела → сообщение. Хранится ≥ `IDEMPOTENCY_TTL_SECONDS` (24 ч), очистка — пачками раз в 10 мин под advisory-замком |
| `attachments` (lab4, lab5) | `id uuid` | FK `(chat_id, owner_id) → chat_members`; `UNIQUE object_key`, `UNIQUE staging_key` (`COLLATE "C"`); `CHECK` статуса `pending/queued/processing/ready/failed`, формата ключей, типа, размера, пикселей ≤ 40 млн; **`attachments_active_has_source`**: у `queued/processing` есть опубликованный оригинал или staging `present`; `ready` ⇒ `object_key` и `published_version`; `failed` ⇔ `error_code` + `failed_at` | метаданные оригинала. `staging_key` (`s/<128 бит>`) — копия в staging, `staging_state none/present/deleting/deleted`; `object_key` — опубликованный оригинал (`a/<id>/<token>/original`, у строк lab4 — `o/<hex>`). `published_version` — версия pipeline, чьи варианты видны, только растёт |
| `jobs` (lab5) | `id uuid` = job_id | FK на `attachments`; `CHECK` состояния, вида (`upload/replay/reprocess/migrate`), `attempt ≤ max_attempts`, lease есть ⇔ `processing`, `finished_at` ⇔ конечное; частичный `UNIQUE (attachment_id, pipeline_version) WHERE state IN ('queued','processing')` | одна логическая работа «версия V для вложения A». `available_at` — backoff, `lease_token`/`lease_until`/`lease_owner` — аренда текущей попытки (fencing). Индексы: истекающие lease, queued, failed |
| `job_attempts` (lab5) | `token uuid` | FK на `jobs`; `UNIQUE (job_id, attempt)`; `CHECK` исхода `running/succeeded/retry/failed/abandoned/superseded`; опубликованную попытку нельзя «почистить» | один claim worker. `planned_keys` — ключи всех объектов попытки, записаны ДО записи в S3: уборке не нужен List. Частичный индекс — кандидаты на уборку |
| `attachment_variants` (lab5) | `(attachment_id, pipeline_version, name)` | FK на `attachments`, `job_attempts`; `UNIQUE object_key`, `CHECK` имени, типа, размера, длины SHA-256 | опубликованные варианты; первичный ключ — ключ эффекта контракта, дубль физически невозможен |
| `outbox` (lab5) | `id bigint` identity | FK на `jobs`; `attempt ≥ 1` | намерение опубликовать сообщение; пишется в одной транзакции с изменением задания. Частичный индекс `WHERE published_at IS NULL` — работа relay |
| `job_events` (lab5) | `id bigint` identity | FK на `jobs` | аудит: создание, claim, retry с задержкой, lease_expired, replay/reprocess (оператор и причина), результат, внедрённые отказы. Без секретов и имён файлов. View `failed_jobs` — реестр failed |
| `message_attachments` (lab4) | `(message_id, position)` | FK на `messages` и `attachments`, `UNIQUE (message_id, attachment_id)`, индекс по `attachment_id` | целостность ссылок (вложение, на которое ссылается сообщение, удалить нельзя) и обратный поиск «используется ли вложение» |
| `schema_migrations` | `version` | checksum файла | какие миграции применены; изменённую задним числом миграцию мигратор не применит |
**Почему `bytea` для текста.** Контракт разрешает символ U+0000, а тип `text` в PostgreSQL не может содержать байт NUL (`DataError`). Поэтому `display_name`, `title` и `text` хранятся как байты UTF-8. Длину в code points проверяет API, а `CHECK` в байтах — страховка (1 code point ≤ 4 байта).
## Индексы и запросы
- `messages_chat_keyset (chat_id, created_at, id)`. Первая страница — `WHERE chat_id=$1 ORDER BY created_at, id LIMIT n`, следующая — `WHERE chat_id=$1 AND (created_at, id) > ($2, $3) ORDER BY ... LIMIT n`. Сравнение строк `(created_at, id) > (...)` попадает в `Index Cond`: поиск начинается прямо с позиции cursor и читает только `n+1` строк. Запросов два, а не один с `($2 IS NULL OR ...)`: иначе при generic plan условие cursor уходит в `Filter`, и поздняя страница сканирует всю историю чата до неё.
- `chat_members_user_keyset (user_id, chat_created_at, chat_id)` — список чатов пользователя тем же keyset-способом.
- `users_username_key` — вход по username и уникальность.
- `sessions_expires_at` — очистка истёкших сессий.
## Транзакционные границы
| Операция | Транзакция | Что гарантирует |
| --- | --- | --- |
| Регистрация | один `INSERT` | `UniqueViolation` → 409; ровно одна строка при гонке |
| Создание чата | `INSERT chats` → `INSERT chat_members` (все участники одним запросом) → `COMMIT` | неизвестный участник вызывает FK-ошибку **после** вставки чата; откат удаляет и чат, и частичное членство |
| Сообщение (lab3, с ключом) | проверка членства → `INSERT idempotency_keys … ON CONFLICT DO UPDATE … WHERE ключ старше 24 ч` → если вставлен: `UPDATE chats … RETURNING` → `INSERT messages`; если нет: прочитать сохранённое сообщение и сравнить отпечаток → `COMMIT`. По умолчанию всё это — одна SQL-функция `post_message` в autocommit (одно обращение к БД) | ключ, сообщение и «результат» коммитятся вместе или не коммитятся вовсе: «висящего» ключа нет. Конкурентный повтор ждёт на уникальном индексе завершения первой транзакции и затем видит её результат (READ COMMITTED, новый снимок на каждый оператор). Другое тело → 409, тот же — тот же Message |
| Сообщение с `attachment_ids` (lab4, lab5) | функция `post_message_v3` (0005): проверка членства → проверка вложений (этого чата, не `pending`; `failed`/карантин → 409; `FOR SHARE`) → только если всё хорошо — захват ключа → `UPDATE chats` → `INSERT messages (…, attachment_ids)` → `INSERT message_attachments` | чужое/неизвестное/незавершённое вложение — 404, в карантине — 409, ключ при этом не «сгорает». Порядок `attachment_ids` хранится массивом в строке сообщения: страница истории остаётся одним диапазонным сканом индекса |
| Загрузка вложения (lab5) | `INSERT attachments … 'pending'` (autocommit) → S3 PUT в staging (Content-MD5) → **одна транзакция**: `UPDATE … SET status='queued' WHERE status='pending'` + `INSERT jobs` + `INSERT outbox` + `INSERT job_events` → 202 | 202 только когда оригинал в staging и задание с outbox зафиксированы. Сбой до COMMIT оставляет невидимый `pending`, его убирает janitor. Компенсации в обработчике нет |
| Claim (worker) | `SELECT jobs … FOR UPDATE` → решение (no-op / superseded / работа) → `SELECT attachments … FOR UPDATE` → `UPDATE jobs` (processing, attempt+1, lease, token) + `INSERT job_attempts` + `UPDATE attachments` (processing) + событие | дубль доставки видит конечное состояние или чужой lease и ничего не делает |
| Результат (worker) | `SELECT jobs … FOR UPDATE` (проверка токена) → `SELECT attachments … FOR UPDATE` → если версия не новее опубликованной: `superseded`; иначе `INSERT attachment_variants` ×3 + `UPDATE attachments` (ready, published_version, object_key) + `UPDATE jobs/job_attempts` + событие → потом ack | результат публикуется атомарно и только владельцем текущей аренды; версия только растёт |
| Retry / failed (worker), lease (relay) | под блокировкой задания: попытка `retry`/`failed`/`abandoned`; задание `queued` с `available_at` + новая строка outbox, или `failed` (реестр) | повтор идёт тем же путём outbox; бесконечного немого retry нет |
| Replay / reprocess (jobctl), уборка staging | `SELECT attachments … FOR UPDATE` (одна и та же блокировка) → проверки → новое задание + outbox, либо `staging_state='deleting'` | уборка и replay сериализованы строкой вложения |
| Порядок блокировок | везде, где нужны обе строки: сначала `jobs`, потом `attachments` | нет взаимных ожиданий в разном порядке |
| Сообщение (lab2-часть) | проверка членства → `UPDATE chats SET last_message_at = greatest(clock_timestamp(), last_message_at + 1 мкс) RETURNING` → `INSERT messages` → `COMMIT` | строка чата заблокирована до конца транзакции, поэтому писатели одного чата идут по очереди. Время сообщений строго растёт **в порядке коммитов**: страница по cursor не пропустит сообщение, закоммиченное «задним числом» |
| Вход | `SELECT` пользователя, проверка Argon2id, запись сессии | неверный пароль ничего не пишет |
| Logout | `DELETE` сессии (или `DEL` в Valkey) | повтор с тем же токеном — 401 |
Чтение истории не требует snapshot между HTTP-запросами (так в контракте): новое сообщение появится на следующей странице. Список чатов сортируется по `chats.created_at = clock_timestamp()` без блокировки. Два чата, создаваемые одновременно, могут закоммититься не в порядке времени. Тогда у обхода, который уже начался, такой чат может оказаться «до» cursor; новый обход его увидит. Чаты создаются редко, поэтому мы не сериализуем их глобальным замком; это ограничение описано в REPORT.md.
## Сессии
- Токен: `secrets.token_urlsafe(32)` — 256 бит случайности, в ответе 43 символа. В хранилище лежит только SHA-256 токена. Для случайного 256-битного значения быстрого хеша достаточно, медленный KDF нужен только для низкоэнтропийных паролей.
- `SESSION_STORE=valkey` (по умолчанию): ключ `session:<sha256-hex>`, значение `{user_id, expires_at}`. Срок жизни задаётся абсолютным `PXAT expires_at`, поэтому рестарт его не продлевает. Включён `appendonly yes` + `appendfsync always`: подтверждённые вход и logout сохраняются до ответа клиенту. Valkey — **единственное** хранилище сессий, это не кэш над PostgreSQL. Поэтому нет второй копии, которая могла бы «оживить» отозванный токен после отказа. Если Valkey недоступен, проверить сессию нельзя: защищённые запросы и logout получают 503, анонимный доступ не открывается.
- `SESSION_STORE=postgres`: таблица `sessions`, проверка `expires_at > now()` в запросе.
+48
View File
@@ -0,0 +1,48 @@
# Ответы на вопросы защиты ЛР 5
Подробности и схемы: [PIPELINE.md](PIPELINE.md). Тесты: [test_pipeline_flow.py](../student-tests/test_pipeline_flow.py), [test_consistency.py](../student-tests/test_consistency.py), трек 2: [bench/pipeline_faults.py](../bench/pipeline_faults.py).
## Чем publisher confirm отличается от consumer ack?
- **Publisher confirm** — ответ брокера **отправителю** (у нас relay): «сообщение принято и записано в quorum-очередь на диск». Без confirm relay не знает, дошло ли сообщение, поэтому строку outbox он помечает `published_at` только после confirm. `mandatory=True`: если сообщение некуда положить, брокер вернёт его, и это будет ошибка, а не тихая потеря.
- **Consumer ack** — ответ **потребителя** (worker) брокеру: «можно удалить сообщение, работа сделана». Worker шлёт ack только после COMMIT результата в PostgreSQL. Если упасть до ack, брокер отдаст сообщение снова.
- Это две разные границы. Confirm говорит «намерение надёжно лежит в очереди», ack — «эффект надёжно сохранён». Между ними могут пройти часы (worker остановлен), и сообщение всё это время лежит в quorum log на volume `rabbitmqdata`. Тест: worker остановлен → upload 202 → relay публикует (confirm) → рестарт брокера → сообщение на месте → worker стартует → ack после ready.
## Что именно уже сохранено в момент 202?
1. **Оригинал** — полностью и уже проверенный (лимиты, PNG/JPEG-валидаторы, 413/415 решаются до записи), в приватном bucket `messenger-staging`. S3 подтвердил PUT с Content-MD5.
2. **Метаданные + задание + строка outbox** — одной транзакцией PostgreSQL: вложение `queued`, `jobs` (`queued`, attempt 0), `outbox`.
Чего ещё нет: варианта, опубликованного оригинала, сообщения в брокере (его отправит relay). После 202 можно убить API — ничего не пропадёт. Если брокер лежит, upload всё равно 202: API с брокером вообще не связан. Сбой **до** COMMIT задания (окно «после staging») 202 не даёт: клиент получает 503, строка `pending` невидима, janitor убирает staging и строку (test_consistency).
## Почему повторная доставка нормальна и где ключ идемпотентности job?
- Гарантия at-least-once неизбежна: relay может упасть после confirm, но до отметки в outbox; worker может упасть после COMMIT, но до ack; соединение рвётся. Сообщение придёт ещё раз — это не ошибка, а цена того, что мы его не теряем.
- **Ключ идемпотентности задания — `jobs.id` (job_id) в PostgreSQL.** Каждая доставка начинается с `claim` под `SELECT … FOR UPDATE` строки задания: `succeeded` → ack без работы; `processing` с живым lease → ack (его судьбу решит reaper); backoff не истёк → ack. Попадание в работу возможно только из `queued`.
- **Ключ эффекта — `(attachment_id, pipeline_version, variant)`**: первичный ключ `attachment_variants`. Объекты пишутся под ключами своей попытки (`a/<id>/<token>/thumbnail`); опубликовано ровно то, на что ссылается один COMMIT. Дубль не создаёт второго набора, а мусор прерванных попыток удаляет уборка.
- Это не exactly-once доставка: работа может выполниться дважды (зависший worker досчитает). Exactly-once только у видимого результата.
## Как отличить зависший worker от долго работающего и не запустить два неконтролируемых дубля?
- **Lease с heartbeat.** Claim даёт попытке `lease_until = now + 30 s` и случайный `lease_token`. Живой worker продлевает lease каждые 10 с (`UPDATE … WHERE lease_token = мой`). Долго работающий продлевает, зависший — нет.
- **Потолок времени.** Даже живой heartbeat не продлевает lease дольше `JOB_TIMEOUT_SECONDS` (60 с); дочерний процесс с Pillow в этот момент убивается.
- **Reaper** (в relay, раз в 5 с) возвращает задания с истёкшим lease в `queued` через outbox. Попытка помечается `abandoned`, токен обнуляется.
- **Fencing токеном.** Второй исполнитель может появиться, но опубликовать результат может только владелец текущего токена: COMMIT результата, retry, heartbeat — все с условием `lease_token = мой`. Старая попытка, если оживёт, получит `fenced` и ничего не изменит; её объекты лежат под её токеном, их удалит уборка.
- **Сторона брокера.** AMQP heartbeat 10 с: соединение замороженного клиента закрывается, его неподтверждённые сообщения возвращаются в очередь. `consumer_timeout` 5 мин — для подключённого, но не отвечающего ack.
- Тест: два worker, `docker pause` того, кто держит lease → reaper → второй worker публикует → `unpause` → опубликованный результат не меняется, попытки `[abandoned, succeeded]`.
## Частые уточняющие вопросы
**Почему RabbitMQ, а не Valkey Streams?** Термины README (confirm, ack, prefetch, DLX) — это его родные механизмы; quorum queue пишет на диск до confirm. Брокер отделён от хранилища сессий, отказ одного не задевает другое. Retry, lease и реестр failed всё равно в PostgreSQL, поэтому сложной логики брокера (TTL-очередей) нет.
**Зачем outbox, а не «COMMIT, потом publish в API»?** Между COMMIT и publish процесс может умереть — задание есть, сообщения нет. Outbox пишется в той же транзакции, relay дошлёт. Проверено остановкой брокера и relay.
**Почему staging в отдельном bucket?** У ключей разные права: API может только **писать** в staging и **читать** конечный bucket; worker читает/пишет оба; никто, кроме auditor, не может List. Это проверяет `s3-init` при каждом старте (`api: read staging → refused`, `api: write final → refused`).
**Может ли уборка удалить исходник принятой работы?** Нет, и на трёх уровнях: (1) кандидаты — только `ready` или `failed` старше retention; (2) решение повторяется под блокировкой строки в момент пометки `deleting`, которую берёт и replay; (3) CHECK `attachments_active_has_source` в БД запрещает `queued/processing` без источника. Тесты: retention 0 при `queued` (relay остановлен) — staging цел, а ручной UPDATE отвергнут БД; гонка «уборка прочитала кандидатов → replay → уборка продолжила» воспроизведена паузой `pause_cleanup`.
**Replay = повтор задания?** Нет. `jobctl replay` разрешён только для `failed` с живым источником. Он создаёт **новое** задание `replay_of=<старое>` и пишет оператора и причину в аудит. Для `ready` — отказ `already_ready`, ничего не создаётся.
**Чем постоянная ошибка отличается от временной?** Постоянная не исправится повтором с тем же входом: `invalid_image`, `image_too_large`, `source_missing`, `source_corrupt` → сразу `failed`. Временная — S3/БД недоступны, таймаут, процесс убит → повтор с backoff (full jitter), не более 5 claim-ов, затем `retry_exhausted`.
**Почему 415 в API, а не в worker?** Контракт требует 415 на upload. Преподаватель ловил «202 → failed/invalid_image» в чужих PR. Проверки lab4 (свой PNG-валидатор с проверкой фильтра строк и zlib-потока, `djpeg -strict`) остались синхронными; тесты включают все случаи из рецензий.
+128
View File
@@ -0,0 +1,128 @@
# Pipeline обработки вложений (lab5)
Схема: [migrations/0005_pipeline.sql](../migrations/0005_pipeline.sql). Код: API — [attachments.py](../src/messenger/attachments.py), переходы заданий — [jobs.py](../src/messenger/jobs.py), relay — [relay.py](../src/messenger/relay.py), worker — [worker.py](../src/messenger/worker.py), картинки — [imaging.py](../src/messenger/imaging.py), версии — [pipeline.py](../src/messenger/pipeline.py), оператор — [jobctl.py](../src/messenger/jobctl.py), аудит — [audit.py](../src/messenger/audit.py).
## Кто что делает
```text
клиент ──POST──▶ LB ──▶ API ──(1) INSERT attachments 'pending' ──▶ PostgreSQL
│ (2) PUT оригинал в messenger-staging ──▶ S3 (staging)
│ (3) ОДНА транзакция: 'queued' + jobs + outbox ──▶ PostgreSQL
└─ 202 queued
relay: outbox ─(4) publish + publisher confirm─▶ RabbitMQ (quorum queue) ─(5) deliver─▶ worker
worker: (6) claim: lease + token попытки ─▶ (7) читает источник, сверяет SHA-256 ─▶ (8) варианты
в дочернем процессе ─▶ (9) PUT a/<id>/<token>/* в messenger-attachments ─▶
(10) ОДНА транзакция: варианты + attachment 'ready' (с проверкой токена) ─▶ (11) ack ─▶
(12) staging 'deleting' → S3 DELETE → 'deleted'
```
- **Источник истины — PostgreSQL**: состояние задания, попытки, lease, время следующей попытки (`available_at`), реестр failed, аудит (`job_events`). Брокер только доставляет `job_id`.
- **API не знает брокер** (нет даже сети `queue`). Брокер упал — upload всё равно 202, задания копятся в outbox.
- В сообщении только поля [jobs.schema.json](../contracts/jobs.schema.json): `schema_version, job_id, type, attachment_id, pipeline_version, attempt, created_at`. Никаких байтов, URL, ключей S3, имени файла. Worker берёт `content_type`, размер, SHA-256 и ключ источника из БД.
## Что сохранено в момент 202
1. Полный, **проверенный** оригинал лежит в приватном bucket `messenger-staging`: S3 подтвердил PUT и Content-MD5. Проверки 413/415 делаются до этого, синхронно, теми же валидаторами, что в lab4 (PNG — свой потоковый, JPEG — `djpeg -strict`).
2. Строка `attachments` в статусе `queued`, строка `jobs` (`queued`, attempt 0) и строка `outbox` — **в одной транзакции**, закоммичены (fsync PostgreSQL).
Значит, после 202 можно убить API, relay, broker и worker: работа восстановится из этих двух записей. Честная граница: staging — это уже S3, а не «временная папка». На одном Docker-хосте «устойчиво» значит «переживает рестарт процессов и контейнеров с volumes», а не потерю диска.
## Состояния
Вложение (`attachments.status`):
| Статус | Видно клиенту | Как попадает | Как выходит |
| --- | --- | --- | --- |
| `pending` | нет (404) | INSERT до PUT в staging | → `queued` (COMMIT задания) или удаляется janitor через `PENDING_GRACE_SECONDS` |
| `queued` | да, content 409 | COMMIT задания; retry; истёк lease; replay | → `processing` при claim |
| `processing` | да, content 409 | claim worker | → `ready` / `queued` (retry, lease) / `failed` |
| `ready` | да, варианты | COMMIT результата | никогда не возвращается назад. Reprocess новой версии не меняет статус |
| `failed` | да, `error_code`, content 409 | постоянная ошибка или попытки кончились | → `queued` только через `jobctl replay` |
Задание (`jobs.state`): `queued → processing → succeeded | failed | superseded`, `processing → queued` (retry, lease, graceful stop). `superseded` — старая версия pipeline, когда опубликована более новая.
Ограничения в самой БД (CHECK) не дают коду ошибиться:
- `attachments_active_has_source`: у `queued/processing` есть источник — опубликованный оригинал или staging в состоянии `present`. **Уборка физически не может пометить staging принятой работы**;
- `jobs_lease`: lease есть ровно тогда, когда `processing`;
- `jobs_one_active`: одно активное задание на `(attachment, pipeline_version)`;
- PK `attachment_variants (attachment_id, pipeline_version, name)` — ключ эффекта из контракта.
## Окна отказа (contracts/attachment-states.md)
| Окно | Что остаётся | Кто восстанавливает | Проверка |
| --- | --- | --- | --- |
| после staging, до записи задания | `pending` + объект staging, задания нет, 503 клиенту | janitor API: объект, потом строка (после grace) | `API_FAULT_POINTS=after_s3_put`, test_consistency |
| после COMMIT, до publish | строка outbox без `published_at` | relay при следующем проходе; никто не создаёт задание вручную | broker/relay остановлены, test_pipeline_flow |
| после publish, до записи confirm | сообщение в очереди + неотмеченная строка outbox | relay публикует ещё раз → дубль → no-op | `RELAY_FAULT_POINTS=crash_after_publish` |
| после записи S3, до COMMIT результата | объекты под ключами попытки 1, не опубликованы | lease истекает → reaper → попытка 2 со своими ключами; уборка удаляет ключи попытки 1 | `WORKER_FAULT_POINTS=crash_after_s3_write` |
| после COMMIT результата, до ack | `ready` | redelivery → claim видит `succeeded` → ack без работы | `WORKER_FAULT_POINTS=crash_after_commit` |
| worker умер/завис в processing | lease без продления | reaper (в relay, раз в 5 с) → `queued` + outbox; commit старой попытки отвергается токеном | `crash_after_claim`, `docker pause` |
## Publisher confirm ≠ consumer ack
- **Publisher confirm** (relay ← broker): «брокер принял сообщение и записал его в quorum log». Это граница «намерение передано в очередь»; после неё relay ставит `published_at`.
- **Consumer ack** (worker → broker): «результат работы устойчиво зафиксирован». Worker шлёт ack только **после COMMIT** результата (или после COMMIT решения «retry/failed/no-op»).
- Между ними может пройти сколько угодно времени и случиться любой сбой. Confirm без ack = сообщение ждёт в очереди; потеря ack = повторная доставка.
## Идемпотентность и повторная доставка
Доставка at-least-once: дубль может появиться из relay (crash до отметки), из брокера (нет ack из-за падения worker, разрыв соединения, consumer_timeout), от оператора. Поэтому каждая доставка начинается с `claim` под блокировкой строки `jobs`:
| Состояние задания | Решение | ack |
| --- | --- | --- |
| `succeeded/failed/superseded` | no-op (`noop_finished`) | да |
| `processing` (lease держит другой) | no-op (`noop_leased`), его смерть обработает reaper | да |
| `queued`, `available_at` в будущем | no-op (`noop_not_due`), outbox опубликует вовремя | да |
| `queued`, опубликована версия ≥ своей | `superseded` | да |
| `queued`, пора | claim: attempt+1, новый `lease_token`, строка `job_attempts` с заранее известными ключами | после результата |
Ключ идемпотентности задания — `job_id` (строка в БД), ключ эффекта — `(attachment_id, pipeline_version, variant)`. Объекты пишутся под ключами `a/<attachment>/<token>/<name>`: у каждой попытки свои. Опубликовано ровно то, на что ссылается COMMIT результата. **Fencing**: COMMIT проходит, только если `jobs.lease_token` всё ещё равен токену попытки. Reaper обнуляет токен, поэтому «проснувшаяся» старая попытка ничего не опубликует.
Это не exactly-once **доставка**. Сообщение может прийти несколько раз, а работа выполниться дважды (например, зависший worker досчитает варианты). Exactly-once — только **видимый эффект**: одна опубликованная запись на ключ эффекта, монотонная версия, мусор попыток убирается.
## Зависший vs долго работающий worker
- Долго работающий продлевает lease каждые `JOB_LEASE_SECONDS/3` (heartbeat в БД, `WHERE lease_token = мой`).
- Зависший (`docker pause`, deadlock, потеря сети к БД) не продлевает; через `JOB_LEASE_SECONDS` reaper возвращает задание.
- Worker, у которого жив heartbeat, но зависла обработка, ограничен `JOB_TIMEOUT_SECONDS`: дочерний процесс убивается, heartbeat перестаёт продлевать lease после этого срока.
- Если heartbeat узнал, что lease потерян, попытка отменяется сама. Даже если не отменилась — её COMMIT отвергнет fencing.
- Брокер со своей стороны: AMQP heartbeat 10 с закрывает соединение замороженного клиента и возвращает его неподтверждённые сообщения; `consumer_timeout` 5 мин — для подключённого, но не отвечающего ack.
## Retry, failed, replay
- `JOB_MAX_ATTEMPTS=5` claim-ов на задание. Backoff — full jitter: `uniform(0, min(JOB_RETRY_MAX_SECONDS, JOB_RETRY_BASE_SECONDS·2^(n−1)))`. Задержка хранится в `jobs.available_at` и строке outbox — повтор проходит тем же путём outbox → broker, без TTL-очередей.
- Постоянные ошибки (сразу `failed`): `invalid_image`, `image_too_large`, `source_missing`, `source_corrupt`. Временные: `storage_unavailable`, `processing_timeout`, `processing_killed`, `processing_failed`. Когда попытки кончились — `retry_exhausted`.
- Реестр failed — view `failed_jobs` (`jobctl list-failed`). DLQ RabbitMQ (`messenger.attachment-jobs.dlq`) — для «ядовитых» сообщений: не по схеме или превысили `x-delivery-limit=20`.
- Страховка от потерянного сообщения: `queued`-задание без claim и без публикаций дольше `QUEUED_REPUBLISH_SECONDS` получает новую строку outbox.
- `jobctl replay <id>`: только для `failed` с живым источником, создаёт **новое** задание `kind=replay, replay_of=<failed>`, пишет оператора и причину в `job_events`. Для `ready` — отказ `already_ready`, ничего не создаётся.
## Уборка (worker), всегда под блокировкой строки
- staging `ready` — сразу после COMMIT результата; staging `failed` — через `STAGING_RETENTION_SECONDS`. Порядок: под `UPDATE … WHERE <условие заново>` пометить `deleting` → S3 DELETE → `deleted`. Replay берёт ту же блокировку: либо replay первым (строка уже `queued`, уборка её пропустит), либо уборка первой (replay видит `deleting` и отказывает `source_missing`).
- Объекты попыток, которые не опубликовали результат (`retry/failed/abandoned/superseded`): удаляются по `planned_keys` через `ORPHAN_GRACE_SECONDS`. Перед этим проверяется, что токен не текущий и ни один ключ не опубликован. Новые результаты (replay, другая попытка) лежат под другими ключами — устаревший проход не может их удалить.
- `pending` без задания — janitor API (как в lab4).
- Опубликованные варианты старых версий pipeline сохраняются (ограничение, см. REPORT).
## Версии pipeline (трек 2)
Версия фиксируется в задании при создании (`PIPELINE_VERSION` для upload, `jobctl reprocess --pipeline N` для готового вложения). Версии 1/2/3 отличаются параметрами кодеков, геометрия — по контракту. Публикация: только если `N > published_version`; иначе `superseded`. Reprocess неготового вложения запрещён: его единственный источник — staging текущего задания.
## Лимиты worker
| Что | Чем |
| --- | --- |
| параллельность | prefetch = `WORKER_CONCURRENCY` (2) + семафор на дочерние процессы |
| bytes | размер из БД ≤ `MAX_UPLOAD_BYTES` проверяется до скачивания; длина и SHA-256 скачанного = БД |
| пиксели | `width×height` из заголовка ≤ `MAX_IMAGE_PIXELS` до декодирования; JPEG декодируется с DCT-масштабом (`draft`) |
| память | `RLIMIT_AS = IMAGE_MAX_MEMORY_MB` (768) у дочернего процесса; контейнер 1536m без swap |
| время | `JOB_TIMEOUT_SECONDS` (60): дочерний процесс убивается, lease перестаёт продлеваться |
## Варианты
| Вариант | Формат | Геометрия | Параметры v1 |
| --- | --- | --- | --- |
| thumbnail | JPEG baseline 4:2:0 | вписан в 256×256, без увеличения, округление вниз, ≥1 px | q=85, optimize |
| crop | JPEG | центральный квадрат → 128×128 (маленькие увеличиваются) | q=85 |
| optimized | WebP lossy | вписан в 1280×1280, без увеличения, alpha сохраняется | q=80, method=4 |
EXIF orientation применяется к пикселям; в варианты не копируются EXIF, XMP, ICC, комментарии. Пиксели считаются sRGB. Alpha при ресайзе — premultiplied (без цветных ореолов), для JPEG композится на белый. 16-битный серый масштабируется (`/257`), а не обрезается. Оригинал публикуется побайтно без изменений. Уменьшение размера маленьких файлов не обещается.
+33
View File
@@ -0,0 +1,33 @@
## Лабораторная 5
Автор / группа: Боданюк Алексей, БВТ2302
Целевая оценка (3/4/5): 5
Трек 5, если заявлен: трек 2 «Доказанная идемпотентность pipeline» (versioned pipeline + автоматический fault injection)
Что реализовано и что перенесено: реализация lab4 перенесена отдельным коммитом без изменений (`5112be8`). Добавлено:
- upload 201 → 202: оригинал в приватном staging-bucket + одна транзакция `queued` + задание + outbox;
- RabbitMQ 4.3.7 (quorum queue, publisher confirms, DLX/DLQ, пользователи с минимальными правами, без management UI);
- relay (transactional outbox, reaper истёкших lease);
- отдельный worker: lease с heartbeat и fencing по токену попытки, варианты thumbnail/crop/WebP в дочернем процессе с лимитами памяти, времени и пикселей, ack только после COMMIT;
- retry с full jitter, реестр failed и `jobctl replay/reprocess`;
- уборка staging и мусора попыток под блокировкой строки;
- read-only аудит инвариантов.
Reconciler lab4 убран, причина — в REPORT. Подробно — REPORT.md, docs/PIPELINE.md, docs/DEFENSE.md.
Команды запуска из чистого clone: REPORT.md → «Запуск из чистого clone»: `python3 scripts/init_secrets.py`, `cp .env.example .env`, `docker compose --env-file .env up -d --build --wait`. Windows — docs/WINDOWS.md.
Результаты проверок и ссылка на REPORT.md: REPORT.md → «Доказательства критериев»; вывод прогона из чистого clone — в evidence/: make check/validate/test, persistence, failover, сценарий защиты, свои тесты, матрица трека 2, аудит.
Ограничения / известные ошибки: REPORT.md → «Ограничения и следующие шаги»: один Docker-хост, опубликованные варианты старых версий не удаляются, fsync SeaweedFS.
Источники и использование ИИ: REPORT.md, шапка. Код, тесты и отчёт написаны с помощью Claude Code; все прогоны реально выполнены.
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
- [x] Контракт и публичные тесты не ослаблены.
- [x] make check и make test выполнены; приложен реальный вывод.
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
+114
View File
@@ -0,0 +1,114 @@
# Запуск на ноутбуке с Windows и сценарий защиты ЛР 5
Команды — в **PowerShell** из папки проекта (где лежит `compose.yaml`). Переменные `$env:...` действуют до закрытия окна.
## 1. Что установить один раз
| Программа | Зачем | Важно |
| --- | --- | --- |
| [Git for Windows](https://git-scm.com/download/win) | clone и Git Bash | путь по умолчанию `C:\Program Files\Git`: оттуда `scripts\*.cmd` запускают `.sh`-хуки |
| [Docker Desktop](https://www.docker.com/products/docker-desktop/) | PostgreSQL, Valkey, SeaweedFS (S3), RabbitMQ, HAProxy, API, relay, worker | backend WSL 2; в Settings → Resources ≥ 4 CPU и ≥ 8 ГБ RAM (сумма лимитов контейнеров ~6,5 ГБ) |
| [Python 3.12+](https://www.python.org/downloads/windows/) | secrets, публичные и свои тесты, сценарии | галочка **Add python.exe to PATH** |
| GNU make (необязательно) | `make check/test/...` | `winget install ezwinports.make`, затем **новое** окно; в каждом окне `$env:Path += ";C:\Program Files\Git\usr\bin"` (рецептам нужен `sh`) |
## 2. Развернуть проект (заранее, нужен интернет)
```powershell
git clone https://gitea.privcloud.tech/wfa/mtusi2026lab5 mtusi2026lab5
cd mtusi2026lab5
git checkout solution/bvt2302-bodanyuk
python scripts\init_secrets.py # пароли БД/Valkey, 4 пары ключей S3, пользователи RabbitMQ -> .\secrets
Copy-Item .env.example .env
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build --wait
```
Первый запуск качает образы (~1,2 ГБ) и собирает образ приложения — 3–10 минут. Команда завершается, когда postgres, valkey, s3, broker, обе реплики api, lb, relay и worker в `healthy`, а `migrate` и `s3-init` вышли с кодом 0. Проверки прав S3: `docker compose logs s3-init`.
Окружение для своих тестов (один раз):
```powershell
python -m venv .venv
.venv\Scripts\python -m pip install --require-hashes --no-deps -r requirements.txt
.venv\Scripts\python -m pip install -r requirements-test.txt -r requirements-dev.txt
```
Стенды ЛР 3/4 занимают порт 8080 — остановить: `docker compose -p mtusi-lab4 stop` (данные сохранятся).
## 3. Перед защитой
```powershell
$env:PYTHONUTF8 = "1"; $env:Path += ";C:\Program Files\Git\usr\bin"
docker compose up -d --wait
make check test PYTHON=python # 202 -> ready, настоящий JPEG 256x160
make jobs # задания по состояниям, хвост outbox
```
## 4. Сценарий защиты README — по шагам
**Шаг 1. `make test`**: API возвращает 202, GET доходит до ready, оригинал и настоящий JPEG thumbnail проверяются (см. раздел 3).
**Шаги 2–3. Worker остановлен → 202 → content 409 → рестарт API и брокера с volumes → worker → ready.** Скрипт печатает каждый шаг, ID вложения и сообщения, код ответа; токены не печатает:
```powershell
.venv\Scripts\python scripts\demo_pipeline.py
```
Что он делает:
1. `docker compose stop worker`;
2. upload → **202 queued**; `GET /content` и `?variant=thumbnail` → **409**; обычное сообщение → 201; сообщение с этим вложением → 201;
3. показывает строку outbox (`published_at` заполнен — relay получил confirm) и глубину очереди `messenger.attachment-jobs` (1);
4. `docker compose restart api broker` (volumes не трогаются), ждёт готовности; очередь снова показывает 1, вложение по-прежнему `queued`;
5. `docker compose start worker` → **ready**, скачивает thumbnail (JPEG 256×160), сверяет SHA-256 и размеры;
6. печатает журнал задания (`jobctl show`): `created → claimed → succeeded`, одна попытка.
То же автоматически: `.venv\Scripts\python -m pytest student-tests\test_pipeline_flow.py -k worker_stopped -v`.
**Шаг 4. Уровень 4 вживую.**
```powershell
# crash после записи в S3 до ack/COMMIT; разрыв COMMIT/publish; publish/confirm:
.venv\Scripts\python -m pytest student-tests\test_pipeline_flow.py -k "crash or broker_down or relay" -v
# retry с backoff, retry_exhausted -> реестр failed -> replay; replay готового -> отказ:
.venv\Scripts\python -m pytest student-tests\test_pipeline_flow.py -k "retry or permanent" -v
make failed # реестр failed
docker compose run --rm --no-deps jobctl replay <attachment_id> --operator alice --reason "причина устранена"
docker compose run --rm --no-deps jobctl show <attachment_id> # задания, попытки, аудит
# зависший worker (docker pause) теряет lease, второй worker публикует, первый не может:
.venv\Scripts\python -m pytest student-tests\test_pipeline_flow.py -k hung -v -s
```
**Трек 2 вживую.**
```powershell
make audit # инварианты I1-I7 по всей БД и обоим bucket (read-only)
.venv\Scripts\python bench\pipeline_faults.py --output evidence\track2-demo --uploads 3 # ~15 мин
```
Готовые результаты: [evidence/track2/summary.txt](../evidence/track2/summary.txt).
**Публичные проверки сохранности и failover.**
```powershell
make test-persistence ACTION_SCRIPT=scripts/restart.cmd PYTHON=python # restart всего стенда с volumes
make test-failover ACTION_SCRIPT=scripts/stop-one.cmd PYTHON=python
make restore PYTHON=python
```
**Все свои тесты** (~40 мин): `.venv\Scripts\python -m pytest student-tests -v`.
## 5. Если что-то пошло не так
| Симптом | Что сделать |
| --- | --- |
| `error during connect … dockerDesktopLinuxEngine` | Docker Desktop не запущен — запустить и подождать минуту |
| `port is already allocated` на 8080/8404 | стенд lab3/lab4 (`docker compose -p mtusi-lab4 stop`) или в `.env` `APP_PUBLISH_PORT=8081`, `LB_STATS_PORT=8405` |
| `secrets/... not found` | не выполнен `python scripts\init_secrets.py` |
| `s3-init` exit 1 | `docker compose logs s3-init`: какая проверка доступа не прошла |
| broker долго `starting` | первый старт RabbitMQ ~20 с; `docker compose logs broker` |
| вложение висит в `queued` | `make jobs`: если `outbox_due > 0` — смотреть `docker compose logs relay`; если очередь не пуста — `docker compose logs worker` |
| `UnicodeDecodeError` в `tests\*.py` | не задан `$env:PYTHONUTF8 = "1"` |
| локальный `.env` устарел | сравнить с `.env.example`: значения `.env` перекрывают умолчания compose |
| начать с чистого листа | `docker compose down -v` (удаляет учебные данные: БД, bucket, очередь) → `up -d --build --wait` |
Остановить после защиты: `docker compose down` (данные сохранятся).
+392
View File
@@ -0,0 +1,392 @@
# Clean clone: secrets, config, build, migrations from zero, start, versions
# 2026-10-31T14:18:15Z, commit cf6e929 docs: PIPELINE, DEFENSE, DATA_MODEL, WINDOWS для lab5; черновик REPORT
$ git status --short --branch
## solution/bvt2302-bodanyuk...origin/solution/bvt2302-bodanyuk
[exit 0, 0.1 s]
$ C:\Users\wfa22\AppData\Local\Python\pythoncore-3.14-64\python.exe --version
Python 3.14.6
[exit 0, 0.0 s]
$ docker version --format client {{.Client.Version}} / server {{.Server.Version}}
client 29.8.0 / server 29.8.0
[exit 0, 0.1 s]
$ docker compose version
Docker Compose version v5.5.1
[exit 0, 0.1 s]
$ make --version
GNU Make 4.4.1
Built for Windows32
Copyright (C) 1988-2023 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
[exit 0, 0.0 s]
$ python scripts/init_secrets.py
created secrets/postgres_password
created secrets/valkey_password
created secrets/database_url
created secrets/cache_url
created secrets/s3_admin_access_key_id
created secrets/s3_admin_secret_access_key
created secrets/s3_api_access_key_id
created secrets/s3_api_secret_access_key
created secrets/s3_worker_access_key_id
created secrets/s3_worker_secret_access_key
created secrets/s3_auditor_access_key_id
created secrets/s3_auditor_secret_access_key
created secrets/rabbitmq_relay_password
created secrets/rabbitmq_worker_password
created secrets/rabbitmq_users.json
created secrets/broker_url_relay
created secrets/broker_url_worker
[exit 0, 0.1 s]
$ cp .env.example .env
$ docker compose --env-file .env config --quiet
[exit 0, 0.2 s]
$ docker compose --env-file .env up -d --build --wait
#1 [internal] load local bake definitions
#1 reading from stdin 1.32kB 0.0s done
#1 DONE 0.0s
#2 [migrate internal] load build definition from Dockerfile
#2 transferring dockerfile: 2.96kB done
#2 DONE 0.1s
#3 [migrate] resolve image config for docker-image://docker.io/docker/dockerfile:1
#3 DONE 6.2s
#4 [migrate] docker-image://docker.io/docker/dockerfile:1@sha256:4edf897a3ffa55b89f906fc8cc78afdb3f1834cc9c7083565e611a8a7d5fe99e
#4 resolve docker.io/docker/dockerfile:1@sha256:4edf897a3ffa55b89f906fc8cc78afdb3f1834cc9c7083565e611a8a7d5fe99e 0.0s done
#4 CACHED
#5 [api internal] load metadata for docker.io/library/python:3.13.16-slim-bookworm@sha256:a1165e272e578941b84abc79e4ab38a0305cd12803a5c4247979ac7655f4d641
#5 DONE 2.1s
#6 [migrate internal] load .dockerignore
#6 transferring context: 196B done
#6 DONE 0.1s
#7 [migrate 1/9] FROM docker.io/library/python:3.13.16-slim-bookworm@sha256:a1165e272e578941b84abc79e4ab38a0305cd12803a5c4247979ac7655f4d641
#7 resolve docker.io/library/python:3.13.16-slim-bookworm@sha256:a1165e272e578941b84abc79e4ab38a0305cd12803a5c4247979ac7655f4d641 0.1s done
#7 DONE 0.1s
#8 [api internal] load build context
#8 transferring context: 525.52kB 0.1s done
#8 transferring context: 525.52kB 0.1s done
#8 DONE 0.2s
#9 [api 2/9] WORKDIR /app
#9 CACHED
#10 [api 3/9] COPY requirements.txt ./
#10 CACHED
#11 [api 4/9] RUN pip install --root-user-action=ignore --require-hashes --no-deps -r requirements.txt
#11 CACHED
#12 [api 5/9] RUN apt-get update && apt-get install -y --no-install-recommends libjpeg-turbo-progs=1:2.1.5-2 && rm -rf /var/lib/apt/lists/*
#12 CACHED
#13 [api 6/9] RUN groupadd --system --gid 10001 app && useradd --system --uid 10001 --gid app --no-create-home --shell /usr/sbin/nologin app
#13 CACHED
#14 [api 7/9] COPY src/ ./src/
#14 DONE 0.1s
#15 [api 8/9] COPY migrations/ ./migrations/
#15 DONE 0.1s
#16 [migrate 9/9] COPY contracts/openapi.json ./contracts/openapi.json
#16 DONE 0.1s
#17 [api] exporting to image
#17 exporting layers
#17 exporting layers 0.3s done
#17 exporting manifest sha256:d5ce436c70dc889fae295b9c569550143a49023a8c8c276e83ec5b3e3e156d4d 0.0s done
#17 exporting config sha256:bd8b08e1de339150644db0527530d2ee10f7fdac39fb495916259bb92f8157ea 0.1s done
#17 exporting attestation manifest sha256:88b54cc6ae37ccc6d7bed5b2f499e6d2ad7b184c25c8f8da067db4010c4f341f 0.1s done
#17 exporting manifest list sha256:7689cb4ef3a9f3649524415f9528e0c84610759d6536e522dc5ea0d4305e3878
#17 exporting manifest list sha256:7689cb4ef3a9f3649524415f9528e0c84610759d6536e522dc5ea0d4305e3878 0.0s done
#17 naming to docker.io/library/mtusi-messenger:lab5 0.0s done
#17 unpacking to docker.io/library/mtusi-messenger:lab5
#17 unpacking to docker.io/library/mtusi-messenger:lab5 0.2s done
#17 DONE 0.8s
#18 [migrate] exporting to image
#18 exporting layers 0.3s done
#18 exporting manifest sha256:9b9171737d004d0514b7adf53f37158be51e19440ab86d15192ef7d71bcf1ec0 0.1s done
#18 exporting config sha256:2b03ff83f38876a18738b5fcf9676e1c840ca6162cdee4dd6252e1cab242448e 0.1s done
#18 exporting attestation manifest sha256:b62c3a0d59a966c45c4de062852cb7c68895fe85e1e669dce3bfe885f907ac72 0.1s done
#18 exporting manifest list sha256:a3c335533065814c753479d7820efef885c03a58eb62edbf2e21d0f267be982a 0.0s done
#18 naming to docker.io/library/mtusi-messenger:lab5 done
#18 unpacking to docker.io/library/mtusi-messenger:lab5 0.2s done
#18 DONE 0.9s
#19 [api] resolving provenance for metadata file
#19 DONE 0.0s
#20 [migrate] resolving provenance for metadata file
#20 DONE 0.0s
Image mtusi-messenger:lab5 Building
Image mtusi-messenger:lab5 Building
Image mtusi-messenger:lab5 Built
Image mtusi-messenger:lab5 Built
Network mtusi-lab5_data Creating
Network mtusi-lab5_edge Creating
Network mtusi-lab5_data Creating
Network mtusi-lab5_queue Creating
Network mtusi-lab5_queue Creating
Volume mtusi-lab5_pgdata Creating
Volume mtusi-lab5_pgdata Creating
Volume mtusi-lab5_s3data Creating
Volume mtusi-lab5_s3data Creating
Volume mtusi-lab5_rabbitmqdata Creating
Volume mtusi-lab5_rabbitmqdata Creating
Volume mtusi-lab5_valkeydata Creating
Volume mtusi-lab5_valkeydata Creating
Network mtusi-lab5_edge Creating
Network mtusi-lab5_storage Creating
Network mtusi-lab5_storage Creating
Volume mtusi-lab5_valkeydata Created
Volume mtusi-lab5_valkeydata Created
Volume mtusi-lab5_pgdata Created
Volume mtusi-lab5_pgdata Created
Volume mtusi-lab5_s3data Created
Volume mtusi-lab5_s3data Created
Volume mtusi-lab5_rabbitmqdata Created
Volume mtusi-lab5_rabbitmqdata Created
Network mtusi-lab5_data Created
Network mtusi-lab5_data Created
Container mtusi-lab5-valkey-1 Creating
Container mtusi-lab5-postgres-1 Creating
Network mtusi-lab5_storage Created
Network mtusi-lab5_storage Created
Container mtusi-lab5-s3-1 Creating
Network mtusi-lab5_queue Created
Network mtusi-lab5_queue Created
Container mtusi-lab5-broker-1 Creating
Network mtusi-lab5_edge Created
Network mtusi-lab5_edge Created
Container mtusi-lab5-postgres-1 Created
Container mtusi-lab5-migrate-1 Creating
Container mtusi-lab5-valkey-1 Created
Container mtusi-lab5-broker-1 Created
Container mtusi-lab5-s3-1 Created
Container mtusi-lab5-migrate-1 Created
Container mtusi-lab5-s3-init-1 Creating
Container mtusi-lab5-relay-1 Creating
Container mtusi-lab5-s3-init-1 Created
Container mtusi-lab5-api-2 Creating
Container mtusi-lab5-api-1 Creating
Container mtusi-lab5-worker-1 Creating
Container mtusi-lab5-relay-1 Created
Container mtusi-lab5-worker-1 Created
Container mtusi-lab5-api-1 Created
Container mtusi-lab5-api-2 Created
Container mtusi-lab5-lb-1 Creating
Container mtusi-lab5-lb-1 Created
Container mtusi-lab5-s3-1 Starting
Container mtusi-lab5-valkey-1 Starting
Container mtusi-lab5-postgres-1 Starting
Container mtusi-lab5-broker-1 Starting
Container mtusi-lab5-s3-1 Started
Container mtusi-lab5-valkey-1 Started
Container mtusi-lab5-postgres-1 Started
Container mtusi-lab5-postgres-1 Waiting
Container mtusi-lab5-broker-1 Started
Container mtusi-lab5-postgres-1 Healthy
Container mtusi-lab5-migrate-1 Starting
Container mtusi-lab5-migrate-1 Started
Container mtusi-lab5-s3-1 Waiting
Container mtusi-lab5-postgres-1 Waiting
Container mtusi-lab5-broker-1 Waiting
Container mtusi-lab5-migrate-1 Waiting
Container mtusi-lab5-migrate-1 Waiting
Container mtusi-lab5-s3-1 Healthy
Container mtusi-lab5-postgres-1 Healthy
Container mtusi-lab5-migrate-1 Exited
Container mtusi-lab5-migrate-1 Exited
Container mtusi-lab5-s3-init-1 Starting
Container mtusi-lab5-s3-init-1 Started
Container mtusi-lab5-postgres-1 Waiting
Container mtusi-lab5-valkey-1 Waiting
Container mtusi-lab5-migrate-1 Waiting
Container mtusi-lab5-s3-1 Waiting
Container mtusi-lab5-s3-init-1 Waiting
Container mtusi-lab5-migrate-1 Waiting
Container mtusi-lab5-postgres-1 Waiting
Container mtusi-lab5-broker-1 Waiting
Container mtusi-lab5-s3-init-1 Waiting
Container mtusi-lab5-s3-1 Waiting
Container mtusi-lab5-postgres-1 Healthy
Container mtusi-lab5-migrate-1 Exited
Container mtusi-lab5-s3-1 Healthy
Container mtusi-lab5-s3-1 Healthy
Container mtusi-lab5-postgres-1 Healthy
Container mtusi-lab5-valkey-1 Healthy
Container mtusi-lab5-migrate-1 Exited
Container mtusi-lab5-broker-1 Healthy
Container mtusi-lab5-broker-1 Healthy
Container mtusi-lab5-relay-1 Starting
Container mtusi-lab5-relay-1 Started
Container mtusi-lab5-s3-init-1 Exited
Container mtusi-lab5-worker-1 Starting
Container mtusi-lab5-s3-init-1 Exited
Container mtusi-lab5-api-2 Starting
Container mtusi-lab5-worker-1 Started
Container mtusi-lab5-api-2 Started
Container mtusi-lab5-api-1 Starting
Container mtusi-lab5-api-1 Started
Container mtusi-lab5-api-2 Waiting
Container mtusi-lab5-api-1 Waiting
Container mtusi-lab5-api-2 Healthy
Container mtusi-lab5-api-1 Healthy
Container mtusi-lab5-lb-1 Starting
Container mtusi-lab5-lb-1 Started
Container mtusi-lab5-valkey-1 Waiting
Container mtusi-lab5-postgres-1 Waiting
Container mtusi-lab5-s3-init-1 Waiting
Container mtusi-lab5-migrate-1 Waiting
Container mtusi-lab5-api-2 Waiting
Container mtusi-lab5-api-1 Waiting
Container mtusi-lab5-s3-1 Waiting
Container mtusi-lab5-relay-1 Waiting
Container mtusi-lab5-broker-1 Waiting
Container mtusi-lab5-lb-1 Waiting
Container mtusi-lab5-worker-1 Waiting
Container mtusi-lab5-valkey-1 Healthy
Container mtusi-lab5-broker-1 Healthy
Container mtusi-lab5-worker-1 Healthy
Container mtusi-lab5-relay-1 Healthy
Container mtusi-lab5-postgres-1 Healthy
Container mtusi-lab5-migrate-1 Exited
Container mtusi-lab5-s3-1 Healthy
Container mtusi-lab5-s3-init-1 Exited
Container mtusi-lab5-api-2 Healthy
Container mtusi-lab5-api-1 Healthy
Container mtusi-lab5-lb-1 Healthy
[exit 0, 41.2 s]
$ docker compose ps -a --format table {{.Service}} {{.Image}} {{.Status}}
SERVICE IMAGE STATUS
api mtusi-messenger:lab5 Up 11 seconds (healthy)
api mtusi-messenger:lab5 Up 12 seconds (healthy)
broker rabbitmq:4.3.7-alpine@sha256:b1f997f74103d08fc1f20a13890dc44fe6cfa51d528cf521b480ada988d3ffa5 Up 26 seconds (healthy)
lb haproxy:3.2.26-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122 Up 5 seconds (healthy)
migrate mtusi-messenger:lab5 Exited (0) 19 seconds ago
postgres postgres:18.6-bookworm@sha256:afc7e2d441324c0388fa80c3d24f733b4194a4eb7f47dd8ee2b08eb1a24a647c Up 26 seconds (healthy)
relay mtusi-messenger:lab5 Up 15 seconds (healthy)
s3 chrislusf/seaweedfs:4.46@sha256:08d516132314207d10c8e37cbffc1f32b147d870169688734cc61c6231625b62 Up 27 seconds (healthy)
s3-init mtusi-messenger:lab5 Exited (0) 12 seconds ago
valkey valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571 Up 27 seconds (healthy)
worker mtusi-messenger:lab5 Up 12 seconds (healthy)
[exit 0, 0.3 s]
$ docker compose logs --no-log-prefix migrate
migrate: 0001_init: applied
migrate: 0002_idempotency_keys: applied
migrate: 0003_post_message_function: applied
migrate: 0004_attachments: applied
migrate: 0005_pipeline: applied
migrate: done, 5 migration file(s) checked
[exit 0, 0.3 s]
$ docker compose logs --no-log-prefix s3-init
s3-bootstrap: bucket messenger-attachments: created
s3-bootstrap: bucket messenger-staging: created
s3-bootstrap: sentinel health/sentinel: written
s3-bootstrap: anonymous GET object of messenger-attachments: HTTP 403 -> refused
s3-bootstrap: anonymous LIST of messenger-attachments: HTTP 403 -> refused
s3-bootstrap: anonymous GET object of messenger-staging: HTTP 403 -> refused
s3-bootstrap: anonymous LIST of messenger-staging: HTTP 403 -> refused
s3-bootstrap: api: write staging: allowed -> OK
s3-bootstrap: api: delete staging (janitor): allowed -> OK
s3-bootstrap: api: read staging: refused (403) -> OK
s3-bootstrap: api: read final: allowed -> OK
s3-bootstrap: api: write final: refused (AccessDenied) -> OK
s3-bootstrap: api: list final: refused (AccessDenied) -> OK
s3-bootstrap: api: list staging: refused (AccessDenied) -> OK
s3-bootstrap: api: create bucket: refused (AccessDenied) -> OK
s3-bootstrap: api: read another bucket: refused (403) -> OK
s3-bootstrap: worker: read staging: allowed -> OK
s3-bootstrap: worker: write final: allowed -> OK
s3-bootstrap: worker: delete final: allowed -> OK
s3-bootstrap: worker: write staging: allowed -> OK
s3-bootstrap: worker: delete staging: allowed -> OK
s3-bootstrap: worker: list final: refused (AccessDenied) -> OK
s3-bootstrap: worker: create bucket: refused (AccessDenied) -> OK
s3-bootstrap: worker: read another bucket: refused (403) -> OK
s3-bootstrap: auditor: list final: allowed -> OK
s3-bootstrap: auditor: list staging: allowed -> OK
s3-bootstrap: auditor: read final: allowed -> OK
s3-bootstrap: auditor: write final: refused (AccessDenied) -> OK
s3-bootstrap: auditor: delete staging: refused (AccessDenied) -> OK
s3-bootstrap: api: buckets visible in ListBuckets: [] -> OK
s3-bootstrap: done: private buckets, least-privilege keys verified
[exit 0, 0.3 s]
$ C:\Users\wfa22\AppData\Local\Python\pythoncore-3.14-64\python.exe scripts/lbctl.py replicas
mtusi-lab5-api-1 X-Instance-Id=d08185c0e3f3 running health=healthy pid=83074 started=2026-10-31T14:18:45.487 ip=172.25.0.7,172.26.0.5,172.28.0.3
mtusi-lab5-api-2 X-Instance-Id=85c7cde066aa running health=healthy pid=82998 started=2026-10-31T14:18:45.132 ip=172.25.0.6,172.26.0.4,172.28.0.2
[exit 0, 0.5 s]
$ C:\Users\wfa22\AppData\Local\Python\pythoncore-3.14-64\python.exe scripts/lbctl.py status
api1 172.28.0.3 UP mtusi-lab5-api-1 X-Instance-Id=d08185c0e3f3
api2 172.28.0.2 UP mtusi-lab5-api-2 X-Instance-Id=85c7cde066aa
(other slots: MAINT, no container)
[exit 0, 0.7 s]
$ docker compose exec -T broker rabbitmqctl -q list_users
user tags
relay []
worker []
[exit 0, 2.0 s]
$ docker compose exec -T broker rabbitmqctl -q list_queues name type durable messages consumers arguments
name type durable messages consumers arguments
messenger.attachment-jobs quorum true 0 1 [{"x-dead-letter-exchange","messenger.jobs.dlx"},{"x-delivery-limit",20},{"x-queue-type","quorum"}]
messenger.attachment-jobs.dlq quorum true 0 0 [{"x-queue-type","quorum"}]
[exit 0, 2.0 s]
$ docker compose exec -T broker rabbitmqctl -q list_permissions
user configure write read
relay ^$ ^messenger\.jobs$ ^$
worker ^$ ^$ ^messenger\.attachment-jobs$
[exit 0, 3.9 s]
$ docker inspect (limits)
/mtusi-lab5-api-1 cpus=1000000000 memory=536870912 memswap=536870912 image=mtusi-messenger:lab5
/mtusi-lab5-api-2 cpus=1000000000 memory=536870912 memswap=536870912 image=mtusi-messenger:lab5
/mtusi-lab5-broker-1 cpus=1000000000 memory=536870912 memswap=1073741824 image=rabbitmq:4.3.7-alpine@sha256:b1f997f74103d08fc1f20a13890dc44fe6cfa51d528cf521b480ada988d3ffa5
/mtusi-lab5-lb-1 cpus=1000000000 memory=134217728 memswap=268435456 image=haproxy:3.2.26-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122
/mtusi-lab5-postgres-1 cpus=2000000000 memory=1073741824 memswap=2147483648 image=postgres:18.6-bookworm@sha256:afc7e2d441324c0388fa80c3d24f733b4194a4eb7f47dd8ee2b08eb1a24a647c
/mtusi-lab5-relay-1 cpus=500000000 memory=268435456 memswap=536870912 image=mtusi-messenger:lab5
/mtusi-lab5-s3-1 cpus=1000000000 memory=1073741824 memswap=2147483648 image=chrislusf/seaweedfs:4.46@sha256:08d516132314207d10c8e37cbffc1f32b147d870169688734cc61c6231625b62
/mtusi-lab5-valkey-1 cpus=500000000 memory=268435456 memswap=536870912 image=valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571
/mtusi-lab5-worker-1 cpus=2000000000 memory=1610612736 memswap=1610612736 image=mtusi-messenger:lab5
[exit 0, 0.1 s]
$ C:\Users\wfa22\AppData\Local\Python\pythoncore-3.14-64\python.exe -m venv .venv
[exit 0, 7.0 s]
$ C:\Users\wfa22\Desktop\Высоконагруженные приложения\lab5-clean\.venv\Scripts\python.exe -m pip install -q --require-hashes --no-deps -r requirements.txt
[notice] A new release of pip is available: 26.1.2 -> 26.2.2
[notice] To update, run: C:\Users\wfa22\Desktop\Высоконагруженные приложения\lab5-clean\.venv\Scripts\python.exe -m pip install --upgrade pip
[exit 0, 28.9 s]
$ C:\Users\wfa22\Desktop\Высоконагруженные приложения\lab5-clean\.venv\Scripts\python.exe -m pip install -q -r requirements-test.txt -r requirements-dev.txt
[notice] A new release of pip is available: 26.1.2 -> 26.2.2
[notice] To update, run: C:\Users\wfa22\Desktop\Высоконагруженные приложения\lab5-clean\.venv\Scripts\python.exe -m pip install --upgrade pip
[exit 0, 16.0 s]
+60
View File
@@ -0,0 +1,60 @@
# Defense steps 2-3: worker stopped, upload 202, content 409, restart API and broker with volumes, worker started, ready + thumbnail
# 2026-10-31T14:22:23Z, commit cf6e929 docs: PIPELINE, DEFENSE, DATA_MODEL, WINDOWS для lab5; черновик REPORT
Containers BEFORE:
mtusi-lab5-api-1 host=d08185c0e3f3 running exit=0 pid=94963 started=2026-10-31T14:21:47.426
mtusi-lab5-api-2 host=85c7cde066aa running exit=0 pid=96896 started=2026-10-31T14:22:15.716
mtusi-lab5-broker-1 host=broker running exit=0 pid=89550 started=2026-10-31T14:20:17.480
mtusi-lab5-lb-1 host=a22e1c19fc90 running exit=0 pid=92390 started=2026-10-31T14:21:12.759
mtusi-lab5-migrate-1 host=fa0a8a1c9191 exited exit=0 pid=0 started=2026-10-31T14:21:14.217
mtusi-lab5-postgres-1 host=7961919f90c9 running exit=0 pid=89433 started=2026-10-31T14:20:16.605
mtusi-lab5-relay-1 host=9b6249446ece running exit=0 pid=92854 started=2026-10-31T14:21:16.976
mtusi-lab5-s3-1 host=bdee3ea030a4 running exit=0 pid=90402 started=2026-10-31T14:20:36.421
mtusi-lab5-s3-init-1 host=2c85c6921c88 exited exit=0 pid=0 started=2026-10-31T14:21:17.299
mtusi-lab5-valkey-1 host=d53b8a88e5b5 running exit=0 pid=89376 started=2026-10-31T14:20:16.424
mtusi-lab5-worker-1 host=ee8c11f59aa8 running exit=0 pid=93271 started=2026-10-31T14:21:22.639
$ python scripts/demo_pipeline.py
[17:22:24] 1. docker compose stop worker
worker exited
[17:22:26] 2. upload while the worker is stopped
POST /chats/{id}/attachments -> 202 [X-Instance-Id 85c7cde066aa] {"id":"e9d4a7b9-a5da-4c05-a12d-abb95c9a1ff5","chat_id":"d60cc7c6-9ce0-4a81-90ca-3fb3e0e4abbb","owner_id":"7ef6ca59-758c-4753-8037-d00537802aba","filename":"sample.png","content_type":"image/png","size_bytes":111817,"sha256":"99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75","status":
attachment_id = e9d4a7b9-a5da-4c05-a12d-abb95c9a1ff5 status = queued
GET /attachments/{id}/content -> 409 [X-Instance-Id d08185c0e3f3] {"error":{"code":"conflict","message":"Вложение ещё не готово","request_id":"3c6fd35c-0ce9-4f9f-8551-8b9a4eebb88c"}}
GET /attachments/{id}/content?variant=thumbnail -> 409 [X-Instance-Id 85c7cde066aa] {"error":{"code":"conflict","message":"Вложение ещё не готово","request_id":"d017985f-e358-4a88-9459-70e377707782"}}
POST /messages (text only) -> 201 [X-Instance-Id d08185c0e3f3] {"id":"fda54822-f633-4f82-946c-fcee50e0e124","chat_id":"d60cc7c6-9ce0-4a81-90ca-3fb3e0e4abbb","sender_id":"41252a17-4106-481a-8a43-a5187721c7b9","text":"обычное сообщение работает","created_at":"2026-10-31T14:22:26.348105Z","attachment_ids":[]}
POST /messages attachment_ids=[queued id] -> 201 [X-Instance-Id 85c7cde066aa] {"id":"279910fd-0f7c-4123-bd16-ae3fe1e52833","chat_id":"d60cc7c6-9ce0-4a81-90ca-3fb3e0e4abbb","sender_id":"7ef6ca59-758c-4753-8037-d00537802aba","text":"фото","created_at":"2026-10-31T14:22:26.360988Z","attachment_ids":["e9d4a7b9-a5da-4c05-a12d-abb95c9a1ff5"]}
job + outbox in PostgreSQL: c59c75a5-67d1-48e6-95cd-b6af894c4e4b state=queued attempt=0 | outbox published_at=2026-10-31 14:22:26.626499+00
RabbitMQ queue messenger.attachment-jobs: messages=1 consumers=0
[17:22:38] 3. docker compose restart api broker (volumes preserved)
RabbitMQ queue after the restart: messages=1 consumers=0
GET /attachments/{id} -> 200 [X-Instance-Id 85c7cde066aa] {"id":"e9d4a7b9-a5da-4c05-a12d-abb95c9a1ff5","chat_id":"d60cc7c6-9ce0-4a81-90ca-3fb3e0e4abbb","owner_id":"7ef6ca59-758c-4753-8037-d00537802aba","filename":"sample.png","content_type":"image/png","size_bytes":111817,"sha256":"99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75","status":
[17:23:00] 4. docker compose start worker
GET /attachments/{id} until ready -> 200 [X-Instance-Id 85c7cde066aa] {"id":"e9d4a7b9-a5da-4c05-a12d-abb95c9a1ff5","chat_id":"d60cc7c6-9ce0-4a81-90ca-3fb3e0e4abbb","owner_id":"7ef6ca59-758c-4753-8037-d00537802aba","filename":"sample.png","content_type":"image/png","size_bytes":111817,"sha256":"99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75","status":
GET /content?variant=thumbnail -> 200 [X-Instance-Id d08185c0e3f3] 4679 bytes, Content-Type image/jpeg
thumbnail: real JPEG 256x160, sha256 matches metadata: True
original unchanged byte for byte: True
message 279910fd-0f7c-4123-bd16-ae3fe1e52833 still references it: {e9d4a7b9-a5da-4c05-a12d-abb95c9a1ff5}
[17:23:13] 5. job history (jobctl show)
2026-10-31 14:22:26.316695+00:00 created attempt=None actor=api:85c7cde066aa
2026-10-31 14:23:12.130790+00:00 claimed attempt=1 actor=worker:ee8c11f59aa8
2026-10-31 14:23:12.981082+00:00 succeeded attempt=1 actor=worker:ee8c11f59aa8
[exit 0, 53.7 s]
Containers AFTER (api-*, broker restarted; worker stopped and started):
mtusi-lab5-api-1 host=d08185c0e3f3 running exit=0 pid=99058 started=2026-10-31T14:22:43.321
mtusi-lab5-api-2 host=85c7cde066aa running exit=0 pid=98980 started=2026-10-31T14:22:42.925
mtusi-lab5-broker-1 host=broker running exit=0 pid=98657 started=2026-10-31T14:22:40.329
mtusi-lab5-lb-1 host=a22e1c19fc90 running exit=0 pid=92390 started=2026-10-31T14:21:12.759
mtusi-lab5-migrate-1 host=fa0a8a1c9191 exited exit=0 pid=0 started=2026-10-31T14:23:01.939
mtusi-lab5-postgres-1 host=7961919f90c9 running exit=0 pid=89433 started=2026-10-31T14:20:16.605
mtusi-lab5-relay-1 host=9b6249446ece running exit=0 pid=92854 started=2026-10-31T14:21:16.976
mtusi-lab5-s3-1 host=bdee3ea030a4 running exit=0 pid=90402 started=2026-10-31T14:20:36.421
mtusi-lab5-s3-init-1 host=2c85c6921c88 exited exit=0 pid=0 started=2026-10-31T14:23:04.208
mtusi-lab5-valkey-1 host=d53b8a88e5b5 running exit=0 pid=89376 started=2026-10-31T14:20:16.424
mtusi-lab5-worker-1 host=ee8c11f59aa8 running exit=0 pid=1259 started=2026-10-31T14:23:09.985
+17
View File
@@ -0,0 +1,17 @@
{
"lab": 5,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.066,
"concurrency": 4,
"successful_requests": 5515,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 183.429,
"successful_latency_ms": {
"p50": 17.96,
"p95": 43.491,
"p99": 58.653
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+17
View File
@@ -0,0 +1,17 @@
# make check, make validate (venv), make test
# 2026-10-31T14:19:59Z, commit cf6e929 docs: PIPELINE, DEFENSE, DATA_MODEL, WINDOWS для lab5; черновик REPORT
$ make check
python scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
[exit 0, 1.2 s]
$ make validate PYTHON=.venv/Scripts/python.exe
.venv/Scripts/python.exe scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
[exit 0, 2.3 s]
$ make test
python tests/smoke.py --base-url "http://localhost:8080"
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
[exit 0, 3.3 s]
+394
View File
@@ -0,0 +1,394 @@
# Own tests: unit + stand (pytest -v); failures restored in finally
# 2026-10-31T14:23:18Z, commit cf6e929 docs: PIPELINE, DEFENSE, DATA_MODEL, WINDOWS для lab5; черновик REPORT
$ python -m pytest student-tests -v
============================= test session starts =============================
platform win32 -- Python 3.14.6, pytest-9.1.1, pluggy-1.7.0 -- C:\Users\wfa22\Desktop\Высоконагруженные приложения\lab5-clean\.venv\Scripts\python.exe
rootdir: C:\Users\wfa22\Desktop\Высоконагруженные приложения\lab5-clean
plugins: anyio-4.15.1
collecting ... collected 381 items
student-tests/test_api.py::test_register_never_returns_password_and_login_returns_bearer PASSED [ 0%]
student-tests/test_api.py::test_duplicate_username_is_409 PASSED [ 0%]
student-tests/test_api.py::test_bad_password_on_registration_is_400[short-11ch] PASSED [ 0%]
student-tests/test_api.py::test_bad_password_on_registration_is_400[ ] PASSED [ 1%]
student-tests/test_api.py::test_bad_password_on_registration_is_400[ \t \n \t \n \t \n ] PASSED [ 1%]
student-tests/test_api.py::test_bad_password_on_registration_is_400[\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f] PASSED [ 1%]
student-tests/test_api.py::test_edge_passwords_register_and_login[\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f] PASSED [ 1%]
student-tests/test_api.py::test_edge_passwords_register_and_login[with:colons:inside] PASSED [ 2%]
student-tests/test_api.py::test_edge_passwords_register_and_login[Twelve chars] PASSED [ 2%]
student-tests/test_api.py::test_wrong_password_and_unknown_user_give_the_same_401 PASSED [ 2%]
student-tests/test_api.py::test_malformed_basic_is_401_not_500[Basic \xe9] PASSED [ 2%]
student-tests/test_api.py::test_malformed_basic_is_401_not_500[Basic !!!] PASSED [ 3%]
student-tests/test_api.py::test_malformed_basic_is_401_not_500[Basic bm9fY29sb24=] PASSED [ 3%]
student-tests/test_api.py::test_malformed_basic_is_401_not_500[Basic //46eA==] PASSED [ 3%]
student-tests/test_api.py::test_malformed_basic_is_401_not_500[Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 3%]
student-tests/test_api.py::test_malformed_basic_is_401_not_500[] PASSED [ 4%]
student-tests/test_api.py::test_logout_revokes_only_this_token PASSED [ 4%]
student-tests/test_api.py::test_x_user_id_basic_and_garbage_do_not_authenticate PASSED [ 4%]
student-tests/test_api.py::test_malformed_json_is_400[{] PASSED [ 4%]
student-tests/test_api.py::test_malformed_json_is_400[] PASSED [ 5%]
student-tests/test_api.py::test_malformed_json_is_400[[]] PASSED [ 5%]
student-tests/test_api.py::test_malformed_json_is_400[null] PASSED [ 5%]
student-tests/test_api.py::test_malformed_json_is_400[{"username": "abc_def", "display_name": NaN, "password": "Twelve-chars"}] PASSED [ 6%]
student-tests/test_api.py::test_malformed_json_is_400[{"username": "abc_def", "display_name": "x", "password": "Twelve-chars"}{"a": 1}] PASSED [ 6%]
student-tests/test_api.py::test_malformed_json_is_400[{"username": "abc_def", "display_name": "\ud800", "password": "Twelve-chars"}] PASSED [ 6%]
student-tests/test_api.py::test_invalid_registration_fields_are_400[body0] PASSED [ 6%]
student-tests/test_api.py::test_invalid_registration_fields_are_400[body1] PASSED [ 7%]
student-tests/test_api.py::test_invalid_registration_fields_are_400[body2] PASSED [ 7%]
student-tests/test_api.py::test_invalid_registration_fields_are_400[body3] PASSED [ 7%]
student-tests/test_api.py::test_invalid_registration_fields_are_400[body4] PASSED [ 7%]
student-tests/test_api.py::test_invalid_registration_fields_are_400[body5] PASSED [ 8%]
student-tests/test_api.py::test_unicode_limits_are_code_points_and_nul_is_stored PASSED [ 8%]
student-tests/test_api.py::test_oversized_body_and_wrong_content_type PASSED [ 8%]
student-tests/test_api.py::test_chat_validation PASSED [ 8%]
student-tests/test_api.py::test_foreign_chat_is_indistinguishable_from_missing PASSED [ 9%]
student-tests/test_api.py::test_chat_list_order_pagination_and_isolation PASSED [ 9%]
student-tests/test_api.py::test_history_pages_without_loss_or_duplicates PASSED [ 9%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[limit=0] PASSED [ 9%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[limit=101] PASSED [ 10%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[limit=abc] PASSED [ 10%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[limit=1&limit=2] PASSED [ 10%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[cursor=] PASSED [ 11%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[cursor=garbage] PASSED [ 11%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[cursor=djF8bXx4fDF8Mg] PASSED [ 11%]
student-tests/test_api.py::test_bad_limit_or_cursor_is_400[cursor=djF8bXx4fDk5OTk5OTk5OTk5OTk5OTk5OTk5fHk=] PASSED [ 11%]
student-tests/test_api.py::test_cursor_bound_to_chat PASSED [ 12%]
student-tests/test_api.py::test_read_after_write PASSED [ 12%]
student-tests/test_api.py::test_malformed_cursor_values_are_400_on_both_lists PASSED [ 12%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[\xff] PASSED [ 12%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"first","TEXT":"second"}] PASSED [ 13%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"a","text":"b"}] PASSED [ 13%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":123}] PASSED [ 13%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"valid"}}] PASSED [ 13%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"valid"}]] PASSED [ 14%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"x"} {}] PASSED [ 14%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"x","sender_id":"11111111-1111-4111-8111-111111111111"}] PASSED [ 14%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"x","attachment_ids":null}] PASSED [ 14%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":"x","attachment_ids":["nope"]}] PASSED [ 15%]
student-tests/test_api.py::test_bad_message_body_is_400_and_nothing_is_stored[{"text":" \n\t "}] PASSED [ 15%]
student-tests/test_api.py::test_ff_byte_body_on_registration_is_contract_error PASSED [ 15%]
student-tests/test_api.py::test_text_is_stored_verbatim_and_length_counts_raw_text PASSED [ 16%]
student-tests/test_api.py::test_unknown_attachment_ids_are_404 PASSED [ 16%]
student-tests/test_api.py::test_member_ids_are_compared_as_uuids_not_strings PASSED [ 16%]
student-tests/test_api.py::test_non_ascii_or_garbage_bearer_is_401_not_500[Bearer \xe9] PASSED [ 16%]
student-tests/test_api.py::test_non_ascii_or_garbage_bearer_is_401_not_500[Bearer .] PASSED [ 17%]
student-tests/test_api.py::test_non_ascii_or_garbage_bearer_is_401_not_500[Bearer a b] PASSED [ 17%]
student-tests/test_api.py::test_non_ascii_or_garbage_bearer_is_401_not_500[Bearer \xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9] PASSED [ 17%]
student-tests/test_api.py::test_non_ascii_or_garbage_bearer_is_401_not_500[bearer\taaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 17%]
student-tests/test_api.py::test_login_with_a_body_is_rejected PASSED [ 18%]
student-tests/test_api.py::test_password_range_is_12_to_128_code_points PASSED [ 18%]
student-tests/test_api.py::test_every_api_response_carries_instance_and_request_id PASSED [ 18%]
student-tests/test_api.py::test_unicode_whitespace_only_strings_are_400[\xa0] PASSED [ 18%]
student-tests/test_api.py::test_unicode_whitespace_only_strings_are_400[\u2003\u2003] PASSED [ 19%]
student-tests/test_api.py::test_unicode_whitespace_only_strings_are_400[ \xa0\t\u3000] PASSED [ 19%]
student-tests/test_api.py::test_odd_registration_bodies_are_400_and_the_api_survives[{"username":"num_probe","display_name":"x","password":1e1000}] PASSED [ 19%]
student-tests/test_api.py::test_odd_registration_bodies_are_400_and_the_api_survives[{"username":"ff_probe","display_name":"x","password":"12345678901\xff"}] PASSED [ 19%]
student-tests/test_api.py::test_odd_registration_bodies_are_400_and_the_api_survives[{"username":"num_probe","display_name":1,"password":"Twelve-chars-ok"}] PASSED [ 20%]
student-tests/test_api.py::test_more_than_100_members_is_400 PASSED [ 20%]
student-tests/test_api.py::test_cursor_of_one_list_is_rejected_by_the_other PASSED [ 20%]
student-tests/test_attachments.py::test_png_and_jpeg_roundtrip_byte_for_byte PASSED [ 20%]
student-tests/test_attachments.py::test_metadata_reveals_no_storage_details PASSED [ 21%]
student-tests/test_attachments.py::test_original_is_not_stored_on_api_containers PASSED [ 21%]
student-tests/test_attachments.py::test_outsider_and_unknown_get_404 PASSED [ 21%]
student-tests/test_attachments.py::test_attachment_ids_are_checked_per_chat PASSED [ 22%]
student-tests/test_attachments.py::test_message_with_attachments_and_history PASSED [ 22%]
student-tests/test_attachments.py::test_idempotent_replay_with_attachments PASSED [ 22%]
student-tests/test_attachments.py::test_message_body_validation[{"attachment_ids":["%(a)s"]}] PASSED [ 22%]
student-tests/test_attachments.py::test_message_body_validation[{"text":null,"attachment_ids":["%(a)s"]}] PASSED [ 23%]
student-tests/test_attachments.py::test_message_body_validation[{"text":1,"attachment_ids":["%(a)s"]}] PASSED [ 23%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":null}] PASSED [ 23%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":"%(a)s"}] PASSED [ 23%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":{}}] PASSED [ 24%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":["%(a)s","%] PASSED [ 24%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":["%(a)s",1]] PASSED [ 24%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":["not-a-uui] PASSED [ 24%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"","attachment_ids":[]}] PASSED [ 25%]
student-tests/test_attachments.py::test_message_body_validation[{"text":" "}] PASSED [ 25%]
student-tests/test_attachments.py::test_message_body_validation[{"text":"x","attachment_ids":[],"sender_] PASSED [ 25%]
student-tests/test_attachments.py::test_at_most_ten_attachments PASSED [ 25%]
student-tests/test_attachments.py::test_size_limit_through_the_load_balancer PASSED [ 26%]
student-tests/test_attachments.py::test_pixel_limit_before_decoding PASSED [ 26%]
student-tests/test_attachments.py::test_exactly_40_megapixels_is_accepted PASSED [ 26%]
student-tests/test_attachments.py::test_bad_content_is_415[png: first 33 bytes of the fixture] PASSED [ 27%]
student-tests/test_attachments.py::test_bad_content_is_415[png: truncated] PASSED [ 27%]
student-tests/test_attachments.py::test_bad_content_is_415[png: corrupt IDAT, valid CRC] PASSED [ 27%]
student-tests/test_attachments.py::test_bad_content_is_415[png: fewer rows than IHDR] PASSED [ 27%]
student-tests/test_attachments.py::test_bad_content_is_415[png: flipped byte] PASSED [ 28%]
student-tests/test_attachments.py::test_bad_content_is_415[png: bytes after IEND] PASSED [ 28%]
student-tests/test_attachments.py::test_bad_content_is_415[jpeg: no scan data after SOS] PASSED [ 28%]
student-tests/test_attachments.py::test_bad_content_is_415[jpeg: truncated] PASSED [ 28%]
student-tests/test_attachments.py::test_bad_content_is_415[review: png row filter 5] PASSED [ 29%]
student-tests/test_attachments.py::test_bad_content_is_415[review: png row filter 0xff] PASSED [ 29%]
student-tests/test_attachments.py::test_bad_content_is_415[review: png IDAT not-a-zlib-stream] PASSED [ 29%]
student-tests/test_attachments.py::test_bad_content_is_415[review: jpeg 27 bytes, no tables/scan] PASSED [ 29%]
student-tests/test_attachments.py::test_bad_content_is_415[review: jpeg SOS component not in SOF] PASSED [ 30%]
student-tests/test_attachments.py::test_bad_content_is_415[mime: png bytes declared jpeg] PASSED [ 30%]
student-tests/test_attachments.py::test_bad_content_is_415[mime: jpeg bytes declared png] PASSED [ 30%]
student-tests/test_attachments.py::test_bad_content_is_415[mime: gif declared png] PASSED [ 30%]
student-tests/test_attachments.py::test_bad_content_is_415[mime: html declared png] PASSED [ 31%]
student-tests/test_attachments.py::test_bad_content_is_415[type: text/plain] PASSED [ 31%]
student-tests/test_attachments.py::test_bad_content_is_415[type: octet-stream] PASSED [ 31%]
student-tests/test_attachments.py::test_bad_content_is_415[type: multipart] PASSED [ 32%]
student-tests/test_attachments.py::test_bad_content_is_415[type: missing] PASSED [ 32%]
student-tests/test_attachments.py::test_empty_body_is_400 PASSED [ 32%]
student-tests/test_attachments.py::test_bad_filename_is_400[missing] PASSED [ 32%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=] PASSED [ 33%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=%20%20%20] PASSED [ 33%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=.] PASSED [ 33%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=..] PASSED [ 33%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=a%2Fb.png] PASSED [ 34%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=a%5Cb.png] PASSED [ 34%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=a%00b.png] PASSED [ 34%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=c1%C2%85.png] PASSED [ 34%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=tab%09.png] PASSED [ 35%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=photo%E2%80%AEgnp.exe] PASSED [ 35%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=%FF%FE.png] PASSED [ 35%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=a.png&filename=b.png] PASSED [ 35%]
student-tests/test_attachments.py::test_bad_filename_is_400[filename=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 36%]
student-tests/test_attachments.py::test_unicode_filename_is_kept_and_safely_exposed PASSED [ 36%]
student-tests/test_attachments.py::test_variant_parameter PASSED [ 36%]
student-tests/test_balancing.py::test_one_session_is_served_by_every_real_replica PASSED [ 37%]
student-tests/test_balancing.py::test_write_on_one_replica_is_read_on_the_other PASSED [ 37%]
student-tests/test_balancing.py::test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready[0-pg_hba] PASSED [ 37%]
student-tests/test_balancing.py::test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready[0-network] PASSED [ 37%]
student-tests/test_balancing.py::test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready[1-pg_hba] PASSED [ 38%]
student-tests/test_balancing.py::test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready[1-network] PASSED [ 38%]
student-tests/test_balancing.py::test_graceful_stop_of_each_replica_loses_no_request[0] PASSED [ 38%]
student-tests/test_balancing.py::test_graceful_stop_of_each_replica_loses_no_request[1] PASSED [ 38%]
student-tests/test_balancing.py::test_killed_replica_bounded_errors_recovery_and_no_duplicates[0] PASSED [ 39%]
student-tests/test_balancing.py::test_killed_replica_bounded_errors_recovery_and_no_duplicates[1] PASSED [ 39%]
student-tests/test_balancing.py::test_graceful_shutdown_order_in_logs PASSED [ 39%]
student-tests/test_balancing.py::test_full_restart_lb_rediscovers_all_replicas PASSED [ 39%]
student-tests/test_balancing.py::test_scale_up_and_down_is_picked_up_without_errors PASSED [ 40%]
student-tests/test_balancing.py::test_compose_policy_limits_ports_secrets_images PASSED [ 40%]
student-tests/test_balancing.py::test_running_containers_have_limits_and_no_bypass_ports PASSED [ 40%]
student-tests/test_balancing.py::test_migrations_ran_once_by_the_migrate_service PASSED [ 40%]
student-tests/test_consistency.py::test_interrupted_and_stalled_uploads_leave_nothing PASSED [ 41%]
student-tests/test_consistency.py::test_crash_after_staging_before_job_is_cleaned_by_janitor PASSED [ 41%]
student-tests/test_consistency.py::test_lost_answer_after_job_commit_still_becomes_ready PASSED [ 41%]
student-tests/test_consistency.py::test_fresh_pending_upload_is_not_touched_by_janitor PASSED [ 41%]
student-tests/test_db.py::test_registration_race_exactly_one_201_and_seven_409 PASSED [ 42%]
student-tests/test_db.py::test_create_chat_rolls_back_after_the_chat_row_was_inserted PASSED [ 42%]
student-tests/test_db.py::test_migrations_rerun_is_a_noop PASSED [ 42%]
student-tests/test_db.py::test_100_messages_from_10_clients_keep_order_and_cursor_walk PASSED [ 43%]
student-tests/test_db.py::test_secrets_are_not_stored_in_plain_text PASSED [ 43%]
student-tests/test_explain.py::test_late_page_uses_index_range_not_filter PASSED [ 43%]
student-tests/test_failures.py::test_valkey_failure[stop] PASSED [ 43%]
student-tests/test_failures.py::test_valkey_failure[pause] PASSED [ 44%]
student-tests/test_failures.py::test_postgres_failure[stop] PASSED [ 44%]
student-tests/test_failures.py::test_postgres_failure[pause] PASSED [ 44%]
student-tests/test_failures.py::test_locked_table_gives_bounded_503 PASSED [ 44%]
student-tests/test_failures.py::test_logout_during_valkey_outage_is_never_lost PASSED [ 45%]
student-tests/test_idempotency.py::test_replay_returns_the_same_201_and_message_from_every_replica PASSED [ 45%]
student-tests/test_idempotency.py::test_other_body_with_the_same_key_is_409_and_keeps_the_original PASSED [ 45%]
student-tests/test_idempotency.py::test_key_order_and_missing_attachment_ids_are_the_same_body PASSED [ 45%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[] PASSED [ 46%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 46%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[\u043a\u043b\u044e\u0447] PASSED [ 46%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[a b] PASSED [ 46%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[a/b] PASSED [ 47%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[a,b] PASSED [ 47%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[a\tb] PASSED [ 47%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_400[*] PASSED [ 48%]
student-tests/test_idempotency.py::test_repeated_key_header_is_400 PASSED [ 48%]
student-tests/test_idempotency.py::test_longest_key_and_every_allowed_character PASSED [ 48%]
student-tests/test_idempotency.py::test_scope_is_user_plus_chat_plus_key PASSED [ 48%]
student-tests/test_idempotency.py::test_outsider_and_revoked_session_never_see_the_stored_result PASSED [ 49%]
student-tests/test_idempotency.py::test_concurrent_same_key_through_different_replicas_creates_exactly_one PASSED [ 49%]
student-tests/test_idempotency.py::test_concurrent_same_key_different_bodies_one_wins PASSED [ 49%]
student-tests/test_idempotency.py::test_failure_after_the_key_insert_rolls_everything_back PASSED [ 49%]
student-tests/test_idempotency.py::test_client_timeout_then_retry_with_the_same_key_gives_the_committed_message PASSED [ 50%]
student-tests/test_idempotency.py::test_lock_timeout_is_a_transient_503_that_is_not_recorded PASSED [ 50%]
student-tests/test_idempotency.py::test_replay_after_the_serving_replica_is_stopped PASSED [ 50%]
student-tests/test_pipeline_flow.py::test_upload_is_202_queued_then_ready_with_contract_variants PASSED [ 50%]
student-tests/test_pipeline_flow.py::test_queued_attachment_is_attachable_failed_is_not PASSED [ 51%]
student-tests/test_pipeline_flow.py::test_worker_stopped_upload_202_content_409_restart_api_and_broker_then_ready PASSED [ 51%]
student-tests/test_pipeline_flow.py::test_broker_down_commit_to_publish_gap_is_closed_by_the_outbox PASSED [ 51%]
student-tests/test_pipeline_flow.py::test_relay_down_job_waits_in_outbox_not_lost PASSED [ 51%]
student-tests/test_pipeline_flow.py::test_crash_after_publish_before_confirm_is_recorded_gives_a_harmless_duplicate PASSED [ 52%]
student-tests/test_pipeline_flow.py::test_duplicate_and_reordered_deliveries_are_noops PASSED [ 52%]
student-tests/test_pipeline_flow.py::test_worker_crash_before_side_effect_lease_expires_and_job_completes PASSED [ 52%]
student-tests/test_pipeline_flow.py::test_worker_crash_after_s3_write_before_commit_republishes_without_duplicates PASSED [ 53%]
student-tests/test_pipeline_flow.py::test_worker_crash_after_commit_before_ack_redelivery_is_noop PASSED [ 53%]
student-tests/test_pipeline_flow.py::test_transient_errors_are_retried_with_jittered_backoff PASSED [ 53%]
student-tests/test_pipeline_flow.py::test_retry_exhausted_failed_registry_then_replay PASSED [ 53%]
student-tests/test_pipeline_flow.py::test_permanent_error_fails_at_once_without_retries PASSED [ 54%]
student-tests/test_pipeline_flow.py::test_memory_and_time_limits_of_the_worker PASSED [ 54%]
student-tests/test_pipeline_flow.py::test_bad_message_is_dead_lettered_not_processed PASSED [ 54%]
student-tests/test_pipeline_flow.py::test_hung_worker_loses_its_lease_and_cannot_publish PASSED [ 54%]
student-tests/test_pipeline_flow.py::test_graceful_worker_stop_finishes_the_running_attempt PASSED [ 55%]
student-tests/test_pipeline_flow.py::test_concurrency_is_bounded_by_prefetch PASSED [ 55%]
student-tests/test_pipeline_flow.py::test_queued_staging_is_never_deleted_even_after_retention PASSED [ 55%]
student-tests/test_pipeline_flow.py::test_retention_deletes_failed_staging_then_replay_is_refused PASSED [ 55%]
student-tests/test_pipeline_flow.py::test_cleanup_racing_a_replay_never_deletes_the_replayed_source PASSED [ 56%]
student-tests/test_pipeline_flow.py::test_reprocess_of_a_not_ready_upload_is_refused PASSED [ 56%]
student-tests/test_pipeline_flow.py::test_zz_invariants_hold_after_all_scenarios PASSED [ 56%]
student-tests/test_sessions.py::test_short_ttl_expires[valkey] PASSED [ 56%]
student-tests/test_sessions.py::test_short_ttl_expires[postgres] PASSED [ 57%]
student-tests/test_sessions.py::test_restart_does_not_extend_ttl PASSED [ 57%]
student-tests/test_sessions.py::test_postgres_session_store PASSED [ 57%]
student-tests/test_storage_failures.py::test_s3_outage_is_503_and_text_keeps_working[stop] PASSED [ 58%]
student-tests/test_storage_failures.py::test_s3_outage_is_503_and_text_keeps_working[pause] PASSED [ 58%]
student-tests/test_storage_failures.py::test_upload_survives_failover_of_the_serving_replica PASSED [ 58%]
student-tests/test_storage_failures.py::test_bucket_is_private_outside_the_api PASSED [ 58%]
student-tests/test_storage_failures.py::test_s3_restart_keeps_objects PASSED [ 59%]
student-tests/unit/test_images.py::test_public_fixture_is_accepted PASSED [ 59%]
student-tests/unit/test_images.py::test_valid_png_kinds[rgba] PASSED [ 59%]
student-tests/unit/test_images.py::test_valid_png_kinds[palette] PASSED [ 59%]
student-tests/unit/test_images.py::test_valid_png_kinds[1bit] PASSED [ 60%]
student-tests/unit/test_images.py::test_valid_png_kinds[gray] PASSED [ 60%]
student-tests/unit/test_images.py::test_valid_png_kinds[noise] PASSED [ 60%]
student-tests/unit/test_images.py::test_valid_png_kinds[1x1] PASSED [ 60%]
student-tests/unit/test_images.py::test_interlaced_png_is_accepted PASSED [ 61%]
student-tests/unit/test_images.py::test_broken_png_is_415[first 33 bytes of the fixture] PASSED [ 61%]
student-tests/unit/test_images.py::test_broken_png_is_415[truncated (no IEND)] PASSED [ 61%]
student-tests/unit/test_images.py::test_broken_png_is_415[truncated in IDAT] PASSED [ 61%]
student-tests/unit/test_images.py::test_broken_png_is_415[flipped byte -> CRC error] PASSED [ 62%]
student-tests/unit/test_images.py::test_broken_png_is_415[garbage IDAT with valid CRC] PASSED [ 62%]
student-tests/unit/test_images.py::test_broken_png_is_415[fewer rows than IHDR] PASSED [ 62%]
student-tests/unit/test_images.py::test_broken_png_is_415[bytes after IEND (polyglot)] PASSED [ 62%]
student-tests/unit/test_images.py::test_broken_png_is_415[text] PASSED [ 63%]
student-tests/unit/test_images.py::test_broken_png_is_415[gif] PASSED [ 63%]
student-tests/unit/test_images.py::test_broken_png_is_415[two bytes of a signature] PASSED [ 63%]
student-tests/unit/test_images.py::test_pixel_limit_is_checked_from_the_header PASSED [ 64%]
student-tests/unit/test_images.py::test_png_verification_is_streaming_and_fast PASSED [ 64%]
student-tests/unit/test_images.py::test_jpeg_header_is_parsed_incrementally PASSED [ 64%]
student-tests/unit/test_images.py::test_valid_jpeg[base] SKIPPED (dj...) [ 64%]
student-tests/unit/test_images.py::test_valid_jpeg[prog] SKIPPED (dj...) [ 65%]
student-tests/unit/test_images.py::test_broken_jpeg_is_415[no scan data after SOS-] SKIPPED [ 65%]
student-tests/unit/test_images.py::test_broken_jpeg_is_415[truncated-] SKIPPED [ 65%]
student-tests/unit/test_images.py::test_good_filenames[photo.png] PASSED [ 65%]
student-tests/unit/test_images.py::test_good_filenames[\u0444\u043e\u0442\u043e \u043e\u0442\u043f\u0443\u0441\u043a\u0430.jpg] PASSED [ 66%]
student-tests/unit/test_images.py::test_good_filenames[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 66%]
student-tests/unit/test_images.py::test_good_filenames[emoji \U0001f468\u200d\U0001f469\u200d\U0001f467.png] PASSED [ 66%]
student-tests/unit/test_images.py::test_good_filenames[ x ] PASSED [ 66%]
student-tests/unit/test_images.py::test_good_filenames[..x] PASSED [ 67%]
student-tests/unit/test_images.py::test_bad_filenames[] PASSED [ 67%]
student-tests/unit/test_images.py::test_bad_filenames[ ] PASSED [ 67%]
student-tests/unit/test_images.py::test_bad_filenames[\u3000] PASSED [ 67%]
student-tests/unit/test_images.py::test_bad_filenames[.] PASSED [ 68%]
student-tests/unit/test_images.py::test_bad_filenames[..] PASSED [ 68%]
student-tests/unit/test_images.py::test_bad_filenames[a/b.png] PASSED [ 68%]
student-tests/unit/test_images.py::test_bad_filenames[a\\b.png] PASSED [ 69%]
student-tests/unit/test_images.py::test_bad_filenames[a\x00b] PASSED [ 69%]
student-tests/unit/test_images.py::test_bad_filenames[c1\x85.png] PASSED [ 69%]
student-tests/unit/test_images.py::test_bad_filenames[tab\t.png] PASSED [ 69%]
student-tests/unit/test_images.py::test_bad_filenames[del\x7f.png] PASSED [ 70%]
student-tests/unit/test_images.py::test_bad_filenames[x\u2028y] PASSED [ 70%]
student-tests/unit/test_images.py::test_bad_filenames[photo\u202egnp.exe] PASSED [ 70%]
student-tests/unit/test_images.py::test_bad_filenames[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 70%]
student-tests/unit/test_images.py::test_filename_must_be_single_and_present PASSED [ 71%]
student-tests/unit/test_images.py::test_query_must_be_valid_utf8 PASSED [ 71%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size0-256-expected0] PASSED [ 71%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size1-256-expected1] PASSED [ 71%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size2-256-expected2] PASSED [ 72%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size3-256-expected3] PASSED [ 72%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size4-256-expected4] PASSED [ 72%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size5-256-expected5] PASSED [ 72%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size6-256-expected6] PASSED [ 73%]
student-tests/unit/test_pipeline.py::test_fit_rounds_down_without_upscaling[size7-1280-expected7] PASSED [ 73%]
student-tests/unit/test_pipeline.py::test_center_square PASSED [ 73%]
student-tests/unit/test_pipeline.py::test_public_fixture_variants_match_the_contract PASSED [ 74%]
student-tests/unit/test_pipeline.py::test_small_image_is_not_upscaled_but_crop_is PASSED [ 74%]
student-tests/unit/test_pipeline.py::test_big_image_is_bounded_by_1280 PASSED [ 74%]
student-tests/unit/test_pipeline.py::test_exif_orientation_is_applied_and_dropped PASSED [ 74%]
student-tests/unit/test_pipeline.py::test_alpha_is_composited_on_white_for_jpeg_and_kept_for_webp PASSED [ 75%]
student-tests/unit/test_pipeline.py::test_metadata_is_not_copied PASSED [ 75%]
student-tests/unit/test_pipeline.py::test_png_modes_are_processed[RGBA] PASSED [ 75%]
student-tests/unit/test_pipeline.py::test_png_modes_are_processed[P] PASSED [ 75%]
student-tests/unit/test_pipeline.py::test_png_modes_are_processed[1] PASSED [ 76%]
student-tests/unit/test_pipeline.py::test_png_modes_are_processed[L] PASSED [ 76%]
student-tests/unit/test_pipeline.py::test_png_modes_are_processed[LA] PASSED [ 76%]
student-tests/unit/test_pipeline.py::test_png_modes_are_processed[RGB] PASSED [ 76%]
student-tests/unit/test_pipeline.py::test_16_bit_grey_is_scaled_not_clipped PASSED [ 77%]
student-tests/unit/test_pipeline.py::test_pipeline_versions_differ_in_bytes_not_in_geometry PASSED [ 77%]
student-tests/unit/test_pipeline.py::test_pixel_limit_is_checked_before_decoding PASSED [ 77%]
student-tests/unit/test_pipeline.py::test_child_process_protocol_round_trip PASSED [ 77%]
student-tests/unit/test_pipeline.py::test_encoded_message_matches_jobs_schema_and_carries_ids_only PASSED [ 78%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change0] PASSED [ 78%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change1] PASSED [ 78%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change2] PASSED [ 79%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change3] PASSED [ 79%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change4] PASSED [ 79%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change5] PASSED [ 79%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change6] PASSED [ 80%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change7] PASSED [ 80%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change8] PASSED [ 80%]
student-tests/unit/test_pipeline.py::test_invalid_messages_are_rejected[change9] PASSED [ 80%]
student-tests/unit/test_pipeline.py::test_garbage_is_rejected PASSED [ 81%]
student-tests/unit/test_pipeline.py::test_backoff_is_full_jitter_and_capped PASSED [ 81%]
student-tests/unit/test_pipeline.py::test_pipeline_settings PASSED [ 81%]
student-tests/unit/test_unit.py::test_valid_passwords[Twelve-chars] PASSED [ 81%]
student-tests/unit/test_unit.py::test_valid_passwords[\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f] PASSED [ 82%]
student-tests/unit/test_unit.py::test_valid_passwords[\u043f\u0430\u0440\u043e\u043b\u044c:\u0441:\u0434\u0432\u043e\u0435\u0442\u043e\u0447\u0438\u044f\u043c\u0438] PASSED [ 82%]
student-tests/unit/test_unit.py::test_valid_passwords[\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600\U0001f600] PASSED [ 82%]
student-tests/unit/test_unit.py::test_valid_passwords[a b c d e f g] PASSED [ 82%]
student-tests/unit/test_unit.py::test_invalid_passwords[short-11ch] PASSED [ 83%]
student-tests/unit/test_unit.py::test_invalid_passwords[\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f] PASSED [ 83%]
student-tests/unit/test_unit.py::test_invalid_passwords[ ] PASSED [ 83%]
student-tests/unit/test_unit.py::test_invalid_passwords[\t\n\u3000\t\n\u3000\t\n\u3000\t\n\u3000\t\n\u3000] PASSED [ 83%]
student-tests/unit/test_unit.py::test_invalid_passwords[\ud800\ud800\ud800\ud800\ud800\ud800\ud800\ud800\ud800\ud800\ud800\ud800] PASSED [ 84%]
student-tests/unit/test_unit.py::test_invalid_passwords[None] PASSED [ 84%]
student-tests/unit/test_unit.py::test_invalid_passwords[123456789012] PASSED [ 84%]
student-tests/unit/test_unit.py::test_text_may_contain_nul_but_not_lone_surrogates PASSED [ 85%]
student-tests/unit/test_unit.py::test_cursor_roundtrip_and_binding PASSED [ 85%]
student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v1|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|253402300800000000|11111111-1111-4111-8111-111111111111] PASSED [ 85%]
student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v1|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|9999999999999999999|11111111-1111-4111-8111-111111111111] PASSED [ 85%]
student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v1|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|-1|11111111-1111-4111-8111-111111111111] PASSED [ 86%]
student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v1|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|1|not-a-uuid] PASSED [ 86%]
student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v1|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|1|11111111-1111-4111-8111-11111111111G] PASSED [ 86%]
student-tests/unit/test_unit.py::test_broken_cursors_are_400_not_500[v2|m|3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11|1|11111111-1111-4111-8111-111111111111] PASSED [ 86%]
student-tests/unit/test_unit.py::test_time_helpers_are_exact PASSED [ 87%]
student-tests/unit/test_unit.py::test_basic_is_parsed_and_password_may_contain_colons PASSED [ 87%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[None] PASSED [ 87%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[] PASSED [ 87%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic] PASSED [ 88%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic \xe9] PASSED [ 88%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic !!!!] PASSED [ 88%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic bm8tY29sb24=] PASSED [ 88%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic //46cHc=] PASSED [ 89%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic OnBhc3N3b3Jk] PASSED [ 89%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic YWxpY2U6] PASSED [ 89%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic 0JDQu9C40YHQsDpwdw==] PASSED [ 90%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 90%]
student-tests/unit/test_unit.py::test_bad_basic_is_401_with_basic_challenge[Basic AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA] PASSED [ 90%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[None] PASSED [ 90%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[] PASSED [ 91%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Bearer] PASSED [ 91%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Bearer short] PASSED [ 91%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!] PASSED [ 91%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Basic YWxpY2U6cGFzc3dvcmQtMTIz] PASSED [ 92%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Token aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] PASSED [ 92%]
student-tests/unit/test_unit.py::test_bad_bearer_is_401_with_bearer_challenge[Bearer \xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9\xe9] PASSED [ 92%]
student-tests/unit/test_unit.py::test_bearer_ok PASSED [ 92%]
student-tests/unit/test_unit.py::test_argon2id_hash_and_verify PASSED [ 93%]
student-tests/unit/test_unit.py::test_s3_settings_are_validated_and_contract_limits_cannot_be_raised PASSED [ 93%]
student-tests/unit/test_unit.py::test_settings_read_secret_files_and_contract_names PASSED [ 93%]
student-tests/unit/test_unit.py::test_valid_idempotency_keys[a] PASSED [ 93%]
student-tests/unit/test_unit.py::test_valid_idempotency_keys[kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk] PASSED [ 94%]
student-tests/unit/test_unit.py::test_valid_idempotency_keys[A-Za-z0-9._:-] PASSED [ 94%]
student-tests/unit/test_unit.py::test_valid_idempotency_keys[2026-10-16T10:00:00.1] PASSED [ 94%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[None] PASSED [ 95%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[] PASSED [ 95%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk] PASSED [ 95%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[\u043a\u043b\u044e\u0447] PASSED [ 95%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[a b] PASSED [ 96%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[a/b] PASSED [ 96%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[a,b] PASSED [ 96%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[a\tb] PASSED [ 96%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[a\x00b] PASSED [ 97%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[*] PASSED [ 97%]
student-tests/unit/test_unit.py::test_invalid_idempotency_keys[\xe9] PASSED [ 97%]
student-tests/unit/test_unit.py::test_duplicate_keys_and_garbage_json_are_rejected[{"text":"a","text":"b"}] PASSED [ 97%]
student-tests/unit/test_unit.py::test_duplicate_keys_and_garbage_json_are_rejected[{"a":{"x":1,"x":2}}] PASSED [ 98%]
student-tests/unit/test_unit.py::test_duplicate_keys_and_garbage_json_are_rejected[\xff] PASSED [ 98%]
student-tests/unit/test_unit.py::test_duplicate_keys_and_garbage_json_are_rejected[{"text":"x"} {}] PASSED [ 98%]
student-tests/unit/test_unit.py::test_attachment_ids_absent_equals_empty_and_is_validated PASSED [ 98%]
student-tests/unit/test_unit.py::test_request_fingerprint_ignores_key_order_and_default_attachments PASSED [ 99%]
student-tests/unit/test_unit.py::test_instance_id_defaults_to_hostname_and_is_validated PASSED [ 99%]
student-tests/unit/test_unit.py::test_idempotency_ttl_cannot_be_below_24_hours PASSED [ 99%]
student-tests/unit/test_unit.py::test_message_write_path_setting PASSED [100%]
================= 377 passed, 4 skipped in 1515.54s (0:25:15) =================
[exit 0, 1516.9 s]
+74
View File
@@ -0,0 +1,74 @@
# make test-failover with scripts/stop-one: which container is really stopped, restore, repeat
# 2026-10-31T14:21:25Z, commit cf6e929 docs: PIPELINE, DEFENSE, DATA_MODEL, WINDOWS для lab5; черновик REPORT
--- run 1; running API replicas BEFORE:
mtusi-lab5-api-1 host=d08185c0e3f3 running exit=0 pid=91728 started=2026-10-31T14:21:03.235
mtusi-lab5-api-2 host=85c7cde066aa running exit=0 pid=91671 started=2026-10-31T14:21:02.858
$ make test-failover ACTION_SCRIPT=scripts/stop-one.cmd
python tests/resilience.py --mode failover --action-script "scripts/stop-one.cmd" --base-url "http://localhost:8080"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 126, "failed_attempts": 0, "first_recovery_seconds": 6.326}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
[exit 0, 19.4 s]
AFTER (the stopped replica, left stopped by the hook):
mtusi-lab5-api-1 host=d08185c0e3f3 exited exit=0 pid=0 started=2026-10-31T14:21:03.235
$ C:\Users\wfa22\AppData\Local\Python\pythoncore-3.14-64\python.exe scripts/lbctl.py status
api2 172.28.0.2 UP mtusi-lab5-api-2 X-Instance-Id=85c7cde066aa
(other slots: MAINT, no container)
[exit 0, 0.9 s]
$ sh scripts/restore-api.sh
mtusi-lab5-api-1 Up 6 seconds (healthy)
mtusi-lab5-api-2 Up 50 seconds (healthy)
Container mtusi-lab5-api-2 Running
Container mtusi-lab5-api-1 Starting
Container mtusi-lab5-api-1 Started
Container mtusi-lab5-api-2 Waiting
Container mtusi-lab5-api-1 Waiting
Container mtusi-lab5-api-2 Healthy
Container mtusi-lab5-api-1 Healthy
[exit 0, 6.9 s]
$ C:\Users\wfa22\AppData\Local\Python\pythoncore-3.14-64\python.exe scripts/lbctl.py wait-up 2
2 API replica(s) UP in HAProxy after 0.6 s: ['85c7cde066aa', 'd08185c0e3f3']
[exit 0, 1.4 s]
--- run 2; running API replicas BEFORE:
mtusi-lab5-api-1 host=d08185c0e3f3 running exit=0 pid=94963 started=2026-10-31T14:21:47.426
mtusi-lab5-api-2 host=85c7cde066aa running exit=0 pid=91671 started=2026-10-31T14:21:02.858
$ make test-failover ACTION_SCRIPT=scripts/stop-one.cmd
python tests/resilience.py --mode failover --action-script "scripts/stop-one.cmd" --base-url "http://localhost:8080"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 129, "failed_attempts": 0, "first_recovery_seconds": 6.074}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
[exit 0, 18.0 s]
AFTER (the stopped replica, left stopped by the hook):
mtusi-lab5-api-2 host=85c7cde066aa exited exit=0 pid=0 started=2026-10-31T14:21:02.858
$ C:\Users\wfa22\AppData\Local\Python\pythoncore-3.14-64\python.exe scripts/lbctl.py status
api1 172.28.0.3 UP mtusi-lab5-api-1 X-Instance-Id=d08185c0e3f3
(other slots: MAINT, no container)
[exit 0, 0.7 s]
$ sh scripts/restore-api.sh
mtusi-lab5-api-1 Up 34 seconds (healthy)
mtusi-lab5-api-2 Up 6 seconds (healthy)
Container mtusi-lab5-api-1 Running
Container mtusi-lab5-api-2 Starting
Container mtusi-lab5-api-2 Started
Container mtusi-lab5-api-2 Waiting
Container mtusi-lab5-api-1 Waiting
Container mtusi-lab5-api-2 Healthy
Container mtusi-lab5-api-1 Healthy
[exit 0, 7.4 s]
$ C:\Users\wfa22\AppData\Local\Python\pythoncore-3.14-64\python.exe scripts/lbctl.py wait-up 2
2 API replica(s) UP in HAProxy after 0.6 s: ['85c7cde066aa', 'd08185c0e3f3']
[exit 0, 1.6 s]
Replicas stopped by the public test across runs: ['mtusi-lab5-api-1', 'mtusi-lab5-api-2']
+38
View File
@@ -0,0 +1,38 @@
# make test-persistence: restart of LB, API replicas, relay, worker, PostgreSQL, Valkey, S3, RabbitMQ
# 2026-10-31T14:20:06Z, commit cf6e929 docs: PIPELINE, DEFENSE, DATA_MODEL, WINDOWS для lab5; черновик REPORT
Containers BEFORE:
mtusi-lab5-api-1 host=d08185c0e3f3 running exit=0 pid=83074 started=2026-10-31T14:18:45.487
mtusi-lab5-api-2 host=85c7cde066aa running exit=0 pid=82998 started=2026-10-31T14:18:45.132
mtusi-lab5-broker-1 host=broker running exit=0 pid=82136 started=2026-10-31T14:18:30.831
mtusi-lab5-lb-1 host=a22e1c19fc90 running exit=0 pid=83486 started=2026-10-31T14:18:51.489
mtusi-lab5-migrate-1 host=fa0a8a1c9191 exited exit=0 pid=0 started=2026-10-31T14:18:36.261
mtusi-lab5-postgres-1 host=7961919f90c9 running exit=0 pid=82047 started=2026-10-31T14:18:30.501
mtusi-lab5-relay-1 host=9b6249446ece running exit=0 pid=82799 started=2026-10-31T14:18:41.997
mtusi-lab5-s3-1 host=bdee3ea030a4 running exit=0 pid=81901 started=2026-10-31T14:18:29.927
mtusi-lab5-s3-init-1 host=2c85c6921c88 exited exit=0 pid=0 started=2026-10-31T14:18:38.517
mtusi-lab5-valkey-1 host=d53b8a88e5b5 running exit=0 pid=81977 started=2026-10-31T14:18:30.236
mtusi-lab5-worker-1 host=ee8c11f59aa8 running exit=0 pid=82939 started=2026-10-31T14:18:44.768
$ make test-persistence ACTION_SCRIPT=scripts/restart.cmd
python tests/resilience.py --mode persistence --action-script "scripts/restart.cmd" --base-url "http://localhost:8080"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
[exit 0, 76.0 s]
Containers AFTER (new pid/started for lb, api-*, relay, worker, postgres, valkey, s3, broker; volumes kept):
mtusi-lab5-api-1 host=d08185c0e3f3 running exit=0 pid=91728 started=2026-10-31T14:21:03.235
mtusi-lab5-api-2 host=85c7cde066aa running exit=0 pid=91671 started=2026-10-31T14:21:02.858
mtusi-lab5-broker-1 host=broker running exit=0 pid=89550 started=2026-10-31T14:20:17.480
mtusi-lab5-lb-1 host=a22e1c19fc90 running exit=0 pid=92390 started=2026-10-31T14:21:12.759
mtusi-lab5-migrate-1 host=fa0a8a1c9191 exited exit=0 pid=0 started=2026-10-31T14:21:14.217
mtusi-lab5-postgres-1 host=7961919f90c9 running exit=0 pid=89433 started=2026-10-31T14:20:16.605
mtusi-lab5-relay-1 host=9b6249446ece running exit=0 pid=92854 started=2026-10-31T14:21:16.976
mtusi-lab5-s3-1 host=bdee3ea030a4 running exit=0 pid=90402 started=2026-10-31T14:20:36.421
mtusi-lab5-s3-init-1 host=2c85c6921c88 exited exit=0 pid=0 started=2026-10-31T14:21:17.299
mtusi-lab5-valkey-1 host=d53b8a88e5b5 running exit=0 pid=89376 started=2026-10-31T14:20:16.424
mtusi-lab5-worker-1 host=ee8c11f59aa8 running exit=0 pid=93271 started=2026-10-31T14:21:22.639
$ C:\Users\wfa22\AppData\Local\Python\pythoncore-3.14-64\python.exe scripts/lbctl.py wait-up 2
2 API replica(s) UP in HAProxy after 0.6 s: ['85c7cde066aa', 'd08185c0e3f3']
[exit 0, 1.5 s]
+112
View File
@@ -0,0 +1,112 @@
# Track 2: bench/pipeline_faults.py (duplicate, reorder, crashes, stale versions, hung worker) + read-only audit of the invariants
# 2026-10-31T14:48:35Z, commit cf6e929 docs: PIPELINE, DEFENSE, DATA_MODEL, WINDOWS для lab5; черновик REPORT
$ C:\Users\wfa22\Desktop\Высоконагруженные приложения\lab5-clean\.venv\Scripts\python.exe bench/pipeline_faults.py --output evidence/track2 --uploads 5
[2026-10-31T14:48:37Z] baseline_no_faults
[2026-10-31T14:48:54Z] duplicate_publish
[2026-10-31T14:49:25Z] duplicate_and_reverse_order
[2026-10-31T14:49:56Z] relay_crash_after_confirm_before_mark
[2026-10-31T14:50:27Z] worker_crash_before_side_effect
[2026-10-31T14:51:19Z] worker_crash_after_s3_before_commit
[2026-10-31T14:52:05Z] worker_crash_after_commit_before_ack
[2026-10-31T14:53:10Z] transient_errors_then_success
[2026-10-31T14:53:42Z] two_workers_duplicate_publish
[2026-10-31T14:54:22Z] versions_scenario
[2026-10-31T14:55:08Z] queued_reorder_scenario
[2026-10-31T14:56:08Z] hung_worker_scenario
bcd68c4d813f0d14a490156098130cab5e63ae21352e9fc620b8ac85f48df995
bcd68c4d813f0d14a490156098130cab5e63ae21352e9fc620b8ac85f48df995
scenario uploads ready claims problems
baseline_no_faults 5 5 5 0
duplicate_publish 5 5 5 0
duplicate_and_reverse_order 5 5 5 0
relay_crash_after_confirm_before_mark 5 5 5 0
worker_crash_before_side_effect 5 5 14 0
worker_crash_after_s3_before_commit 5 5 10 0
worker_crash_after_commit_before_ack 5 5 5 0
transient_errors_then_success 5 5 15 0
two_workers_duplicate_publish 5 5 5 0
stale_version_and_reorder 1 - - 0
reordered_versions_in_queue 1 - 2 0
hung_worker_docker_pause 1 - 2 0
audit after all scenarios: ok=True violations=0 objects={'final': 523, 'staging': 2, 'published': 522, 'checksums_verified': True}
[exit 0, 515.1 s]
$ docker compose run --rm auditor --verify-checksums
{
"ok": true,
"violations": [],
"notes": [],
"attachments": {
"failed": 4,
"pending": 2,
"ready": 129
},
"jobs": {
"superseded": 2,
"succeeded": 131,
"failed": 6
},
"objects": {
"final": 523,
"staging": 2,
"published": 522,
"checksums_verified": true
}
}
Container mtusi-lab5-auditor-run-e2fdeabd6d0f Creating
Container mtusi-lab5-auditor-run-e2fdeabd6d0f Created
[exit 0, 7.2 s]
$ docker compose run --rm jobctl stats
{
"jobs": {
"failed": 6,
"succeeded": 131,
"superseded": 2
},
"outbox_unpublished": 0,
"outbox_due": 0
}
Container mtusi-lab5-jobctl-run-6f68d2c5bb69 Creating
Container mtusi-lab5-jobctl-run-6f68d2c5bb69 Created
[exit 0, 5.0 s]
$ C:\Users\wfa22\AppData\Local\Python\pythoncore-3.14-64\python.exe scripts/lbctl.py wait-up 2
2 API replica(s) UP in HAProxy after 0.7 s: ['1fb1ea74a42b', '492b7b24bd1f']
[exit 0, 1.7 s]
$ C:\Users\wfa22\AppData\Local\Python\pythoncore-3.14-64\python.exe tests/load.py --duration 30 --concurrency 4 --output evidence/load.json
{
"lab": 5,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.066,
"concurrency": 4,
"successful_requests": 5515,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 183.429,
"successful_latency_ms": {
"p50": 17.96,
"p95": 43.491,
"p99": 58.653
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
[exit 0, 31.5 s]
$ docker compose ps -a --format table {{.Service}} {{.Status}}
SERVICE STATUS
api Up 10 minutes (healthy)
api Up 11 minutes (healthy)
broker Up 23 minutes (healthy)
lb Up 30 minutes (healthy)
migrate Exited (0) About a minute ago
postgres Up 11 minutes (healthy)
relay Up 2 minutes (healthy)
s3 Up 9 minutes (healthy)
s3-init Exited (0) About a minute ago
valkey Up 13 minutes (healthy)
worker Up About a minute (healthy)
[exit 0, 0.4 s]
+277
View File
@@ -0,0 +1,277 @@
{
"experiment": "track 2: idempotency of the versioned pipeline under injected faults",
"started": "2026-10-31T14:48:37Z",
"finished": "2026-10-31T14:57:10Z",
"host": {
"os": "Windows-10-10.0.19045-SP0",
"python": "3.14.6"
},
"uploads_per_plain_scenario": 5,
"scenarios": [
{
"scenario": "baseline_no_faults",
"faults": {
"worker": {}
},
"uploads": 5,
"ready": 5,
"claims_total": 5,
"max_claims": 1,
"time_to_ready_s": {
"p50": 2.21,
"max": 3.15
},
"event_sequences": [
"created > claimed > succeeded"
],
"problems": {}
},
{
"scenario": "duplicate_publish",
"faults": {
"relay": {
"RELAY_FAULT_POINTS": "duplicate_publish"
}
},
"uploads": 5,
"ready": 5,
"claims_total": 5,
"max_claims": 1,
"time_to_ready_s": {
"p50": 1.89,
"max": 2.52
},
"event_sequences": [
"created > claimed > succeeded"
],
"problems": {}
},
{
"scenario": "duplicate_and_reverse_order",
"faults": {
"relay": {
"RELAY_FAULT_POINTS": "duplicate_publish,reverse_order"
}
},
"uploads": 5,
"ready": 5,
"claims_total": 5,
"max_claims": 1,
"time_to_ready_s": {
"p50": 1.89,
"max": 2.52
},
"event_sequences": [
"created > claimed > succeeded"
],
"problems": {}
},
{
"scenario": "relay_crash_after_confirm_before_mark",
"faults": {
"relay": {
"RELAY_FAULT_POINTS": "crash_after_publish"
}
},
"uploads": 5,
"ready": 5,
"claims_total": 5,
"max_claims": 1,
"time_to_ready_s": {
"p50": 1.89,
"max": 2.83
},
"event_sequences": [
"created > claimed > fault_injected > succeeded",
"created > claimed > succeeded"
],
"problems": {}
},
{
"scenario": "worker_crash_before_side_effect",
"faults": {
"worker": {
"WORKER_FAULT_POINTS": "crash_after_claim",
"JOB_LEASE_SECONDS": "6",
"ORPHAN_GRACE_SECONDS": "3",
"CLEANUP_INTERVAL_SECONDS": "1"
}
},
"uploads": 5,
"ready": 5,
"claims_total": 14,
"max_claims": 3,
"time_to_ready_s": {
"p50": 21.66,
"max": 21.68
},
"event_sequences": [
"created > claimed > fault_injected > lease_expired > claimed > lease_expired > claimed > succeeded",
"created > claimed > fault_injected > lease_expired > claimed > succeeded",
"created > claimed > lease_expired > claimed > fault_injected > lease_expired > claimed > succeeded"
],
"problems": {}
},
{
"scenario": "worker_crash_after_s3_before_commit",
"faults": {
"worker": {
"WORKER_FAULT_POINTS": "crash_after_s3_write",
"JOB_LEASE_SECONDS": "6",
"ORPHAN_GRACE_SECONDS": "3",
"CLEANUP_INTERVAL_SECONDS": "1"
}
},
"uploads": 5,
"ready": 5,
"claims_total": 10,
"max_claims": 2,
"time_to_ready_s": {
"p50": 15.49,
"max": 16.13
},
"event_sequences": [
"created > claimed > fault_injected > lease_expired > claimed > succeeded"
],
"problems": {}
},
{
"scenario": "worker_crash_after_commit_before_ack",
"faults": {
"worker": {
"WORKER_FAULT_POINTS": "crash_after_commit",
"JOB_LEASE_SECONDS": "6",
"ORPHAN_GRACE_SECONDS": "3",
"CLEANUP_INTERVAL_SECONDS": "1"
}
},
"uploads": 5,
"ready": 5,
"claims_total": 5,
"max_claims": 1,
"time_to_ready_s": {
"p50": 5.3,
"max": 8.4
},
"event_sequences": [
"created > claimed > succeeded > fault_injected"
],
"problems": {}
},
{
"scenario": "transient_errors_then_success",
"faults": {
"worker": {
"WORKER_FAULT_POINTS": "transient_error=2",
"JOB_RETRY_BASE_SECONDS": "0.5",
"JOB_LEASE_SECONDS": "6",
"ORPHAN_GRACE_SECONDS": "3",
"CLEANUP_INTERVAL_SECONDS": "1"
}
},
"uploads": 5,
"ready": 5,
"claims_total": 15,
"max_claims": 3,
"time_to_ready_s": {
"p50": 4.11,
"max": 4.13
},
"event_sequences": [
"created > claimed > retry_scheduled > claimed > retry_scheduled > claimed > succeeded"
],
"problems": {}
},
{
"scenario": "two_workers_duplicate_publish",
"faults": {
"worker": {}
},
"uploads": 5,
"ready": 5,
"claims_total": 5,
"max_claims": 1,
"time_to_ready_s": {
"p50": 1.58,
"max": 2.21
},
"event_sequences": [
"created > claimed > succeeded"
],
"problems": {}
},
{
"scenario": "stale_version_and_reorder",
"uploads": 1,
"statuses_seen_during_reprocess": [
"ready"
],
"job_states": [
"succeeded:v1",
"superseded:v2",
"succeeded:v3"
],
"published_version": 3,
"variant_rows_by_version": 6,
"objects": 10,
"events": [
"created",
"claimed",
"succeeded",
"created",
"claimed",
"created",
"claimed",
"succeeded",
"superseded"
],
"problems": []
},
{
"scenario": "reordered_versions_in_queue",
"job_states": [
"succeeded:v1",
"superseded:v2",
"succeeded:v3"
],
"claims": 2,
"published_version": 3,
"events": [
"created",
"claimed",
"succeeded",
"created",
"created",
"claimed",
"succeeded",
"superseded"
],
"problems": []
},
{
"scenario": "hung_worker_docker_pause",
"frozen": "bcd68c4d813f",
"claims": 2,
"events": [
"created",
"claimed",
"lease_expired",
"claimed",
"succeeded"
],
"problems": []
}
],
"audit_after_all": {
"ok": true,
"violations": [],
"notes": 0,
"objects": {
"final": 523,
"staging": 2,
"published": 522,
"checksums_verified": true
}
},
"violations": 0
}
+14
View File
@@ -0,0 +1,14 @@
scenario uploads ready claims problems
baseline_no_faults 5 5 5 0
duplicate_publish 5 5 5 0
duplicate_and_reverse_order 5 5 5 0
relay_crash_after_confirm_before_mark 5 5 5 0
worker_crash_before_side_effect 5 5 14 0
worker_crash_after_s3_before_commit 5 5 10 0
worker_crash_after_commit_before_ack 5 5 5 0
transient_errors_then_success 5 5 15 0
two_workers_duplicate_publish 5 5 5 0
stale_version_and_reorder 1 - - 0
reordered_versions_in_queue 1 - 2 0
hung_worker_docker_pause 1 - 2 0
audit after all scenarios: ok=True violations=0 objects={'final': 523, 'staging': 2, 'published': 522, 'checksums_verified': True}
+1
View File
@@ -0,0 +1 @@
[].
+24
View File
@@ -0,0 +1,24 @@
# RabbitMQ 4.3 of the lab 5 stand (compose service `broker`), mounted as conf.d/20-lab5.conf.
# Only AMQP 0-9-1 on 5672 inside the internal network `queue`: no management UI, no Prometheus
# listener (enabled_plugins is empty), nothing published on the host.
listeners.tcp.default = 5672
# Users, permissions and topology are imported from files at every boot (idempotent):
# /etc/rabbitmq/definitions.d/topology.json exchanges, quorum queues, bindings (this repo)
# /etc/rabbitmq/definitions.d/users.json users relay/worker + permissions (Docker secret,
# generated by scripts/init_secrets.py)
# With imported definitions no default `guest` user is created.
definitions.import_backend = local_filesystem
definitions.local.path = /etc/rabbitmq/definitions.d
definitions.skip_if_unchanged = false
# A delivery that stays unacked longer than this closes the consumer's channel and the message
# is returned to the queue (a worker that hangs while connected). Far above JOB_TIMEOUT_SECONDS.
consumer_timeout = 300000
# The container has a 512 MiB limit; flow control starts well before the cgroup OOM.
vm_memory_high_watermark.relative = 0.5
disk_free_limit.absolute = 200MB
log.console = true
log.console.level = info
+21
View File
@@ -0,0 +1,21 @@
{
"vhosts": [{"name": "/"}],
"exchanges": [
{"name": "messenger.jobs", "vhost": "/", "type": "direct", "durable": true, "auto_delete": false,
"internal": false, "arguments": {}},
{"name": "messenger.jobs.dlx", "vhost": "/", "type": "fanout", "durable": true, "auto_delete": false,
"internal": false, "arguments": {}}
],
"queues": [
{"name": "messenger.attachment-jobs", "vhost": "/", "durable": true, "auto_delete": false,
"arguments": {"x-queue-type": "quorum", "x-delivery-limit": 20, "x-dead-letter-exchange": "messenger.jobs.dlx"}},
{"name": "messenger.attachment-jobs.dlq", "vhost": "/", "durable": true, "auto_delete": false,
"arguments": {"x-queue-type": "quorum"}}
],
"bindings": [
{"source": "messenger.jobs", "vhost": "/", "destination": "messenger.attachment-jobs", "destination_type": "queue",
"routing_key": "attachment.process.v1", "arguments": {}},
{"source": "messenger.jobs.dlx", "vhost": "/", "destination": "messenger.attachment-jobs.dlq",
"destination_type": "queue", "routing_key": "", "arguments": {}}
]
}
+19 -12
View File
@@ -2,11 +2,14 @@
# Entry point of the compose service `s3` (SeaweedFS 4.46, one container: master + volume +
# filer + S3 gateway). Renders the S3 identities from Docker secrets, then execs `weed`.
#
# Identities (SeaweedFS s3.json, actions scoped to the bucket):
# bootstrap-admin Admin (create bucket) -> only s3-init has these keys
# messenger-api Read + Write on S3_BUCKET -> API replicas (no List, no Admin)
# messenger-reconciler Read + Write + List on S3_BUCKET -> reconciler CLI (needs the listing)
# There is NO anonymous identity, so every unsigned request is refused: the bucket is private.
# Two private buckets (lab 5): S3_STAGING_BUCKET holds originals accepted by the API before 202,
# S3_BUCKET holds the published originals and variants written by the worker.
# Identities (SeaweedFS s3.json, actions scoped to a bucket):
# bootstrap-admin Admin (create buckets) -> only s3-init has these keys
# messenger-api Write staging, Read final -> API replicas (no List, no Admin)
# messenger-worker Read + Write staging, Read + Write final -> worker (no List, no Admin)
# messenger-auditor Read + List both buckets (no Write) -> invariant checker (tools profile)
# There is NO anonymous identity, so every unsigned request is refused: the buckets are private.
#
# Exposure: master (9333), volume (8080), filer (8888) with their web UIs and gRPC listen on
# 127.0.0.1 INSIDE the container only (-ip.bind); only the S3 API port 8333 listens on the
@@ -15,6 +18,7 @@ set -eu
umask 077
secret() { tr -d '\r\n' < "/run/secrets/$1"; }
bucket="${S3_BUCKET:?S3_BUCKET is required}"
staging="${S3_STAGING_BUCKET:?S3_STAGING_BUCKET is required}"
cat > /tmp/s3.json <<EOF
{
"identities": [
@@ -23,17 +27,20 @@ cat > /tmp/s3.json <<EOF
"actions": ["Admin", "Read", "Write", "List", "Tagging"]},
{"name": "messenger-api",
"credentials": [{"accessKey": "$(secret s3_api_access_key_id)", "secretKey": "$(secret s3_api_secret_access_key)"}],
"actions": ["Read:${bucket}", "Write:${bucket}"]},
{"name": "messenger-reconciler",
"credentials": [{"accessKey": "$(secret s3_reconciler_access_key_id)", "secretKey": "$(secret s3_reconciler_secret_access_key)"}],
"actions": ["Read:${bucket}", "Write:${bucket}", "List:${bucket}"]}
"actions": ["Write:${staging}", "Read:${bucket}"]},
{"name": "messenger-worker",
"credentials": [{"accessKey": "$(secret s3_worker_access_key_id)", "secretKey": "$(secret s3_worker_secret_access_key)"}],
"actions": ["Read:${staging}", "Write:${staging}", "Read:${bucket}", "Write:${bucket}"]},
{"name": "messenger-auditor",
"credentials": [{"accessKey": "$(secret s3_auditor_access_key_id)", "secretKey": "$(secret s3_auditor_secret_access_key)"}],
"actions": ["Read:${staging}", "List:${staging}", "Read:${bucket}", "List:${bucket}"]}
]
}
EOF
# Memory: by default SeaweedFS buffers every in-flight upload without a limit and the Go runtime
# keeps freed heap; measured ~1 GB under 16 parallel 9.4 MiB PUTs (evidence/memory). The upload
# limits make excess PUTs wait inside SeaweedFS instead of growing the heap, and GOMEMLIMIT (set
# in compose.yaml below the container limit) makes the Go GC return memory before the cgroup OOM.
# keeps freed heap; measured ~1 GB under 16 parallel 9.4 MiB PUTs (lab 4). The upload limits make
# excess PUTs wait inside SeaweedFS instead of growing the heap, and GOMEMLIMIT (set in
# compose.yaml below the container limit) makes the Go GC return memory before the cgroup OOM.
exec weed server \
-dir=/data \
-ip=127.0.0.1 -ip.bind=127.0.0.1 \
+260
View File
@@ -0,0 +1,260 @@
-- 0005 (lab 5): asynchronous processing of attachments. Details: docs/PIPELINE.md.
--
-- Upload (API): INSERT attachment 'pending' (intent: the staging key is known before the PUT)
-- -> PUT original into the PRIVATE STAGING bucket
-- -> ONE transaction: attachment 'queued' + jobs row + outbox row -> 202.
-- Relay: outbox row -> publish to RabbitMQ with publisher confirm -> outbox.published_at.
-- Worker: claim job (lease + attempt token) -> variants into the final bucket under keys of
-- THIS attempt -> ONE transaction: variants + attachment 'ready' (fenced by the
-- lease token, never downgrading published_version) -> ack -> staging deleted.
--
-- PostgreSQL is the source of truth for the work: state, attempts, lease, backoff (available_at)
-- and the failed registry. The broker only delivers job ids (at least once).
-- ------------------------------------------------------------------ attachments
ALTER TABLE attachments DROP CONSTRAINT attachments_status;
ALTER TABLE attachments ADD CONSTRAINT attachments_status
CHECK (status IN ('pending', 'queued', 'processing', 'ready', 'failed'));
-- object_key = key of the ORIGINAL in the final bucket. NULL until the worker publishes it.
-- Keys of lab 4 ('o/<hex>') stay valid; lab 5 writes 'a/<attachment>/<attempt token>/original'.
ALTER TABLE attachments ALTER COLUMN object_key DROP NOT NULL;
ALTER TABLE attachments DROP CONSTRAINT attachments_object_key_format;
ALTER TABLE attachments ADD CONSTRAINT attachments_object_key_format
CHECK (object_key ~ '^(o/[0-9a-f]{32}|a/[0-9a-f-]{36}/[0-9a-f]{32}/original)$');
ALTER TABLE attachments
-- Key of the original in the staging bucket ('s/<128 random bits>'), written by the API.
ADD COLUMN staging_key text COLLATE "C",
-- none (lab 4 row) | present | deleting (marked, S3 DELETE pending) | deleted
ADD COLUMN staging_state text NOT NULL DEFAULT 'none',
-- pipeline version whose variants are published (GET shows them); only ever grows.
ADD COLUMN published_version integer,
ADD COLUMN error_code text,
ADD COLUMN failed_at timestamptz,
ADD CONSTRAINT attachments_staging_key_key UNIQUE (staging_key),
ADD CONSTRAINT attachments_staging_key_format CHECK (staging_key ~ '^s/[0-9a-f]{32}$'),
ADD CONSTRAINT attachments_staging_state CHECK (staging_state IN ('none', 'present', 'deleting', 'deleted')),
ADD CONSTRAINT attachments_staging_has_key CHECK (staging_state = 'none' OR staging_key IS NOT NULL),
ADD CONSTRAINT attachments_published_version CHECK (published_version >= 1),
ADD CONSTRAINT attachments_error_code CHECK (error_code ~ '^[a-z_]{1,64}$');
-- Lab 4 rows: a 'pending' intent of lab 4 never got its object confirmed and has no staging copy;
-- it becomes a failed upload (invisible: its id was never returned). A lab 4 'ready' row has its
-- original in the final bucket but no thumbnail yet: it is queued for pipeline 1 (below).
UPDATE attachments SET status = 'failed', error_code = 'upload_incomplete', failed_at = clock_timestamp()
WHERE status = 'pending';
UPDATE attachments SET status = 'queued' WHERE status = 'ready';
-- Structural guarantees (the database refuses a buggy cleanup or worker):
-- * work that is queued/processing always has a source: the published original or the staging
-- copy - the cleanup can never mark the staging of an accepted upload as deleting;
-- * ready = published original + published pipeline version; failed = error code.
ALTER TABLE attachments
ADD CONSTRAINT attachments_pending_staging CHECK (status <> 'pending' OR staging_state = 'present'),
ADD CONSTRAINT attachments_active_has_source
CHECK (status NOT IN ('queued', 'processing') OR object_key IS NOT NULL OR staging_state = 'present'),
ADD CONSTRAINT attachments_ready_published
CHECK (status <> 'ready' OR (object_key IS NOT NULL AND published_version IS NOT NULL)),
ADD CONSTRAINT attachments_failed_code
CHECK ((status = 'failed') = (error_code IS NOT NULL AND failed_at IS NOT NULL));
-- Janitor of the API: the lab 4 partial index on pending rows stays as is.
-- Cleanup of the worker: staging copies that may be deleted (ready: at once; failed: after retention).
CREATE INDEX attachments_staging_cleanup ON attachments (updated_at)
WHERE staging_state IN ('present', 'deleting') AND status IN ('ready', 'failed');
-- ------------------------------------------------------------------ jobs
-- One row = one logical piece of work: "build pipeline version V for attachment A".
-- job_id never changes on redelivery; `attempt` counts claims by workers (managed attempts).
CREATE TABLE jobs (
id uuid PRIMARY KEY,
attachment_id uuid NOT NULL REFERENCES attachments (id),
pipeline_version integer NOT NULL,
kind text NOT NULL, -- upload | replay | reprocess | migrate
replay_of uuid REFERENCES jobs (id),
state text NOT NULL DEFAULT 'queued',
attempt integer NOT NULL DEFAULT 0,
max_attempts integer NOT NULL,
available_at timestamptz NOT NULL DEFAULT clock_timestamp(), -- backoff: not before
lease_token uuid, -- token of the attempt that holds the job
lease_owner text,
lease_until timestamptz,
error_code text,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
finished_at timestamptz,
CONSTRAINT jobs_pipeline_version CHECK (pipeline_version >= 1),
CONSTRAINT jobs_kind CHECK (kind IN ('upload', 'replay', 'reprocess', 'migrate')),
CONSTRAINT jobs_replay CHECK ((kind = 'replay') = (replay_of IS NOT NULL)),
CONSTRAINT jobs_state CHECK (state IN ('queued', 'processing', 'succeeded', 'failed', 'superseded')),
CONSTRAINT jobs_attempts CHECK (attempt >= 0 AND max_attempts BETWEEN 1 AND 100 AND attempt <= max_attempts),
-- A lease exists exactly while the job is processing.
CONSTRAINT jobs_lease CHECK ((state = 'processing') = (lease_token IS NOT NULL AND lease_until IS NOT NULL)),
CONSTRAINT jobs_finished CHECK ((state IN ('succeeded', 'failed', 'superseded')) = (finished_at IS NOT NULL)),
CONSTRAINT jobs_failed_code CHECK (state <> 'failed' OR error_code IS NOT NULL),
CONSTRAINT jobs_error_code CHECK (error_code ~ '^[a-z_]{1,64}$')
);
-- At most ONE active job per effect set (attachment, pipeline version): a second upload job,
-- replay or reprocess of the same version cannot exist while one is queued/processing.
CREATE UNIQUE INDEX jobs_one_active ON jobs (attachment_id, pipeline_version) WHERE state IN ('queued', 'processing');
CREATE INDEX jobs_attachment ON jobs (attachment_id, created_at);
CREATE INDEX jobs_lease_expiry ON jobs (lease_until) WHERE state = 'processing'; -- reaper
CREATE INDEX jobs_queued ON jobs (updated_at) WHERE state = 'queued'; -- lost-message guard
CREATE INDEX jobs_failed ON jobs (finished_at) WHERE state = 'failed'; -- failed registry
-- One row per claim of a job by a worker. The token is part of every object key the attempt
-- writes, so the keys of an attempt are known without listing the bucket (planned_keys), and an
-- attempt that is no longer the lease holder can never publish (fencing by token).
CREATE TABLE job_attempts (
token uuid PRIMARY KEY,
job_id uuid NOT NULL REFERENCES jobs (id),
attempt integer NOT NULL,
worker text NOT NULL,
source text NOT NULL, -- staging | original
planned_keys text[] NOT NULL,
outcome text NOT NULL DEFAULT 'running',
error_code text,
started_at timestamptz NOT NULL DEFAULT clock_timestamp(),
finished_at timestamptz,
objects_cleaned_at timestamptz,
CONSTRAINT job_attempts_number UNIQUE (job_id, attempt),
CONSTRAINT job_attempts_source CHECK (source IN ('staging', 'original')),
CONSTRAINT job_attempts_outcome
CHECK (outcome IN ('running', 'succeeded', 'retry', 'failed', 'abandoned', 'superseded')),
CONSTRAINT job_attempts_finished CHECK ((outcome = 'running') = (finished_at IS NULL)),
-- Objects of a successful attempt are published: they are never cleaned.
CONSTRAINT job_attempts_cleaned CHECK (objects_cleaned_at IS NULL OR outcome NOT IN ('running', 'succeeded'))
);
CREATE INDEX job_attempts_cleanup ON job_attempts (finished_at)
WHERE outcome IN ('retry', 'failed', 'abandoned', 'superseded') AND objects_cleaned_at IS NULL;
-- Published variants. The primary key is the idempotency key of the EFFECT from the contract:
-- (attachment_id, pipeline_version, variant) exists at most once, whatever the deliveries.
CREATE TABLE attachment_variants (
attachment_id uuid NOT NULL REFERENCES attachments (id),
pipeline_version integer NOT NULL,
name text NOT NULL,
object_key text COLLATE "C" NOT NULL,
content_type text NOT NULL,
size_bytes integer NOT NULL,
width integer NOT NULL,
height integer NOT NULL,
sha256 bytea NOT NULL,
attempt_token uuid NOT NULL REFERENCES job_attempts (token),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (attachment_id, pipeline_version, name),
CONSTRAINT attachment_variants_key UNIQUE (object_key),
CONSTRAINT attachment_variants_key_format CHECK (object_key ~ '^a/[0-9a-f-]{36}/[0-9a-f]{32}/(thumbnail|crop|optimized)$'),
CONSTRAINT attachment_variants_name CHECK (name IN ('thumbnail', 'crop', 'optimized')),
CONSTRAINT attachment_variants_type CHECK (content_type IN ('image/jpeg', 'image/webp')),
CONSTRAINT attachment_variants_size CHECK (size_bytes >= 1 AND width >= 1 AND height >= 1),
CONSTRAINT attachment_variants_sha256 CHECK (octet_length(sha256) = 32)
);
-- Transactional outbox: written in the SAME transaction as the job (upload, retry, replay,
-- reprocess, lease expiry). The relay publishes due rows and marks them; a crash after the
-- publish but before the mark publishes again (a duplicate the worker ignores).
CREATE TABLE outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
job_id uuid NOT NULL REFERENCES jobs (id),
attempt integer NOT NULL, -- the attempt this delivery is meant for
available_at timestamptz NOT NULL DEFAULT clock_timestamp(),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
published_at timestamptz,
publish_failures integer NOT NULL DEFAULT 0,
CONSTRAINT outbox_attempt CHECK (attempt >= 1)
);
CREATE INDEX outbox_due ON outbox (available_at, id) WHERE published_at IS NULL;
CREATE INDEX outbox_job ON outbox (job_id);
CREATE INDEX outbox_published ON outbox (published_at) WHERE published_at IS NOT NULL; -- purge
-- Audit of every transition (no secrets, no file names): replay/reprocess requests with the
-- operator and reason, claims, retries with their delay, lease expiries, results.
CREATE TABLE job_events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
job_id uuid NOT NULL REFERENCES jobs (id),
at timestamptz NOT NULL DEFAULT clock_timestamp(),
event text NOT NULL,
attempt integer,
actor text NOT NULL,
error_code text,
detail jsonb NOT NULL DEFAULT '{}'
);
CREATE INDEX job_events_job ON job_events (job_id, id);
-- Failed registry for the operator (jobctl list-failed).
CREATE VIEW failed_jobs AS
SELECT j.id AS job_id, j.attachment_id, j.pipeline_version, j.kind, j.attempt, j.max_attempts, j.error_code,
j.finished_at, a.status AS attachment_status, a.staging_state
FROM jobs j JOIN attachments a ON a.id = j.attachment_id
WHERE j.state = 'failed';
-- Lab 4 'ready' rows (now queued): a job for pipeline 1 from their published original.
WITH queued AS (
SELECT a.id, gen_random_uuid() AS job_id FROM attachments a WHERE a.status = 'queued'
), created AS (
INSERT INTO jobs (id, attachment_id, pipeline_version, kind, max_attempts)
SELECT q.job_id, q.id, 1, 'migrate', 5 FROM queued q RETURNING id
)
INSERT INTO outbox (job_id, attempt) SELECT c.id, 1 FROM created c;
-- post_message_v3 = post_message_v2 (0004) with the lab 5 attachment states: queued, processing
-- and ready attachments of this chat may be attached; failed (or quarantined) -> 409; pending,
-- foreign or unknown -> 404. Everything else (key claim, chat clock, one transaction) unchanged.
CREATE FUNCTION post_message_v3(p_user uuid, p_chat uuid, p_key text, p_hash bytea, p_message uuid,
p_text bytea, p_ttl_seconds integer, p_attachments uuid[])
RETURNS TABLE (o_status text, o_id uuid, o_text bytea, o_created_at timestamptz, o_attachments uuid[])
LANGUAGE plpgsql VOLATILE AS $$
DECLARE
v_created timestamptz;
v_found integer;
v_usable integer;
v_check text := 'ok';
BEGIN
PERFORM 1 FROM chat_members m WHERE m.chat_id = p_chat AND m.user_id = p_user;
IF NOT FOUND THEN
RETURN QUERY SELECT 'not_found'::text, NULL::uuid, NULL::bytea, NULL::timestamptz, NULL::uuid[];
RETURN;
END IF;
IF cardinality(p_attachments) > 0 THEN
-- FOR SHARE: a concurrent transition to failed/quarantine waits until this message commits.
SELECT count(*), count(*) FILTER (WHERE a.lost_at IS NULL AND a.status <> 'failed') INTO v_found, v_usable
FROM (SELECT a.lost_at, a.status FROM attachments a
WHERE a.id = ANY (p_attachments) AND a.chat_id = p_chat AND a.status <> 'pending'
FOR SHARE) a;
IF v_found <> cardinality(p_attachments) THEN
v_check := 'attachment_not_found';
ELSIF v_usable <> v_found THEN
v_check := 'attachment_conflict';
END IF;
END IF;
IF v_check = 'ok' THEN
INSERT INTO idempotency_keys AS k (user_id, chat_id, key, request_hash, message_id)
VALUES (p_user, p_chat, p_key, p_hash, p_message)
ON CONFLICT (user_id, chat_id, key) DO UPDATE
SET request_hash = EXCLUDED.request_hash, message_id = EXCLUDED.message_id, created_at = clock_timestamp()
WHERE k.created_at < clock_timestamp() - make_interval(secs => p_ttl_seconds);
IF FOUND THEN
UPDATE chats c SET last_message_at = greatest(clock_timestamp(), c.last_message_at + interval '1 microsecond')
WHERE c.id = p_chat RETURNING c.last_message_at INTO v_created;
INSERT INTO messages (id, chat_id, sender_id, text, created_at, attachment_ids)
VALUES (p_message, p_chat, p_user, p_text, v_created, p_attachments);
INSERT INTO message_attachments (message_id, position, attachment_id)
SELECT p_message, (a.ord - 1)::smallint, a.id
FROM unnest(p_attachments) WITH ORDINALITY AS a(id, ord);
RETURN QUERY SELECT 'created'::text, p_message, p_text, v_created, p_attachments;
RETURN;
END IF;
END IF;
RETURN QUERY
SELECT CASE WHEN k.request_hash = p_hash THEN 'replayed' ELSE 'conflict' END, m.id, m.text, m.created_at,
m.attachment_ids
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
WHERE k.user_id = p_user AND k.chat_id = p_chat AND k.key = p_key;
IF NOT FOUND THEN
RETURN QUERY SELECT CASE WHEN v_check = 'ok' THEN 'retry' ELSE v_check END,
NULL::uuid, NULL::bytea, NULL::timestamptz, NULL::uuid[];
END IF;
END
$$;
+5 -1
View File
@@ -16,5 +16,9 @@ redis==8.1.0
argon2-cffi==25.1.0
# Lab 4: S3 client (async botocore over aiohttp; requests are cancellable, unlike libpq cancel).
aiobotocore==3.9.2
# Images are checked without Pillow: PNG by src/messenger/images.py, JPEG by libjpeg-turbo
# Lab 5: AMQP 0-9-1 client for RabbitMQ (publisher confirms, consumer acks, prefetch); last 9.x line.
aio-pika==9.6.2
# Lab 5: image variants in the worker only (thumbnail/crop JPEG, WebP). Same version as the tests.
pillow==12.3.0
# Uploads are still checked without Pillow: PNG by src/messenger/images.py, JPEG by libjpeg-turbo
# `djpeg -strict` (Debian package libjpeg-turbo-progs, see Dockerfile).
+105 -1
View File
@@ -4,6 +4,10 @@
#
# pip-compile --generate-hashes --no-emit-index-url --no-index --output-file=requirements.txt --strip-extras requirements.in
#
aio-pika==9.6.2 \
--hash=sha256:2a5478af920d169795071c9c09c7542cd8cdece60438cf7804533dcbcce93b7f \
--hash=sha256:c49e9246080dc8ffa1bb0e4aca407bf3d8ad78c3ee3a93df88b68fe65d7a49b9
# via -r requirements.in
aiobotocore==3.9.2 \
--hash=sha256:363b4892423b272eb84afbb58000da0be6ccd0cf8a68b98438c957d05b841efc \
--hash=sha256:8e32238c5bd77717ab1ac90077ff51ab141d025528115ccc7cc9b50b2d176e5f
@@ -179,6 +183,10 @@ aioitertools==0.13.0 \
--hash=sha256:0be0292b856f08dfac90e31f4739432f4cb6d7520ab9eb73e143f4f2fa5259be \
--hash=sha256:620bd241acc0bbb9ec819f1ab215866871b4bbd1f73836a55f799200ee86950c
# via aiobotocore
aiormq==6.9.4 \
--hash=sha256:0e7c01b662804e1cc7ace9a17794e8c1192a27fc2afa96162362a6e61ae8e8ef \
--hash=sha256:726a8586695e863fba68cf88842065ab12348c9438dcebdfc9d0bddaf6083277
# via aio-pika
aiosignal==1.4.0 \
--hash=sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e \
--hash=sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7
@@ -794,6 +802,99 @@ multidict==6.9.1 \
# aiobotocore
# aiohttp
# yarl
pamqp==3.3.0 \
--hash=sha256:40b8795bd4efcf2b0f8821c1de83d12ca16d5760f4507836267fd7a02b06763b \
--hash=sha256:c901a684794157ae39b52cbf700db8c9aae7a470f13528b9d7b4e5f7202f8eb0
# via aiormq
pillow==12.3.0 \
--hash=sha256:00808c5e14ef63ac5161091d242999076604ff74b883423a11e5d7bbb38bf756 \
--hash=sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a \
--hash=sha256:06ff022112bc9cbf83b60f8e028d94ad87b60621706487e65f673de61610ab59 \
--hash=sha256:0740a512dc522224c77d9aa5a8d70d8b7d73fb91f2c21125d8d025d3b8990e45 \
--hash=sha256:0847a763afefb695bc912d7c131e7e0632d4edc1d8698f58ddabec8e46b8b6d3 \
--hash=sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df \
--hash=sha256:0feb2e9d6ad6c9e3c06effe9d00f3f1e618a6643273576b016f591e9315a7139 \
--hash=sha256:10e41f0fbf1eec8cfd234b8fe17a4caac7c9d0db4c204d3c173a8f9f6ef3232b \
--hash=sha256:1182d52bc2d5e5d7d0949503aa7e36d12f42205dc287e4883f407b1988820d39 \
--hash=sha256:164b31cd1a0490ab6efae01aa5df49da7061be0af1b30e035b6e9a1bfe34ee6e \
--hash=sha256:1657923d2d45afb66526e5b933e5b3052e6bdea196c90d3abb2424e18c77dae8 \
--hash=sha256:186941b6aef820ad110fb01fb06eb925374dc3a21b17e37ec9a53b250c6fe2d1 \
--hash=sha256:1cca606cd25738df4ed873d5ad46bbdb3d83b5cbca291f6b4ff13a4df6b0bbe8 \
--hash=sha256:21900ce7ba264168cd50defae43cd75d25c833ad4ad6e73ffc5596d12e25ac89 \
--hash=sha256:236ff70b9312fb68943c703aa842ca6a758abfa45ac187a5e7c1452e96ef72b5 \
--hash=sha256:23aceaa007d6172b02c277f0cd359c79492bbb14f7072b4ede9fbcaf20648130 \
--hash=sha256:23d27a3e0307ec2244cc51e7287b919aa68d097504ebe19df4e76a98a3eea5bd \
--hash=sha256:24870b09b224f7ae3c39ed07d10e819d06f8720bc551847b1d623832b5b0e28d \
--hash=sha256:251bf95b67017e27b13d82f5b326234ca62d70f9cf4c2b9032de2358a3b12c7b \
--hash=sha256:25b9b82bb22e6e2b3cd07b39c68b7b862001226cb3dff7130d1cb914121b39ed \
--hash=sha256:28ce87c5ab450a9dd970b52e5aca5fe63ed432d18a2eaddd1979a00a1ba24ace \
--hash=sha256:300557495eb45ebb8aec96c2da9c4be642fbf7cd937278b4013ba894ea8eb0eb \
--hash=sha256:30f2aa603c41533cc25c05acd0da21636e84a315768feb631c937177db558931 \
--hash=sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510 \
--hash=sha256:37d6d0a00072fd2948eb22bce7e1475f34569d90c87c59f7a2ec59541b77f7a6 \
--hash=sha256:37dc8f7bbb66efe481bb60defacef820c950c24713fb44962ed6aa2a50966de1 \
--hash=sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce \
--hash=sha256:3edce1d53195db527e0191f84b71d02022de0540bf43a16ed734ed7537b07385 \
--hash=sha256:446c34dcc4324b084a53b705127dc15717b22c5e140ae0a3c38349d4efec071e \
--hash=sha256:4998562bf62a445225f22e07c896bb04b35b1b1f2eb6d760584c9c51d7a5f78c \
--hash=sha256:4b0a7fe987b14c31ebda6083f74f22b561fd3739bc0ac51e019622e3d72668c7 \
--hash=sha256:4e8c2a84d977f50b9daed6eeaf3baef67d00d5d74d932288f02cb94518ee3ace \
--hash=sha256:4f883547d4b7f0495ebe7056b0cc2aea76094e7a4abc8e933540f3271df27d9c \
--hash=sha256:514435a37670e3e5e08f3945b68718b6ed329bb84367777e16f9f4dfe1e61a0f \
--hash=sha256:53aa02d20d10c3d814d536aa4e5ac9b84ca0ff5a88377963b085ad6822f93e64 \
--hash=sha256:5594fc43d548a7ed94949d139aa1341b270f1863f11cfd37f5a6c8b778a6b67f \
--hash=sha256:571b9fcb07b97ef3a492028fb3d2dc0993ca23a06138b0315286566d29ef718a \
--hash=sha256:57b3d78c95ba9059768b10e28b813002261d3f3dfc55cc48b0c988f625175827 \
--hash=sha256:5afb51d599ea772b8365ae807ae557f18bccfe46ab261fd1c2a9ed700fc6eb17 \
--hash=sha256:6b02afb9b97f65fbca5f31db6a2a3ba21aa93030225f150fa3f249717e938fb4 \
--hash=sha256:6c0016e7b354317c4e9e525b937ac8596c38d2d232b419529b9cd7a1cd46e39a \
--hash=sha256:71d6097b330eea8fd15097780c8e89cb1a8ce7838669f48c5bacd6f663dd4701 \
--hash=sha256:756c768d0c9c2955feb7a56c37ea24aea2e369f8d36a88da270b6a9f19e62b5e \
--hash=sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91 \
--hash=sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66 \
--hash=sha256:85f998ea1848bc6757289e739cfbdda3a04adfd58b02fc018ce54d754a5ce468 \
--hash=sha256:8728f216dcdb6e6d555cf971cb34076139ad74b31fc2c14da4fafc741c5f6217 \
--hash=sha256:877c3f311ff35410f690861c4409e7ccbf0cd2f878e50628a28e5a0bb689e658 \
--hash=sha256:8cd2f7bdda092d99c9fc2fb7391354f306d01443d22785d0cbfafa2e2c8bb418 \
--hash=sha256:8e95e1385e4998ae9694eeaa4730ba5457ff61185b3a55e2e7bea0880aef452a \
--hash=sha256:962864dc93511324d51ddbb5b9f8731bf71675b93ca612a07441896f4688fb8c \
--hash=sha256:9cf95fe4d0f84c82d282745d9bb08ad9f926efa00be4697e767b814ce40d4330 \
--hash=sha256:9e881fca225083806662a5c43d627d215f258ff43c890f831966c7d7ba9c7402 \
--hash=sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09 \
--hash=sha256:a45650e8ce7fafffd731db8550230db6b0d306d181a90b67d3e6bca2f1990930 \
--hash=sha256:a876864214e136f0eb367788dbd7df045f4806801518e2cfe9e13229cfe06d8f \
--hash=sha256:ae26d61dfa7a47befdc7572b521024e8745f3d809bd95ca9505a7bba9ef849ec \
--hash=sha256:af8d94b0db561cf68b88a267c5c44b49e134f525d0dc2cb7ed413a66bc23559a \
--hash=sha256:b343699e8308bdc51978310e1c959c584e7869cc8c40780058c87da7781a1e94 \
--hash=sha256:b3c777e849237620b022f7f297dd67705f9f5cf1685f09f02e46f93e92725468 \
--hash=sha256:b629de27fda84b42cde7edef0d85f13b958b47f6e9bbcbba9b673c562a89bd8b \
--hash=sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965 \
--hash=sha256:ba54cfebe86920a559a7c4d6b9050791c20513650a1952ebe3368c7dc70306f8 \
--hash=sha256:bcb46e2f9feff8d06323983bd83ed00c201fdcab3d74973e7072a889b3979fcd \
--hash=sha256:bcc33feacfaefce60c12fd500a277533bdc02b10a19f7f6d348763d8140bbba7 \
--hash=sha256:bf16ba1b4d0b6b7c8e534936632270cf70eb00dbe09005bc345b2677b726855c \
--hash=sha256:cf1845d02ad822a369a49f2bb9345b1614744267682e7a03527dc3bf6eea1777 \
--hash=sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35 \
--hash=sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9 \
--hash=sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f \
--hash=sha256:dc624f6bc473dacdf7ef7eb8678d0d08edf15cd94fad6ae5c7d6cc67a4e4902f \
--hash=sha256:e158cb00350dc278f3b91551101aa7d12415a66ebf2c91d8d5ac14e56ddd3ad0 \
--hash=sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c \
--hash=sha256:e795b7eb908249c4e43c7c99fac7c2c75dab0c43566e37db472a355f63693d71 \
--hash=sha256:e7e480451b9fa137494bccd3a7d69adbe8ac65a87d97be61e11f1b1050a5bac3 \
--hash=sha256:e91206ee562682b51b98ef4b26a6ef48fd84e15fd4c4bc5ec768eb641d206838 \
--hash=sha256:e9871b1ffbfa9656b60aeee92ed5136a5742696006fa322b29ea3d8da0ecc9cf \
--hash=sha256:e9aeb04d6aef139de265b29683e119b638208f88cf73cdd1658aa07221165321 \
--hash=sha256:ebaea975e03d3141d9d3a507df75c9b3ec90fa9d2ffd07567b3a978d9d790b26 \
--hash=sha256:f0606c8bf2cdefea14a43530f7657cbbb7ecf1c4222512492ef4a4434a9501ec \
--hash=sha256:f13c32a3abd6079a66d9526e18dad9b6d280384d49d7c54040cd57b6424041d9 \
--hash=sha256:f7401aebd7f581d7f83a439d87d474999317ee099218e5ad25d125290990ba65 \
--hash=sha256:fa4ecea169a355be7a3ade2c783e2ed12f0e40d2c5621cda8b3297faf7fbb9f5 \
--hash=sha256:fbd139c8447d25dd750ab79ee274cc5e1fe80fc56340ab10b18a195e1b6eca3e \
--hash=sha256:fdafc9cce40277e0f7a0feabce0ee50dd2fa1800f3b38015e51296b5e814048d \
--hash=sha256:fe3cca2e4e8a592be0f269a1ca4835c25199d9f3ce815c8491048f785b0a0198 \
--hash=sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7
# via -r requirements.in
propcache==0.5.4 \
--hash=sha256:004e685b315646c410771836e72a44f143bbe624f29653a42687815069a303d5 \
--hash=sha256:02c0a34f16889cf800f10f0247a564d8ce6eeab6ffcd7c87198f769067eb8432 \
@@ -1353,4 +1454,7 @@ yarl==1.25.1 \
--hash=sha256:f53dcd26694f148f738edc052b5a69234833e739f10f4c3287bdfd8ec0f7b326 \
--hash=sha256:f61964f235a43738bfac50da46fc4254943a7eea3051aeb0b6fc7c992c29fadc \
--hash=sha256:fe01645169a2112aa1d4ebc3e4c5f029c5c8f97adfc32e5d37c993b39a994d75
# via aiohttp
# via
# aio-pika
# aiohttp
# aiormq
+32 -13
View File
@@ -1,12 +1,13 @@
#!/usr/bin/env python3
"""Run every check of REPORT.md on the current checkout and save the real output in evidence/.
python scripts/collect_evidence.py # ~60 min; the stand must NOT be running yet
python scripts/collect_evidence.py # ~90 min; the stand must NOT be running yet
Intended for a CLEAN CLONE (fresh volumes): it creates secrets and .env, builds and starts the
stand, then runs make check/validate/test/test-persistence/test-failover, the own tests, the
lab 4 experiments (memory under concurrent uploads, reconciler faults and cost), and records
container states before/after every hook. Prints no secrets
stand, then runs make check/validate/test/test-persistence/test-failover, the lab 5 defense
scenario (scripts/demo_pipeline.py), the own tests, the track 2 fault-injection matrix
(bench/pipeline_faults.py) and the invariant audit, and records container states before/after
every hook and the real resource limits (docker inspect). Prints no secrets
(hook output is shown by the public tests as suppressed; our scripts print names and states only).
On Windows the hooks are the scripts/*.cmd wrappers (Git Bash) and make needs Git's usr/bin.
"""
@@ -98,6 +99,13 @@ def main() -> int:
log.run(["docker", "compose", "logs", "--no-log-prefix", "migrate"])
log.run(["docker", "compose", "logs", "--no-log-prefix", "s3-init"]) # bucket + access-model verdicts
log.run([PYTHON, "scripts/lbctl.py", "replicas"]); log.run([PYTHON, "scripts/lbctl.py", "status"])
log.run(["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_users"])
log.run(["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", "type",
"durable", "messages", "consumers", "arguments"])
log.run(["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_permissions"])
ids = subprocess.run(["docker", "compose", "ps", "-q"], cwd=ROOT, capture_output=True, text=True).stdout.split()
log.run(["docker", "inspect", "-f", "{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}} "
"memswap={{.HostConfig.MemorySwap}} image={{.Config.Image}}", *ids], shown="docker inspect (limits)")
# venv for validate / own tests
if not Path(VENV_PY).exists():
log.run([PYTHON, "-m", "venv", ".venv"])
@@ -111,11 +119,13 @@ def main() -> int:
log.run([make, "test", f"PYTHON={MAKE_PY}"], shown="make test")
# 3. persistence with states before/after
log = Log("test-persistence.txt", "make test-persistence: restart of LB, all API replicas, PostgreSQL, Valkey, S3")
log = Log("test-persistence.txt", "make test-persistence: restart of LB, API replicas, relay, worker, PostgreSQL, "
"Valkey, S3, RabbitMQ")
log.note("Containers BEFORE:\n" + "\n".join(states()))
log.run([make, "test-persistence", f"ACTION_SCRIPT=scripts/restart{HOOK}", f"PYTHON={MAKE_PY}"],
shown=f"make test-persistence ACTION_SCRIPT=scripts/restart{HOOK}")
log.note("Containers AFTER (new pid/started for lb, api-*, postgres, valkey, s3; volumes kept):\n" + "\n".join(states()))
log.note("Containers AFTER (new pid/started for lb, api-*, relay, worker, postgres, valkey, s3, broker; volumes "
"kept):\n" + "\n".join(states()))
log.run([PYTHON, "scripts/lbctl.py", "wait-up", "2"])
# 4. failover: until BOTH replicas have been the stopped one (each run is a real public test)
@@ -144,16 +154,25 @@ def main() -> int:
break
log.note(f"Replicas stopped by the public test across runs: {sorted(stopped)}")
# 5. own tests
# 5. lab 5 defense scenario: worker stopped -> 202 -> 409 -> restart api+broker -> worker -> ready
log = Log("demo-pipeline.txt", "Defense steps 2-3: worker stopped, upload 202, content 409, restart API and broker "
"with volumes, worker started, ready + thumbnail")
log.note("Containers BEFORE:\n" + "\n".join(states()))
log.run([VENV_PY, "scripts/demo_pipeline.py"], shown="python scripts/demo_pipeline.py", timeout=900)
log.note("Containers AFTER (api-*, broker restarted; worker stopped and started):\n" + "\n".join(states()))
# 6. own tests
log = Log("student-tests.txt", "Own tests: unit + stand (pytest -v); failures restored in finally")
log.run([VENV_PY, "-m", "pytest", "student-tests", "-v", "-p", "no:cacheprovider"], shown="python -m pytest student-tests -v",
timeout=3600)
timeout=5400)
# 6. lab 4 experiments (level 4 memory, track 2 reconciler) and the public load script
log = Log("lab4-runs.txt", "Lab 4: memory under 16 simultaneous uploads, reconciler faults + cost, load.py")
log.run([VENV_PY, "bench/upload_memory.py", "--output", "evidence/memory"], timeout=3600)
log.run([VENV_PY, "bench/reconcile_faults.py", "--output", "evidence/reconcile"], timeout=1800)
log.run([VENV_PY, "bench/reconcile_cost.py", "--output", "evidence/reconcile"], timeout=3600)
# 7. track 2: fault-injection matrix + audit; lab 3 load script
log = Log("track2-runs.txt", "Track 2: bench/pipeline_faults.py (duplicate, reorder, crashes, stale versions, hung "
"worker) + read-only audit of the invariants")
log.run([VENV_PY, "bench/pipeline_faults.py", "--output", "evidence/track2", "--uploads", "5"], timeout=5400)
log.run(["docker", "compose", "run", "--rm", "--no-deps", "-T", "auditor", "--verify-checksums"],
shown="docker compose run --rm auditor --verify-checksums", timeout=900)
log.run(["docker", "compose", "run", "--rm", "--no-deps", "-T", "jobctl", "stats"], shown="docker compose run --rm jobctl stats")
log.run([PYTHON, "scripts/lbctl.py", "wait-up", "2"])
log.run([PYTHON, "tests/load.py", "--duration", "30", "--concurrency", "4", "--output", "evidence/load.json"])
log.run(["docker", "compose", "ps", "-a", "--format", "table {{.Service}}\t{{.Status}}"])
+15 -4
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env python3
"""Defense scenario, steps 1-2 (README): upload the fixture, send a message with attachment_ids,
"""Lab 4 defense scenario (kept in lab 5; upload is now 202 queued, the download waits for ready):
upload the fixture, send a message with attachment_ids,
download as the second member and compare SHA-256; the outsider gets 404; an unauthenticated
request straight to S3 (from inside the storage network) is refused, the signed one works.
@@ -67,6 +68,16 @@ def user(c: Client, label: str) -> dict:
return {"id": session["user"]["id"], "token": session["token"], "name": name}
def wait_ready(c: Client, actor: dict, attachment_id: str, timeout: float = 60):
import time
deadline = time.monotonic() + timeout
while True:
st, h, b = c.call("GET", f"/api/v1/attachments/{attachment_id}", token=actor["token"])
if st != 200 or json.loads(b)["status"] in ("ready", "failed") or time.monotonic() > deadline:
return st, h, b
time.sleep(0.3)
def main() -> int:
p = argparse.ArgumentParser()
p.add_argument("--base-url", default="http://127.0.0.1:8080")
@@ -77,7 +88,7 @@ def main() -> int:
alice, bob, eve = user(c, "alice"), user(c, "bob"), user(c, "eve")
print(f"users: alice, bob (members), eve (outsider)")
status, _, body = c.call("POST", "/api/v1/chats", token=alice["token"],
body={"title": "Демо lab4", "member_ids": [alice["id"], bob["id"]]})
body={"title": "Демо lab5", "member_ids": [alice["id"], bob["id"]]})
chat = json.loads(body)
print("\n1. upload -> message -> download by the second member")
@@ -88,8 +99,8 @@ def main() -> int:
st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"],
body={"text": "", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex})
show("POST /chats/{id}/messages text='' attachment_ids=[id]", st, h, b)
st, h, b = c.call("GET", f"/api/v1/attachments/{att['id']}", token=bob["token"])
show("GET /attachments/{id} (bob)", st, h, b)
st, h, b = wait_ready(c, bob, att["id"])
show("GET /attachments/{id} (bob) until ready", st, h, b)
st, h, got = c.call("GET", f"/api/v1/attachments/{att['id']}/content", token=bob["token"])
show("GET /attachments/{id}/content (bob)", st, h, got, binary=True)
same = hashlib.sha256(got).hexdigest() == hashlib.sha256(content).hexdigest() == att["sha256"]
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
"""Lab 5 defense scenario, steps 2-3 (README): worker stopped -> upload 202 -> content 409 while the
rest of the API works -> a message with the attachment is created -> API and broker restarted with
their volumes -> worker started -> the same attachment becomes ready, thumbnail downloadable.
python scripts/demo_pipeline.py [--base-url http://127.0.0.1:8080]
Prints every step with HTTP codes, IDs, the outbox row and the queue depth; never prints tokens or
keys. Creates synthetic users. Always starts the worker again at the end.
"""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import subprocess
import sys
import time
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from demo_attachments import FIXTURE, ROOT, Client, show, user, wait_ready # noqa: E402
def compose(*args: str, check: bool = True) -> str:
return subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True, encoding="utf-8",
check=check, timeout=300).stdout
def psql(sql: str) -> str:
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c", sql).strip()
def queue_depth() -> str:
"""messages/consumers of the jobs queue; rabbitmqctl refreshes these counters every ~5 s."""
time.sleep(6)
out = compose("exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", "messages", "consumers")
line = next(l for l in out.splitlines() if l.startswith("messenger.attachment-jobs\t"))
_, messages, consumers = line.split("\t")
return f"messages={messages} consumers={consumers}"
def wait_api(c: Client, timeout: float = 120) -> None:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
if c.call("GET", "/health/ready")[0] == 200:
return
except OSError:
pass
time.sleep(1)
raise SystemExit("API did not become ready")
def step(text: str) -> None:
print(f"\n[{time.strftime('%H:%M:%S')}] {text}")
def main() -> int:
p = argparse.ArgumentParser()
p.add_argument("--base-url", default="http://127.0.0.1:8080")
args = p.parse_args()
c = Client(args.base_url)
content = FIXTURE.read_bytes()
alice, bob = user(c, "alice"), user(c, "bob")
_, _, body = c.call("POST", "/api/v1/chats", token=alice["token"],
body={"title": "Демо lab5", "member_ids": [alice["id"], bob["id"]]})
chat = json.loads(body)
try:
step("1. docker compose stop worker")
compose("stop", "worker")
print(" " + compose("ps", "-a", "--format", "{{.Service}} {{.State}}", "worker").strip())
step("2. upload while the worker is stopped")
st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", token=alice["token"],
raw=content, headers={"Content-Type": "image/png"})
show("POST /chats/{id}/attachments", st, h, b)
att = json.loads(b)
print(f" attachment_id = {att['id']} status = {att['status']}")
for query in ("", "?variant=thumbnail"):
st, h, b = c.call("GET", f"/api/v1/attachments/{att['id']}/content{query}", token=bob["token"])
show(f"GET /attachments/{{id}}/content{query}", st, h, b)
st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/messages", token=bob["token"],
body={"text": "обычное сообщение работает"}, headers={"Idempotency-Key": uuid.uuid4().hex})
show("POST /messages (text only)", st, h, b)
st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"],
body={"text": "фото", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex})
show("POST /messages attachment_ids=[queued id]", st, h, b)
message_id = json.loads(b)["id"]
time.sleep(2)
print(" job + outbox in PostgreSQL: " + psql(
"SELECT j.id || ' state=' || j.state || ' attempt=' || j.attempt || ' | outbox published_at=' || "
f"coalesce(o.published_at::text, 'NULL') FROM jobs j JOIN outbox o ON o.job_id = j.id "
f"WHERE j.attachment_id = '{att['id']}'"))
print(" RabbitMQ queue messenger.attachment-jobs: " + queue_depth())
step("3. docker compose restart api broker (volumes preserved)")
compose("restart", "api", "broker")
wait_api(c)
time.sleep(3)
print(" RabbitMQ queue after the restart: " + queue_depth())
st, h, b = c.call("GET", f"/api/v1/attachments/{att['id']}", token=bob["token"])
show("GET /attachments/{id}", st, h, b)
finally:
step("4. docker compose start worker")
compose("start", "worker")
st, h, b = wait_ready(c, bob, att["id"], timeout=90)
show("GET /attachments/{id} until ready", st, h, b)
ready = json.loads(b)
thumb = next(v for v in ready["variants"] if v["name"] == "thumbnail")
st, h, data = c.call("GET", f"/api/v1/attachments/{att['id']}/content?variant=thumbnail", token=bob["token"])
show("GET /content?variant=thumbnail", st, h, data, binary=True)
from PIL import Image
size = Image.open(io.BytesIO(data)).size
ok = (st == 200 and hashlib.sha256(data).hexdigest() == thumb["sha256"] and size == (256, 160)
and ready["status"] == "ready")
print(f" thumbnail: real JPEG {size[0]}x{size[1]}, sha256 matches metadata: {ok}")
st, h, orig = c.call("GET", f"/api/v1/attachments/{att['id']}/content", token=bob["token"])
print(f" original unchanged byte for byte: {orig == content}")
print(f" message {message_id} still references it: "
f"{psql(f'SELECT attachment_ids FROM messages WHERE id = {chr(39)}{message_id}{chr(39)}')}")
step("5. job history (jobctl show)")
shown = json.loads(compose("run", "--rm", "--no-deps", "-T", "jobctl", "show", att["id"]))
for e in shown["events"]:
print(f" {e['at']} {e['event']:16} attempt={e['attempt']} actor={e['actor']}")
return 0 if ok and orig == content else 1
if __name__ == "__main__":
sys.exit(main())
+32 -5
View File
@@ -9,6 +9,9 @@ Delete ./secrets together with the volumes (`docker compose down -v`) to start o
"""
from __future__ import annotations
import base64
import hashlib
import json
import os
import secrets
import sys
@@ -24,8 +27,8 @@ def write(name: str, value: str) -> None:
print(f"keep secrets/{name}")
return
path.write_text(value + "\n", encoding="utf-8", newline="\n")
# Readable by the container users (postgres, valkey, seaweedfs, app uid 10001) through the
# compose bind mount. Local synthetic lab credentials only.
# Readable by the container users (postgres, valkey, seaweedfs, rabbitmq, app uid 10001)
# through the compose bind mount. Local synthetic lab credentials only.
os.chmod(path, 0o644)
print(f"created secrets/{name}")
@@ -34,17 +37,41 @@ def read(name: str) -> str:
return (SECRETS / name).read_text(encoding="utf-8").strip()
def rabbit_hash(password: str) -> str:
"""RabbitMQ `rabbit_password_hashing_sha256`: base64(salt + sha256(salt + password)), 4-byte salt.
The broker stores and compares only this hash; the plain password is in the client's URL."""
salt = secrets.token_bytes(4)
return base64.b64encode(salt + hashlib.sha256(salt + password.encode("utf-8")).digest()).decode("ascii")
def main() -> int:
SECRETS.mkdir(exist_ok=True)
write("postgres_password", secrets.token_urlsafe(24)) # [A-Za-z0-9_-]: safe inside URLs
write("valkey_password", secrets.token_urlsafe(24))
write("database_url", f"postgresql://messenger:{read('postgres_password')}@postgres:5432/messenger")
write("cache_url", f"redis://:{read('valkey_password')}@valkey:6379/0")
# Lab 4: three separate S3 key pairs (SeaweedFS identities, infra/seaweedfs/start.sh):
# admin = bucket bootstrap only; api = Read+Write on the bucket; reconciler = + List.
for who in ("admin", "api", "reconciler"):
# S3 key pairs (SeaweedFS identities, infra/seaweedfs/start.sh): admin = bucket bootstrap only;
# api = Write staging + Read final; worker = Read/Write both; auditor = Read + List (no Write).
for who in ("admin", "api", "worker", "auditor"):
write(f"s3_{who}_access_key_id", "AK" + secrets.token_hex(9).upper())
write(f"s3_{who}_secret_access_key", secrets.token_hex(20))
# Lab 5: RabbitMQ users. relay may only publish to the jobs exchange, worker may only consume
# the jobs queue; neither may declare/delete anything (configure "^$").
write("rabbitmq_relay_password", secrets.token_urlsafe(24))
write("rabbitmq_worker_password", secrets.token_urlsafe(24))
users = {
"users": [{"name": who, "password_hash": rabbit_hash(read(f"rabbitmq_{who}_password")),
"hashing_algorithm": "rabbit_password_hashing_sha256", "tags": []} for who in ("relay", "worker")],
"permissions": [
{"user": "relay", "vhost": "/", "configure": "^$", "write": "^messenger\\.jobs$", "read": "^$"},
{"user": "worker", "vhost": "/", "configure": "^$", "write": "^$", "read": "^messenger\\.attachment-jobs$"},
],
}
write("rabbitmq_users.json", json.dumps(users, indent=1))
for who in ("relay", "worker"):
# AMQP heartbeat 10 s: a frozen client loses its connection after ~2 missed heartbeats, and
# the broker returns its unacked messages to the queue for the other consumers.
write(f"broker_url_{who}", f"amqp://{who}:{read(f'rabbitmq_{who}_password')}@broker:5672/?heartbeat=10")
return 0
+12 -9
View File
@@ -1,18 +1,21 @@
#!/bin/sh
# Restart hook for `make test-persistence ACTION_SCRIPT=scripts/restart.sh`.
# Restarts EVERY process of the stand: LB, all API replicas, PostgreSQL, Valkey and S3 (SeaweedFS).
# Volumes, schema and data are preserved: no `down -v`, no FLUSH, no re-seed.
# Restarts EVERY process of the stand: LB, all API replicas, relay, worker(s), PostgreSQL, Valkey,
# S3 (SeaweedFS) and the broker (RabbitMQ). Volumes, schema, data and queued messages are
# preserved: no `down -v`, no FLUSH, no purge, no re-seed.
# Output is suppressed by the test; run it by hand to see the steps.
set -eu
cd "$(dirname "$0")/.."
# 1. Entry point and API first: no request is served while the stores restart underneath.
docker compose stop lb api
# 1. Entry point, API and the pipeline processes first: nothing is served or processed while the
# stores restart underneath.
docker compose stop lb api relay worker
# 2. Stores: clean shutdown (PostgreSQL checkpoint, Valkey AOF fsync, SeaweedFS volume/filer
# flush), then start again. The S3 bytes live on the named volume s3data.
docker compose restart postgres valkey s3
# 3. API replicas (wait for healthy stores via depends_on), then the LB. HAProxy resolves
# the new replica addresses through Docker DNS by itself - no stale backend list.
# flush, RabbitMQ quorum log), then start again. Bytes live on s3data, messages on rabbitmqdata.
docker compose restart postgres valkey s3 broker
# 3. API replicas (wait for healthy stores via depends_on), the LB, then relay and worker. HAProxy
# resolves the new replica addresses through Docker DNS by itself - no stale backend list.
docker compose start api
docker compose start lb
echo "restart.sh: lb, api (all replicas), postgres, valkey and s3 restarted with volumes preserved"
docker compose start relay worker
echo "restart.sh: lb, api (all replicas), relay, worker, postgres, valkey, s3 and broker restarted with volumes preserved"
+59 -34
View File
@@ -22,7 +22,7 @@ from starlette.types import ASGIApp, Message as AsgiMessage, Receive, Scope, Sen
from . import attachments, authhdr, cursor, docs, passwords, repo, validation
from .config import Settings
from .db import Database
from .errors import BASIC_CHALLENGE, ApiError, InvalidRequest, NotFound, PayloadTooLarge, Unauthorized, Unavailable
from .errors import BASIC_CHALLENGE, ApiError, Conflict, InvalidRequest, NotFound, PayloadTooLarge, Unauthorized, Unavailable
from .sessions import SessionStore, build_store
from .storage import ObjectMissing, Storage
from .timefmt import rfc3339
@@ -132,6 +132,10 @@ def storage_of(request: Request) -> Storage:
return request.app.state.storage
def staging_of(request: Request) -> Storage:
return request.app.state.staging
async def authenticate(request: Request) -> str:
"""User id of a valid Bearer session, otherwise 401. X-User-Id is ignored since lab 2.
@@ -363,16 +367,17 @@ async def list_messages(request: Request) -> JSONResponse:
return ok({"items": [m.to_json() for m in items], "next_cursor": next_cursor})
# ------------------------------------------------------------------ attachments (lab 4)
# ------------------------------------------------------------------ attachments (lab 4, lab 5)
def fault(request: Request, point: str) -> None:
"""Failure injection for the level 4 experiments (FAULT_POINTS, compose.faults.yaml only)."""
"""Failure injection for the experiments (FAULT_POINTS of the api service, compose variable
API_FAULT_POINTS; empty in normal runs)."""
if point in request.app.state.settings.fault_points:
log.warning("fault_injected", extra={"fields": {"request_id": request.state.request_id, "point": point}})
raise Unavailable("Внедрённый отказ: " + point)
async def upload_attachment(request: Request) -> JSONResponse:
"""POST /chats/{chat_id}/attachments?filename=...: raw PNG/JPEG -> 201 ready (attachments.py)."""
"""POST /chats/{chat_id}/attachments?filename=...: raw PNG/JPEG -> 202 queued (attachments.py)."""
settings: Settings = request.app.state.settings
reader = attachments.BodyReader(request)
slots: asyncio.Semaphore = request.app.state.upload_slots
@@ -406,23 +411,25 @@ async def upload_attachment(request: Request) -> JSONResponse:
async def store_upload(request: Request, db: Database, chat_id: str, user_id: str, filename: str,
upload: attachments.Upload) -> JSONResponse:
"""intent (pending) -> S3 PUT -> ready -> 201 (order and failure analysis: docs/CONSISTENCY.md)."""
"""intent (pending) -> staging PUT -> queued + job + outbox -> 202 (docs/PIPELINE.md).
No resize here: the worker does it; a stopped worker only delays `ready`."""
settings: Settings = request.app.state.settings
attachment_id = uuid.uuid4()
object_key = attachments.new_object_key()
storage = storage_of(request)
staging_key = attachments.new_staging_key()
await attachments.create_intent(db, attachment_id, chat_id, user_id, filename, upload.info, len(upload.data),
upload.sha256, object_key)
await storage.put(object_key, upload.data, upload.info.content_type,
{"attachment-id": str(attachment_id), "sha256": upload.sha256.hex()})
upload.sha256, staging_key)
await staging_of(request).put(staging_key, upload.data, upload.info.content_type,
{"attachment-id": str(attachment_id), "sha256": upload.sha256.hex()})
fault(request, "after_s3_put")
attachment = await attachments.mark_ready(db, attachment_id)
attachment = await attachments.enqueue(db, attachment_id, settings)
if attachment is None:
raise Unavailable("Загрузка не завершена, повторите запрос")
fault(request, "after_ready_commit")
log.info("attachment_created", extra={"fields": {"request_id": request.state.request_id,
"attachment_id": attachment.id, "chat_id": chat_id,
"size": attachment.size_bytes, "type": attachment.content_type}})
return ok(attachment.to_json(), 201)
fault(request, "after_enqueue_commit")
log.info("attachment_queued", extra={"fields": {"request_id": request.state.request_id,
"attachment_id": attachment.id, "chat_id": chat_id,
"size": attachment.size_bytes, "type": attachment.content_type,
"pipeline_version": settings.pipeline_version}})
return ok(attachment.to_json(), 202)
async def get_attachment(request: Request) -> JSONResponse:
@@ -439,46 +446,60 @@ def content_disposition(filename: str) -> str:
async def download_attachment(request: Request) -> Response:
"""Original bytes through the authorized API: no redirect, no public S3 URL. Streamed from
S3 in 64 KiB chunks (memory per download does not depend on the file size)."""
"""Original or variant bytes through the authorized API: no redirect, no public S3 URL.
queued/processing/failed -> 409 (not ready); a variant a ready attachment lacks -> 404.
Streamed from S3 in 64 KiB chunks (memory per download does not depend on the file size)."""
user_id = await authenticate(request)
attachment_id = path_uuid(request, "attachment_id")
query = validation.query_items(request.scope["query_string"])
try:
validation.variant_param(query)
except validation.NotFoundVariant:
variant = validation.variant_param(query)
except ApiError:
await attachments.get_visible(db_of(request), user_id, attachment_id) # 404 for outsiders first
raise NotFound("Такого варианта у вложения нет") from None
raise
attachment = await attachments.get_visible(db_of(request), user_id, attachment_id)
if attachment.status != "ready":
raise Conflict("Обработка вложения не удалась" if attachment.status == "failed" else "Вложение ещё не готово")
if attachment.lost:
raise NotFound("Оригинал вложения утрачен")
if variant == "original":
key, size_expected, media_type, etag = (attachment.object_key, attachment.size_bytes,
attachment.content_type, attachment.sha256)
name = attachment.filename
else:
found = attachment.variant(variant)
if found is None:
raise NotFound("Такого варианта у вложения нет")
key, size_expected, media_type, etag = found.object_key, found.size_bytes, found.content_type, found.sha256
stem = attachment.filename.rsplit(".", 1)[0] or "image"
name = stem + "-" + variant + (".webp" if media_type == "image/webp" else ".jpg")
try:
size, chunks = await storage_of(request).open_stream(attachment.object_key)
size, chunks = await storage_of(request).open_stream(key)
except ObjectMissing:
# A ready row without its object: data loss, reported by the reconciler (quarantine).
log.error("attachment_object_missing", extra={"fields": {"request_id": request.state.request_id,
"attachment_id": attachment.id}})
raise NotFound("Оригинал вложения утрачен") from None
if size != attachment.size_bytes:
"attachment_id": attachment.id, "variant": variant}})
raise Unavailable("Файл вложения временно недоступен") from None
if size != size_expected:
log.error("attachment_size_mismatch", extra={"fields": {"request_id": request.state.request_id,
"attachment_id": attachment.id}})
"attachment_id": attachment.id, "variant": variant}})
await chunks.aclose()
raise Unavailable("Оригинал вложения временно недоступен")
raise Unavailable("Файл вложения временно недоступен")
headers = {
"Content-Length": str(size),
"Content-Disposition": content_disposition(attachment.filename),
"Content-Disposition": content_disposition(name),
"X-Content-Type-Options": "nosniff",
"Cache-Control": "private, no-store",
"ETag": '"' + attachment.sha256 + '"',
"ETag": '"' + etag + '"',
}
return StreamingResponse(chunks, media_type=attachment.content_type, headers=headers)
return StreamingResponse(chunks, media_type=media_type, headers=headers)
def create_app(settings: Settings | None = None) -> Starlette:
settings = settings or Settings.from_env()
db = Database(settings)
sessions = build_store(settings, db)
storage = Storage(settings)
storage = Storage(settings) # final bucket: Read
staging = Storage(settings, bucket=settings.s3_staging_bucket) # staging bucket: Write (+ janitor DELETE)
async def purge_loop() -> None:
"""Housekeeping: expired Idempotency-Key rows (older than IDEMPOTENCY_TTL_SECONDS)."""
@@ -492,12 +513,12 @@ def create_app(settings: Settings | None = None) -> Starlette:
pass # database unavailable right now; next round
async def janitor_loop(every: float) -> None:
"""Level 4 cleanup: intents of failed uploads older than PENDING_GRACE_SECONDS (attachments.py).
"""Cleanup of intents of failed uploads older than PENDING_GRACE_SECONDS (attachments.py).
Every replica runs it; the advisory lock lets one round run at a time."""
while True:
await asyncio.sleep(every * (0.5 + random.random()))
try:
removed = await attachments.clean_stale_pending(db, storage, settings.pending_grace_seconds)
removed = await attachments.clean_stale_pending(db, staging, settings.pending_grace_seconds)
if removed:
log.info("stale_uploads_removed", extra={"fields": {"count": removed}})
except ApiError:
@@ -524,11 +545,13 @@ def create_app(settings: Settings | None = None) -> Starlette:
passwords.configure(settings.hash_concurrency)
await db.open()
await storage.open()
await staging.open()
log.info("dependencies_configured", extra={"fields": {
"session_store": sessions.name, "session_ttl_s": settings.session_ttl_seconds,
"db_pool_max": settings.db_pool_max, "db_timeout_s": settings.db_timeout_seconds,
"instance_id": settings.instance_id, "drain_s": settings.drain_seconds,
"message_write_path": settings.message_write_path, "s3_bucket": settings.s3_bucket,
"s3_staging_bucket": settings.s3_staging_bucket, "pipeline_version": settings.pipeline_version,
"upload_concurrency": settings.upload_concurrency, "verify_concurrency": settings.image_verify_concurrency,
"pending_grace_s": settings.pending_grace_seconds,
"fault_points": sorted(settings.fault_points)}})
@@ -543,6 +566,7 @@ def create_app(settings: Settings | None = None) -> Starlette:
for task in tasks:
task.cancel()
await sessions.close()
await staging.close()
await storage.close()
await db.close()
@@ -578,6 +602,7 @@ def create_app(settings: Settings | None = None) -> Starlette:
app.state.db = db
app.state.sessions = sessions
app.state.storage = storage
app.state.staging = staging
app.state.upload_slots = asyncio.Semaphore(settings.upload_concurrency)
app.state.verify_slots = asyncio.Semaphore(settings.image_verify_concurrency)
app.state.draining = False
+86 -47
View File
@@ -1,26 +1,29 @@
"""Attachments (lab 4): metadata in PostgreSQL, original bytes in the private S3 bucket.
"""Attachments: metadata in PostgreSQL, bytes in private S3 buckets (lab 4), processed
asynchronously by the worker (lab 5, docs/PIPELINE.md).
Upload (POST /chats/{id}/attachments, raw PNG/JPEG body), in this order:
auth -> membership (404) -> filename / Content-Type / Content-Length (400/415/413)
-> upload slot (at most UPLOAD_CONCURRENCY bodies per replica, else 503 + Retry-After)
-> body in chunks: size limit, read deadline, format + pixel count from the first bytes
-> full integrity check (images.verify) -> SHA-256 / size known
-> INSERT row status='pending' with a fresh random object_key, COMMIT (intent)
-> PUT object to S3 (Content-MD5)
-> UPDATE status='ready' WHERE status='pending', COMMIT -> 201 ready.
-> full integrity check (images.verify) -> SHA-256 / size known (415 is decided HERE)
-> INSERT row status='pending' with a fresh random staging key, COMMIT (intent)
-> PUT the original into the STAGING bucket (Content-MD5)
-> ONE transaction: status 'pending' -> 'queued' + jobs row + outbox row, COMMIT
-> 202 queued.
Why 201 is honest: it is sent only after BOTH the object and the ready row are durable.
What a failure between the steps leaves behind, and who removes it (docs/CONSISTENCY.md):
What is durable at 202: the complete, verified original in the staging bucket (S3 confirmed the
PUT and its MD5), the metadata row, the job and the outbox row that makes the relay publish it.
A crash of the API after the answer loses nothing; a broker that is down only delays the publish.
* before the intent COMMIT: nothing (no object was written);
* after the intent, before/while PUT, before the ready COMMIT: a 'pending' row (+ maybe the
object). The client got 503 and may retry (a new attachment). The janitor (below) deletes the
object - idempotent, a missing key is fine - and then the row, once it is older than
PENDING_GRACE_SECONDS. Nothing is compensated in the request path: after a lost answer of
COMMIT we do not know whether the row is ready, and deleting the object could destroy a
ready attachment. Only the janitor decides, under a row lock, from the committed state;
* after the ready COMMIT (answer lost): a correct ready attachment the client does not know.
Failures between the steps (docs/PIPELINE.md, failure windows):
* before the intent COMMIT: nothing was written;
* after the intent, before/while PUT, or between PUT and the job COMMIT (FAULT_POINTS=after_s3_put):
a 'pending' row (+ maybe the staging object), invisible to everybody (404). The client got 503
and may retry (a new attachment). The janitor deletes the staging object - idempotent - and then
the row once it is older than PENDING_GRACE_SECONDS, deciding under the row lock;
* after the job COMMIT, answer lost (FAULT_POINTS=after_enqueue_commit): a correct queued
attachment the client does not know; the worker processes it as usual.
"""
from __future__ import annotations
@@ -36,11 +39,11 @@ import psycopg
from psycopg import errors as pg_errors
from starlette.requests import Request
from . import images
from . import images, jobs
from .config import Settings
from .db import Database
from .errors import ApiError, InvalidRequest, NotFound, PayloadTooLarge, Unavailable, UnsupportedMediaType
from .storage import OBJECT_PREFIX, Storage
from .storage import STAGING_PREFIX, Storage
from .timefmt import rfc3339
log = logging.getLogger("messenger.attachments")
@@ -48,6 +51,21 @@ log = logging.getLogger("messenger.attachments")
JANITOR_LOCK_ID = 2026_04 # advisory lock: one janitor round at a time across all replicas
@dataclass(frozen=True, slots=True)
class Variant:
name: str
content_type: str
size_bytes: int
width: int
height: int
sha256: str
object_key: str
def to_json(self) -> dict:
return {"name": self.name, "content_type": self.content_type, "size_bytes": self.size_bytes,
"width": self.width, "height": self.height, "sha256": self.sha256}
@dataclass(frozen=True, slots=True)
class Attachment:
id: str
@@ -57,100 +75,121 @@ class Attachment:
content_type: str
size_bytes: int
sha256: str
object_key: str
object_key: str | None # published original in the final bucket (None until the worker publishes it)
status: str
created_at: dt.datetime
updated_at: dt.datetime
lost: bool = False
error_code: str | None = None
published_version: int | None = None
variants: tuple[Variant, ...] = ()
def to_json(self) -> dict:
"""Public representation: no object key, no bucket, no internal state."""
"""Public representation: no object keys, no buckets, no job internals."""
return {"id": self.id, "chat_id": self.chat_id, "owner_id": self.owner_id, "filename": self.filename,
"content_type": self.content_type, "size_bytes": self.size_bytes, "sha256": self.sha256,
"status": "ready", "variants": [], "error_code": None,
"status": self.status, "variants": [v.to_json() for v in self.variants] if self.status == "ready" else [],
"error_code": self.error_code if self.status == "failed" else None,
"created_at": rfc3339(self.created_at), "updated_at": rfc3339(self.updated_at)}
def variant(self, name: str) -> Variant | None:
return next((v for v in self.variants if v.name == name), None)
COLUMNS = ("a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.object_key, "
"a.status, a.created_at, a.updated_at, a.lost_at IS NOT NULL")
"a.status, a.created_at, a.updated_at, a.lost_at IS NOT NULL, a.error_code, a.published_version")
def _attachment(row) -> Attachment:
def _attachment(row, variants: tuple[Variant, ...] = ()) -> Attachment:
return Attachment(str(row[0]), str(row[1]), str(row[2]), row[3], row[4], row[5], bytes(row[6]).hex(), row[7],
row[8], row[9], row[10], row[11])
row[8], row[9], row[10], row[11], row[12], row[13], variants)
def new_object_key() -> str:
def new_staging_key() -> str:
"""Server-generated, 128 random bits, unrelated to the attachment id and the filename."""
return OBJECT_PREFIX + secrets.token_hex(16)
return STAGING_PREFIX + secrets.token_hex(16)
# ------------------------------------------------------------------ SQL
async def create_intent(db: Database, attachment_id: uuid.UUID, chat_id: str, owner_id: str, filename: str,
info: images.ImageInfo, size: int, sha256: bytes, object_key: str) -> None:
info: images.ImageInfo, size: int, sha256: bytes, staging_key: str) -> None:
async def work(conn: psycopg.AsyncConnection) -> None:
await conn.execute(
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, "
"width, height, object_key, status) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'pending')",
"width, height, staging_key, staging_state, status) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'present', 'pending')",
(attachment_id, chat_id, owner_id, filename, info.content_type, size, sha256, info.width, info.height,
object_key))
staging_key))
try:
await db.run(work, transaction=False)
except pg_errors.ForeignKeyViolation:
raise NotFound("Чат не найден") from None
async def mark_ready(db: Database, attachment_id: uuid.UUID) -> Attachment | None:
"""pending -> ready. None if the row is no longer pending (the janitor removed a stale intent)."""
async def enqueue(db: Database, attachment_id: uuid.UUID, settings: Settings) -> Attachment | None:
"""pending -> queued + job + outbox row in ONE transaction (the durable handoff before 202).
None if the row is no longer pending (the janitor removed a stale intent)."""
async def work(conn: psycopg.AsyncConnection) -> Attachment | None:
cur = await conn.execute(
"UPDATE attachments a SET status = 'ready', updated_at = clock_timestamp() "
"UPDATE attachments a SET status = 'queued', updated_at = clock_timestamp() "
f"WHERE a.id = %s AND a.status = 'pending' RETURNING {COLUMNS}", (attachment_id,))
row = await cur.fetchone()
return _attachment(row) if row else None
return await db.run(work, transaction=False)
if row is None:
return None
await jobs.create_job(conn, attachment_id, settings.pipeline_version, "upload", settings.job_max_attempts,
"api:" + settings.instance_id)
return _attachment(row)
return await db.run(work)
async def get_visible(db: Database, user_id: str, attachment_id: str) -> Attachment:
"""A READY attachment of a chat the user is a member of; anything else is 404 (unknown,
foreign chat, unfinished upload) - existence of foreign objects is never revealed."""
"""An attachment of a chat the user is a member of, in any state but the invisible intent
'pending'; anything else is 404 (unknown, foreign chat, unfinished upload) - existence of
foreign objects is never revealed. A ready attachment comes with its published variants."""
async def work(conn: psycopg.AsyncConnection) -> Attachment:
cur = await conn.execute(
f"SELECT {COLUMNS} FROM attachments a "
"JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = %s "
"WHERE a.id = %s AND a.status = 'ready'", (user_id, attachment_id))
"WHERE a.id = %s AND a.status <> 'pending'", (user_id, attachment_id))
row = await cur.fetchone()
if row is None:
raise NotFound("Вложение не найдено")
return _attachment(row)
return await db.run(work, transaction=False)
variants: tuple[Variant, ...] = ()
if row[8] == "ready":
cur = await conn.execute(
"SELECT name, content_type, size_bytes, width, height, sha256, object_key FROM attachment_variants "
"WHERE attachment_id = %s AND pipeline_version = %s "
"ORDER BY array_position(ARRAY['thumbnail', 'crop', 'optimized'], name)", (row[0], row[13]))
variants = tuple(Variant(r[0], r[1], r[2], r[3], r[4], bytes(r[5]).hex(), r[6]) for r in await cur.fetchall())
return _attachment(row, variants)
# REPEATABLE READ is not needed: the variant rows of a published version never change.
return await db.run(work)
async def clean_stale_pending(db: Database, storage: Storage, grace_seconds: int, batch: int = 20) -> int:
"""Janitor round: remove intents of uploads that never became ready.
async def clean_stale_pending(db: Database, staging: Storage, grace_seconds: int, batch: int = 20) -> int:
"""Janitor round: remove intents of uploads that never got their job (no 202 was sent).
Under FOR UPDATE: an upload that is (impossibly) still running would block on the row in
mark_ready and then find it gone (-> 503), so a ready attachment can never lose its object.
Order: object first (idempotent), row second; a crash in between leaves the pending row and
the next round repeats. Only status='pending' rows older than the grace period are touched:
fresh uploads and ready/used attachments are never selected.
enqueue() and then find it gone (-> 503). Order: staging object first (idempotent), row second;
a crash in between leaves the pending row and the next round repeats. Only status='pending'
rows older than the grace period are touched: queued/processing/ready/failed never.
"""
async def work(conn: psycopg.AsyncConnection) -> int:
cur = await conn.execute("SELECT pg_try_advisory_xact_lock(%s)", (JANITOR_LOCK_ID,))
if not (await cur.fetchone())[0]:
return 0
cur = await conn.execute(
"SELECT id, object_key FROM attachments WHERE status = 'pending' "
"SELECT id, staging_key FROM attachments WHERE status = 'pending' "
"AND created_at < clock_timestamp() - make_interval(secs => %s) "
"ORDER BY created_at LIMIT %s FOR UPDATE SKIP LOCKED", (grace_seconds, batch))
rows = await cur.fetchall()
if not rows:
return 0
await asyncio.gather(*(storage.delete(key) for _, key in rows))
await asyncio.gather(*(staging.delete(key) for _, key in rows))
await conn.execute("DELETE FROM attachments WHERE id = ANY(%s) AND status = 'pending'",
([r[0] for r in rows],))
return len(rows)
return await db.run(work, deadline=storage.timeout + 5)
return await db.run(work, deadline=staging.timeout + 5)
# ------------------------------------------------------------------ request body
+190
View File
@@ -0,0 +1,190 @@
"""Track 2: read-only checker of the pipeline invariants: `python -m messenger.audit`
(compose service `auditor`, profile tools; `make audit`).
Read-only by construction: every database transaction is `READ ONLY` (PostgreSQL refuses any
write), and the S3 key pair of the auditor has Read + List only. Output: one JSON report; exit 1
if any invariant is violated.
Invariants (docs/PIPELINE.md):
I1 no lost work - a queued/processing attachment has an active job; an active job has an
outbox row (published or due) - nothing waits for a message that nobody sends.
I2 one effect - per (attachment, pipeline_version) either no variant rows or exactly the
three variants, all written by ONE successful attempt of a job of that version.
I3 published data - every published object (original, variants) exists with the stored size
(--verify-checksums: and the stored SHA-256).
I4 monotonic - published_version = the highest version with a succeeded job; a ready
attachment is never queued/processing again (published_version stays set).
I5 source kept - an active job whose original is not published still has its staging copy
(state present AND the object exists in the staging bucket).
I6 no stray data - every object in the buckets is referenced: published, staging of a live row,
or planned by an attempt whose objects were not cleaned yet. An object of an
already cleaned attempt is reported as `leaked_object` (written by a stalled
attempt after its cleanup: garbage, never a loss).
I7 attempts - a succeeded job has exactly one succeeded attempt; at most one running attempt
per job, and it is the lease holder.
"""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
import sys
from .config import ConfigError, Settings
from .db import Database
from .errors import Unavailable
from .pipeline import VARIANT_NAMES
from .storage import ObjectMissing, SENTINEL_KEY, Storage
async def rows(db: Database, sql: str, params=()) -> list[tuple]:
async def work(conn):
await conn.execute("SET TRANSACTION READ ONLY")
cur = await conn.execute(sql, params)
return await cur.fetchall()
return await db.run(work, deadline=db.deadline)
async def list_all(storage: Storage, prefix: str) -> dict[str, int]:
found, after = {}, None
while True:
page, more = await storage.list_page(prefix, after, 1000)
for item in page:
found[item.key] = item.size
if not more or not page:
return found
after = page[-1].key
async def audit(settings: Settings, verify: bool) -> dict:
db = Database(settings, name="messenger-audit")
final = Storage(settings)
staging = Storage(settings, bucket=settings.s3_staging_bucket)
await db.open()
await final.open()
await staging.open()
violations: list[dict] = []
notes: list[dict] = []
def bad(kind: str, **detail) -> None:
violations.append({"invariant": kind, **{k: str(v) for k, v in detail.items()}})
try:
# I1: queued/processing attachment without an active job; active job without outbox row.
for (aid,) in await rows(db, "SELECT a.id FROM attachments a WHERE a.status IN ('queued', 'processing') "
"AND NOT EXISTS (SELECT 1 FROM jobs j WHERE j.attachment_id = a.id "
"AND j.state IN ('queued', 'processing'))"):
bad("I1_no_active_job", attachment_id=aid)
for (jid,) in await rows(db, "SELECT j.id FROM jobs j WHERE j.state = 'queued' AND NOT EXISTS "
"(SELECT 1 FROM outbox o WHERE o.job_id = j.id)"):
bad("I1_queued_without_outbox", job_id=jid)
# I2: exactly three variants per published version, one successful attempt of that version.
for aid, version, names, tokens in await rows(
db, "SELECT attachment_id, pipeline_version, array_agg(name ORDER BY name), "
"array_agg(DISTINCT attempt_token) FROM attachment_variants GROUP BY 1, 2"):
if sorted(names) != sorted(VARIANT_NAMES):
bad("I2_variant_set", attachment_id=aid, version=version, names=names)
if len(tokens) != 1:
bad("I2_mixed_attempts", attachment_id=aid, version=version, attempts=len(tokens))
for aid, version, outcome, jversion in await rows(
db, "SELECT v.attachment_id, v.pipeline_version, ja.outcome, j.pipeline_version "
"FROM attachment_variants v JOIN job_attempts ja ON ja.token = v.attempt_token "
"JOIN jobs j ON j.id = ja.job_id WHERE ja.outcome <> 'succeeded' OR j.pipeline_version "
"<> v.pipeline_version OR j.attachment_id <> v.attachment_id"):
bad("I2_variant_from_unsuccessful_attempt", attachment_id=aid, version=version, outcome=outcome)
# I4: published_version = highest succeeded version; ready <=> published.
for aid, status, published, best in await rows(
db, "SELECT a.id, a.status, a.published_version, (SELECT max(j.pipeline_version) FROM jobs j "
"WHERE j.attachment_id = a.id AND j.state = 'succeeded') FROM attachments a "
"WHERE a.published_version IS DISTINCT FROM (SELECT max(j.pipeline_version) FROM jobs j "
"WHERE j.attachment_id = a.id AND j.state = 'succeeded') "
"OR (a.published_version IS NOT NULL AND a.status <> 'ready')"):
bad("I4_published_version", attachment_id=aid, status=status, published=published, best_succeeded=best)
# I7: attempts.
for (jid,) in await rows(db, "SELECT j.id FROM jobs j WHERE j.state = 'succeeded' AND (SELECT count(*) "
"FROM job_attempts a WHERE a.job_id = j.id AND a.outcome = 'succeeded') <> 1"):
bad("I7_succeeded_attempts", job_id=jid)
for jid, token in await rows(db, "SELECT a.job_id, a.token FROM job_attempts a JOIN jobs j ON j.id = a.job_id "
"WHERE a.outcome = 'running' AND j.lease_token IS DISTINCT FROM a.token"):
bad("I7_running_not_holder", job_id=jid, token=token)
# I3 + I5 + I6: storage.
published = {k: (s, h) for k, s, h in await rows(
db, "SELECT object_key, size_bytes, sha256 FROM attachment_variants UNION ALL "
"SELECT object_key, size_bytes, sha256 FROM attachments WHERE object_key IS NOT NULL")}
staging_live = {k: (s, st, status) for k, s, st, status in await rows(
db, "SELECT staging_key, size_bytes, staging_state, status FROM attachments WHERE staging_key IS NOT NULL")}
planned_open, planned_cleaned = set(), set()
for keys, cleaned in await rows(db, "SELECT planned_keys, objects_cleaned_at IS NOT NULL FROM job_attempts"):
(planned_cleaned if cleaned else planned_open).update(keys)
final_objects = await list_all(final, "")
staging_objects = await list_all(staging, "")
for key, (size, sha) in published.items():
if key not in final_objects:
bad("I3_published_missing", key=key)
elif final_objects[key] != size:
bad("I3_published_size", key=key, stored=size, actual=final_objects[key])
elif verify:
data = await final.read_all(key, limit=settings.max_upload_bytes)
if hashlib.sha256(data).digest() != bytes(sha):
bad("I3_published_checksum", key=key)
for key, (size, state, status) in staging_live.items():
# 'pending' may lack its object (the PUT failed: the janitor removes the row); accepted
# work (queued/processing) must have it.
active = status in ("queued", "processing")
if state == "present" and key not in staging_objects and active:
bad("I5_staging_missing", key=key, status=status)
for (aid,) in await rows(db, "SELECT a.id FROM attachments a WHERE a.status IN ('queued', 'processing') "
"AND a.object_key IS NULL AND a.staging_state <> 'present'"):
bad("I5_active_without_source", attachment_id=aid)
for key in final_objects:
if key == SENTINEL_KEY or key in published or key in planned_open:
continue
if key in planned_cleaned:
notes.append({"kind": "leaked_object", "key": key})
else:
bad("I6_unknown_final_object", key=key)
for key in staging_objects:
if key == SENTINEL_KEY:
continue
row = staging_live.get(key)
if row is None:
bad("I6_unknown_staging_object", key=key)
elif row[1] == "deleted":
notes.append({"kind": "staging_marked_deleted_still_present", "key": key})
counts = dict(await rows(db, "SELECT status, count(*) FROM attachments GROUP BY status"))
jobs = dict(await rows(db, "SELECT state, count(*) FROM jobs GROUP BY state"))
return {"ok": not violations, "violations": violations, "notes": notes,
"attachments": counts, "jobs": jobs,
"objects": {"final": len(final_objects), "staging": len(staging_objects),
"published": len(published), "checksums_verified": verify}}
finally:
await staging.close()
await final.close()
await db.close()
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(prog="audit", description="Read-only check of the pipeline invariants")
p.add_argument("--verify-checksums", action="store_true", help="read every published object and compare SHA-256")
args = p.parse_args(argv)
try:
settings = Settings.from_env()
except ConfigError as exc:
print(f"configuration error: {exc}", file=sys.stderr)
return 2
try:
report = asyncio.run(audit(settings, args.verify_checksums))
except (Unavailable, ObjectMissing) as exc:
print(json.dumps({"ok": False, "error": "store_unavailable", "detail": type(exc).__name__}))
return 1
print(json.dumps(report, ensure_ascii=False, indent=1, default=str))
return 0 if report["ok"] else 1
if __name__ == "__main__":
sys.exit(main())
+86
View File
@@ -0,0 +1,86 @@
"""RabbitMQ (AMQP 0-9-1) for the attachment jobs: topology names and the message format.
Topology (declared by the broker itself from its definitions file at boot, infra/rabbitmq and
scripts/init_secrets.py; the relay and the worker have NO configure permission and declare nothing):
exchange messenger.jobs direct, durable
queue messenger.attachment-jobs quorum (Raft log on disk), bound with routing key
attachment.process.v1; x-delivery-limit and dead-lettering to
exchange messenger.jobs.dlx fanout -> queue messenger.attachment-jobs.dlq (quorum)
Publisher side (relay): persistent message, `mandatory` (an unroutable message is returned, not
silently dropped), channel in confirm mode - `publish()` returns only after the broker has
written the message to the quorum log (publisher confirm). Consumer side (worker): manual ack
after the durable effect, prefetch = WORKER_CONCURRENCY.
The message carries IDs and service fields only (contracts/jobs.schema.json): no bytes, no URL,
no S3 key, no filename, no credentials. The worker takes every trusted detail from PostgreSQL.
"""
from __future__ import annotations
import datetime as dt
import json
import re
import uuid
EXCHANGE = "messenger.jobs"
QUEUE = "messenger.attachment-jobs"
DLX = "messenger.jobs.dlx"
DLQ = "messenger.attachment-jobs.dlq"
ROUTING_KEY = "attachment.process.v1"
JOB_TYPE = "attachment.process.v1"
MAX_MESSAGE_BYTES = 4096
REQUIRED = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"}
OPTIONAL = {"traceparent", "tracestate"}
TRACEPARENT_RE = re.compile(r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}")
DATETIME_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z")
class BadMessage(ValueError):
"""Not a valid job message (schema v1): dead-lettered, never processed."""
def rfc3339(value: dt.datetime) -> str:
return value.astimezone(dt.timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def encode(job_id: str, attachment_id: str, pipeline_version: int, attempt: int, created_at: dt.datetime) -> bytes:
body = {"schema_version": 1, "job_id": job_id, "type": JOB_TYPE, "attachment_id": attachment_id,
"pipeline_version": pipeline_version, "attempt": attempt, "created_at": rfc3339(created_at)}
return json.dumps(body, separators=(",", ":")).encode()
def decode(raw: bytes) -> dict:
"""Strict check against contracts/jobs.schema.json (additionalProperties: false)."""
if len(raw) > MAX_MESSAGE_BYTES:
raise BadMessage("too large")
try:
body = json.loads(raw)
except (ValueError, UnicodeError):
raise BadMessage("not JSON") from None
if not isinstance(body, dict):
raise BadMessage("not an object")
keys = set(body)
if not REQUIRED <= keys or keys - REQUIRED - OPTIONAL:
raise BadMessage("wrong fields")
if body["schema_version"] != 1 or isinstance(body["schema_version"], bool) or body["type"] != JOB_TYPE:
raise BadMessage("unsupported schema/type")
for name in ("job_id", "attachment_id"):
if not isinstance(body[name], str):
raise BadMessage(name)
try:
uuid.UUID(body[name])
except ValueError:
raise BadMessage(name) from None
for name in ("pipeline_version", "attempt"):
value = body[name]
if not isinstance(value, int) or isinstance(value, bool) or value < 1:
raise BadMessage(name)
if not isinstance(body["created_at"], str) or not DATETIME_RE.fullmatch(body["created_at"]):
raise BadMessage("created_at")
if "traceparent" in body and not (isinstance(body["traceparent"], str) and TRACEPARENT_RE.fullmatch(body["traceparent"])):
raise BadMessage("traceparent")
if "tracestate" in body and not (isinstance(body["tracestate"], str) and len(body["tracestate"]) <= 512):
raise BadMessage("tracestate")
return body
+119 -12
View File
@@ -10,7 +10,7 @@ from __future__ import annotations
import os
import re
import socket
from dataclasses import dataclass
from dataclasses import dataclass, field
from pathlib import Path
@@ -134,7 +134,29 @@ class Settings:
jpeg_max_memory_mb: int = 256
pending_grace_seconds: int = 900
janitor_interval_seconds: float = 60.0
# Lab 5: staging bucket (API writes, worker reads) and the asynchronous pipeline (jobs_settings()).
s3_staging_bucket: str = "messenger-staging"
broker_url: str = ""
pipeline_version: int = 1
job_max_attempts: int = 5
job_timeout_seconds: float = 60.0
job_lease_seconds: float = 30.0
job_retry_base_seconds: float = 2.0
job_retry_max_seconds: float = 60.0
worker_concurrency: int = 2
worker_shutdown_seconds: float = 20.0
image_max_memory_mb: int = 768
staging_retention_seconds: int = 86400
orphan_grace_seconds: int = 600
cleanup_interval_seconds: float = 30.0
relay_poll_seconds: float = 0.5
relay_batch: int = 50
queued_republish_seconds: float = 300.0
fault_points: frozenset[str] = frozenset()
fault_values: dict[str, int] = field(default_factory=dict)
def fault_value(self, point: str, default: int = 0) -> int:
return self.fault_values.get(point, default)
@property
def db_statement_timeout_ms(self) -> int:
@@ -142,7 +164,8 @@ class Settings:
return max(100, int(self.db_timeout_seconds * 1000) - 500)
@classmethod
def from_env(cls) -> "Settings":
def from_env(cls, *, s3_credentials: bool = True) -> "Settings":
"""s3_credentials=False: processes without S3 access (relay, jobctl)."""
log_level = os.environ.get("LOG_LEVEL", "info").strip().lower() or "info"
if log_level not in {"debug", "info", "warning", "error"}:
raise ConfigError(f"LOG_LEVEL must be debug/info/warning/error, got {log_level!r}")
@@ -185,32 +208,71 @@ class Settings:
# Track 1: `function` = one SQL call per send (migration 0003), `multi` = the previous
# multi-statement transaction; both have identical semantics (A/B on one image).
message_write_path=_choice("MESSAGE_WRITE_PATH", "function", {"function", "multi"}),
**s3_settings(),
**s3_settings(credentials_required=s3_credentials),
**jobs_settings(broker_required=False),
)
# Contract limits (contracts/README.md): configurable DOWN for experiments, never above them.
CONTRACT_MAX_UPLOAD_BYTES = 10 * 1024 * 1024
CONTRACT_MAX_IMAGE_PIXELS = 40_000_000
# Failure points for the level 4 experiments only (compose.faults.yaml); empty in normal runs.
FAULT_POINTS = {"after_s3_put", "after_ready_commit"}
# Failure points for the experiments only (FAULT_POINTS of ONE service, compose variables
# API_/RELAY_/WORKER_FAULT_POINTS); empty in normal runs. `name` or `name=<integer>`.
FAULT_POINTS = {
# API, upload: between the staging PUT and the job COMMIT / after the job COMMIT, before 202.
"after_s3_put", "after_enqueue_commit",
# Relay: crash after the broker confirmed a publish but before outbox.published_at is
# committed; publish every message twice; publish a batch in reverse order.
"crash_after_publish", "duplicate_publish", "reverse_order",
# Worker: crash after the claim (before any side effect), after the S3 writes (before the
# result COMMIT), after the result COMMIT (before the ack); transient failure of the first N
# attempts; permanent failure; slow processing (N s, lease kept alive) of every job or only of
# pipeline version `slow_pipeline`; hang: stop the heartbeat and sleep N s inside processing.
"crash_after_claim", "crash_after_s3_write", "crash_after_commit", "transient_error", "permanent_error",
"slow", "slow_pipeline", "hang",
# Worker cleanup: pause N s after reading the candidates, before locking/deleting them.
"pause_cleanup",
}
def _faults() -> tuple[frozenset[str], dict[str, int]]:
names, values = set(), {}
for item in os.environ.get("FAULT_POINTS", "").split(","):
name, _, raw = item.strip().partition("=")
if not name:
continue
if name not in FAULT_POINTS:
raise ConfigError(f"FAULT_POINTS may contain only {sorted(FAULT_POINTS)}")
if raw:
if not raw.isdigit():
raise ConfigError(f"FAULT_POINTS value of {name} must be an integer")
values[name] = int(raw)
names.add(name)
return frozenset(names), values
def _bucket(name: str, default: str) -> str:
bucket = os.environ.get(name, default).strip() or default
if not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", bucket):
raise ConfigError(f"{name} is not a valid bucket name: {bucket!r}")
return bucket
def s3_settings(*, credentials_required: bool = True) -> dict:
"""S3 part of Settings; also used by the reconciler/bootstrap CLIs with their own keys."""
faults = frozenset(f.strip() for f in os.environ.get("FAULT_POINTS", "").split(",") if f.strip())
if faults - FAULT_POINTS:
raise ConfigError(f"FAULT_POINTS may contain only {sorted(FAULT_POINTS)}")
"""S3 part of Settings; also used by the bootstrap CLI with its own keys."""
faults, fault_values = _faults()
endpoint = os.environ.get("S3_ENDPOINT", "http://s3:8333").strip() or "http://s3:8333"
if not re.fullmatch(r"https?://[A-Za-z0-9.\-]+(:[0-9]{1,5})?/?", endpoint):
raise ConfigError(f"S3_ENDPOINT must be http(s)://host[:port], got {endpoint!r}")
bucket = os.environ.get("S3_BUCKET", "messenger-attachments").strip() or "messenger-attachments"
if not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", bucket):
raise ConfigError(f"S3_BUCKET is not a valid bucket name: {bucket!r}")
bucket = _bucket("S3_BUCKET", "messenger-attachments")
staging = _bucket("S3_STAGING_BUCKET", "messenger-staging")
if staging == bucket:
raise ConfigError("S3_STAGING_BUCKET must differ from S3_BUCKET")
return dict(
s3_endpoint=endpoint,
s3_region=os.environ.get("S3_REGION", "us-east-1").strip() or "us-east-1",
s3_bucket=bucket,
s3_staging_bucket=staging,
s3_access_key_id=_secret("S3_ACCESS_KEY_ID", required=credentials_required),
s3_secret_access_key=_secret("S3_SECRET_ACCESS_KEY", required=credentials_required),
s3_timeout_seconds=_float("S3_TIMEOUT_SECONDS", 3.0, 0.2, 30.0),
@@ -233,4 +295,49 @@ def s3_settings(*, credentials_required: bool = True) -> dict:
pending_grace_seconds=_int("PENDING_GRACE_SECONDS", 900, 1, 7 * 24 * 3600),
janitor_interval_seconds=_float("JANITOR_INTERVAL_SECONDS", 60.0, 0.0, 3600.0),
fault_points=faults,
fault_values=fault_values,
)
def jobs_settings(*, broker_required: bool) -> dict:
"""Lab 5 pipeline: retries, lease, worker limits, cleanup, relay (docs/PIPELINE.md)."""
from .pipeline import PIPELINES # local import: pipeline.py imports nothing from here
timeout = _float("JOB_TIMEOUT_SECONDS", 60.0, 1.0, 600.0)
lease = _float("JOB_LEASE_SECONDS", 30.0, 2.0, 600.0)
base = _float("JOB_RETRY_BASE_SECONDS", 2.0, 0.0, 600.0)
cap = _float("JOB_RETRY_MAX_SECONDS", 60.0, 0.0, 3600.0)
if base > cap:
raise ConfigError("JOB_RETRY_BASE_SECONDS must not exceed JOB_RETRY_MAX_SECONDS")
orphan_grace = _int("ORPHAN_GRACE_SECONDS", 600, 1, 7 * 24 * 3600)
version = _int("PIPELINE_VERSION", 1, 1, 1000)
if version not in PIPELINES:
raise ConfigError(f"PIPELINE_VERSION must be one of {sorted(PIPELINES)}")
return dict(
broker_url=_secret("BROKER_URL", required=broker_required),
# Pipeline version of the jobs created by new uploads (track 2: versioned pipeline).
pipeline_version=version,
# Managed attempts (claims) per job before failed/retry_exhausted.
job_max_attempts=_int("JOB_MAX_ATTEMPTS", 5, 1, 100),
# Hard limit of ONE attempt: the image child process is killed, the lease is no longer renewed.
job_timeout_seconds=timeout,
# Lease of a claimed job, renewed by the heartbeat every lease/3 while the attempt runs.
job_lease_seconds=lease,
# Backoff of transient failures: full jitter, uniform(0, min(max, base * 2^(attempt-1))).
job_retry_base_seconds=base,
job_retry_max_seconds=cap,
# Jobs processed at once by ONE worker process = RabbitMQ prefetch (basic.qos).
worker_concurrency=_int("WORKER_CONCURRENCY", 2, 1, 32),
worker_shutdown_seconds=_float("WORKER_SHUTDOWN_SECONDS", 20.0, 0.0, 120.0),
# Address-space limit (RLIMIT_AS) of the child process that decodes/encodes ONE image.
image_max_memory_mb=_int("IMAGE_MAX_MEMORY_MB", 768, 128, 8192),
# Staging copy of a FAILED attachment is kept this long for a replay, then deleted.
staging_retention_seconds=_int("STAGING_RETENTION_SECONDS", 86400, 0, 30 * 24 * 3600),
# Objects of attempts that did not publish are deleted once the attempt ended this long ago.
orphan_grace_seconds=orphan_grace,
cleanup_interval_seconds=_float("CLEANUP_INTERVAL_SECONDS", 30.0, 0.0, 3600.0),
relay_poll_seconds=_float("RELAY_POLL_SECONDS", 0.5, 0.05, 60.0),
relay_batch=_int("RELAY_BATCH", 50, 1, 1000),
# A queued job whose message has not led to a claim for this long is published again
# (message lost in the broker, dead-lettered, purged): no accepted job waits forever.
queued_republish_seconds=_float("QUEUED_REPUBLISH_SECONDS", 300.0, 5.0, 86400.0),
)
+3 -3
View File
@@ -55,7 +55,7 @@ def _forget(task: asyncio.Task) -> None:
class Database:
def __init__(self, settings: Settings):
def __init__(self, settings: Settings, name: str = "messenger-api"):
self.deadline = settings.db_timeout_seconds
options = (
f"-c statement_timeout={settings.db_statement_timeout_ms} "
@@ -68,12 +68,12 @@ class Database:
max_size=settings.db_pool_max,
timeout=settings.db_timeout_seconds, # max wait for a free connection
open=False,
name="messenger",
name=name,
check=AsyncConnectionPool.check_connection, # drop connections broken by a DB restart
kwargs={
"options": options,
"connect_timeout": max(1, int(settings.db_timeout_seconds)),
"application_name": "messenger-api",
"application_name": name, # visible in pg_stat_activity: api / relay / worker
# Autocommit connections: a single statement (post_message function, ping) is its
# own transaction with ONE round trip; multi-statement work uses an explicit
# conn.transaction() (BEGIN ... COMMIT), see run().
+15 -3
View File
@@ -1,12 +1,24 @@
"""Docker HEALTHCHECK probe without curl/wget in the image: `python -m messenger.healthcheck`."""
"""Docker HEALTHCHECK probe without curl/wget in the image: `python -m messenger.healthcheck`.
(no arguments) API: GET /health/ready on the local port
--file /tmp/heartbeat --max-age 30 relay/worker: the main loop wrote its heartbeat recently
(it writes it only while its database/broker work)
"""
from __future__ import annotations
import os
import sys
import time
import urllib.request
def main() -> int:
def main(argv: list[str]) -> int:
if len(argv) == 4 and argv[0] == "--file" and argv[2] == "--max-age":
try:
with open(argv[1], encoding="ascii") as f:
return 0 if time.time() - float(f.read().strip()) <= float(argv[3]) else 1
except (OSError, ValueError):
return 1
port = os.environ.get("APP_PORT", "8080").strip() or "8080"
try:
with urllib.request.urlopen(f"http://127.0.0.1:{port}/health/ready", timeout=2) as response:
@@ -16,4 +28,4 @@ def main() -> int:
if __name__ == "__main__":
sys.exit(main())
sys.exit(main(sys.argv[1:]))
+208
View File
@@ -0,0 +1,208 @@
"""Variants of ONE image, built in a separate child process with hard limits (lab 5 worker).
parent (worker): await render(data, content_type, version, ...) -> list[Rendered]
child: python -m messenger.imaging --type image/png --pipeline 1 ...
stdin: original bytes; stdout: one JSON header line + variant bytes
Why a child process per image:
* memory: RLIMIT_AS (IMAGE_MAX_MEMORY_MB) caps the address space of the decoder; a picture that
needs more fails with MemoryError -> `image_too_large` (permanent), the worker keeps running;
* time: the parent kills the child at JOB_TIMEOUT_SECONDS (C code of Pillow cannot be
interrupted inside a thread) -> `processing_timeout` (transient, bounded by JOB_MAX_ATTEMPTS);
* pixels: the size is read from the header and checked against MAX_IMAGE_PIXELS BEFORE the
pixels are decoded (`Image.open` is lazy).
A crash of the decoder (signal) is a transient `processing_killed`: the next attempt may run
with less memory pressure; JOB_MAX_ATTEMPTS bounds it.
Geometry and encoder settings: pipeline.py. Alpha is handled in premultiplied form (RGBa) while
resizing, so transparent pixels do not bleed their colour into the edges; for JPEG the result is
then composited onto white.
"""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import io
import json
import sys
import warnings
from dataclasses import dataclass
from .pipeline import CONTENT_TYPES, CROP_SIDE, OPTIMIZED_BOX, PIPELINES, THUMBNAIL_BOX, center_square, fit
EXIT_INVALID = 3 # the bytes are not a decodable PNG/JPEG
EXIT_TOO_LARGE = 4 # pixel limit or memory limit
HEADER_LIMIT = 4096
class ProcessingError(Exception):
"""Outcome of an attempt that did not produce variants. `permanent`: another attempt with the
same input cannot succeed (job -> failed at once); otherwise retry with backoff."""
def __init__(self, code: str, permanent: bool):
super().__init__(code)
self.code = code
self.permanent = permanent
@dataclass(frozen=True, slots=True)
class Rendered:
name: str
content_type: str
width: int
height: int
data: bytes
@property
def sha256(self) -> bytes:
return hashlib.sha256(self.data).digest()
# ------------------------------------------------------------------ parent side
async def render(data: bytes, content_type: str, pipeline_version: int, *, max_pixels: int, timeout: float,
memory_mb: int) -> list[Rendered]:
process = await asyncio.create_subprocess_exec(
sys.executable, "-m", "messenger.imaging", "--type", content_type, "--pipeline", str(pipeline_version),
"--max-pixels", str(max_pixels), "--memory-mb", str(memory_mb),
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
try:
out, _ = await asyncio.wait_for(process.communicate(data), timeout)
except asyncio.TimeoutError:
process.kill()
await process.wait()
raise ProcessingError("processing_timeout", permanent=False) from None
except asyncio.CancelledError:
process.kill()
await process.wait()
raise
code = process.returncode
if code == EXIT_INVALID:
raise ProcessingError("invalid_image", permanent=True)
if code == EXIT_TOO_LARGE:
raise ProcessingError("image_too_large", permanent=True)
if code is None or code < 0:
raise ProcessingError("processing_killed", permanent=False) # OOM killer or another signal
if code != 0:
raise ProcessingError("processing_failed", permanent=False)
return parse_output(out)
def parse_output(out: bytes) -> list[Rendered]:
newline = out.find(b"\n", 0, HEADER_LIMIT)
if newline < 0:
raise ProcessingError("processing_failed", permanent=False)
header = json.loads(out[:newline])
pos = newline + 1
result = []
for item in header["variants"]:
size = int(item["size"])
result.append(Rendered(item["name"], item["content_type"], int(item["width"]), int(item["height"]),
out[pos:pos + size]))
pos += size
if pos != len(out) or [r.name for r in result] != list(CONTENT_TYPES):
raise ProcessingError("processing_failed", permanent=False)
return result
# ------------------------------------------------------------------ child side
def build(data: bytes, content_type: str, pipeline_version: int, max_pixels: int) -> list[Rendered]:
"""Decode once, build every variant. Raises the Pillow/OS errors of a bad file."""
from PIL import Image, ImageOps
pipeline = PIPELINES[pipeline_version]
warnings.simplefilter("ignore", Image.DecompressionBombWarning) # our own pixel limit below
Image.MAX_IMAGE_PIXELS = max_pixels
expected = {"image/png": "PNG", "image/jpeg": "JPEG"}[content_type]
img = Image.open(io.BytesIO(data), formats=[expected]) # header only: nothing decoded yet
width, height = img.size
if width * height > max_pixels:
raise TooLarge()
if expected == "JPEG":
# DCT scaling: decode a big JPEG directly at 1/2..1/8 of its size, never below what the
# largest variant needs (the box stays square, so EXIF rotation does not matter).
img.draft("RGB", (OPTIMIZED_BOX, OPTIMIZED_BOX))
img.load()
img = ImageOps.exif_transpose(img) # orientation goes into the pixels, the tag is dropped
img = _normalize(img)
alpha = img.mode == "RGBA"
base = img.convert("RGBa") if alpha else img # premultiplied alpha for resampling
del img
def finish(im, *, flatten: bool):
if alpha:
im = im.convert("RGBA")
if flatten:
white = Image.new("RGB", im.size, (255, 255, 255))
white.paste(im, mask=im.getchannel("A"))
im = white
im.info = {} # no EXIF/XMP/ICC/comments of the source in a variant
return im
def resized(im, size):
return im if im.size == size else im.resize(size, Image.Resampling.LANCZOS, reducing_gap=3.0)
thumbnail = finish(resized(base, fit(*base.size, THUMBNAIL_BOX)), flatten=True)
crop = finish(resized(base.crop(center_square(*base.size)), (CROP_SIDE, CROP_SIDE)), flatten=True)
optimized = finish(resized(base, fit(*base.size, OPTIMIZED_BOX)), flatten=False)
out = []
for name, im in (("thumbnail", thumbnail), ("crop", crop), ("optimized", optimized)):
buf = io.BytesIO()
if CONTENT_TYPES[name] == "image/jpeg":
im.save(buf, "JPEG", quality=pipeline.jpeg_quality, optimize=True, subsampling=2, progressive=False)
else:
im.save(buf, "WEBP", quality=pipeline.webp_quality, method=pipeline.webp_method, exif=b"",
icc_profile="", xmp=b"")
out.append(Rendered(name, CONTENT_TYPES[name], im.width, im.height, buf.getvalue()))
return out
class TooLarge(Exception):
pass
def _normalize(img):
"""Any PNG/JPEG mode -> RGB, or RGBA when the image has transparency."""
if img.mode.startswith("I;16") or img.mode == "I":
# 16-bit grey: scale 0..65535 to 0..255 (a plain convert("L") would clip to white).
img = img.convert("I").point(lambda v: v * (1 / 257)).convert("L")
has_alpha = img.mode in ("RGBA", "LA", "PA", "La", "RGBa") or "transparency" in img.info
return img.convert("RGBA" if has_alpha else "RGB") if img.mode != ("RGBA" if has_alpha else "RGB") else img
def child_main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--type", required=True, choices=["image/png", "image/jpeg"])
parser.add_argument("--pipeline", type=int, required=True, choices=sorted(PIPELINES))
parser.add_argument("--max-pixels", type=int, required=True)
parser.add_argument("--memory-mb", type=int, required=True)
args = parser.parse_args(argv)
try:
import resource
limit = args.memory_mb * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
except (ImportError, ValueError, OSError):
pass # not Linux (unit tests on Windows): the container memory limit still applies
data = sys.stdin.buffer.read()
try:
variants = build(data, args.type, args.pipeline, args.max_pixels)
except (TooLarge, MemoryError):
return EXIT_TOO_LARGE
except Exception as exc: # noqa: BLE001 - every decoder error of the CONTENT is "invalid image"
from PIL import Image
if isinstance(exc, Image.DecompressionBombError):
return EXIT_TOO_LARGE
if isinstance(exc, (OSError, SyntaxError, ValueError, EOFError, KeyError, IndexError, TypeError)):
return EXIT_INVALID
raise
header = {"variants": [{"name": v.name, "content_type": v.content_type, "width": v.width, "height": v.height,
"size": len(v.data)} for v in variants]}
sys.stdout.buffer.write(json.dumps(header).encode() + b"\n")
for v in variants:
sys.stdout.buffer.write(v.data)
sys.stdout.buffer.flush()
return 0
if __name__ == "__main__":
sys.exit(child_main())
+220
View File
@@ -0,0 +1,220 @@
"""Operator CLI for attachment jobs: `python -m messenger.jobctl ...` (compose service `jobctl`).
list-failed [--limit N] failed registry (view failed_jobs), newest first
show <attachment_id> attachment state, its jobs, attempts and audit events
stats jobs by state, outbox backlog
replay <attachment_id> --operator NAME --reason TEXT
failed -> queued: a NEW job (kind=replay, replay_of = the failed job) with a fresh attempt
budget. Refused (exit 3, nothing changed) unless the attachment is failed AND its source
still exists (staging copy present or original published). "Repeat" never means
"run a finished job again": a ready attachment is refused (already_ready).
reprocess <attachment_id> --pipeline N --operator NAME --reason TEXT
Track 2: build a NEWER pipeline version of a READY attachment from its published original.
Refused unless ready, N known, N > published version and no job of version >= N active.
A not-yet-ready upload is refused: its only source is the staging copy that belongs to the
running job, and its result would race with the first publication.
Every decision is taken under the attachments row lock, the same lock the cleanup takes before it
marks a staging copy `deleting`: either the replay sees the copy and the cleanup then skips the
row (no longer failed), or the cleanup marked it first and the replay refuses (source_missing).
Output: one JSON document on stdout, without secrets or file names.
"""
from __future__ import annotations
import argparse
import asyncio
import json
import re
import sys
import uuid
from . import jobs
from .config import ConfigError, Settings
from .db import Database
from .errors import Unavailable
from .pipeline import PIPELINES
OPERATOR_RE = re.compile(r"[A-Za-z0-9._-]{1,64}")
EXIT_REFUSED = 3
class Refused(Exception):
pass
def operator(value: str) -> str:
if not OPERATOR_RE.fullmatch(value):
raise argparse.ArgumentTypeError("operator must match [A-Za-z0-9._-]{1,64}")
return value
def reason(value: str) -> str:
value = value.strip()
if not 1 <= len(value) <= 200 or any(ord(ch) < 32 for ch in value):
raise argparse.ArgumentTypeError("reason: 1-200 printable characters")
return value
def attachment_id(value: str) -> str:
try:
return str(uuid.UUID(value))
except ValueError:
raise argparse.ArgumentTypeError("not a UUID") from None
async def lock_attachment(conn, attachment: str):
cur = await conn.execute(
"SELECT status, staging_state, object_key IS NOT NULL, published_version FROM attachments "
"WHERE id = %s FOR UPDATE", (attachment,))
row = await cur.fetchone()
if row is None or row[0] == "pending":
raise Refused("not_found")
return row
async def replay(conn, args, settings: Settings) -> dict:
status, staging_state, has_original, _ = await lock_attachment(conn, args.attachment_id)
if status == "ready":
raise Refused("already_ready")
if status != "failed":
raise Refused("not_failed:" + status)
if not has_original and staging_state != "present":
raise Refused("source_missing") # staging removed by the retention cleanup
cur = await conn.execute(
"SELECT id, pipeline_version FROM jobs WHERE attachment_id = %s AND state = 'failed' "
"ORDER BY finished_at DESC LIMIT 1", (args.attachment_id,))
last = await cur.fetchone()
if last is None:
raise Refused("no_failed_job")
cur = await conn.execute("SELECT 1 FROM jobs WHERE attachment_id = %s AND state IN ('queued', 'processing')",
(args.attachment_id,))
if await cur.fetchone():
raise Refused("active_job")
await conn.execute(
"UPDATE attachments SET status = 'queued', error_code = NULL, failed_at = NULL, updated_at = clock_timestamp() "
"WHERE id = %s", (args.attachment_id,))
actor = "jobctl:" + args.operator
await jobs.event(conn, last[0], "replay_requested", actor, reason=args.reason)
job_id = await jobs.create_job(conn, args.attachment_id, last[1], "replay", settings.job_max_attempts, actor,
replay_of=last[0], reason=args.reason)
return {"result": "queued", "job_id": str(job_id), "replay_of": str(last[0]), "pipeline_version": last[1]}
async def reprocess(conn, args, settings: Settings) -> dict:
status, _, _, published = await lock_attachment(conn, args.attachment_id)
if args.pipeline not in PIPELINES:
raise Refused("unknown_pipeline")
if status != "ready":
raise Refused("not_ready:" + status)
if args.pipeline <= published:
raise Refused("not_newer")
cur = await conn.execute(
"SELECT max(pipeline_version) FROM jobs WHERE attachment_id = %s AND state IN ('queued', 'processing')",
(args.attachment_id,))
(active,) = await cur.fetchone()
if active is not None and active >= args.pipeline:
raise Refused("newer_or_same_active")
job_id = await jobs.create_job(conn, args.attachment_id, args.pipeline, "reprocess", settings.job_max_attempts,
"jobctl:" + args.operator, reason=args.reason)
return {"result": "queued", "job_id": str(job_id), "pipeline_version": args.pipeline,
"published_version": published}
async def list_failed(conn, args, settings: Settings) -> dict:
cur = await conn.execute(
"SELECT job_id, attachment_id, pipeline_version, kind, attempt, max_attempts, error_code, finished_at, "
"attachment_status, staging_state FROM failed_jobs ORDER BY finished_at DESC LIMIT %s", (args.limit,))
cols = [d.name for d in cur.description]
return {"failed": [dict(zip(cols, r)) for r in await cur.fetchall()]}
async def show(conn, args, settings: Settings) -> dict:
cur = await conn.execute(
"SELECT status, error_code, published_version, staging_state, object_key IS NOT NULL AS original_published, "
"updated_at FROM attachments WHERE id = %s", (args.attachment_id,))
row = await cur.fetchone()
if row is None:
raise Refused("not_found")
attachment = dict(zip([d.name for d in cur.description], row))
async def rows(sql: str) -> list[dict]:
c = await conn.execute(sql, (args.attachment_id,))
names = [d.name for d in c.description]
return [dict(zip(names, r)) for r in await c.fetchall()]
return {
"attachment": attachment,
"jobs": await rows("SELECT id, pipeline_version, kind, state, attempt, max_attempts, error_code, replay_of, "
"created_at, finished_at FROM jobs WHERE attachment_id = %s ORDER BY created_at"),
"attempts": await rows("SELECT a.job_id, a.attempt, a.token, a.worker, a.source, a.outcome, a.error_code, "
"a.started_at, a.finished_at, a.objects_cleaned_at FROM job_attempts a "
"JOIN jobs j ON j.id = a.job_id WHERE j.attachment_id = %s ORDER BY a.started_at"),
"variants": await rows("SELECT pipeline_version, name, content_type, size_bytes, width, height, "
"encode(sha256, 'hex') AS sha256 FROM attachment_variants WHERE attachment_id = %s "
"ORDER BY pipeline_version, name"),
"events": await rows("SELECT e.job_id, e.at, e.event, e.attempt, e.actor, e.error_code, e.detail "
"FROM job_events e JOIN jobs j ON j.id = e.job_id WHERE j.attachment_id = %s "
"ORDER BY e.id"),
}
async def stats(conn, args, settings: Settings) -> dict:
cur = await conn.execute("SELECT state, count(*) FROM jobs GROUP BY state ORDER BY state")
by_state = {r[0]: r[1] for r in await cur.fetchall()}
cur = await conn.execute("SELECT count(*), count(*) FILTER (WHERE available_at <= clock_timestamp()) "
"FROM outbox WHERE published_at IS NULL")
pending, due = await cur.fetchone()
return {"jobs": by_state, "outbox_unpublished": pending, "outbox_due": due}
COMMANDS = {"replay": replay, "reprocess": reprocess, "list-failed": list_failed, "show": show, "stats": stats}
def arguments(argv: list[str] | None) -> argparse.Namespace:
p = argparse.ArgumentParser(prog="jobctl", description="Attachment jobs: failed registry, replay, reprocess")
sub = p.add_subparsers(dest="command", required=True)
for name in ("replay", "reprocess"):
s = sub.add_parser(name)
s.add_argument("attachment_id", type=attachment_id)
if name == "reprocess":
s.add_argument("--pipeline", type=int, required=True)
s.add_argument("--operator", type=operator, required=True)
s.add_argument("--reason", type=reason, required=True)
s = sub.add_parser("list-failed")
s.add_argument("--limit", type=int, default=50)
s = sub.add_parser("show")
s.add_argument("attachment_id", type=attachment_id)
sub.add_parser("stats")
return p.parse_args(argv)
async def run(args: argparse.Namespace) -> int:
settings = Settings.from_env(s3_credentials=False)
db = Database(settings, name="messenger-jobctl")
await db.open()
try:
writes = args.command in ("replay", "reprocess")
result = await db.run(lambda c: COMMANDS[args.command](c, args, settings), deadline=10)
print(json.dumps(result, ensure_ascii=False, indent=1, default=str))
return 0 if not writes or result.get("result") == "queued" else 1
except Refused as exc:
print(json.dumps({"result": "refused", "reason": str(exc)}))
return EXIT_REFUSED
except Unavailable:
print(json.dumps({"result": "error", "reason": "database_unavailable"}))
return 1
finally:
await db.close()
def main(argv: list[str] | None = None) -> int:
args = arguments(argv)
try:
return asyncio.run(run(args))
except ConfigError as exc:
print(f"configuration error: {exc}", file=sys.stderr)
return 2
if __name__ == "__main__":
sys.exit(main())
+398
View File
@@ -0,0 +1,398 @@
"""State machine of attachment jobs in PostgreSQL (lab 5). Every transition is ONE transaction.
Lock order, everywhere both rows are locked: the jobs row FIRST, then the attachments row
(claim, complete, retry, lease expiry). Replay/reprocess/cleanup lock only the attachments row
and insert NEW job rows. So two transitions never wait on each other in opposite order.
Fencing: a claim gives the attempt a fresh random `lease_token`. Every later write of that attempt
(heartbeat, result, retry) is conditional on `jobs.lease_token = <its token>` under the jobs row
lock. When the lease expires, the reaper clears the token; from then on the old attempt - even if
its process is still alive (paused, slow) - can neither publish nor schedule anything, and the
objects it wrote under its own keys are garbage for the cleanup.
Monotonic publication: a result of pipeline version V is published only if V is greater than the
published version of the attachment; otherwise the job ends as `superseded` and nothing visible
changes. `ready` never goes back to queued/processing.
"""
from __future__ import annotations
import datetime as dt
import json
import random
import uuid
from dataclasses import dataclass
import psycopg
from .pipeline import VARIANT_NAMES
from .storage import attempt_key
ACTIVE = ("queued", "processing")
def backoff_delay(attempt: int, base: float, cap: float, rnd=random.random) -> float:
"""Full jitter (AWS Architecture Blog, "Exponential Backoff And Jitter"): uniform in
[0, min(cap, base * 2^(attempt-1))]. Spreads the retries of many jobs that failed together."""
return rnd() * min(cap, base * (2 ** max(0, attempt - 1)))
async def event(conn: psycopg.AsyncConnection, job_id, name: str, actor: str, *, attempt: int | None = None,
error_code: str | None = None, **detail) -> None:
await conn.execute(
"INSERT INTO job_events (job_id, event, attempt, actor, error_code, detail) VALUES (%s, %s, %s, %s, %s, %s)",
(job_id, name, attempt, actor, error_code, json.dumps(detail, default=str)))
async def create_job(conn: psycopg.AsyncConnection, attachment_id, pipeline_version: int, kind: str,
max_attempts: int, actor: str, *, replay_of=None, **detail) -> uuid.UUID:
"""jobs row + its first outbox row + audit, in the CALLER's transaction."""
job_id = uuid.uuid4()
await conn.execute(
"INSERT INTO jobs (id, attachment_id, pipeline_version, kind, replay_of, max_attempts) "
"VALUES (%s, %s, %s, %s, %s, %s)", (job_id, attachment_id, pipeline_version, kind, replay_of, max_attempts))
await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, 1)", (job_id,))
await event(conn, job_id, "created", actor, kind=kind, pipeline_version=pipeline_version,
replay_of=str(replay_of) if replay_of else None, **detail)
return job_id
# ------------------------------------------------------------------ relay
@dataclass(frozen=True, slots=True)
class Due:
outbox_id: int
job_id: str
attachment_id: str
pipeline_version: int
attempt: int
created_at: dt.datetime
job_state: str
async def due_outbox(conn: psycopg.AsyncConnection, batch: int) -> list[Due]:
"""Due, unpublished outbox rows, locked for this relay pass (SKIP LOCKED: several relays
never publish the same row at the same time - a crash may still publish it twice)."""
cur = await conn.execute(
"SELECT o.id, o.job_id, j.attachment_id, j.pipeline_version, o.attempt, j.created_at, j.state "
"FROM outbox o JOIN jobs j ON j.id = o.job_id "
"WHERE o.published_at IS NULL AND o.available_at <= clock_timestamp() "
"ORDER BY o.available_at, o.id LIMIT %s FOR UPDATE OF o SKIP LOCKED", (batch,))
return [Due(r[0], str(r[1]), str(r[2]), r[3], r[4], r[5], r[6]) for r in await cur.fetchall()]
async def mark_published(conn: psycopg.AsyncConnection, ids: list[int]) -> None:
if ids:
await conn.execute("UPDATE outbox SET published_at = clock_timestamp() WHERE id = ANY(%s)", (ids,))
async def count_publish_failure(conn: psycopg.AsyncConnection, ids: list[int]) -> None:
if ids:
await conn.execute("UPDATE outbox SET publish_failures = publish_failures + 1 WHERE id = ANY(%s)", (ids,))
async def expire_leases(conn: psycopg.AsyncConnection, actor: str, limit: int = 50) -> int:
"""Reaper: processing jobs whose lease ran out (the worker died, hung or lost its database).
The attempt is abandoned; the job goes back to queued with a new outbox row, or to failed
`retry_exhausted` when it used all its attempts."""
cur = await conn.execute(
"SELECT id, attempt, max_attempts, lease_token, attachment_id FROM jobs "
"WHERE state = 'processing' AND lease_until < clock_timestamp() "
"ORDER BY lease_until LIMIT %s FOR UPDATE SKIP LOCKED", (limit,))
rows = await cur.fetchall()
for job_id, attempt, max_attempts, token, attachment_id in rows:
await conn.execute(
"UPDATE job_attempts SET outcome = 'abandoned', error_code = 'lease_expired', finished_at = clock_timestamp() "
"WHERE token = %s AND outcome = 'running'", (token,))
if attempt >= max_attempts:
await _fail(conn, job_id, attachment_id, "retry_exhausted", actor, attempt, cause="lease_expired")
else:
await conn.execute(
"UPDATE jobs SET state = 'queued', lease_token = NULL, lease_owner = NULL, lease_until = NULL, "
"available_at = clock_timestamp(), updated_at = clock_timestamp() WHERE id = %s", (job_id,))
await conn.execute(
"UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() "
"WHERE id = %s AND status = 'processing'", (attachment_id,))
await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, %s)", (job_id, attempt + 1))
await event(conn, job_id, "lease_expired", actor, attempt=attempt)
return len(rows)
async def republish_stale(conn: psycopg.AsyncConnection, older_than: float, actor: str, limit: int = 50) -> int:
"""Lost-message guard: a queued, due job that has had no unpublished outbox row and no
publish for `older_than` seconds gets a new outbox row (its message was lost by the broker,
dead-lettered after too many redeliveries, or the queue was purged)."""
cur = await conn.execute(
"SELECT j.id, j.attempt FROM jobs j "
"WHERE j.state = 'queued' AND j.available_at < clock_timestamp() - make_interval(secs => %s) "
"AND j.updated_at < clock_timestamp() - make_interval(secs => %s) "
"AND NOT EXISTS (SELECT 1 FROM outbox o WHERE o.job_id = j.id AND (o.published_at IS NULL "
" OR o.published_at > clock_timestamp() - make_interval(secs => %s))) "
"ORDER BY j.updated_at LIMIT %s FOR UPDATE OF j SKIP LOCKED", (older_than, older_than, older_than, limit))
rows = await cur.fetchall()
for job_id, attempt in rows:
await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, %s)", (job_id, attempt + 1))
await event(conn, job_id, "republished", actor, attempt=attempt)
return len(rows)
async def purge_outbox(conn: psycopg.AsyncConnection, keep_seconds: int = 7 * 86400) -> int:
cur = await conn.execute(
"DELETE FROM outbox WHERE id IN (SELECT id FROM outbox WHERE published_at < clock_timestamp() "
"- make_interval(secs => %s) LIMIT 1000)", (keep_seconds,))
return cur.rowcount
# ------------------------------------------------------------------ worker
@dataclass(frozen=True, slots=True)
class Claim:
job_id: str
attachment_id: str
pipeline_version: int
attempt: int
max_attempts: int
token: str
source: str # staging | original
source_key: str
content_type: str
size_bytes: int
sha256: bytes
write_original: bool # the original is not published yet: this attempt publishes it too
def key(self, name: str) -> str:
return attempt_key(self.attachment_id, self.token, name)
@dataclass(frozen=True, slots=True)
class Noop:
reason: str # finished | leased | not_due | superseded | unknown_job
async def claim(conn: psycopg.AsyncConnection, job_id: str, worker: str, lease_seconds: float) -> Claim | Noop:
cur = await conn.execute(
"SELECT state, attempt, max_attempts, available_at > clock_timestamp(), attachment_id, pipeline_version "
"FROM jobs WHERE id = %s FOR UPDATE", (job_id,))
row = await cur.fetchone()
if row is None:
return Noop("unknown_job")
state, attempt, max_attempts, not_due, attachment_id, version = row
if state not in ACTIVE:
return Noop("finished") # duplicate/redelivery of a finished job: ack, nothing else
if state == "processing":
return Noop("leased") # another attempt holds the lease; the reaper handles its death
if not_due:
return Noop("not_due") # backoff not over: the outbox publishes it at available_at
cur = await conn.execute(
"SELECT status, published_version, object_key, staging_key, staging_state, content_type, size_bytes, sha256 "
"FROM attachments WHERE id = %s FOR UPDATE", (attachment_id,))
status, published, object_key, staging_key, staging_state, content_type, size, sha = await cur.fetchone()
actor = "worker:" + worker
if published is not None and published >= version:
# A newer (or the same) version is already published: this job can only be stale.
await _finish(conn, job_id, "superseded", None)
await event(conn, job_id, "superseded", actor, attempt=attempt, published_version=published)
return Noop("superseded")
if object_key is not None:
source, source_key = "original", object_key
elif staging_state == "present":
source, source_key = "staging", staging_key
else:
# Cannot happen while the CHECK attachments_active_has_source holds; fail visibly anyway.
await _fail(conn, job_id, attachment_id, "source_missing", actor, attempt)
return Noop("finished")
token = uuid.uuid4().hex
attempt += 1
write_original = object_key is None
names = (("original",) if write_original else ()) + VARIANT_NAMES
planned = [attempt_key(str(attachment_id), token, n) for n in names]
await conn.execute(
"UPDATE jobs SET state = 'processing', attempt = %s, lease_token = %s, lease_owner = %s, "
"lease_until = clock_timestamp() + make_interval(secs => %s), updated_at = clock_timestamp() WHERE id = %s",
(attempt, token, worker, lease_seconds, job_id))
await conn.execute(
"INSERT INTO job_attempts (token, job_id, attempt, worker, source, planned_keys) VALUES (%s, %s, %s, %s, %s, %s)",
(token, job_id, attempt, worker, source, planned))
await conn.execute(
"UPDATE attachments SET status = 'processing', updated_at = clock_timestamp() WHERE id = %s AND status = 'queued'",
(attachment_id,))
await event(conn, job_id, "claimed", actor, attempt=attempt, source=source, token=token)
return Claim(str(job_id), str(attachment_id), version, attempt, max_attempts, token, source, source_key,
content_type, size, bytes(sha), write_original)
async def heartbeat(conn: psycopg.AsyncConnection, claim: Claim, lease_seconds: float) -> bool:
"""Extend the lease; False = the lease was lost (expired and taken over): stop the attempt."""
cur = await conn.execute(
"UPDATE jobs SET lease_until = clock_timestamp() + make_interval(secs => %s) "
"WHERE id = %s AND state = 'processing' AND lease_token = %s", (lease_seconds, claim.job_id, claim.token))
return cur.rowcount == 1
async def _holds_lease(conn: psycopg.AsyncConnection, claim: Claim) -> bool:
cur = await conn.execute("SELECT state = 'processing' AND lease_token = %s FROM jobs WHERE id = %s FOR UPDATE",
(claim.token, claim.job_id))
row = await cur.fetchone()
return bool(row and row[0])
async def complete(conn: psycopg.AsyncConnection, claim: Claim, variants, worker: str) -> str:
"""Publish the result of an attempt atomically: variant rows + attachment ready + job succeeded.
Returns succeeded | superseded | fenced (this attempt lost its lease: nothing written)."""
actor = "worker:" + worker
if not await _holds_lease(conn, claim):
return "fenced"
cur = await conn.execute("SELECT published_version FROM attachments WHERE id = %s FOR UPDATE", (claim.attachment_id,))
(published,) = await cur.fetchone()
if published is not None and published >= claim.pipeline_version:
await _end_attempt(conn, claim, "superseded", None)
await _finish(conn, claim.job_id, "superseded", None)
await event(conn, claim.job_id, "superseded", actor, attempt=claim.attempt, published_version=published)
return "superseded"
for v in variants:
await conn.execute(
"INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, "
"size_bytes, width, height, sha256, attempt_token) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
(claim.attachment_id, claim.pipeline_version, v.name, claim.key(v.name), v.content_type, len(v.data),
v.width, v.height, v.sha256, claim.token))
await conn.execute(
"UPDATE attachments SET status = 'ready', published_version = %s, error_code = NULL, failed_at = NULL, "
"object_key = COALESCE(object_key, %s), updated_at = clock_timestamp() WHERE id = %s",
(claim.pipeline_version, claim.key("original") if claim.write_original else None, claim.attachment_id))
await _end_attempt(conn, claim, "succeeded", None)
await _finish(conn, claim.job_id, "succeeded", None)
await event(conn, claim.job_id, "succeeded", actor, attempt=claim.attempt, pipeline_version=claim.pipeline_version)
return "succeeded"
async def retry_or_fail(conn: psycopg.AsyncConnection, claim: Claim, code: str, permanent: bool, worker: str,
base: float, cap: float) -> tuple[str, float]:
"""After a failed attempt: permanent error or no attempts left -> failed (failed registry);
otherwise queued again after a jittered backoff. Returns (outcome, delay seconds)."""
actor = "worker:" + worker
if not await _holds_lease(conn, claim):
return "fenced", 0.0
if permanent or claim.attempt >= claim.max_attempts:
final = code if permanent else "retry_exhausted"
await _end_attempt(conn, claim, "failed", code)
await _fail(conn, claim.job_id, claim.attachment_id, final, actor, claim.attempt, cause=code)
return "failed", 0.0
delay = backoff_delay(claim.attempt, base, cap)
await _end_attempt(conn, claim, "retry", code)
await conn.execute(
"UPDATE jobs SET state = 'queued', lease_token = NULL, lease_owner = NULL, lease_until = NULL, error_code = %s, "
"available_at = clock_timestamp() + make_interval(secs => %s), updated_at = clock_timestamp() WHERE id = %s",
(code, delay, claim.job_id))
await conn.execute(
"UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() WHERE id = %s AND status = 'processing'",
(claim.attachment_id,))
await conn.execute(
"INSERT INTO outbox (job_id, attempt, available_at) "
"VALUES (%s, %s, clock_timestamp() + make_interval(secs => %s))", (claim.job_id, claim.attempt + 1, delay))
await event(conn, claim.job_id, "retry_scheduled", actor, attempt=claim.attempt, error_code=code,
delay_s=round(delay, 3))
return "retry", delay
async def release(conn: psycopg.AsyncConnection, claim: Claim, worker: str) -> str:
"""Graceful stop of a worker with an attempt still running: give the job back at once
(without waiting for the lease to expire). The claim already counted as an attempt."""
if not await _holds_lease(conn, claim):
return "fenced"
await _end_attempt(conn, claim, "abandoned", "worker_shutdown")
if claim.attempt >= claim.max_attempts:
await _fail(conn, claim.job_id, claim.attachment_id, "retry_exhausted", "worker:" + worker, claim.attempt,
cause="worker_shutdown")
return "failed"
await conn.execute(
"UPDATE jobs SET state = 'queued', lease_token = NULL, lease_owner = NULL, lease_until = NULL, "
"available_at = clock_timestamp(), updated_at = clock_timestamp() WHERE id = %s", (claim.job_id,))
await conn.execute(
"UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() WHERE id = %s AND status = 'processing'",
(claim.attachment_id,))
await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, %s)", (claim.job_id, claim.attempt + 1))
await event(conn, claim.job_id, "released", "worker:" + worker, attempt=claim.attempt)
return "released"
async def _end_attempt(conn: psycopg.AsyncConnection, claim: Claim, outcome: str, code: str | None) -> None:
await conn.execute(
"UPDATE job_attempts SET outcome = %s, error_code = %s, finished_at = clock_timestamp() "
"WHERE token = %s AND outcome = 'running'", (outcome, code, claim.token))
async def _finish(conn: psycopg.AsyncConnection, job_id, state: str, code: str | None) -> None:
await conn.execute(
"UPDATE jobs SET state = %s, error_code = %s, lease_token = NULL, lease_owner = NULL, lease_until = NULL, "
"finished_at = clock_timestamp(), updated_at = clock_timestamp() WHERE id = %s", (state, code, job_id))
async def _fail(conn: psycopg.AsyncConnection, job_id, attachment_id, code: str, actor: str, attempt: int,
**detail) -> None:
"""Job -> failed (registry). The attachment becomes failed only if it is not ready: a failed
reprocess of a newer version leaves the published result in place."""
await _finish(conn, job_id, "failed", code)
await conn.execute(
"UPDATE attachments SET status = 'failed', error_code = %s, failed_at = clock_timestamp(), "
"updated_at = clock_timestamp() WHERE id = %s AND status IN ('queued', 'processing')", (code, attachment_id))
await event(conn, job_id, "failed", actor, attempt=attempt, error_code=code, **detail)
# ------------------------------------------------------------------ cleanup (worker)
async def staging_to_delete(conn: psycopg.AsyncConnection, retention_seconds: int, limit: int = 50) -> list[str]:
"""Candidates only (no lock): ready attachments (staging no longer needed) and failed ones
older than the retention. The decision is re-checked under the row lock in mark_staging_deleting."""
cur = await conn.execute(
"SELECT id FROM attachments WHERE staging_state IN ('present', 'deleting') AND (status = 'ready' OR "
"(status = 'failed' AND failed_at < clock_timestamp() - make_interval(secs => %s))) "
"ORDER BY updated_at LIMIT %s", (retention_seconds, limit))
return [str(r[0]) for r in await cur.fetchall()]
async def mark_staging_deleting(conn: psycopg.AsyncConnection, attachment_id: str, retention_seconds: int) -> str | None:
"""Under the attachment row lock, decide AGAIN from the committed state and mark the staging copy
`deleting` BEFORE the S3 DELETE. A replay that committed in between made the row queued, so it
no longer matches; a replay that comes later sees `deleting` and refuses. Queued/processing
rows never match (and the CHECK attachments_active_has_source forbids it anyway)."""
cur = await conn.execute(
"UPDATE attachments SET staging_state = 'deleting' " # internal state: updated_at stays (public field)
"WHERE id = %s AND staging_state IN ('present', 'deleting') AND (status = 'ready' OR (status = 'failed' "
"AND failed_at < clock_timestamp() - make_interval(secs => %s) AND NOT EXISTS (SELECT 1 FROM jobs j "
"WHERE j.attachment_id = attachments.id AND j.state IN ('queued', 'processing')))) RETURNING staging_key",
(attachment_id, retention_seconds))
row = await cur.fetchone()
return row[0] if row else None
async def mark_staging_deleted(conn: psycopg.AsyncConnection, attachment_id: str) -> None:
await conn.execute(
"UPDATE attachments SET staging_state = 'deleted' WHERE id = %s AND staging_state = 'deleting'", (attachment_id,))
async def attempts_to_clean(conn: psycopg.AsyncConnection, grace_seconds: int, limit: int = 50) -> list[str]:
cur = await conn.execute(
"SELECT token FROM job_attempts WHERE outcome IN ('retry', 'failed', 'abandoned', 'superseded') "
"AND objects_cleaned_at IS NULL AND finished_at < clock_timestamp() - make_interval(secs => %s) "
"ORDER BY finished_at LIMIT %s", (grace_seconds, limit))
return [r[0].hex for r in await cur.fetchall()]
async def lock_attempt_for_cleanup(conn: psycopg.AsyncConnection, token: str) -> list[str] | None:
"""Keys of an attempt that can never publish: it ended without success, it is not the lease
holder of its job (tokens are never reused) and nothing published references its keys."""
cur = await conn.execute(
"SELECT ja.planned_keys FROM job_attempts ja JOIN jobs j ON j.id = ja.job_id "
"WHERE ja.token = %s AND ja.objects_cleaned_at IS NULL "
"AND ja.outcome IN ('retry', 'failed', 'abandoned', 'superseded') "
"AND j.lease_token IS DISTINCT FROM ja.token FOR UPDATE OF ja", (token,))
row = await cur.fetchone()
if row is None:
return None
keys = list(row[0])
cur = await conn.execute(
"SELECT EXISTS (SELECT 1 FROM attachment_variants WHERE object_key = ANY(%s)) "
"OR EXISTS (SELECT 1 FROM attachments WHERE object_key = ANY(%s))", (keys, keys))
if (await cur.fetchone())[0]:
return None # published: never delete (would be a bug elsewhere; logged by the caller)
return keys
async def mark_attempt_cleaned(conn: psycopg.AsyncConnection, token: str) -> None:
await conn.execute("UPDATE job_attempts SET objects_cleaned_at = clock_timestamp() WHERE token = %s", (token,))
+63
View File
@@ -0,0 +1,63 @@
"""Versioned image pipeline (lab 5): WHAT the worker builds for one attachment. Pure definitions,
no I/O; the pixels are produced by imaging.py in a child process.
Every pipeline version builds the same three variants with the geometry of the contract; versions
differ only in encoder parameters, so the published version is visible in the bytes (sha256):
thumbnail JPEG, fits into 256x256, keeps the aspect ratio, never upscales, floor rounding
(minimum 1 px), EXIF orientation applied, alpha composited onto white;
crop JPEG, centred square 128x128 (small images ARE upscaled, the contract allows it);
optimized WebP, fits into 1280x1280, never upscales, alpha kept.
Metadata: nothing of the source is copied into a variant - no EXIF (orientation is applied to
the pixels instead), no XMP, no ICC profile, no comments (the pixels are treated as sRGB).
The original is published byte for byte and keeps everything.
Track 2: the version of a job is fixed when the job is created (PIPELINE_VERSION for uploads,
`jobctl reprocess --pipeline N` later). A result is published only if its version is greater
than the published one, so an old job can never overwrite a newer result.
"""
from __future__ import annotations
from dataclasses import dataclass
THUMBNAIL_BOX = 256
CROP_SIDE = 128
OPTIMIZED_BOX = 1280
VARIANT_NAMES = ("thumbnail", "crop", "optimized")
CONTENT_TYPES = {"thumbnail": "image/jpeg", "crop": "image/jpeg", "optimized": "image/webp"}
@dataclass(frozen=True, slots=True)
class Pipeline:
version: int
jpeg_quality: int # thumbnail and crop: baseline JPEG, 4:2:0, optimized Huffman tables
webp_quality: int # optimized: lossy WebP
webp_method: int # 0 (fast) .. 6 (slow, smaller)
PIPELINES = {
1: Pipeline(1, jpeg_quality=85, webp_quality=80, webp_method=4),
# Versions 2 and 3 exist for the track 2 experiments (reprocess, reorder, stale jobs):
# different encoder settings -> different bytes, identical geometry.
2: Pipeline(2, jpeg_quality=80, webp_quality=75, webp_method=4),
3: Pipeline(3, jpeg_quality=90, webp_quality=85, webp_method=5),
}
def fit(width: int, height: int, box: int) -> tuple[int, int]:
"""Size inside box x box keeping the aspect ratio, never upscaling, rounded DOWN, >= 1 px.
Integer arithmetic: 320x200 -> 256x160 exactly, 1x1000 -> 1x256 (0.256 -> 1 px minimum)."""
if width <= box and height <= box:
return width, height
if width >= height:
return box, max(1, height * box // width)
return max(1, width * box // height), box
def center_square(width: int, height: int) -> tuple[int, int, int, int]:
"""Crop box (left, top, right, bottom) of the centred square with side min(width, height)."""
side = min(width, height)
left = (width - side) // 2
top = (height - side) // 2
return left, top, left + side, top + side
-437
View File
@@ -1,437 +0,0 @@
"""Reconciler of the two stores (lab 4, track 2): S3 objects vs attachment rows in PostgreSQL.
docker compose run --rm reconciler # dry-run: report only (default)
docker compose run --rm reconciler --apply # fix what is safe to fix
docker compose run --rm reconciler --verify-checksums # also read every object (SHA-256)
How it walks: both sides are read as key-ordered streams and merge-joined - ListObjectsV2
pages (prefix o/, byte order) against keyset pages of `attachments ORDER BY object_key`
(COLLATE "C" = the same byte order, unique index). Memory does not depend on the bucket size;
cost is ~N/1000 S3 list requests + N/page DB pages (measured: docs/CONSISTENCY.md).
What it finds and what --apply does (nothing else is ever changed):
kind condition --apply
orphan_object object, no row, older than --grace delete the object
stale_intent row 'pending' older than --grace (+/- object) delete object, then row
missing_object row 'ready', object absent, older than --grace quarantine the row
size_mismatch row 'ready', object size != size_bytes quarantine the row
checksum_mismatch row 'ready', SHA-256 differs (--verify-checksums) quarantine the row
restored_object row quarantined, object present and correct again remove the quarantine
(a checksum quarantine only with --verify-checksums)
fresh_* the same, but younger than --grace nothing (in-flight upload)
Safety:
* dry-run is read-only BY CONSTRUCTION: the PostgreSQL session runs with
default_transaction_read_only=on and the S3 wrapper has no write methods, so even a bug in
the planner cannot modify a store;
* ready rows are never deleted - a used (or unused) ready attachment can only be quarantined,
which is reversible; objects that have a row are never deleted unless the row is a stale
intent; anything younger than --grace is never touched;
* every action re-checks its condition right before acting, under a row lock (FOR UPDATE)
where a row exists, so the live API racing with the reconciler cannot be hurt;
* object first, row second: an interrupted run leaves a state the next run repairs;
re-running is idempotent (the second run finds nothing to do);
* safety valve: --apply refuses to delete more than --max-orphan-fraction of the scanned
objects (pointing it at the wrong/empty database would otherwise wipe the bucket).
"""
from __future__ import annotations
import argparse
import asyncio
import datetime as dt
import hashlib
import json
import sys
import time
from collections import Counter
from collections.abc import AsyncIterator
from dataclasses import dataclass, field
import psycopg
from .config import ConfigError, Settings, _float, _secret, s3_settings
from .errors import Unavailable
from .storage import OBJECT_PREFIX, ListedObject, ObjectMissing, Storage
KINDS = ("orphan_object", "stale_intent", "missing_object", "size_mismatch", "checksum_mismatch",
"restored_object", "fresh_orphan_object", "fresh_intent", "fresh_missing_object")
MIN_SAFE_GRACE = 60.0 # > the longest possible upload (queue 5 s + body 30 s + verify 10 s + S3)
ACTION_OF = {"orphan_object": "delete_object", "stale_intent": "delete_intent", "missing_object": "quarantine",
"size_mismatch": "quarantine", "checksum_mismatch": "quarantine", "restored_object": "unquarantine"}
def log(text: str) -> None:
print(f"reconcile: {text}", file=sys.stderr, flush=True)
@dataclass(frozen=True, slots=True)
class Row:
id: str
key: str
status: str
size: int
sha256: bytes
created_at: dt.datetime
updated_at: dt.datetime
lost_reason: str | None
used: bool
@dataclass(slots=True)
class Finding:
kind: str
key: str
attachment_id: str | None = None
used: bool = False
detail: str = ""
result: str = "planned" # planned | applied | skipped:<why> | failed:<why>
@dataclass
class Stats:
objects: int = 0
rows: int = 0
consistent: int = 0
s3_list_requests: int = 0
s3_head_requests: int = 0
s3_get_bytes: int = 0
db_pages: int = 0
class ReadOnlyStorage:
"""The dry-run view of S3: listing and reading only - there is no delete to call."""
def __init__(self, storage: Storage):
self._s = storage
async def list_page(self, *args, **kwargs):
return await self._s.list_page(*args, **kwargs)
async def head(self, key: str):
return await self._s.head(key)
async def read_all(self, key: str, limit: int) -> bytes:
return await self._s.read_all(key, limit)
class Reconciler:
def __init__(self, conn: psycopg.AsyncConnection, storage: Storage | ReadOnlyStorage, *, grace: float,
page_size: int, verify: bool, apply: bool):
self.conn = conn
self.s3 = storage
self.grace = grace
self.page_size = page_size
self.verify = verify
self.apply = apply
self.stats = Stats()
self.findings: list[Finding] = []
# ---------------------------------------------------------- streams
async def objects(self) -> AsyncIterator[ListedObject]:
after = None
while True:
page, more = await self.s3.list_page(OBJECT_PREFIX, after, self.page_size)
self.stats.s3_list_requests += 1
for item in page:
self.stats.objects += 1
yield item
if not more or not page:
return
after = page[-1].key
async def rows(self) -> AsyncIterator[Row]:
after = ""
while True:
cur = await self.conn.execute(
"SELECT a.id, a.object_key, a.status, a.size_bytes, a.sha256, a.created_at, a.updated_at, "
"a.lost_reason, EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id) "
"FROM attachments a WHERE a.object_key > %s ORDER BY a.object_key LIMIT %s",
(after, self.page_size))
page = await cur.fetchall()
self.stats.db_pages += 1
for r in page:
self.stats.rows += 1
yield Row(str(r[0]), r[1], r[2], r[3], bytes(r[4]), r[5], r[6], r[7], r[8])
if len(page) < self.page_size:
return
after = page[-1][1]
# ---------------------------------------------------------- planning (read-only)
async def scan(self) -> None:
cur = await self.conn.execute("SELECT clock_timestamp()")
self.db_now = (await cur.fetchone())[0]
self.s3_now = time.time()
objects, rows = self.objects(), self.rows()
obj = await anext(objects, None)
row = await anext(rows, None)
while obj is not None or row is not None:
if row is None or (obj is not None and obj.key < row.key):
self.object_only(obj)
obj = await anext(objects, None)
elif obj is None or row.key < obj.key:
self.row_only(row)
row = await anext(rows, None)
else:
await self.both(obj, row)
obj = await anext(objects, None)
row = await anext(rows, None)
def row_old(self, row: Row) -> bool:
return (self.db_now - max(row.created_at, row.updated_at)).total_seconds() > self.grace
def object_only(self, obj: ListedObject) -> None:
old = self.s3_now - obj.last_modified_ts > self.grace
self.add(Finding("orphan_object" if old else "fresh_orphan_object", obj.key))
def row_only(self, row: Row) -> None:
if row.status == "pending":
self.add(Finding("stale_intent" if self.row_old(row) else "fresh_intent", row.key, row.id,
detail="object absent"))
elif row.lost_reason is not None:
self.stats.consistent += 1 # already quarantined, still missing: nothing new
else:
self.add(Finding("missing_object" if self.row_old(row) else "fresh_missing_object", row.key, row.id,
used=row.used))
async def both(self, obj: ListedObject, row: Row) -> None:
if row.status == "pending":
self.add(Finding("stale_intent" if self.row_old(row) else "fresh_intent", row.key, row.id,
detail="object present"))
return
problem = await self.object_problem(row, obj.size)
if problem:
if row.lost_reason is None:
self.add(Finding(problem, row.key, row.id, used=row.used))
else:
self.stats.consistent += 1 # quarantined and still broken
elif row.lost_reason == "checksum_mismatch" and not self.verify:
# Same size, but this pass does not read the bytes: it cannot prove the object is the
# original again, so a checksum quarantine is lifted only by --verify-checksums.
self.stats.consistent += 1
elif row.lost_reason is not None:
self.add(Finding("restored_object", row.key, row.id, used=row.used))
else:
self.stats.consistent += 1
async def object_problem(self, row: Row, size: int) -> str | None:
if size != row.size:
return "size_mismatch"
if self.verify:
data = await self.s3.read_all(row.key, row.size)
self.stats.s3_get_bytes += len(data)
if hashlib.sha256(data).digest() != row.sha256:
return "checksum_mismatch"
return None
def add(self, finding: Finding) -> None:
if finding.kind not in ACTION_OF:
finding.result = "not_actionable"
self.findings.append(finding)
# ---------------------------------------------------------- actions (--apply only)
async def run_actions(self, max_orphan_fraction: float) -> None:
orphans = sum(1 for f in self.findings if f.kind == "orphan_object")
if self.stats.objects and orphans > max_orphan_fraction * self.stats.objects:
raise SafetyValve(f"{orphans} of {self.stats.objects} objects look orphaned "
f"(> {max_orphan_fraction:.0%}); wrong database? nothing was changed")
handlers = {"delete_object": self.delete_object, "delete_intent": self.delete_intent,
"quarantine": self.quarantine, "unquarantine": self.unquarantine}
for finding in self.findings:
action = ACTION_OF.get(finding.kind)
if action is None:
continue
try:
finding.result = await handlers[action](finding)
except (Unavailable, psycopg.OperationalError) as exc:
finding.result = f"failed:{type(exc).__name__}"
raise # a store is down: stop; the next run continues from the committed state
async def delete_object(self, f: Finding) -> str:
cur = await self.conn.execute("SELECT 1 FROM attachments WHERE object_key = %s", (f.key,))
if await cur.fetchone():
return "skipped:row_appeared"
try:
head = await self.s3.head(f.key)
self.stats.s3_head_requests += 1
except ObjectMissing:
return "skipped:already_gone"
if time.time() - head.last_modified_ts <= self.grace:
return "skipped:object_rewritten_recently"
# No row names this key and the object is older than the grace period. Rows are always
# written BEFORE their object and keys are random and never reused, so no upload can
# still claim it.
await self.s3.delete(f.key)
return "applied"
async def delete_intent(self, f: Finding) -> str:
async with self.conn.transaction():
cur = await self.conn.execute(
"SELECT 1 FROM attachments WHERE id = %s AND status = 'pending' "
"AND greatest(created_at, updated_at) < clock_timestamp() - make_interval(secs => %s) FOR UPDATE",
(f.attachment_id, self.grace))
if await cur.fetchone() is None:
return "skipped:no_longer_stale_intent"
await self.s3.delete(f.key) # object first (idempotent), then the row
await self.conn.execute("DELETE FROM attachments WHERE id = %s AND status = 'pending'",
(f.attachment_id,))
return "applied"
async def quarantine(self, f: Finding) -> str:
async with self.conn.transaction():
cur = await self.conn.execute(
"SELECT size_bytes, sha256 FROM attachments WHERE id = %s AND status = 'ready' "
"AND lost_at IS NULL FOR UPDATE", (f.attachment_id,))
row = await cur.fetchone()
if row is None:
return "skipped:row_changed"
reason = await self.current_problem(f.key, row[0], bytes(row[1]))
if reason is None:
return "skipped:object_ok_now"
await self.conn.execute(
"UPDATE attachments SET lost_at = clock_timestamp(), lost_reason = %s WHERE id = %s",
(reason, f.attachment_id))
return "applied"
async def unquarantine(self, f: Finding) -> str:
async with self.conn.transaction():
cur = await self.conn.execute(
"SELECT size_bytes, sha256, lost_reason FROM attachments WHERE id = %s AND lost_at IS NOT NULL FOR UPDATE",
(f.attachment_id,))
row = await cur.fetchone()
if row is None:
return "skipped:row_changed"
if row[2] == "checksum_mismatch" and not self.verify:
return "skipped:needs_verify_checksums"
if await self.current_problem(f.key, row[0], bytes(row[1])) is not None:
return "skipped:object_still_bad"
await self.conn.execute("UPDATE attachments SET lost_at = NULL, lost_reason = NULL WHERE id = %s",
(f.attachment_id,))
return "applied"
async def current_problem(self, key: str, size: int, sha256: bytes) -> str | None:
"""Fresh look at the object right before changing the row (the listing may be stale)."""
try:
head = await self.s3.head(key)
self.stats.s3_head_requests += 1
except ObjectMissing:
return "missing_object"
if head.size != size:
return "size_mismatch"
if self.verify:
data = await self.s3.read_all(key, size)
self.stats.s3_get_bytes += len(data)
if hashlib.sha256(data).digest() != sha256:
return "checksum_mismatch"
return None
# ---------------------------------------------------------- report
def report(self, mode: str, seconds: float, error: str | None, sample: int) -> dict:
kinds = Counter(f.kind for f in self.findings)
results = Counter(f.result.split(":")[0] for f in self.findings if f.kind in ACTION_OF)
samples = {}
for f in self.findings:
items = samples.setdefault(f.kind, [])
if len(items) < sample:
items.append({"key": f.key, "attachment_id": f.attachment_id, "used": f.used,
"result": f.result, **({"detail": f.detail} if f.detail else {})})
return {
"mode": mode, "grace_seconds": self.grace, "verify_checksums": self.verify,
"duration_seconds": round(seconds, 3), "error": error,
"scanned": {"objects": self.stats.objects, "rows": self.stats.rows, "consistent": self.stats.consistent},
"findings": {k: kinds.get(k, 0) for k in KINDS},
"used_attachments_in_findings": sum(1 for f in self.findings if f.used),
"actions": {"planned": sum(1 for f in self.findings if f.kind in ACTION_OF),
"applied": results.get("applied", 0), "skipped": results.get("skipped", 0),
"failed": results.get("failed", 0)},
"cost": {"s3_list_requests": self.stats.s3_list_requests, "s3_head_requests": self.stats.s3_head_requests,
"s3_get_bytes": self.stats.s3_get_bytes, "db_pages": self.stats.db_pages,
"page_size": self.page_size},
"samples": samples,
}
class SafetyValve(Exception):
pass
def arguments(argv: list[str] | None = None) -> argparse.Namespace:
p = argparse.ArgumentParser(prog="python -m messenger.reconcile", description=__doc__.split("\n")[0])
p.add_argument("--apply", action="store_true", help="fix findings (default: dry-run, read-only)")
p.add_argument("--grace", type=float, default=3600.0,
help="seconds; anything younger is never touched (default 3600, >= PENDING_GRACE_SECONDS)")
p.add_argument("--allow-small-grace", action="store_true",
help="permit --grace below 60 s (tests only: a grace shorter than an upload could remove the "
"intent of an upload that is still running; that upload then fails with 503)")
p.add_argument("--page-size", type=int, default=1000, help="S3 list / DB page size (1..1000)")
p.add_argument("--verify-checksums", action="store_true", help="read every ready object and compare SHA-256")
p.add_argument("--samples", type=int, default=20, help="keys listed per finding kind in the report")
p.add_argument("--max-orphan-fraction", type=float, default=0.5,
help="--apply refuses if more than this share of objects look orphaned (default 0.5)")
args = p.parse_args(argv)
if not 1 <= args.page_size <= 1000:
p.error("--page-size must be 1..1000")
if args.grace < 1 or (args.grace < MIN_SAFE_GRACE and not args.allow_small_grace):
p.error(f"--grace must be >= {MIN_SAFE_GRACE:.0f} s (or >= 1 s with --allow-small-grace)")
if not 0 < args.max_orphan_fraction <= 1:
p.error("--max-orphan-fraction must be in (0, 1]")
return args
async def run(args: argparse.Namespace) -> int:
url = _secret("DATABASE_URL", required=True)
base = s3_settings()
settings = Settings(host="", port=0, env="lab", log_level="info", shutdown_timeout=0, max_body_bytes=1024,
database_url=url, **base)
timeout_ms = int(_float("DB_TIMEOUT_SECONDS", 10.0, 1.0, 120.0) * 1000)
options = f"-c statement_timeout={timeout_ms} -c lock_timeout={timeout_ms // 2}"
if not args.apply:
options += " -c default_transaction_read_only=on" # dry-run: PostgreSQL itself refuses writes
mode = "apply" if args.apply else "dry-run"
storage = Storage(settings)
await storage.open()
started = time.perf_counter()
error = None
code = 0
try:
conn = await psycopg.AsyncConnection.connect(url, autocommit=True, connect_timeout=5, options=options,
application_name=f"messenger-reconcile-{mode}")
except psycopg.OperationalError as exc:
await storage.close()
error = f"store_unavailable: database {type(exc).__name__}"
print(json.dumps({"mode": mode, "error": error}, ensure_ascii=False))
log(error)
return 1
rec = Reconciler(conn, storage if args.apply else ReadOnlyStorage(storage), grace=args.grace,
page_size=args.page_size, verify=args.verify_checksums, apply=args.apply)
try:
log(f"{mode}: scanning bucket {settings.s3_bucket} (prefix {OBJECT_PREFIX}) against table attachments")
await rec.scan()
log(f"scan done: {rec.stats.objects} objects, {rec.stats.rows} rows, {len(rec.findings)} findings")
if args.apply:
await rec.run_actions(args.max_orphan_fraction)
except SafetyValve as exc:
error, code = f"safety_valve: {exc}", 3
except (Unavailable, psycopg.OperationalError) as exc:
error, code = f"store_unavailable: {type(exc).__name__}", 1
finally:
await conn.close()
await storage.close()
print(json.dumps(rec.report(mode, time.perf_counter() - started, error, args.samples), ensure_ascii=False,
indent=1))
if error:
log(error)
return code
def main(argv: list[str] | None = None) -> int:
args = arguments(argv)
try:
return asyncio.run(run(args))
except ConfigError as exc:
print(f"configuration error: {exc}", file=sys.stderr)
return 2
if __name__ == "__main__":
sys.exit(main())
+169
View File
@@ -0,0 +1,169 @@
"""Outbox relay: `python -m messenger.relay` (compose service `relay`, one process).
loop: SELECT due outbox rows FOR UPDATE SKIP LOCKED
-> publish each job message to RabbitMQ, wait for the publisher CONFIRM
-> UPDATE outbox SET published_at -> COMMIT
every few seconds: reaper (expired leases -> queued/failed), lost-message guard.
Why an outbox: the API commits the job and the outbox row in ONE PostgreSQL transaction and never
talks to the broker. A crash between COMMIT and publish leaves the row unpublished; the relay
publishes it when it (or the broker) is back - nobody re-creates a job by hand. While the broker
is down, uploads still get 202 and the rows wait in the outbox.
A crash after the confirm but before the COMMIT of published_at publishes the row once more after
the restart: the queue then holds a duplicate. That is at-least-once delivery; the worker turns
the duplicate into a no-op (jobs.claim). The relay never deletes or rewrites jobs.
"""
from __future__ import annotations
import asyncio
import logging
import sys
import time
import aio_pika
from aio_pika.abc import AbstractChannel, AbstractConnection, AbstractExchange
from . import broker, jobs, logging_setup, service
from .config import ConfigError, Settings
from .db import Database
from .errors import Unavailable
log = logging.getLogger("messenger.relay")
ACTOR = "relay"
MAINTENANCE_SECONDS = 5.0
PURGE_SECONDS = 600.0
class Relay:
def __init__(self, settings: Settings):
self.settings = settings
self.db = Database(settings, name="messenger-relay")
self.connection: AbstractConnection | None = None
self.channel: AbstractChannel | None = None
self.exchange: AbstractExchange | None = None
self.lost: asyncio.Event | None = None
def connected(self) -> bool:
return (self.connection is not None and self.lost is not None and not self.lost.is_set()
and self.channel is not None and not self.channel.is_closed)
async def connect(self) -> None:
self.connection = await aio_pika.connect(
self.settings.broker_url, timeout=5,
client_properties={"connection_name": "relay@" + self.settings.instance_id})
self.lost = service.watch_connection(self.connection)
# Confirm mode: every publish() waits for basic.ack of the broker (message in the quorum log).
self.channel = await self.connection.channel(publisher_confirms=True, on_return_raises=True)
# No declare: the topology belongs to the broker definitions; the relay may only write.
self.exchange = await self.channel.get_exchange(broker.EXCHANGE, ensure=False)
log.info("broker_connected", extra={"fields": {"exchange": broker.EXCHANGE}})
async def disconnect(self) -> None:
if self.connection is not None:
try:
await self.connection.close()
except Exception: # noqa: BLE001 - already broken
pass
self.connection = self.channel = self.exchange = self.lost = None
async def publish_due(self) -> int:
settings = self.settings
exchange = self.exchange
async def work(conn) -> list[jobs.Due]:
rows = await jobs.due_outbox(conn, settings.relay_batch)
if "reverse_order" in settings.fault_points:
rows.reverse()
# Rows of jobs that are no longer queued (finished meanwhile) need no message.
sendable = [r for r in rows if r.job_state == "queued"]
copies = 2 if "duplicate_publish" in settings.fault_points else 1
for row in sendable:
message = aio_pika.Message(
broker.encode(row.job_id, row.attachment_id, row.pipeline_version, row.attempt, row.created_at),
delivery_mode=aio_pika.DeliveryMode.PERSISTENT, content_type="application/json",
message_id=f"{row.job_id}:{row.outbox_id}", type=broker.JOB_TYPE)
for _ in range(copies):
await exchange.publish(message, routing_key=broker.ROUTING_KEY, mandatory=True, timeout=5)
for row in sendable:
# Confirmed by the broker, outbox not marked yet: the window "after publish, before
# the confirm is recorded". The crash rolls this transaction back.
await service.crash_once(settings, self.db, "crash_after_publish", row.job_id, ACTOR,
outbox_id=row.outbox_id)
await jobs.mark_published(conn, [r.outbox_id for r in rows])
return sendable
sent = await self.db.run(work, deadline=10 + 5 * settings.relay_batch)
for row in sent:
log.info("job_published", extra={"fields": {"job_id": row.job_id, "attempt": row.attempt,
"outbox_id": row.outbox_id}})
return len(sent)
async def maintenance(self) -> None:
expired = await self.db.run(lambda c: jobs.expire_leases(c, ACTOR))
republished = await self.db.run(lambda c: jobs.republish_stale(c, self.settings.queued_republish_seconds, ACTOR))
if expired or republished:
log.info("maintenance", extra={"fields": {"leases_expired": expired, "republished": republished}})
async def run(self) -> int:
stop = service.stop_event()
await self.db.open()
next_maintenance = next_purge = 0.0
failures = 0
try:
while not stop.is_set():
healthy = True
now = time.monotonic()
try:
if now >= next_maintenance:
await self.maintenance()
next_maintenance = now + MAINTENANCE_SECONDS
if now >= next_purge:
purged = await self.db.run(jobs.purge_outbox)
next_purge = now + PURGE_SECONDS
if purged:
log.info("outbox_purged", extra={"fields": {"rows": purged}})
except Unavailable:
healthy = False
try:
if not self.connected():
await self.disconnect()
await self.connect()
sent = await self.publish_due()
failures = 0
except Unavailable:
healthy, sent = False, 0
except Exception as exc: # noqa: BLE001 - every broker/channel error, never a crash
# Broker down/unreachable, channel closed, message returned/nacked: nothing marked,
# the rows stay in the outbox (transaction rolled back) and are published later.
failures += 1
healthy, sent = False, 0
log.warning("publish_failed", extra={"fields": {"error": type(exc).__name__, "failures": failures}})
await self.disconnect()
if healthy:
service.beat()
if not sent:
await service.sleep_or_stop(stop, min(5.0, self.settings.relay_poll_seconds * (2 ** min(failures, 3))))
finally:
await self.disconnect()
await self.db.close()
log.info("relay_stopped")
return 0
def main() -> int:
try:
settings = Settings.from_env(s3_credentials=False)
if not settings.broker_url:
raise ConfigError("BROKER_URL_FILE (or BROKER_URL) must be set")
except ConfigError as exc:
print(f"configuration error: {exc}", file=sys.stderr)
return 2
logging_setup.configure(settings.log_level)
log.info("relay_starting", extra={"fields": {"instance_id": settings.instance_id,
"fault_points": sorted(settings.fault_points)}})
return asyncio.run(Relay(settings).run())
if __name__ == "__main__":
sys.exit(main())
+8 -7
View File
@@ -230,11 +230,12 @@ async def _insert_message(conn: psycopg.AsyncConnection, message_id: uuid.UUID,
return created_at
# Attachments a message may reference: ready, of THIS chat (else 404), not quarantined (else 409).
# FOR SHARE keeps a concurrent quarantine (reconciler) from slipping in before COMMIT.
# Attachments a message may reference (lab 5): of THIS chat and not the invisible 'pending' intent
# (else 404); queued/processing/ready are usable, failed or quarantined -> 409.
# FOR SHARE keeps a concurrent transition to failed from slipping in before COMMIT.
CHECK_ATTACHMENTS = (
"SELECT count(*), count(*) FILTER (WHERE a.lost_at IS NULL) FROM ("
"SELECT lost_at FROM attachments WHERE id = ANY(%s::uuid[]) AND chat_id = %s AND status = 'ready' "
"SELECT count(*), count(*) FILTER (WHERE a.lost_at IS NULL AND a.status <> 'failed') FROM ("
"SELECT lost_at, status FROM attachments WHERE id = ANY(%s::uuid[]) AND chat_id = %s AND status <> 'pending' "
"FOR SHARE) a")
@@ -280,7 +281,7 @@ async def post_message(db: Database, user_id: str, chat_id: str, key: str, reque
ever left behind: a crash or 5xx rolls everything back and the client may retry);
* same key, same body (any replica, also concurrently) -> the stored Message, 201, replayed;
* same key, other body -> 409; the membership check comes first, so outsiders always get 404;
* attachments (lab 4) are checked before the key is claimed (same order as post_message_v2).
* attachments (lab 4) are checked before the key is claimed (same order as post_message_v3).
"""
message_id = uuid.uuid4()
attachment_ids = list(attachment_ids)
@@ -308,12 +309,12 @@ async def post_message(db: Database, user_id: str, chat_id: str, key: str, reque
POST_MESSAGE_CALL = ("SELECT o_status, o_id, o_text, o_created_at, o_attachments "
"FROM post_message_v2(%s, %s, %s, %s, %s, %s, %s, %s::uuid[])")
"FROM post_message_v3(%s, %s, %s, %s, %s, %s, %s, %s::uuid[])")
async def post_message_single_call(db: Database, user_id: str, chat_id: str, key: str, request_hash: bytes,
text: str, ttl_seconds: int, attachment_ids: list[str] = ()) -> PostResult:
"""Same contract as post_message, ONE round trip: SQL function post_message_v2 (migration 0004 =
"""Same contract as post_message, ONE round trip: SQL function post_message_v3 (migration 0005 =
0003 + attachment_ids) in autocommit mode, i.e. the call is the whole transaction."""
message_id = uuid.uuid4()
+79 -48
View File
@@ -3,14 +3,15 @@
Idempotent, safe to run on every `docker compose up`:
1. waits until the S3 endpoint answers;
2. creates the bucket with the ADMIN key pair if it does not exist yet (an existing bucket and
its objects are left untouched);
3. writes the sentinel object `health/sentinel` that the API's readiness probe HEADs;
2. creates the final bucket (S3_BUCKET) and the staging bucket (S3_STAGING_BUCKET) with the ADMIN
key pair if they do not exist yet (existing buckets and their objects are left untouched);
3. writes the sentinel object `health/sentinel` into the final bucket (the API readiness HEADs it);
4. proves the access model and FAILS the stand (exit 1) if it is wrong:
* anonymous (unsigned) GET of an object and anonymous LIST of the bucket are refused;
* the API key pair can read/write objects of ITS bucket, but can neither list it, nor create
a bucket, nor see or read another bucket (a canary bucket created here for this check);
* the reconciler key pair can list the bucket but cannot create one.
* anonymous (unsigned) GET of an object and anonymous LIST are refused on both buckets;
* api: writes staging, reads final; cannot read staging, write final, list or create buckets,
nor read another bucket (a canary bucket created here for this check);
* worker: reads and writes both buckets; cannot list or create buckets;
* auditor: reads and lists both buckets; cannot write.
Only file names and verdicts are printed, never key values.
"""
from __future__ import annotations
@@ -57,14 +58,33 @@ def settings_with(keys: tuple[str, str]) -> Settings:
return Settings(host="", port=0, env="lab", log_level="info", shutdown_timeout=0, max_body_bytes=1024, **base)
def pair(prefix: str) -> tuple[str, str]:
return _secret(f"{prefix}ACCESS_KEY_ID", True), _secret(f"{prefix}SECRET_ACCESS_KEY", True)
async def ensure_bucket(admin_s3: Storage, bucket: str) -> bool:
code = await error_code(admin_s3.client.head_bucket(Bucket=bucket))
if code == "":
say(f"bucket {bucket}: exists, kept as is")
return True
if code in ("404", "NoSuchBucket", "NotFound"):
code = await error_code(admin_s3.client.create_bucket(Bucket=bucket))
if code not in ("", "BucketAlreadyOwnedByYou", "BucketAlreadyExists"):
say(f"bucket {bucket}: create failed ({code})")
return False
say(f"bucket {bucket}: created")
return True
say(f"bucket {bucket}: head failed ({code})")
return False
async def run() -> int:
admin = (_secret("S3_ADMIN_ACCESS_KEY_ID", True), _secret("S3_ADMIN_SECRET_ACCESS_KEY", True))
api = (_secret("S3_ACCESS_KEY_ID", True), _secret("S3_SECRET_ACCESS_KEY", True))
reconciler = (_secret("S3_RECONCILER_ACCESS_KEY_ID", True), _secret("S3_RECONCILER_SECRET_ACCESS_KEY", True))
settings = settings_with(admin)
bucket = settings.s3_bucket
admin_s3, api_s3, rec_s3 = Storage(settings), Storage(settings_with(api)), Storage(settings_with(reconciler))
for s in (admin_s3, api_s3, rec_s3):
settings = settings_with(pair("S3_ADMIN_"))
final, staging = settings.s3_bucket, settings.s3_staging_bucket
admin_s3 = Storage(settings)
clients = {"api": Storage(settings_with(pair("S3_"))), "worker": Storage(settings_with(pair("S3_WORKER_"))),
"auditor": Storage(settings_with(pair("S3_AUDITOR_")))}
for s in (admin_s3, *clients.values()):
await s.open()
try:
deadline = time.monotonic() + 60
@@ -77,64 +97,75 @@ async def run() -> int:
say("S3 endpoint does not answer within 60 s")
return 1
await asyncio.sleep(1)
code = await error_code(admin_s3.client.head_bucket(Bucket=bucket))
if code == "":
say(f"bucket {bucket}: exists, kept as is")
elif code in ("404", "NoSuchBucket", "NotFound"):
code = await error_code(admin_s3.client.create_bucket(Bucket=bucket))
if code not in ("", "BucketAlreadyOwnedByYou", "BucketAlreadyExists"):
say(f"bucket {bucket}: create failed ({code})")
for bucket in (final, staging):
if not await ensure_bucket(admin_s3, bucket):
return 1
say(f"bucket {bucket}: created")
else:
say(f"bucket {bucket}: head failed ({code})")
return 1
await admin_s3.put(SENTINEL_KEY, b"ok\n", "text/plain", {})
await admin_s3.client.put_object(Bucket=staging, Key=SENTINEL_KEY, Body=b"ok\n")
say(f"sentinel {SENTINEL_KEY}: written")
canary = bucket + "-canary"
canary = final + "-canary"
if await error_code(admin_s3.client.head_bucket(Bucket=canary)):
await admin_s3.client.create_bucket(Bucket=canary)
await admin_s3.client.put_object(Bucket=canary, Key="canary", Body=b"secret of another bucket")
failures = []
base = settings.s3_endpoint.rstrip("/")
for what, url in (("anonymous GET object", f"{base}/{bucket}/{SENTINEL_KEY}"),
("anonymous LIST bucket", f"{base}/{bucket}?list-type=2")):
status = anonymous_status(url)
verdict = "refused" if status in (401, 403) else "ALLOWED"
say(f"{what}: HTTP {status} -> {verdict}")
if verdict != "refused":
failures.append(what)
for bucket in (final, staging):
for what, url in ((f"anonymous GET object of {bucket}", f"{base}/{bucket}/{SENTINEL_KEY}"),
(f"anonymous LIST of {bucket}", f"{base}/{bucket}?list-type=2")):
status = anonymous_status(url)
verdict = "refused" if status in (401, 403) else "ALLOWED"
say(f"{what}: HTTP {status} -> {verdict}")
if verdict != "refused":
failures.append(what)
probe = "health/bootstrap-probe"
def c(who: str):
return clients[who].client
# (what, coroutine, allowed?) - every refusal must be a real AccessDenied, not an outage.
checks = [
("api: read object", await error_code(api_s3.client.head_object(Bucket=bucket, Key=SENTINEL_KEY)), True),
("api: write object", await error_code(api_s3.client.put_object(Bucket=bucket, Key=probe, Body=b"p")), True),
("api: delete object", await error_code(api_s3.client.delete_object(Bucket=bucket, Key=probe)), True),
("api: list bucket", await error_code(api_s3.client.list_objects_v2(Bucket=bucket, MaxKeys=1)), False),
("api: create bucket", await error_code(api_s3.client.create_bucket(Bucket=bucket + "-x")), False),
("api: read object of another bucket",
await error_code(api_s3.client.head_object(Bucket=canary, Key="canary")), False),
("reconciler: list bucket", await error_code(rec_s3.client.list_objects_v2(Bucket=bucket, MaxKeys=1)), True),
("reconciler: create bucket", await error_code(rec_s3.client.create_bucket(Bucket=bucket + "-x")), False),
("api: write staging", c("api").put_object(Bucket=staging, Key=probe, Body=b"p"), True),
("api: delete staging (janitor)", c("api").delete_object(Bucket=staging, Key=probe), True),
("api: read staging", c("api").head_object(Bucket=staging, Key=SENTINEL_KEY), False),
("api: read final", c("api").head_object(Bucket=final, Key=SENTINEL_KEY), True),
("api: write final", c("api").put_object(Bucket=final, Key=probe, Body=b"p"), False),
("api: list final", c("api").list_objects_v2(Bucket=final, MaxKeys=1), False),
("api: list staging", c("api").list_objects_v2(Bucket=staging, MaxKeys=1), False),
("api: create bucket", c("api").create_bucket(Bucket=final + "-x"), False),
("api: read another bucket", c("api").head_object(Bucket=canary, Key="canary"), False),
("worker: read staging", c("worker").head_object(Bucket=staging, Key=SENTINEL_KEY), True),
("worker: write final", c("worker").put_object(Bucket=final, Key=probe, Body=b"p"), True),
("worker: delete final", c("worker").delete_object(Bucket=final, Key=probe), True),
("worker: write staging", c("worker").put_object(Bucket=staging, Key=probe, Body=b"p"), True),
("worker: delete staging", c("worker").delete_object(Bucket=staging, Key=probe), True),
("worker: list final", c("worker").list_objects_v2(Bucket=final, MaxKeys=1), False),
("worker: create bucket", c("worker").create_bucket(Bucket=final + "-x"), False),
("worker: read another bucket", c("worker").head_object(Bucket=canary, Key="canary"), False),
("auditor: list final", c("auditor").list_objects_v2(Bucket=final, MaxKeys=1), True),
("auditor: list staging", c("auditor").list_objects_v2(Bucket=staging, MaxKeys=1), True),
("auditor: read final", c("auditor").head_object(Bucket=final, Key=SENTINEL_KEY), True),
("auditor: write final", c("auditor").put_object(Bucket=final, Key=probe, Body=b"p"), False),
("auditor: delete staging", c("auditor").delete_object(Bucket=staging, Key=SENTINEL_KEY), False),
]
for what, code, allowed in checks:
ok = (code == "") == allowed
for what, coro, allowed in checks:
code = await error_code(coro)
ok = (code == "") == allowed and code in ("", "AccessDenied", "403")
say(f"{what}: {'allowed' if code == '' else 'refused (' + code + ')'} -> {'OK' if ok else 'WRONG'}")
if not ok:
failures.append(what)
visible = [b["Name"] for b in (await api_s3.client.list_buckets()).get("Buckets", [])]
visible = [b["Name"] for b in (await c("api").list_buckets()).get("Buckets", [])]
say(f"api: buckets visible in ListBuckets: {visible} -> {'OK' if canary not in visible else 'WRONG'}")
if canary in visible:
failures.append("api sees another bucket")
if failures:
say("access model is WRONG: " + ", ".join(failures))
return 1
say("done: private bucket, least-privilege keys verified")
say("done: private buckets, least-privilege keys verified")
return 0
finally:
for s in (admin_s3, api_s3, rec_s3):
for s in (admin_s3, *clients.values()):
await s.close()
+76
View File
@@ -0,0 +1,76 @@
"""Common runtime of the background processes (relay, worker): signals, heartbeat file for the
Docker healthcheck, failure injection that fires once per job and leaves an audit row."""
from __future__ import annotations
import asyncio
import logging
import os
import signal
import time
from pathlib import Path
from . import jobs
from .config import Settings
from .db import Database
log = logging.getLogger("messenger.service")
HEARTBEAT_FILE = Path(os.environ.get("HEARTBEAT_FILE", "/tmp/heartbeat"))
CRASH_EXIT_CODE = 70 # os._exit: no cleanup, no ack, no COMMIT - like SIGKILL in the middle of work
def beat() -> None:
"""Healthcheck input: `python -m messenger.healthcheck --file /tmp/heartbeat --max-age 30`."""
try:
HEARTBEAT_FILE.write_text(str(time.time()), encoding="ascii")
except OSError:
pass
def watch_connection(connection) -> asyncio.Event:
"""Event set when an AMQP connection is closed by ANY side. aio-pika's `is_closed` does not turn
True when the broker drops the connection (found by the broker-restart test: the worker kept
"running" without a consumer), so the close callback is the signal to reconnect."""
lost = asyncio.Event()
connection.close_callbacks.add(lambda *_: lost.set())
return lost
def stop_event() -> asyncio.Event:
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for sig in (signal.SIGTERM, signal.SIGINT):
try:
loop.add_signal_handler(sig, stop.set)
except (NotImplementedError, RuntimeError):
pass # Windows unit tests: no signal handlers
return stop
async def sleep_or_stop(stop: asyncio.Event, seconds: float) -> None:
try:
await asyncio.wait_for(stop.wait(), seconds)
except asyncio.TimeoutError:
pass
async def crash_once(settings: Settings, db: Database, point: str, job_id: str, actor: str, **detail) -> None:
"""Experiments only (FAULT_POINTS): kill THIS process at `point`, once per job (and per `detail`),
across restarts and replicas. The decision is an audit row committed before the crash, so the
restarted process (or another replica) continues normally and the evidence stays in job_events."""
if point not in settings.fault_points:
return
async def record(conn) -> bool:
cur = await conn.execute(
"SELECT 1 FROM job_events WHERE job_id = %s AND event = 'fault_injected' AND detail->>'point' = %s "
"AND detail @> %s::jsonb", (job_id, point, jobs.json.dumps({k: str(v) for k, v in detail.items()})))
if await cur.fetchone():
return False
await jobs.event(conn, job_id, "fault_injected", actor, point=point, **{k: str(v) for k, v in detail.items()})
return True
if await db.run(record):
log.warning("fault_injected_crash", extra={"fields": {"point": point, "job_id": job_id, **detail}})
logging.shutdown()
os._exit(CRASH_EXIT_CODE)
+14 -3
View File
@@ -58,8 +58,10 @@ class ListedObject:
class Storage:
def __init__(self, settings: Settings, *, access_key: str | None = None, secret_key: str | None = None):
self.bucket = settings.s3_bucket
def __init__(self, settings: Settings, *, access_key: str | None = None, secret_key: str | None = None,
bucket: str | None = None):
# Lab 5: one client per bucket - the final bucket (S3_BUCKET) or the staging bucket.
self.bucket = bucket or settings.s3_bucket
self.timeout = settings.s3_timeout_seconds
self._endpoint = settings.s3_endpoint
self._region = settings.s3_region
@@ -174,4 +176,13 @@ class Storage:
SENTINEL_KEY = "health/sentinel"
OBJECT_PREFIX = "o/" # every attachment original lives under o/<random 128-bit hex>
# Lab 4 originals: o/<random 128-bit hex> in the final bucket (still readable).
OBJECT_PREFIX = "o/"
# Lab 5: s/<random 128-bit hex> in the STAGING bucket (written by the API before 202) and
# a/<attachment id>/<attempt token>/<original|thumbnail|crop|optimized> in the final bucket
# (written by the worker; the token makes every attempt write its own keys).
STAGING_PREFIX = "s/"
def attempt_key(attachment_id: str, token: str, name: str) -> str:
return f"a/{attachment_id}/{token}/{name}"
+6 -10
View File
@@ -181,19 +181,15 @@ def filename_param(query: list[tuple[str, str]]) -> str:
return value
ATTACHMENT_VARIANTS = frozenset({"thumbnail", "crop", "optimized"}) # exist in the schema, not in lab 4
ATTACHMENT_VARIANTS = ("original", "thumbnail", "crop", "optimized")
def variant_param(query: list[tuple[str, str]]) -> str:
"""`variant` of GET /attachments/{id}/content: only `original` exists in lab 4. A known variant
name is a missing variant of a ready object (404); anything else is an invalid value (400)."""
"""`variant` of GET /attachments/{id}/content: original (default) or a lab 5 variant name.
Any other value is 400; a known name that a ready attachment lacks is 404 (handler)."""
value = single_query_param(query, "variant")
if value is None or value == "original":
if value is None:
return "original"
if value in ATTACHMENT_VARIANTS:
raise NotFoundVariant()
raise InvalidRequest("variant должен быть original")
class NotFoundVariant(Exception):
"""Raised for a variant that lab 4 does not produce; mapped to 404 by the handler."""
return value
raise InvalidRequest("variant должен быть original, thumbnail, crop или optimized")
+340
View File
@@ -0,0 +1,340 @@
"""Image worker: `python -m messenger.worker` (compose service `worker`, separate from the API).
One delivery of a job message:
decode + validate (schema v1; invalid -> reject -> dead-letter queue)
-> CLAIM in PostgreSQL (jobs.claim): finished/leased/not due/stale -> no-op, ack
-> lease heartbeat every JOB_LEASE_SECONDS/3 while the attempt runs
-> read the source (staging copy or published original), check size + SHA-256 against the DB
-> variants in a child process (imaging.py: pixel, memory and time limits)
-> PUT the original (first publication) and the variants under keys of THIS attempt
-> ONE transaction: variants + attachment ready, fenced by the lease token (jobs.complete)
-> ack -> delete the staging copy (marked in the DB first, then S3).
The ack comes only after the durable effect (the COMMIT). A crash anywhere before it makes
RabbitMQ deliver the message again; the job row then says what is left to do. Failures: a
permanent one (invalid_image, image_too_large, source_missing/corrupt) fails the job at once, a
transient one (S3 down, timeout, killed decoder) is retried with backoff via the outbox, at most
JOB_MAX_ATTEMPTS claims in total.
Concurrency: RabbitMQ prefetch = WORKER_CONCURRENCY unacked messages per worker, and at most
WORKER_CONCURRENCY image child processes. Graceful stop (SIGTERM): stop consuming, let running
attempts finish for WORKER_SHUTDOWN_SECONDS, give the rest back (jobs.release).
The worker also runs the cleanup of the pipeline objects (staging copies that are no longer
needed, objects of attempts that never published) - always decided under a row lock.
"""
from __future__ import annotations
import asyncio
import hashlib
import logging
import sys
import time
import aio_pika
from aio_pika.abc import AbstractChannel, AbstractConnection, AbstractIncomingMessage, AbstractQueue
from . import broker, imaging, jobs, logging_setup, service
from .config import ConfigError, Settings
from .db import Database
from .errors import Unavailable
from .imaging import ProcessingError
from .storage import ObjectMissing, Storage
log = logging.getLogger("messenger.worker")
class Worker:
def __init__(self, settings: Settings):
self.settings = settings
self.name = settings.instance_id
self.actor = "worker:" + self.name
self.db = Database(settings, name="messenger-worker")
self.staging = Storage(settings, bucket=settings.s3_staging_bucket)
self.final = Storage(settings)
self.slots = asyncio.Semaphore(settings.worker_concurrency)
self.tasks: set[asyncio.Task] = set()
self.connection: AbstractConnection | None = None
self.channel: AbstractChannel | None = None
self.queue: AbstractQueue | None = None
self.consumer_tag: str | None = None
self.lost: asyncio.Event | None = None
def connected(self) -> bool:
return (self.connection is not None and self.lost is not None and not self.lost.is_set()
and self.channel is not None and not self.channel.is_closed)
# ---------------------------------------------------------------- broker
async def connect(self) -> None:
self.connection = await aio_pika.connect(
self.settings.broker_url, timeout=5,
client_properties={"connection_name": "worker@" + self.name})
self.lost = service.watch_connection(self.connection)
self.channel = await self.connection.channel()
# Prefetch: the broker keeps at most this many unacked messages in flight to this worker.
await self.channel.set_qos(prefetch_count=self.settings.worker_concurrency)
self.queue = await self.channel.get_queue(broker.QUEUE, ensure=False)
self.consumer_tag = await self.queue.consume(self.on_message, no_ack=False)
log.info("consuming", extra={"fields": {"queue": broker.QUEUE, "prefetch": self.settings.worker_concurrency}})
async def disconnect(self) -> None:
if self.connection is not None:
try:
await self.connection.close()
except Exception: # noqa: BLE001 - already broken
pass
self.connection = self.channel = self.queue = self.lost = None
self.consumer_tag = None
async def on_message(self, message: AbstractIncomingMessage) -> None:
task = asyncio.create_task(self.deliver(message))
self.tasks.add(task)
task.add_done_callback(self.tasks.discard)
@staticmethod
async def settle(action) -> None:
"""ack/nack/reject; the channel may be gone (broker restart): then the broker requeues the
message by itself and the redelivery is a no-op."""
try:
await action
except Exception as exc: # noqa: BLE001
log.warning("settle_failed", extra={"fields": {"error": type(exc).__name__}})
async def deliver(self, message: AbstractIncomingMessage) -> None:
try:
body = broker.decode(message.body)
except broker.BadMessage as exc:
log.error("bad_message", extra={"fields": {"reason": str(exc), "message_id": message.message_id}})
await self.settle(message.reject(requeue=False)) # -> messenger.attachment-jobs.dlq
return
try:
async with self.slots:
outcome = await self.process(body["job_id"])
except Unavailable:
# PostgreSQL (or S3 during a DB step) unavailable: nothing decided. Back to the queue
# after a pause; a claim that did happen is protected by its lease.
log.warning("job_deferred", extra={"fields": {"job_id": body["job_id"]}})
await asyncio.sleep(2)
await self.settle(message.nack(requeue=True))
return
except asyncio.CancelledError:
# Shutdown: back to the queue. If the job was claimed it has been released (new outbox
# row), and one of the two deliveries becomes a no-op.
await self.settle(asyncio.shield(message.nack(requeue=True)))
raise
log.info("job_done", extra={"fields": {"job_id": body["job_id"], "outcome": outcome,
"message_attempt": body["attempt"], "redelivered": message.redelivered}})
await self.settle(message.ack())
# ---------------------------------------------------------------- one attempt
async def process(self, job_id: str) -> str:
settings = self.settings
claim = await self.db.run(lambda c: jobs.claim(c, job_id, self.name, settings.job_lease_seconds))
if isinstance(claim, jobs.Noop):
return "noop_" + claim.reason
await service.crash_once(settings, self.db, "crash_after_claim", job_id, self.actor)
lost = asyncio.Event()
work = asyncio.create_task(self.attempt(claim))
beat = asyncio.create_task(self.heartbeat(claim, work, lost))
try:
variants = await work
except asyncio.CancelledError:
if lost.is_set() and not asyncio.current_task().cancelling():
return "fenced" # lease taken over: this attempt may write nothing more
outcome = await asyncio.shield(self.db.run(lambda c: jobs.release(c, claim, self.name)))
log.info("job_released", extra={"fields": {"job_id": job_id, "outcome": outcome}})
raise
except ProcessingError as exc:
return await self.failed(claim, exc.code, exc.permanent)
except Unavailable:
return await self.failed(claim, "storage_unavailable", False)
finally:
beat.cancel()
await service.crash_once(settings, self.db, "crash_after_s3_write", job_id, self.actor)
outcome = await self.db.run(lambda c: jobs.complete(c, claim, variants, self.name))
await service.crash_once(settings, self.db, "crash_after_commit", job_id, self.actor)
if outcome == "succeeded":
await self.delete_staging(claim.attachment_id)
return outcome
async def failed(self, claim: jobs.Claim, code: str, permanent: bool) -> str:
s = self.settings
outcome, delay = await self.db.run(
lambda c: jobs.retry_or_fail(c, claim, code, permanent, self.name, s.job_retry_base_seconds,
s.job_retry_max_seconds))
log.info("attempt_failed", extra={"fields": {"job_id": claim.job_id, "attempt": claim.attempt, "code": code,
"permanent": permanent, "outcome": outcome,
"delay_s": round(delay, 3)}})
return outcome
async def heartbeat(self, claim: jobs.Claim, work: asyncio.Task, lost: asyncio.Event) -> None:
"""Renew the lease while the attempt is alive and within JOB_TIMEOUT_SECONDS. A hung attempt
stops being renewed, so the reaper can hand the job to another worker; if the lease turns out
to be lost, the attempt is cancelled (its result would be fenced anyway)."""
s = self.settings
if "hang" in s.fault_points:
return # experiment: a hung worker that no longer heartbeats
started = time.monotonic()
while True:
await asyncio.sleep(s.job_lease_seconds / 3)
if time.monotonic() - started > s.job_timeout_seconds:
return
try:
alive = await self.db.run(lambda c: jobs.heartbeat(c, claim, s.job_lease_seconds))
except Unavailable:
continue # the lease may expire meanwhile; the fence protects the result
if not alive:
log.warning("lease_lost", extra={"fields": {"job_id": claim.job_id, "attempt": claim.attempt}})
lost.set()
work.cancel()
return
async def attempt(self, claim: jobs.Claim) -> list[imaging.Rendered]:
s = self.settings
if "hang" in s.fault_points:
await asyncio.sleep(s.fault_value("hang", 3600)) # stuck outside of the time limit
try:
return await asyncio.wait_for(self.build(claim), s.job_timeout_seconds)
except asyncio.TimeoutError:
raise ProcessingError("processing_timeout", permanent=False) from None
async def build(self, claim: jobs.Claim) -> list[imaging.Rendered]:
s = self.settings
started = time.monotonic()
if claim.size_bytes > s.max_upload_bytes:
raise ProcessingError("image_too_large", permanent=True)
source = self.staging if claim.source == "staging" else self.final
try:
data = await source.read_all(claim.source_key, limit=s.max_upload_bytes)
except ObjectMissing:
raise ProcessingError("source_missing", permanent=True) from None
if len(data) != claim.size_bytes or hashlib.sha256(data).digest() != claim.sha256:
raise ProcessingError("source_corrupt", permanent=True)
self.injected(claim)
if "slow" in s.fault_points and s.fault_value("slow_pipeline", claim.pipeline_version) == claim.pipeline_version:
await asyncio.sleep(s.fault_value("slow", 10))
remaining = max(1.0, s.job_timeout_seconds - (time.monotonic() - started))
variants = await imaging.render(data, claim.content_type, claim.pipeline_version,
max_pixels=s.max_image_pixels, timeout=remaining,
memory_mb=s.image_max_memory_mb)
meta = {"attachment-id": claim.attachment_id, "pipeline-version": str(claim.pipeline_version)}
puts = [self.final.put(claim.key(v.name), v.data, v.content_type, meta) for v in variants]
if claim.write_original:
puts.append(self.final.put(claim.key("original"), data, claim.content_type,
{**meta, "sha256": claim.sha256.hex()}))
await asyncio.gather(*puts)
return variants
def injected(self, claim: jobs.Claim) -> None:
s = self.settings
if "permanent_error" in s.fault_points:
raise ProcessingError("invalid_image", permanent=True)
if "transient_error" in s.fault_points and claim.attempt <= s.fault_value("transient_error", 1000):
raise ProcessingError("injected_transient", permanent=False)
# ---------------------------------------------------------------- cleanup
async def delete_staging(self, attachment_id: str) -> None:
"""Mark `deleting` under the row lock (re-checked there), then S3 DELETE, then `deleted`."""
try:
key = await self.db.run(
lambda c: jobs.mark_staging_deleting(c, attachment_id, self.settings.staging_retention_seconds))
if key is None:
return
await self.staging.delete(key)
await self.db.run(lambda c: jobs.mark_staging_deleted(c, attachment_id))
log.info("staging_deleted", extra={"fields": {"attachment_id": attachment_id}})
except Unavailable:
pass # stays present/deleting; the next cleanup pass repeats (DELETE is idempotent)
async def cleanup(self) -> None:
s = self.settings
ids = await self.db.run(lambda c: jobs.staging_to_delete(c, s.staging_retention_seconds))
tokens = await self.db.run(lambda c: jobs.attempts_to_clean(c, s.orphan_grace_seconds))
if "pause_cleanup" in s.fault_points and (ids or tokens):
# Experiment: the race "cleanup read its candidates -> replay commits -> cleanup goes on".
log.warning("cleanup_paused", extra={"fields": {"attachments": ids, "attempts": tokens}})
await asyncio.sleep(s.fault_value("pause_cleanup", 10))
for attachment_id in ids:
await self.delete_staging(attachment_id)
for token in tokens:
keys = await self.db.run(lambda c: jobs.lock_attempt_for_cleanup(c, token))
if keys is None:
continue
await asyncio.gather(*(self.final.delete(k) for k in keys))
await self.db.run(lambda c: jobs.mark_attempt_cleaned(c, token))
log.info("attempt_objects_deleted", extra={"fields": {"token": token, "objects": len(keys)}})
async def cleanup_loop(self, stop: asyncio.Event) -> None:
while not stop.is_set() and self.settings.cleanup_interval_seconds > 0:
await service.sleep_or_stop(stop, self.settings.cleanup_interval_seconds)
try:
await self.cleanup()
except Unavailable:
pass
# ---------------------------------------------------------------- lifecycle
async def run(self) -> int:
stop = service.stop_event()
await self.db.open()
await self.staging.open()
await self.final.open()
cleaner = asyncio.create_task(self.cleanup_loop(stop))
try:
while not stop.is_set():
if not self.connected():
await self.disconnect()
try:
await self.connect()
except Exception as exc: # noqa: BLE001 - broker down: retry in 2 s, never crash
log.warning("broker_unavailable", extra={"fields": {"error": type(exc).__name__}})
await self.disconnect()
if self.connected():
service.beat() # healthy only while a consumer is really attached
await service.sleep_or_stop(stop, 2.0)
await self.shutdown()
finally:
cleaner.cancel()
await self.disconnect()
await self.final.close()
await self.staging.close()
await self.db.close()
log.info("worker_stopped")
return 0
async def shutdown(self) -> None:
"""Stop consuming; running attempts get WORKER_SHUTDOWN_SECONDS, the rest is released."""
if self.queue is not None and self.consumer_tag is not None:
try:
await self.queue.cancel(self.consumer_tag)
except Exception: # noqa: BLE001
pass
pending = set(self.tasks)
log.info("worker_draining", extra={"fields": {"in_flight": len(pending)}})
if pending:
_, pending = await asyncio.wait(pending, timeout=self.settings.worker_shutdown_seconds)
for task in pending:
task.cancel()
if pending:
await asyncio.wait(pending, timeout=10)
def main() -> int:
try:
settings = Settings.from_env()
if not settings.broker_url:
raise ConfigError("BROKER_URL_FILE (or BROKER_URL) must be set")
except ConfigError as exc:
print(f"configuration error: {exc}", file=sys.stderr)
return 2
logging_setup.configure(settings.log_level)
log.info("worker_starting", extra={"fields": {
"instance_id": settings.instance_id, "concurrency": settings.worker_concurrency,
"max_attempts": settings.job_max_attempts, "timeout_s": settings.job_timeout_seconds,
"lease_s": settings.job_lease_seconds, "memory_mb": settings.image_max_memory_mb,
"fault_points": sorted(settings.fault_points)}})
return asyncio.run(Worker(settings).run())
if __name__ == "__main__":
sys.exit(main())
+99 -40
View File
@@ -120,21 +120,33 @@ def service_down(service: str, how: str = "stop"):
wait_stand()
def recreate(service: str, env: dict, scale: int | None = None) -> None:
"""`docker compose up` of ONE service with the given environment (no dependency restarts)."""
cmd = ["docker", "compose", "up", "-d", "--no-deps", "--wait", service]
if scale is not None:
cmd[4:4] = ["--scale", f"{service}={scale}"]
subprocess.run(cmd, cwd=ROOT, env=env, capture_output=True, text=True, check=True, timeout=180)
@contextlib.contextmanager
def api_with_env(**overrides: str):
"""Recreate the api container with environment overrides (e.g. SESSION_TTL_SECONDS=2),
then ALWAYS recreate it with the normal configuration."""
env = {**os.environ, **overrides}
subprocess.run(["docker", "compose", "up", "-d", "--wait", "api"], cwd=ROOT, env=env,
capture_output=True, text=True, check=True, timeout=180)
wait_stand()
def service_with_env(service: str, scale: int | None = None, **overrides: str):
"""Recreate a service (api, relay, worker) with environment overrides (e.g. FAULT_POINTS of the
worker = WORKER_FAULT_POINTS), then ALWAYS recreate it with the normal configuration."""
clean = {k: v for k, v in os.environ.items() if k not in overrides}
recreate(service, {**os.environ, **overrides}, scale)
if service == "api":
wait_stand()
try:
yield
finally:
clean = {k: v for k, v in os.environ.items() if k not in overrides}
subprocess.run(["docker", "compose", "up", "-d", "--wait", "api"], cwd=ROOT, env=clean,
capture_output=True, text=True, check=True, timeout=180)
wait_stand()
recreate(service, clean, 1 if scale is not None and service != "api" else None)
wait_healthy(service)
if service == "api":
wait_stand()
def api_with_env(**overrides: str):
return service_with_env("api", **overrides)
def running_replicas() -> list[dict]:
@@ -235,7 +247,7 @@ class Api:
def send(self, actor: dict, chat: dict, text: str, key: str | None = None) -> dict:
return self.post_message(actor, chat, {"text": text}, key=key).json()
def upload(self, actor: dict, chat: dict, data, expected=201, *, content_type: str | None = "image/png",
def upload(self, actor: dict, chat: dict, data, expected=202, *, content_type: str | None = "image/png",
filename: str | None = "photo.png", query: str | None = None, headers: dict | None = None):
"""POST raw bytes to /chats/{id}/attachments. `query` replaces the whole query string
(to send hand-made percent-encoding); `data` may be bytes or an iterator (chunked)."""
@@ -247,12 +259,31 @@ class Api:
path = f"/api/v1/chats/{chat['id']}/attachments" + (f"?{query}" if query else "")
if isinstance(data, (bytes, bytearray)):
return self.call("POST", path, expected, token=actor["token"], raw=bytes(data), headers=h,
schema="Attachment" if expected == 201 else None)
schema="Attachment" if expected == 202 else None)
h["Authorization"] = "Bearer " + actor["token"]
response = self.client.post(path, content=data, headers=h)
assert response.status_code == expected, (response.status_code, response.text[:300])
return response
def attachment(self, actor: dict, attachment_id: str, expected=200) -> dict:
return self.call("GET", f"/api/v1/attachments/{attachment_id}", expected, token=actor["token"],
schema="Attachment" if expected == 200 else None).json()
def wait_status(self, actor: dict, attachment_id: str, *statuses: str, timeout: float = 60) -> dict:
"""Poll the metadata until the status is one of `statuses` (default: a final one)."""
wanted = statuses or ("ready", "failed")
deadline = time.monotonic() + timeout
while True:
att = self.attachment(actor, attachment_id)
if att["status"] in wanted:
return att
assert time.monotonic() < deadline, f"attachment stayed {att['status']}, wanted {wanted}"
time.sleep(0.3)
def content(self, actor: dict, attachment_id: str, variant: str | None = None, expected=200):
query = f"?variant={variant}" if variant else ""
return self.call("GET", f"/api/v1/attachments/{attachment_id}/content{query}", expected, token=actor["token"])
def history(self, actor: dict, chat: dict, limit: int) -> tuple[list[dict], int]:
"""Walk all pages; returns (items, number_of_pages)."""
items, pages, cursor = [], 0, None
@@ -300,73 +331,101 @@ def run_hook(name: str, timeout: float = 180, **env: str) -> subprocess.Complete
timeout=timeout, env={**os.environ, **env})
def s3_exec(body: str, service: str = "api", stdin: str | None = None) -> str:
"""Run `body` (async Python, `s` = messenger.storage.Storage) INSIDE a container that holds S3
credentials: `api` (Read+Write, the API's own key pair) or `reconciler` (+List). The S3 port is
not published on the host; this is how the tests inject faults directly into the bucket."""
def s3_exec(body: str, bucket: str = "final", service: str = "worker", stdin: str | None = None) -> str:
"""Run `body` (async Python, `s` = messenger.storage.Storage of the final or the staging bucket)
INSIDE a container that holds S3 credentials: `worker` (Read+Write both buckets, no List) or
`auditor` (Read+List, no Write). The S3 port is not published on the host; this is how the
tests look into the buckets and inject faults."""
script = ("import asyncio, base64, json, sys\n"
"from messenger.config import Settings, s3_settings\n"
"from messenger.storage import Storage, ObjectMissing\n"
"async def main():\n"
" st = Settings(host='', port=0, env='lab', log_level='info', shutdown_timeout=0, max_body_bytes=1024, **s3_settings())\n"
" s = Storage(st)\n"
f" s = Storage(st, bucket=st.s3_staging_bucket if {bucket == 'staging'} else None)\n"
" await s.open()\n"
" try:\n" + "".join(" " + line + "\n" for line in body.splitlines()) +
" finally:\n"
" await s.close()\n"
"asyncio.run(main())\n")
if service == "api":
cmd = ["exec", "-T", "api", "python", "-c", script]
else:
if service == "auditor":
cmd = ["run", "--rm", "--no-deps", "-T", "--entrypoint", "python", service, "-c", script]
else:
cmd = ["exec", "-T", service, "python", "-c", script]
return compose(*cmd, timeout=120, stdin=stdin).stdout.strip()
def s3_put(key: str, data: bytes) -> None:
def s3_put(key: str, data: bytes, bucket: str = "final") -> None:
"""Write raw bytes under `key` (base64 over stdin: Windows limits command lines to 32 KiB)."""
s3_exec(f"await s.put({key!r}, base64.b64decode(sys.stdin.read()), 'image/png', {{}})",
s3_exec(f"await s.put({key!r}, base64.b64decode(sys.stdin.read()), 'image/png', {{}})", bucket,
stdin=base64.b64encode(data).decode())
def s3_delete(key: str) -> None:
s3_exec(f"await s.delete({key!r})")
def s3_delete(key: str, bucket: str = "final") -> None:
s3_exec(f"await s.delete({key!r})", bucket)
def s3_size(key: str) -> int | None:
out = s3_exec(f"try:\n print((await s.head({key!r})).size)\nexcept ObjectMissing:\n print(-1)")
def s3_size(key: str, bucket: str = "final") -> int | None:
out = s3_exec(f"try:\n print((await s.head({key!r})).size)\nexcept ObjectMissing:\n print(-1)", bucket)
size = int(out.splitlines()[-1])
return None if size < 0 else size
def s3_keys() -> set[str]:
"""Every object key under o/ (needs List: runs with the reconciler's key pair)."""
def s3_keys(prefix: str, bucket: str = "final") -> set[str]:
"""Every object key under `prefix` (needs List: runs with the auditor's key pair)."""
out = s3_exec("keys, after = [], None\n"
"while True:\n"
" page, more = await s.list_page('o/', after, 1000)\n"
f" page, more = await s.list_page({prefix!r}, after, 1000)\n"
" keys += [o.key for o in page]\n"
" if not more or not page:\n"
" break\n"
" after = page[-1].key\n"
"print(json.dumps(keys))", service="reconciler")
"print(json.dumps(keys))", bucket, service="auditor")
return set(json.loads(out.splitlines()[-1]))
def reconcile(*args: str, expect_code: int = 0) -> dict:
"""Run the reconciler CLI (compose service, profile tools) and return its JSON report."""
# --no-deps: never let `compose run` start a store that a test has stopped on purpose.
result = compose("run", "--rm", "--no-deps", "-T", "reconciler", "--samples", "100000", *args, check=False,
timeout=300)
assert result.returncode == expect_code, (result.returncode, result.stderr[-2000:])
def jobctl(*args: str, expect_code: int = 0) -> dict:
"""Operator CLI (compose service jobctl, profile tools); returns its JSON output."""
result = compose("run", "--rm", "--no-deps", "-T", "jobctl", *args, check=False, timeout=120)
assert result.returncode == expect_code, (result.returncode, result.stdout[-1000:], result.stderr[-1000:])
return json.loads(result.stdout)
def findings_by_key(report: dict) -> dict[str, dict]:
return {item["key"]: dict(item, kind=kind) for kind, items in report["samples"].items() for item in items}
def audit(*args: str) -> dict:
"""Read-only invariant checker (compose service auditor); asserts that it found no violation."""
result = compose("run", "--rm", "--no-deps", "-T", "auditor", *args, check=False, timeout=300)
report = json.loads(result.stdout)
assert result.returncode == 0 and report["ok"], json.dumps(report.get("violations"), ensure_ascii=False)[:3000]
return report
def job_rows(attachment_id: str) -> list[dict]:
out = psql("SELECT coalesce(json_agg(json_build_object('id', id, 'state', state, 'attempt', attempt, 'kind', kind, "
"'pipeline_version', pipeline_version, 'error_code', error_code) ORDER BY created_at), '[]') "
"FROM jobs WHERE attachment_id = '%s'" % attachment_id)
return json.loads(out)
def events_of(attachment_id: str) -> list[dict]:
out = psql("SELECT coalesce(json_agg(json_build_object('event', e.event, 'attempt', e.attempt, 'actor', e.actor, "
"'error_code', e.error_code, 'detail', e.detail, 'at', e.at) ORDER BY e.id), '[]') "
"FROM job_events e JOIN jobs j ON j.id = e.job_id WHERE j.attachment_id = '%s'" % attachment_id)
return json.loads(out)
def queue_depth(queue: str = "messenger.attachment-jobs") -> int:
out = compose("exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", "messages").stdout
for line in out.splitlines():
name, _, count = line.partition("\t")
if name == queue:
return int(count)
raise AssertionError("queue not found: " + queue)
def attachment_row(attachment_id: str) -> dict | None:
out = psql("SELECT json_build_object('status', status, 'object_key', object_key, 'size', size_bytes, "
"'lost_reason', lost_reason) FROM attachments WHERE id = '%s'" % attachment_id)
"'lost_reason', lost_reason, 'staging_key', staging_key, 'staging_state', staging_state, "
"'published_version', published_version, 'error_code', error_code) "
"FROM attachments WHERE id = '%s'" % attachment_id)
return json.loads(out) if out else None
+24
View File
@@ -91,3 +91,27 @@ def jpeg_bomb_header() -> bytes:
"""SOF0 announcing 20000 x 20000 = 400 Mpx."""
return (b"\xff\xd8\xff\xc0\x00\x11\x08" + struct.pack(">HH", 20000, 20000)
+ b"\x03\x01\x22\x00\x02\x11\x01\x03\x11\x01" + b"\xff\xd9")
# ------------------------------------------------------------------ cases the reviewer used in lab 4/5 PRs
def png_bad_filter(filter_byte: int) -> bytes:
"""PNG 1x1 RGB, correct CRCs and zlib stream, but the row filter byte is not 0..4."""
raw = bytes([filter_byte]) + b"\x00\x00\x00"
return PNG_SIGNATURE + ihdr(1, 1) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
def png_idat_not_zlib() -> bytes:
"""Correct PNG structure, IDAT = b'not-a-zlib-stream' with a recomputed CRC."""
return PNG_SIGNATURE + ihdr(64, 64) + chunk(b"IDAT", b"not-a-zlib-stream") + chunk(b"IEND", b"")
# SOI, SOF0 1x1 grey, SOS, EOI: no tables, no scan data (27 bytes).
JPEG_27_BYTES = bytes.fromhex("ffd8ffc0000b080001000101011100ffda0008010100003f00ffd9")
def jpeg_sos_unknown_component() -> bytes:
"""A valid JPEG whose first SOS component id (byte sos+5) is 250, absent from SOF."""
data = bytearray(jpeg(64, 48))
sos = data.index(b"\xff\xda")
data[sos + 5] = 250
return bytes(data)
+35 -12
View File
@@ -1,10 +1,14 @@
"""Attachments through the load balancer (lab 4, levels 3 and 4): upload/download, ACL, limits,
content checks, filename rules and messages with attachment_ids.
"""Attachments through the load balancer (lab 4, levels 3 and 4; lab 5: upload is 202 queued and
the worker publishes the original + variants): upload/download, ACL, limits, content checks,
filename rules and messages with attachment_ids.
Negative inputs include every case the reviewer used against other lab 4 solutions: corrupted
IDAT with valid CRCs, the first 33 bytes of the fixture, JPEG without scan data, a 20000x10000
header (DecompressionBomb), exactly 10 MiB through the LB, C1 control U+0085 and a whitespace
filename, text=null / missing text / attachment_ids=null in a message."""
filename, text=null / missing text / attachment_ids=null in a message; and the lab 4/5 review
cases: PNG row filter 5 and 0xff, IDAT that is not a zlib stream, the 27-byte JPEG without tables
and scan data, a JPEG whose SOS names a component missing from SOF - all 415 AT UPLOAD, never
202 followed by failed/invalid_image."""
from __future__ import annotations
import hashlib
@@ -42,12 +46,14 @@ def test_png_and_jpeg_roundtrip_byte_for_byte(api, trio):
jpg = imagegen.jpeg(321, 123, noise=True)
for data, ctype in ((SAMPLE, "image/png"), (jpg, "image/jpeg")):
att = api.upload(alice, chat, data, content_type=ctype, filename="кот 😺.bin").json()
assert att["status"] == "ready" and att["variants"] == [] and att["error_code"] is None
assert att["status"] == "queued" and att["variants"] == [] and att["error_code"] is None
assert att["chat_id"] == chat["id"] and att["owner_id"] == alice["id"]
assert att["size_bytes"] == len(data) and att["sha256"] == hashlib.sha256(data).hexdigest()
assert att["content_type"] == ctype and att["filename"] == "кот 😺.bin"
meta = api.call("GET", f"/api/v1/attachments/{att['id']}", 200, token=bob["token"], schema="Attachment").json()
assert meta == att
meta = api.wait_status(bob, att["id"], "ready")
assert {k: v for k, v in meta.items() if k not in ("status", "variants", "updated_at")} == \
{k: v for k, v in att.items() if k not in ("status", "variants", "updated_at")}
assert [v["name"] for v in meta["variants"]] == ["thumbnail", "crop", "optimized"]
got = content(api, bob, att["id"])
assert got.content == data and got.headers["content-type"] == ctype
assert got.headers["content-length"] == str(len(data))
@@ -59,13 +65,16 @@ def test_png_and_jpeg_roundtrip_byte_for_byte(api, trio):
def test_metadata_reveals_no_storage_details(api, trio):
alice, _, _, chat, _ = trio
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(alice, att["id"], "ready")
row = attachment_row(att["id"])
assert row["status"] == "ready" and row["object_key"].startswith("o/")
assert row["status"] == "ready" and row["object_key"].startswith(f"a/{att['id']}/")
assert row["staging_key"].startswith("s/")
text = api.call("GET", f"/api/v1/attachments/{att['id']}", 200, token=alice["token"]).text
assert row["object_key"] not in text and "messenger-attachments" not in text and "s3" not in text.lower()
# The key is random: neither the id nor the filename is part of it.
assert att["id"].replace("-", "") not in row["object_key"] and "photo" not in row["object_key"]
assert s3_size(row["object_key"]) == len(SAMPLE) # the bytes ARE in the bucket
for secret in (row["object_key"], row["staging_key"], "messenger-attachments", "messenger-staging", "a/", "s3"):
assert secret not in text.lower(), secret
# The staging key is random: neither the id nor the filename is part of it.
assert att["id"].replace("-", "") not in row["staging_key"] and "photo" not in row["staging_key"]
assert s3_size(row["object_key"]) == len(SAMPLE) # the published original IS in the final bucket
def test_original_is_not_stored_on_api_containers(api, trio):
@@ -174,6 +183,7 @@ def test_size_limit_through_the_load_balancer(api, trio):
exact = imagegen.png_exactly(10 * MiB)
assert len(exact) == 10 * MiB
att = api.upload(alice, chat, exact).json() # exactly the limit: accepted via LB
api.wait_status(bob, att["id"], "ready")
assert content(api, bob, att["id"]).content == exact
started = time.monotonic()
api.upload(alice, chat, exact + b"\x00", 413) # Content-Length over the limit
@@ -201,6 +211,10 @@ def test_exactly_40_megapixels_is_accepted(api, trio):
data = imagegen.png(8000, 5000, compress_level=9) # 40 000 000 px, ~120 KB file
att = api.upload(alice, chat, data).json()
assert att["size_bytes"] == len(data)
# Lab 5: the worker processes the biggest allowed picture within its memory limit.
ready = api.wait_status(alice, att["id"], "ready", timeout=120)
assert {v["name"]: (v["width"], v["height"]) for v in ready["variants"]} == \
{"thumbnail": (256, 160), "crop": (128, 128), "optimized": (1280, 800)}
# ------------------------------------------------------------------ content checks
@@ -213,6 +227,11 @@ BROKEN = {
"png: bytes after IEND": (SAMPLE + b"<?php echo 1; ?>", "image/png"),
"jpeg: no scan data after SOS": (imagegen.jpeg_without_scan_data(), "image/jpeg"),
"jpeg: truncated": (imagegen.jpeg(400, 300, noise=True)[:5000], "image/jpeg"),
"review: png row filter 5": (imagegen.png_bad_filter(5), "image/png"),
"review: png row filter 0xff": (imagegen.png_bad_filter(0xFF), "image/png"),
"review: png IDAT not-a-zlib-stream": (imagegen.png_idat_not_zlib(), "image/png"),
"review: jpeg 27 bytes, no tables/scan": (imagegen.JPEG_27_BYTES, "image/jpeg"),
"review: jpeg SOS component not in SOF": (imagegen.jpeg_sos_unknown_component(), "image/jpeg"),
"mime: png bytes declared jpeg": (SAMPLE, "image/jpeg"),
"mime: jpeg bytes declared png": (imagegen.jpeg(), "image/png"),
"mime: gif declared png": (b"GIF89a" + bytes(100), "image/png"),
@@ -253,6 +272,7 @@ def test_unicode_filename_is_kept_and_safely_exposed(api, trio):
name = 'отчёт "Q3"; ok.png'
att = api.upload(alice, chat, SAMPLE, filename=name).json()
assert att["filename"] == name
api.wait_status(alice, att["id"], "ready")
disposition = content(api, alice, att["id"]).headers["content-disposition"]
assert '"' not in disposition.split('filename="')[1].split('";')[0] # quotes neutralised in the fallback
assert "filename*=UTF-8''" in disposition
@@ -262,7 +282,10 @@ def test_unicode_filename_is_kept_and_safely_exposed(api, trio):
def test_variant_parameter(api, trio):
alice, _, eve, chat, _ = trio
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(alice, att["id"], "ready")
assert content(api, alice, att["id"], query="?variant=original").content == SAMPLE
content(api, alice, att["id"], 404, query="?variant=thumbnail") # schema name, not produced in lab 4
assert content(api, alice, att["id"], query="?variant=thumbnail").headers["content-type"] == "image/jpeg"
content(api, alice, att["id"], 400, query="?variant=huge")
content(api, alice, att["id"], 400, query="?variant=thumbnail&variant=crop")
content(api, eve, att["id"], 404, query="?variant=thumbnail") # outsider: 404, nothing revealed
content(api, eve, att["id"], 404, query="?variant=huge") # outsider first, then the value
+20 -12
View File
@@ -278,15 +278,15 @@ def test_scale_up_and_down_is_picked_up_without_errors(api):
def test_compose_policy_limits_ports_secrets_images():
config = json.loads(compose("config", "--format", "json").stdout)
services = config["services"]
# The reconciler (profile "tools") is started on demand and not part of the running stand.
assert set(services) == {"postgres", "valkey", "s3", "migrate", "s3-init", "api", "lb"}
# auditor and jobctl (profile "tools") are started on demand and not part of the running stand.
assert set(services) == {"postgres", "valkey", "s3", "broker", "migrate", "s3-init", "api", "lb", "relay", "worker"}
for name, svc in services.items():
limits = svc.get("deploy", {}).get("resources", {}).get("limits", {})
assert limits.get("cpus") and limits.get("memory"), f"{name}: CPU/RAM limits"
assert "container_name" not in svc, f"{name}: container_name prevents scaling"
if name in ("api", "migrate"):
assert "build" in svc # built from this repository's source
elif name == "s3-init":
elif name in ("s3-init", "relay", "worker"):
assert svc["image"] == services["api"]["image"] # the same locally built image
else:
assert "@sha256:" in svc["image"], f"{name}: image must be pinned by digest"
@@ -294,21 +294,28 @@ def test_compose_policy_limits_ports_secrets_images():
published = {name: svc.get("ports", []) for name, svc in services.items() if svc.get("ports")}
assert set(published) == {"lb"} and all(p["host_ip"] in ("127.0.0.1", "::1") for p in published["lb"])
secrets = {name: sorted(s["source"] for s in svc.get("secrets", [])) for name, svc in services.items()}
s3_keys = ['s3_admin_access_key_id', 's3_admin_secret_access_key', 's3_api_access_key_id', 's3_api_secret_access_key', 's3_reconciler_access_key_id', 's3_reconciler_secret_access_key']
s3_keys = sorted(f"s3_{who}_{part}" for who in ("admin", "api", "worker", "auditor")
for part in ("access_key_id", "secret_access_key"))
assert secrets == {"postgres": ["postgres_password"], "valkey": ["valkey_password"], "s3": s3_keys,
"migrate": ["database_url"], "s3-init": s3_keys, "lb": [],
# the API: its own S3 key pair only (no admin, no reconciler keys)
"api": ["cache_url", "database_url", "s3_api_access_key_id", "s3_api_secret_access_key"]}
"broker": ["rabbitmq_users"],
# the API: its own S3 key pair only (no admin/worker keys, no broker credentials)
"api": ["cache_url", "database_url", "s3_api_access_key_id", "s3_api_secret_access_key"],
# relay: database + its broker user only; worker: + its own S3 key pair
"relay": ["broker_url_relay", "database_url"],
"worker": ["broker_url_worker", "database_url", "s3_worker_access_key_id",
"s3_worker_secret_access_key"]}
volumes = {name: [v["source"] for v in svc.get("volumes", []) if v["type"] == "volume"]
for name, svc in services.items()}
assert volumes == {"postgres": ["pgdata"], "valkey": ["valkeydata"], "s3": ["s3data"], "migrate": [],
"s3-init": [], "api": [], "lb": []}
"s3-init": [], "api": [], "lb": [], "broker": ["rabbitmqdata"], "relay": [], "worker": []}
networks = {name: sorted(svc.get("networks", {})) for name, svc in services.items()}
assert networks == {"postgres": ["data"], "valkey": ["data"], "s3": ["storage"], "migrate": ["data"],
"s3-init": ["storage"], "api": ["data", "edge", "storage"],
"lb": ["edge"]}, networks # the LB cannot reach the stores at all
assert config["networks"]["data"].get("internal") is True
assert config["networks"]["storage"].get("internal") is True
"s3-init": ["storage"], "api": ["data", "edge", "storage"], "broker": ["queue"],
"relay": ["data", "queue"], "worker": ["data", "queue", "storage"],
"lb": ["edge"]}, networks # the LB cannot reach the stores; the API not the broker
for network in ("data", "storage", "queue"):
assert config["networks"][network].get("internal") is True, network
def test_running_containers_have_limits_and_no_bypass_ports():
@@ -326,7 +333,8 @@ def test_running_containers_have_limits_and_no_bypass_ports():
def test_migrations_ran_once_by_the_migrate_service():
applied = psql("SELECT version FROM schema_migrations ORDER BY version").split()
assert applied == ["0001_init", "0002_idempotency_keys", "0003_post_message_function", "0004_attachments"]
assert applied == ["0001_init", "0002_idempotency_keys", "0003_post_message_function", "0004_attachments",
"0005_pipeline"]
migrate = compose("ps", "-a", "--format", "json", "migrate").stdout
rows = [json.loads(line) for line in migrate.splitlines() if line.strip()]
assert rows and all(r["State"] == "exited" and r["ExitCode"] == 0 for r in rows)
+39 -25
View File
@@ -1,13 +1,15 @@
"""Consistency of PostgreSQL and S3 around one upload (lab 4, level 4).
"""Consistency of PostgreSQL and S3 around one upload (lab 4 level 4, lab 5 failure windows of the API).
The two-store write is: intent row 'pending' -> S3 PUT -> row 'ready' -> 201. Failures between
the steps are injected with FAULT_POINTS (compose variable, empty in normal runs; the API
raises 503 at that exact point, as if the process or the network failed there):
Lab 5 upload: intent row 'pending' -> staging PUT -> ONE transaction 'queued' + job + outbox -> 202.
Failures between the steps are injected with FAULT_POINTS of the api service (compose variable
API_FAULT_POINTS, empty in normal runs; the API raises 503 at that exact point, as if the process
or the network failed there):
* after_s3_put object written, row still pending, client got 503 -> the janitor removes
the object and the row after PENDING_GRACE_SECONDS (here 3 s);
* after_ready_commit row ready and object written, but the answer is lost (client got 503)
-> nothing may be deleted: the attachment stays intact and downloadable.
* after_s3_put "after staging, before the job is written": staging object exists, row
still pending, NO job and NO outbox row; the client got 503 -> invisible,
the janitor removes the staging object and the row after PENDING_GRACE_SECONDS;
* after_enqueue_commit job committed, the answer is lost (client got 503) -> nothing may be
deleted: the worker processes the job and the attachment becomes ready.
Plus: an upload interrupted by the client and a stalled body leave nothing behind."""
from __future__ import annotations
@@ -28,10 +30,18 @@ SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
def rows_of_chat(chat_id: str) -> list[tuple[str, str, str]]:
out = psql(f"SELECT id || ' ' || status || ' ' || object_key FROM attachments WHERE chat_id = '{chat_id}'")
out = psql(f"SELECT id || ' ' || status || ' ' || staging_key FROM attachments WHERE chat_id = '{chat_id}'")
return [tuple(line.split()) for line in out.splitlines() if line]
def jobs_of(attachment_id: str) -> tuple[int, int]:
"""(jobs rows, outbox rows) of an attachment."""
out = psql(f"SELECT (SELECT count(*) FROM jobs WHERE attachment_id = '{attachment_id}') || ' ' || "
f"(SELECT count(*) FROM outbox o JOIN jobs j ON j.id = o.job_id WHERE j.attachment_id = '{attachment_id}')")
jobs, outbox = out.split()
return int(jobs), int(outbox)
def wait_for(condition, timeout: float, what: str) -> None:
deadline = time.monotonic() + timeout
while not condition():
@@ -68,44 +78,48 @@ def test_interrupted_and_stalled_uploads_leave_nothing(api):
assert rows_of_chat(chat["id"]) == [] # nothing was written: the body is checked before any write
def test_crash_between_s3_put_and_commit_is_cleaned_by_janitor(api):
def test_crash_after_staging_before_job_is_cleaned_by_janitor(api):
"""Failure window 1 of contracts/attachment-states.md: the original is in staging, the job is
not written. No 202 was sent, so nothing was promised: the janitor removes the staging copy
(object first) and then the intent row; no job, no message ever existed."""
alice = api.user("alice")
chat = api.chat(alice)
with api_with_env(FAULT_POINTS="after_s3_put", PENDING_GRACE_SECONDS="3", JANITOR_INTERVAL_SECONDS="1"):
with api_with_env(API_FAULT_POINTS="after_s3_put", PENDING_GRACE_SECONDS="3", JANITOR_INTERVAL_SECONDS="1"):
assert api.upload(alice, chat, SAMPLE, 503).json()["error"]["code"] == "unavailable"
[(attachment_id, status, key)] = rows_of_chat(chat["id"])
assert status == "pending" and s3_size(key) == len(SAMPLE) # the orphan-to-be exists
assert status == "pending" and s3_size(key, "staging") == len(SAMPLE) # the orphan-to-be exists
assert jobs_of(attachment_id) == (0, 0) # no job, no outbox row
api.call("GET", f"/api/v1/attachments/{attachment_id}", 404, token=alice["token"]) # invisible
api.post_message(alice, chat, {"text": "", "attachment_ids": [attachment_id]}, 404) # not attachable
wait_for(lambda: rows_of_chat(chat["id"]) == [], 30, "janitor did not remove the stale intent")
assert s3_size(key) is None # object removed first
assert s3_size(key, "staging") is None # object removed first
# Normal configuration again: an upload in the same chat works and is not touched.
att = api.upload(alice, chat, SAMPLE).json()
assert attachment_row(att["id"])["status"] == "ready"
assert api.wait_status(alice, att["id"], "ready")["status"] == "ready"
def test_lost_answer_after_commit_never_deletes_the_object(api):
"""The reviewer found this in another PR: COMMIT succeeded, the answer was lost, the API
'compensated' by deleting the object -> ready row without bytes. Here nothing compensates
in the request path, and the janitor only touches 'pending' rows."""
def test_lost_answer_after_job_commit_still_becomes_ready(api):
"""The job COMMIT succeeded, the answer was lost (503). Nothing compensates in the request path
(the janitor only touches 'pending' rows); the worker processes the job as usual."""
alice, bob = api.user("alice"), api.user("bob")
chat = api.chat(alice, bob)
with api_with_env(FAULT_POINTS="after_ready_commit", PENDING_GRACE_SECONDS="3", JANITOR_INTERVAL_SECONDS="1"):
with api_with_env(API_FAULT_POINTS="after_enqueue_commit", PENDING_GRACE_SECONDS="3", JANITOR_INTERVAL_SECONDS="1"):
api.upload(alice, chat, SAMPLE, 503)
[(attachment_id, status, key)] = rows_of_chat(chat["id"])
assert status == "ready"
time.sleep(6) # several janitor rounds
assert rows_of_chat(chat["id"]) == [(attachment_id, "ready", key)] and s3_size(key) == len(SAMPLE)
assert status in ("queued", "processing", "ready") and jobs_of(attachment_id)[0] == 1
att = api.wait_status(bob, attachment_id, "ready")
time.sleep(4) # several janitor rounds
assert attachment_row(attachment_id)["status"] == "ready"
got = api.call("GET", f"/api/v1/attachments/{attachment_id}/content", 200, token=bob["token"])
assert got.content == SAMPLE
assert got.content == SAMPLE and att["sha256"] == __import__("hashlib").sha256(SAMPLE).hexdigest()
def test_fresh_pending_upload_is_not_touched_by_janitor(api):
"""An intent younger than PENDING_GRACE_SECONDS is an upload in progress: never removed."""
alice = api.user("alice")
chat = api.chat(alice)
with api_with_env(FAULT_POINTS="after_s3_put", PENDING_GRACE_SECONDS="600", JANITOR_INTERVAL_SECONDS="1"):
with api_with_env(API_FAULT_POINTS="after_s3_put", PENDING_GRACE_SECONDS="600", JANITOR_INTERVAL_SECONDS="1"):
api.upload(alice, chat, SAMPLE, 503)
time.sleep(4)
[(_, status, key)] = rows_of_chat(chat["id"])
assert status == "pending" and s3_size(key) == len(SAMPLE)
assert status == "pending" and s3_size(key, "staging") == len(SAMPLE)
+2 -1
View File
@@ -79,7 +79,8 @@ def test_migrations_rerun_is_a_noop():
assert "0002_idempotency_keys: already applied, skipped" in result.stdout
assert "0003_post_message_function: already applied, skipped" in result.stdout
assert "0004_attachments: already applied, skipped" in result.stdout
assert psql("SELECT count(*) FROM schema_migrations") == "4"
assert "0005_pipeline: already applied, skipped" in result.stdout
assert psql("SELECT count(*) FROM schema_migrations") == "5"
assert psql("SELECT count(*) FROM users") == users_before
+501
View File
@@ -0,0 +1,501 @@
"""Lab 5 pipeline against the running stand: 202 -> queued -> ready, variants by the contract,
the failure windows of contracts/attachment-states.md, retries, the failed registry and replay,
lease expiry of a hung worker, cleanup that never deletes accepted work.
Failures are injected with the real mechanisms - docker stop/pause/restart of a service, and
FAULT_POINTS of ONE service recreated with an override (conftest.service_with_env) - and every
test restores the normal stand in `finally`. Each test checks exact HTTP codes AND the rows in
PostgreSQL AND the objects in S3, then the read-only invariant audit (I1-I7) of the whole stand."""
from __future__ import annotations
import hashlib
import io
import json
import subprocess
import time
import uuid
from pathlib import Path
import pytest
from PIL import Image
import imagegen
from conftest import (attachment_row, audit, compose, events_of, job_rows, jobctl, psql, queue_depth, s3_keys,
s3_size, service_down, service_with_env, wait_healthy, wait_stand)
pytestmark = pytest.mark.stack
ROOT = Path(__file__).resolve().parents[1]
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
FAST_LEASE = {"JOB_LEASE_SECONDS": "6"} # the reaper notices a dead attempt within ~11 s
@pytest.fixture()
def pair(api):
alice, bob = api.user("alice"), api.user("bob")
return alice, bob, api.chat(alice, bob)
def wait_for(condition, timeout: float, what: str):
deadline = time.monotonic() + timeout
while True:
value = condition()
if value:
return value
assert time.monotonic() < deadline, what
time.sleep(0.5)
def check_variants(api, actor, att: dict, source: bytes) -> dict[str, bytes]:
"""Download every variant: real format and size decoded with Pillow, size/sha256 = metadata."""
expected = {"thumbnail": ("image/jpeg", "JPEG"), "crop": ("image/jpeg", "JPEG"), "optimized": ("image/webp", "WEBP")}
assert [v["name"] for v in att["variants"]] == list(expected)
src = Image.open(io.BytesIO(source))
w, h = src.size
out = {}
for v in att["variants"]:
got = api.content(actor, att["id"], v["name"])
assert got.headers["content-type"] == expected[v["name"]][0] == v["content_type"]
assert len(got.content) == v["size_bytes"] and hashlib.sha256(got.content).hexdigest() == v["sha256"]
img = Image.open(io.BytesIO(got.content))
assert img.format == expected[v["name"]][1] and img.size == (v["width"], v["height"])
out[v["name"]] = got.content
def fit(box):
if w <= box and h <= box:
return w, h
return (box, max(1, h * box // w)) if w >= h else (max(1, w * box // h), box)
sizes = {v["name"]: (v["width"], v["height"]) for v in att["variants"]}
assert sizes == {"thumbnail": fit(256), "crop": (128, 128), "optimized": fit(1280)}
original = api.content(actor, att["id"])
assert original.content == source # the original is published byte for byte
return out
def published_keys(attachment_id: str) -> list[str]:
return psql(f"SELECT object_key FROM attachment_variants WHERE attachment_id = '{attachment_id}' "
f"UNION ALL SELECT object_key FROM attachments WHERE id = '{attachment_id}' ORDER BY 1").split()
def attempts(attachment_id: str) -> list[dict]:
out = psql("SELECT coalesce(json_agg(json_build_object('attempt', a.attempt, 'outcome', a.outcome, "
"'error_code', a.error_code, 'token', a.token, 'cleaned', a.objects_cleaned_at IS NOT NULL, "
"'keys', a.planned_keys) ORDER BY a.started_at), '[]') FROM job_attempts a JOIN jobs j ON j.id = a.job_id "
f"WHERE j.attachment_id = '{attachment_id}'")
return json.loads(out)
def outbox_of(attachment_id: str) -> list[dict]:
out = psql("SELECT coalesce(json_agg(json_build_object('attempt', o.attempt, 'published', o.published_at IS NOT NULL) "
f"ORDER BY o.id), '[]') FROM outbox o JOIN jobs j ON j.id = o.job_id WHERE j.attachment_id = '{attachment_id}'")
return json.loads(out)
def names(events: list[dict]) -> list[str]:
return [e["event"] for e in events]
# ------------------------------------------------------------------ level 3: the happy path
def test_upload_is_202_queued_then_ready_with_contract_variants(api, pair):
alice, bob, chat = pair
data = imagegen.png(900, 600, noise=True)
response = api.upload(alice, chat, data)
assert response.status_code == 202
att = response.json()
assert att["status"] == "queued" and att["variants"] == [] and att["error_code"] is None
ready = api.wait_status(bob, att["id"], "ready")
assert ready["error_code"] is None and ready["sha256"] == hashlib.sha256(data).hexdigest()
check_variants(api, bob, ready, data)
row = attachment_row(att["id"])
assert row["published_version"] == 1 and row["staging_state"] == "deleted" # staging cleaned after ready
assert s3_size(row["staging_key"], "staging") is None
[job] = job_rows(att["id"])
assert job["state"] == "succeeded" and job["attempt"] == 1 and job["kind"] == "upload"
assert names(events_of(att["id"])) == ["created", "claimed", "succeeded"]
def test_queued_attachment_is_attachable_failed_is_not(api, pair):
alice, bob, chat = pair
with service_down("worker"): # stays queued
att = api.upload(alice, chat, SAMPLE).json()
msg = api.post_message(alice, chat, {"text": "", "attachment_ids": [att["id"]]}).json()
assert msg["attachment_ids"] == [att["id"]]
api.wait_status(alice, att["id"], "ready")
with service_with_env("worker", WORKER_FAULT_POINTS="permanent_error"):
bad = api.upload(alice, chat, SAMPLE).json()
failed = api.wait_status(bob, bad["id"], "failed")
assert failed["error_code"] == "invalid_image" and failed["variants"] == []
api.post_message(alice, chat, {"text": "", "attachment_ids": [bad["id"]]}, 409)
api.content(bob, bad["id"], expected=409)
api.content(bob, bad["id"], "thumbnail", expected=409)
def test_worker_stopped_upload_202_content_409_restart_api_and_broker_then_ready(api, pair):
"""The defence scenario: worker stopped -> upload 202 -> content 409, other messages keep working
-> the message with the attachment is created -> API and broker restarted WITH volumes ->
the job is still in the queue -> worker started -> ready, thumbnail downloadable."""
alice, bob, chat = pair
compose("stop", "worker")
try:
response = api.upload(alice, chat, SAMPLE)
att = response.json()
assert response.status_code == 202 and att["status"] == "queued"
for variant in (None, "thumbnail"):
assert api.content(bob, att["id"], variant, expected=409).json()["error"]["code"] == "conflict"
api.send(bob, chat, "текст работает без worker")
msg = api.post_message(alice, chat, {"text": "фото", "attachment_ids": [att["id"]]}).json()
wait_for(lambda: all(o["published"] for o in outbox_of(att["id"])), 15, "relay did not publish the job")
# rabbitmqctl counters are refreshed every ~5 s (statistics interval): wait, do not sample once.
wait_for(lambda: queue_depth() >= 1, 20, "no message in the queue") # durable message waits in the queue
compose("restart", "api", "broker") # volumes preserved
wait_healthy("api", "broker", "relay")
wait_stand()
wait_for(lambda: queue_depth() >= 1, 20, "the accepted job was lost by the broker restart")
assert api.attachment(bob, att["id"])["status"] == "queued"
finally:
compose("start", "worker")
wait_healthy("worker")
ready = api.wait_status(bob, att["id"], "ready")
check_variants(api, bob, ready, SAMPLE)
items, _ = api.history(bob, chat, 50)
assert any(m["id"] == msg["id"] and m["attachment_ids"] == [att["id"]] for m in items)
[job] = job_rows(att["id"])
assert job["attempt"] == 1 # no duplicate work
# ------------------------------------------------------------------ failure windows
def test_broker_down_commit_to_publish_gap_is_closed_by_the_outbox(api, pair):
"""Window "after COMMIT, before publish": the broker is down, the API still answers 202 (it never
talks to the broker), the outbox row stays unpublished. No manual action: when the broker is
back the relay publishes it and the worker finishes the job."""
alice, bob, chat = pair
with service_down("broker"):
att = api.upload(alice, chat, SAMPLE).json()
assert att["status"] == "queued"
time.sleep(3)
assert outbox_of(att["id"]) == [{"attempt": 1, "published": False}]
api.send(alice, chat, "сообщения работают без брокера")
api.wait_status(bob, att["id"], "ready", timeout=90)
assert outbox_of(att["id"]) == [{"attempt": 1, "published": True}]
assert [j["attempt"] for j in job_rows(att["id"])] == [1]
def test_relay_down_job_waits_in_outbox_not_lost(api, pair):
alice, bob, chat = pair
with service_down("relay"):
att = api.upload(alice, chat, SAMPLE).json()
time.sleep(3)
assert outbox_of(att["id"]) == [{"attempt": 1, "published": False}]
assert api.attachment(bob, att["id"])["status"] == "queued"
api.wait_status(bob, att["id"], "ready")
def test_crash_after_publish_before_confirm_is_recorded_gives_a_harmless_duplicate(api, pair):
"""Window "after publish, before confirm": the relay dies after the broker confirmed the message
but before outbox.published_at is committed. The restarted relay publishes it AGAIN; the
duplicate is a no-op (one claim, one set of variants)."""
alice, bob, chat = pair
with service_with_env("relay", RELAY_FAULT_POINTS="crash_after_publish"):
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(bob, att["id"], "ready", timeout=90)
wait_for(lambda: all(o["published"] for o in outbox_of(att["id"])), 30, "outbox not marked after restart")
events = events_of(att["id"])
assert names(events).count("fault_injected") == 1 and names(events).count("claimed") == 1
assert [j["attempt"] for j in job_rows(att["id"])] == [1]
assert len(published_keys(att["id"])) == 4 # original + 3 variants, once
def test_duplicate_and_reordered_deliveries_are_noops(api, pair):
alice, bob, chat = pair
with service_with_env("relay", RELAY_FAULT_POINTS="duplicate_publish,reverse_order"):
atts = [api.upload(alice, chat, imagegen.png(50 + i, 40)).json() for i in range(4)]
for att in atts:
api.wait_status(bob, att["id"], "ready")
time.sleep(2) # let the duplicates be consumed
for att in atts:
assert names(events_of(att["id"])) == ["created", "claimed", "succeeded"]
assert len(published_keys(att["id"])) == 4
logs = compose("logs", "--no-log-prefix", "worker").stdout
assert '"noop_finished"' in logs or '"noop_leased"' in logs # duplicates were seen and acked
def test_worker_crash_before_side_effect_lease_expires_and_job_completes(api, pair):
"""The worker dies right after the claim. The redelivered message finds a valid lease (no-op);
the reaper returns the job to queued when the lease expires; attempt 2 publishes."""
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="crash_after_claim", **FAST_LEASE):
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(bob, att["id"], "ready", timeout=90)
ev = names(events_of(att["id"]))
assert ev.count("fault_injected") == 1 and "lease_expired" in ev and ev[-1] == "succeeded"
tries = attempts(att["id"])
assert [(a["attempt"], a["outcome"]) for a in tries] == [(1, "abandoned"), (2, "succeeded")]
assert tries[0]["keys"] and all(s3_size(k) is None for k in tries[0]["keys"]) # nothing written
def test_worker_crash_after_s3_write_before_commit_republishes_without_duplicates(api, pair):
"""Window "after the S3 write, before the result COMMIT": objects of attempt 1 exist under ITS keys
but are never published; attempt 2 publishes its own; the cleanup deletes attempt 1's objects
after ORPHAN_GRACE_SECONDS (they can never become published: the token is fenced)."""
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="crash_after_s3_write", ORPHAN_GRACE_SECONDS="2",
CLEANUP_INTERVAL_SECONDS="1", **FAST_LEASE):
att = api.upload(alice, chat, SAMPLE).json()
ready = api.wait_status(bob, att["id"], "ready", timeout=90)
first, second = attempts(att["id"])
assert (first["outcome"], second["outcome"]) == ("abandoned", "succeeded")
assert set(published_keys(att["id"])) == set(second["keys"])
wait_for(lambda: attempts(att["id"])[0]["cleaned"], 30, "orphans of attempt 1 not cleaned")
assert all(s3_size(k) is None for k in first["keys"])
assert all(s3_size(k) is not None for k in second["keys"])
assert s3_keys(f"a/{att['id']}/") == set(second["keys"]) # exactly one set of objects
check_variants(api, bob, ready, SAMPLE)
def test_worker_crash_after_commit_before_ack_redelivery_is_noop(api, pair):
"""Window "after the result COMMIT, before the ack": the message comes back; the job is
succeeded -> ack without any work; the same result stays published."""
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="crash_after_commit"):
att = api.upload(alice, chat, SAMPLE).json()
ready = api.wait_status(bob, att["id"], "ready", timeout=60)
before = published_keys(att["id"])
wait_healthy("worker")
wait_for(lambda: '"noop_finished"' in compose("logs", "--no-log-prefix", "worker").stdout, 30,
"the redelivered message was not acknowledged as a no-op")
ev = names(events_of(att["id"]))
assert ev == ["created", "claimed", "fault_injected", "succeeded"] or ev == ["created", "claimed", "succeeded", "fault_injected"]
assert published_keys(att["id"]) == before and [a["outcome"] for a in attempts(att["id"])] == ["succeeded"]
assert api.attachment(bob, att["id"]) == ready
# ------------------------------------------------------------------ retries and failures
def test_transient_errors_are_retried_with_jittered_backoff(api, pair):
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="transient_error=2", JOB_RETRY_BASE_SECONDS="1",
JOB_RETRY_MAX_SECONDS="8"):
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(bob, att["id"], "ready", timeout=60)
events = events_of(att["id"])
retries = [e for e in events if e["event"] == "retry_scheduled"]
assert [(e["attempt"], e["error_code"]) for e in retries] == [(1, "injected_transient"), (2, "injected_transient")]
for e in retries:
assert 0 <= e["detail"]["delay_s"] <= 1 * 2 ** (e["attempt"] - 1) # full jitter window
assert [(a["attempt"], a["outcome"]) for a in attempts(att["id"])] == [(1, "retry"), (2, "retry"), (3, "succeeded")]
assert [o["attempt"] for o in outbox_of(att["id"])] == [1, 2, 3] # every retry went through the outbox
def test_retry_exhausted_failed_registry_then_replay(api, pair):
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="transient_error", JOB_RETRY_BASE_SECONDS="0.2",
JOB_RETRY_MAX_SECONDS="0.5"):
att = api.upload(alice, chat, SAMPLE).json()
failed = api.wait_status(bob, att["id"], "failed", timeout=60)
assert failed["error_code"] == "retry_exhausted" and failed["variants"] == []
[job] = job_rows(att["id"])
assert (job["state"], job["attempt"], job["error_code"]) == ("failed", 5, "retry_exhausted") # JOB_MAX_ATTEMPTS
registry = jobctl("list-failed", "--limit", "200")["failed"]
assert any(r["attachment_id"] == att["id"] and r["error_code"] == "retry_exhausted" for r in registry)
assert attachment_row(att["id"])["staging_state"] == "present" # kept for the replay
# Operator replay: a NEW job (replay_of = the failed one), audit with operator and reason.
result = jobctl("replay", att["id"], "--operator", "alice", "--reason", "fault removed")
assert result["result"] == "queued" and result["replay_of"] == job["id"]
ready = api.wait_status(bob, att["id"], "ready", timeout=60)
check_variants(api, bob, ready, SAMPLE)
jobs = job_rows(att["id"])
assert [(j["kind"], j["state"]) for j in jobs] == [("upload", "failed"), ("replay", "succeeded")]
ev = events_of(att["id"])
req = next(e for e in ev if e["event"] == "replay_requested")
assert req["actor"] == "jobctl:alice" and req["detail"]["reason"] == "fault removed"
# "Repeat" never re-runs a finished job: a replay of a ready attachment is refused, nothing created.
refused = jobctl("replay", att["id"], "--operator", "alice", "--reason", "again", expect_code=3)
assert refused == {"result": "refused", "reason": "already_ready"}
assert len(job_rows(att["id"])) == 2
def test_permanent_error_fails_at_once_without_retries(api, pair):
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="permanent_error"):
att = api.upload(alice, chat, SAMPLE).json()
failed = api.wait_status(bob, att["id"], "failed")
assert failed["error_code"] == "invalid_image"
assert [(a["attempt"], a["outcome"]) for a in attempts(att["id"])] == [(1, "failed")]
def test_memory_and_time_limits_of_the_worker(api, pair):
"""40 Mpx PNG (valid, accepted by the API) with IMAGE_MAX_MEMORY_MB=200: the child process cannot
allocate the raster -> image_too_large (permanent); the worker itself keeps running.
JOB_TIMEOUT_SECONDS=3 with a 10 s stall -> processing_timeout (transient, retried)."""
alice, bob, chat = pair
with service_with_env("worker", IMAGE_MAX_MEMORY_MB="200"):
att = api.upload(alice, chat, imagegen.png(8000, 5000, compress_level=9)).json()
failed = api.wait_status(bob, att["id"], "failed", timeout=90)
assert failed["error_code"] == "image_too_large"
ok = api.upload(alice, chat, SAMPLE).json() # the same worker still works
api.wait_status(bob, ok["id"], "ready")
with service_with_env("worker", WORKER_FAULT_POINTS="slow=10", JOB_TIMEOUT_SECONDS="3"):
slow = api.upload(alice, chat, SAMPLE).json()
wait_for(lambda: any(a["error_code"] == "processing_timeout" for a in attempts(slow["id"])), 60,
"no processing_timeout")
api.wait_status(bob, slow["id"], "ready", timeout=120) # normal worker finishes it
def test_bad_message_is_dead_lettered_not_processed(api, pair):
"""A message that does not match jobs.schema.json (published here with the relay's own broker
user) is rejected by the worker into the DLQ; nothing is processed."""
before = queue_depth("messenger.attachment-jobs.dlq")
script = ("import asyncio, aio_pika\n"
"async def m():\n"
" url = open('/run/secrets/broker_url').read().strip()\n"
" c = await aio_pika.connect(url)\n"
" ch = await c.channel(publisher_confirms=True)\n"
" ex = await ch.get_exchange('messenger.jobs', ensure=False)\n"
" await ex.publish(aio_pika.Message(b'{\"url\":\"http://evil/x.png\"}'), routing_key='attachment.process.v1')\n"
" await c.close()\n"
"asyncio.run(m())\n")
compose("exec", "-T", "relay", "python", "-c", script)
wait_for(lambda: queue_depth("messenger.attachment-jobs.dlq") == before + 1, 20, "not dead-lettered")
assert '"bad_message"' in compose("logs", "--no-log-prefix", "worker").stdout
# ------------------------------------------------------------------ lease, hung worker, shutdown, concurrency
def worker_containers() -> dict[str, str]:
"""hostname (= lease_owner) -> container id of every running worker."""
ids = compose("ps", "-q", "worker").stdout.split()
out = subprocess.run(["docker", "inspect", "-f", "{{.Config.Hostname}} {{.Id}}", *ids], capture_output=True,
text=True, check=True).stdout
return dict(line.split() for line in out.splitlines())
def test_hung_worker_loses_its_lease_and_cannot_publish(api, pair):
"""Two workers. The one processing the job is frozen (docker pause: no heartbeat). Its lease
expires, the reaper re-queues the job, the other worker publishes it. When the frozen worker
resumes, its result is fenced by the token: the published result does not change."""
alice, bob, chat = pair
with service_with_env("worker", scale=2, WORKER_FAULT_POINTS="slow=8", **FAST_LEASE):
att = api.upload(alice, chat, SAMPLE).json()
owner = wait_for(lambda: psql(f"SELECT lease_owner FROM jobs WHERE attachment_id = '{att['id']}' "
"AND state = 'processing'"), 30, "job never claimed")
frozen = worker_containers()[owner]
subprocess.run(["docker", "pause", frozen], check=True, capture_output=True)
try:
ready = api.wait_status(bob, att["id"], "ready", timeout=120)
published = published_keys(att["id"])
finally:
subprocess.run(["docker", "unpause", frozen], check=True, capture_output=True)
time.sleep(12) # the resumed attempt finishes its sleep and tries to publish
assert published_keys(att["id"]) == published and api.attachment(bob, att["id"]) == ready
tries = attempts(att["id"])
assert [(a["attempt"], a["outcome"]) for a in tries] == [(1, "abandoned"), (2, "succeeded")]
assert "lease_expired" in names(events_of(att["id"]))
check_variants(api, bob, ready, SAMPLE)
def test_graceful_worker_stop_finishes_the_running_attempt(api, pair):
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="slow=5"):
att = api.upload(alice, chat, SAMPLE).json()
wait_for(lambda: api.attachment(bob, att["id"])["status"] == "processing", 30, "never processing")
started = time.monotonic()
compose("stop", "worker") # SIGTERM: drain, not kill
assert time.monotonic() - started < 30
assert attachment_row(att["id"])["status"] == "ready" # committed before the exit
compose("start", "worker")
wait_healthy("worker")
assert [a["outcome"] for a in attempts(att["id"])] == ["succeeded"]
def test_concurrency_is_bounded_by_prefetch(api, pair):
"""WORKER_CONCURRENCY=2: never more than 2 jobs processing and 2 unacked messages at once."""
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="slow=3"):
atts = [api.upload(alice, chat, imagegen.png(30 + i, 30)).json() for i in range(6)]
peak = 0
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
states = [api.attachment(bob, a["id"])["status"] for a in atts]
peak = max(peak, states.count("processing"))
unacked = compose("exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name",
"messages_unacknowledged").stdout
for line in unacked.splitlines():
if line.startswith("messenger.attachment-jobs\t"):
assert int(line.split("\t")[1]) <= 2, line
if all(s == "ready" for s in states):
break
time.sleep(0.3)
assert all(api.attachment(bob, a["id"])["status"] == "ready" for a in atts)
assert peak == 2
# ------------------------------------------------------------------ cleanup never deletes accepted work
def test_queued_staging_is_never_deleted_even_after_retention(api, pair):
"""Reviewer's case in another PR: the worker was down longer than the retention and the cleanup
deleted the original of a job that was still queued. Here: the job waits queued (relay down)
while the cleanup runs every second with retention 0 - the staging copy stays, and the
database itself refuses marking it (CHECK attachments_active_has_source)."""
alice, bob, chat = pair
with service_with_env("worker", STAGING_RETENTION_SECONDS="0", CLEANUP_INTERVAL_SECONDS="1"):
with service_down("relay"):
att = api.upload(alice, chat, SAMPLE).json()
time.sleep(5) # several cleanup passes
row = attachment_row(att["id"])
assert row["status"] == "queued" and row["staging_state"] == "present"
assert s3_size(row["staging_key"], "staging") == len(SAMPLE)
refused = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-c",
f"UPDATE attachments SET staging_state = 'deleting' WHERE id = '{att['id']}'",
check=False)
assert refused.returncode != 0 and "attachments_active_has_source" in refused.stderr
ready = api.wait_status(bob, att["id"], "ready", timeout=60)
check_variants(api, bob, ready, SAMPLE)
def test_retention_deletes_failed_staging_then_replay_is_refused(api, pair):
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="permanent_error", STAGING_RETENTION_SECONDS="1",
CLEANUP_INTERVAL_SECONDS="1"):
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(bob, att["id"], "failed")
wait_for(lambda: attachment_row(att["id"])["staging_state"] == "deleted", 30, "staging not cleaned")
assert s3_size(attachment_row(att["id"])["staging_key"], "staging") is None
refused = jobctl("replay", att["id"], "--operator", "alice", "--reason", "too late", expect_code=3)
assert refused == {"result": "refused", "reason": "source_missing"}
assert api.attachment(bob, att["id"])["status"] == "failed" and len(job_rows(att["id"])) == 1
def test_cleanup_racing_a_replay_never_deletes_the_replayed_source(api, pair):
"""Reviewer's interleaving in another PR: the cleanup READ its candidates (an expired failed
attachment), a replay committed queued, the cleanup went on and deleted the staging copy.
Here the cleanup pauses exactly there (pause_cleanup); the replay commits during the pause;
the cleanup then re-checks under the row lock and skips the row. The replay finishes ready."""
alice, bob, chat = pair
with service_with_env("worker", WORKER_FAULT_POINTS="permanent_error"):
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(bob, att["id"], "failed")
with service_with_env("worker", WORKER_FAULT_POINTS="pause_cleanup=8", STAGING_RETENTION_SECONDS="1",
CLEANUP_INTERVAL_SECONDS="1"):
wait_for(lambda: '"cleanup_paused"' in compose("logs", "--no-log-prefix", "--since", "60s", "worker").stdout
and att["id"] in compose("logs", "--no-log-prefix", "--since", "60s", "worker").stdout,
30, "cleanup did not pick the failed attachment")
result = jobctl("replay", att["id"], "--operator", "alice", "--reason", "race test")
assert result["result"] == "queued"
ready = api.wait_status(bob, att["id"], "ready", timeout=90)
check_variants(api, bob, ready, SAMPLE)
assert attachment_row(att["id"])["staging_state"] == "deleted" # deleted only AFTER ready
def test_reprocess_of_a_not_ready_upload_is_refused(api, pair):
"""Reviewer's case in another PR: worker stopped -> upload 202 -> reprocess with pipeline 2 ->
the attachment stayed queued forever. Here the command is refused and v1 completes."""
alice, bob, chat = pair
with service_down("worker"):
att = api.upload(alice, chat, SAMPLE).json()
refused = jobctl("reprocess", att["id"], "--pipeline", "2", "--operator", "alice", "--reason", "x",
expect_code=3)
assert refused == {"result": "refused", "reason": "not_ready:queued"}
assert len(job_rows(att["id"])) == 1
api.wait_status(bob, att["id"], "ready")
assert attachment_row(att["id"])["published_version"] == 1
def test_zz_invariants_hold_after_all_scenarios():
report = audit("--verify-checksums")
assert report["objects"]["published"] > 0
-217
View File
@@ -1,217 +0,0 @@
"""Track 2: the reconciler of S3 and PostgreSQL (python -m messenger.reconcile).
Faults are injected on BOTH sides, directly into the stores (S3 with the API/reconciler key
pairs from inside the storage network, PostgreSQL with psql):
S3 side: orphan object (no row), object deleted under a ready row, object overwritten with
other bytes (size / same-size checksum), object of a quarantined row restored;
DB side: stale intent with and without object, quarantine mark on a healthy row;
fresh: orphan and intent younger than --grace (an upload in progress).
The tests prove: dry-run changes nothing in either store; --apply fixes exactly the old findings;
fresh and used attachments are never deleted (ready rows only ever get a reversible quarantine);
the second run finds nothing to do; the safety valve and store outages stop the run without
damage. A small --grace (8-30 s, --allow-small-grace) keeps the tests fast."""
from __future__ import annotations
import concurrent.futures
import hashlib
import time
import uuid
from pathlib import Path
import pytest
import imagegen
from conftest import (attachment_row, findings_by_key, psql, reconcile, s3_delete, s3_keys, s3_put, s3_size,
service_down)
pytestmark = pytest.mark.stack
ROOT = Path(__file__).resolve().parents[1]
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
GRACE = ["--grace", "8", "--allow-small-grace"]
# The main scenario needs "fresh" items to stay younger than --grace for the whole dry-run + snapshot
# (each docker exec costs 1-3 s on Windows), hence a longer grace there.
LONG_GRACE = ["--grace", "30", "--allow-small-grace"]
def new_key() -> str:
return "o/" + uuid.uuid4().hex
def insert_intent(chat: dict, owner: dict, key: str, data: bytes, age_seconds: int) -> str:
"""A 'pending' row as an upload leaves it after the intent COMMIT (crash afterwards)."""
attachment_id = str(uuid.uuid4())
psql("INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height, "
"object_key, status, created_at, updated_at) VALUES ('%s', '%s', '%s', 'x.png', 'image/png', %d, "
"decode('%s', 'hex'), 320, 200, '%s', 'pending', clock_timestamp() - make_interval(secs => %d), "
"clock_timestamp() - make_interval(secs => %d))"
% (attachment_id, chat["id"], owner["id"], len(data), hashlib.sha256(data).hexdigest(), key, age_seconds,
age_seconds))
return attachment_id
def snapshot() -> tuple[str, frozenset]:
"""Fingerprint of everything the reconciler could change: every attachment row + the key list."""
rows = psql("SELECT count(*) || ':' || coalesce(md5(string_agg(id::text || status || object_key || "
"coalesce(lost_reason, '-') || updated_at::text, ',' ORDER BY id)), '') FROM attachments")
return rows, frozenset(s3_keys())
def content_status(api, actor, attachment_id) -> int:
return api.client.get(f"/api/v1/attachments/{attachment_id}/content",
headers={"Authorization": "Bearer " + actor["token"]}).status_code
def test_detect_and_safely_fix_faults_on_both_sides(api):
alice, bob = api.user("alice"), api.user("bob")
chat = api.chat(alice, bob)
up = {name: api.upload(alice, chat, imagegen.png(30 + i, 20)).json() for i, name in enumerate("ABCDE")}
data = {name: api.call("GET", f"/api/v1/attachments/{a['id']}/content", 200, token=alice["token"]).content
for name, a in up.items()}
key = {name: attachment_row(a["id"])["object_key"] for name, a in up.items()}
api.post_message(alice, chat, {"text": "used", "attachment_ids": [up["A"]["id"], up["C"]["id"], up["E"]["id"]]})
# ---- inject (old)
orphan_old = new_key()
s3_put(orphan_old, SAMPLE)
stale_with, stale_without = new_key(), new_key()
s3_put(stale_with, SAMPLE)
stale_with_id = insert_intent(chat, alice, stale_with, SAMPLE, 600) # < janitor grace 900 s
stale_without_id = insert_intent(chat, alice, stale_without, SAMPLE, 600)
s3_delete(key["C"]) # ready + used, bytes lost
s3_put(key["D"], data["D"][:len(data["D"]) // 2]) # ready, unused, wrong size
psql(f"UPDATE attachments SET lost_at = clock_timestamp(), lost_reason = 'missing_object' "
f"WHERE id = '{up['E']['id']}'") # quarantined, but bytes are fine
time.sleep(32) # everything above is now older than --grace
# ---- inject (fresh: an upload in progress)
fresh_orphan, fresh_intent = new_key(), new_key()
s3_put(fresh_orphan, SAMPLE)
s3_put(fresh_intent, SAMPLE)
fresh_intent_id = insert_intent(chat, alice, fresh_intent, SAMPLE, 0)
# ---- dry-run: report everything, change nothing
before = snapshot()
dry = reconcile(*LONG_GRACE)
assert snapshot() == before, "dry-run modified a store"
f = findings_by_key(dry)
expected = {orphan_old: "orphan_object", fresh_orphan: "fresh_orphan_object", stale_with: "stale_intent",
stale_without: "stale_intent", fresh_intent: "fresh_intent", key["C"]: "missing_object",
key["D"]: "size_mismatch", key["E"]: "restored_object"}
assert {k: f[k]["kind"] for k in expected} == expected
assert key["A"] not in f and key["B"] not in f
assert f[key["C"]]["used"] is True and dry["mode"] == "dry-run"
assert all(f[k]["result"] in ("planned", "not_actionable") for k in expected)
# ---- apply
applied = findings_by_key(reconcile("--apply", *LONG_GRACE))
for k in (orphan_old, stale_with, stale_without, key["C"], key["D"], key["E"]):
assert applied[k]["result"] == "applied", (k, applied[k])
keys = s3_keys()
assert orphan_old not in keys and stale_with not in keys
assert attachment_row(stale_with_id) is None and attachment_row(stale_without_id) is None
# fresh: untouched
assert fresh_orphan in keys and fresh_intent in keys and attachment_row(fresh_intent_id)["status"] == "pending"
# used, lost bytes: quarantined, NOT deleted; the message still references it
row_c = attachment_row(up["C"]["id"])
assert row_c["status"] == "ready" and row_c["lost_reason"] == "missing_object"
items, _ = api.history(bob, chat, 100)
assert any(up["C"]["id"] in m["attachment_ids"] for m in items)
assert content_status(api, bob, up["C"]["id"]) == 404
api.post_message(alice, chat, {"text": "", "attachment_ids": [up["C"]["id"]]}, 409) # cannot attach a lost file
assert attachment_row(up["D"]["id"])["lost_reason"] == "size_mismatch"
assert attachment_row(up["E"]["id"])["lost_reason"] is None # quarantine lifted
for name in "ABE":
got = api.call("GET", f"/api/v1/attachments/{up[name]['id']}/content", 200, token=bob["token"])
assert got.content == data[name]
# ---- second run: idempotent, nothing left to do for these keys
again = findings_by_key(reconcile("--apply", *LONG_GRACE))
for k in (orphan_old, stale_with, stale_without, key["C"], key["D"], key["E"], key["A"], key["B"]):
assert k not in again, (k, again.get(k))
# ---- the lost object comes back from a backup: the quarantine is lifted, the file is served again
s3_put(key["C"], data["C"])
restored = findings_by_key(reconcile("--apply", *LONG_GRACE))
assert restored[key["C"]]["kind"] == "restored_object" and restored[key["C"]]["result"] == "applied"
assert api.call("GET", f"/api/v1/attachments/{up['C']['id']}/content", 200, token=bob["token"]).content == data["C"]
# tidy up the fresh items of this test once they are old enough
time.sleep(31)
reconcile("--apply", *LONG_GRACE)
assert fresh_orphan not in s3_keys() and attachment_row(fresh_intent_id) is None
def test_checksum_mode_finds_same_size_corruption(api):
alice = api.user("alice")
chat = api.chat(alice)
att = api.upload(alice, chat, SAMPLE).json()
k = attachment_row(att["id"])["object_key"]
s3_put(k, SAMPLE[:1000] + bytes([SAMPLE[1000] ^ 1]) + SAMPLE[1001:]) # same size, other bytes
time.sleep(9)
assert k not in findings_by_key(reconcile(*GRACE)) # sizes match: listing cannot see it
report = reconcile("--verify-checksums", *GRACE)
assert findings_by_key(report)[k]["kind"] == "checksum_mismatch"
assert report["cost"]["s3_get_bytes"] >= len(SAMPLE)
assert findings_by_key(reconcile("--apply", "--verify-checksums", *GRACE))[k]["result"] == "applied"
assert attachment_row(att["id"])["lost_reason"] == "checksum_mismatch"
# A later pass WITHOUT checksums sees "same size" but cannot prove the bytes: the quarantine stays.
assert k not in findings_by_key(reconcile("--apply", *GRACE))
assert attachment_row(att["id"])["lost_reason"] == "checksum_mismatch"
# Restoring the original and verifying lifts it.
s3_put(k, SAMPLE)
lifted = findings_by_key(reconcile("--apply", "--verify-checksums", *GRACE))[k]
assert (lifted["kind"], lifted["result"]) == ("restored_object", "applied")
assert attachment_row(att["id"])["lost_reason"] is None
def test_safety_valve_refuses_mass_deletion():
"""If (almost) every object looked orphaned - e.g. the reconciler pointed at an empty database -
--apply must stop before deleting anything."""
orphan = new_key()
s3_put(orphan, SAMPLE)
time.sleep(9)
report = reconcile("--apply", "--max-orphan-fraction", "0.000001", *GRACE, expect_code=3)
assert report["error"].startswith("safety_valve") and report["actions"]["applied"] == 0
assert orphan in s3_keys()
reconcile("--apply", *GRACE)
assert orphan not in s3_keys()
@pytest.mark.parametrize("service", ["s3", "postgres"])
def test_store_outage_stops_the_run_without_damage(api, service):
with service_down(service, "stop"):
report = reconcile(*GRACE, expect_code=1)
assert report["error"].startswith("store_unavailable")
assert reconcile(*GRACE)["error"] is None
def test_live_uploads_are_never_hurt_by_concurrent_apply(api):
"""Uploads and messages run while --apply runs repeatedly: every upload that got 201 stays
ready and downloadable byte for byte, every message keeps its attachments."""
alice = api.user("alice")
chat = api.chat(alice)
payloads = [imagegen.png(16 + i, 16) for i in range(40)]
done: list[tuple[dict, bytes]] = []
def worker(chunk: list[bytes]) -> None:
for p in chunk:
att = api.upload(alice, chat, p).json()
api.post_message(alice, chat, {"text": "", "attachment_ids": [att["id"]]})
done.append((att, p))
with concurrent.futures.ThreadPoolExecutor(4) as pool:
futures = [pool.submit(worker, payloads[i::4]) for i in range(4)]
runs = 0
while not all(x.done() for x in futures):
report = reconcile("--apply", *GRACE)
assert report["error"] is None
runs += 1
for x in futures:
x.result()
assert runs >= 1 and len(done) == len(payloads)
for att, p in done:
row = attachment_row(att["id"])
assert row["status"] == "ready" and row["lost_reason"] is None and s3_size(row["object_key"]) == len(p)
for att, p in done[::8]:
assert api.call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=alice["token"]).content == p
+6 -1
View File
@@ -1,4 +1,5 @@
"""S3 outages, private bucket and failover of attachments (lab 4, levels 3 and 4).
"""S3 outages, private buckets and failover of attachments (lab 4, levels 3 and 4; lab 5: two
buckets, upload 202 + worker).
Every injected failure is undone in `finally` (conftest.service_down / replica_stopped), and the
stand is waited for until HAProxy sees all replicas UP again."""
@@ -33,6 +34,7 @@ def test_s3_outage_is_503_and_text_keeps_working(api, pair, how):
* after recovery the earlier file is intact."""
alice, bob, chat = pair
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(alice, att["id"], "ready")
with service_down("s3", how):
deadline = time.monotonic() + 15
while api.client.get("/health/ready").status_code != 503:
@@ -63,6 +65,7 @@ def test_upload_survives_failover_of_the_serving_replica(api, pair):
response = api.upload(alice, chat, data)
att, served_by = response.json(), response.headers["x-instance-id"]
replica = next(r for r in running_replicas() if r["hostname"] == served_by)
api.wait_status(bob, att["id"], "ready")
with replica_stopped(replica, "kill"):
for _ in range(5):
got = api.call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"])
@@ -75,6 +78,7 @@ def test_bucket_is_private_outside_the_api(api, pair):
SeaweedFS admin endpoints (master 9333, filer 8888, volume 8080) are not reachable."""
alice, _, chat = pair
att = api.upload(alice, chat, SAMPLE).json()
api.wait_status(alice, att["id"], "ready")
key = attachment_row(att["id"])["object_key"]
probe = (
"import urllib.request as u, urllib.error as e, socket\n"
@@ -102,6 +106,7 @@ def test_s3_restart_keeps_objects(api, pair):
alice, bob, chat = pair
data = imagegen.png_of_size(200_000)
att = api.upload(alice, chat, data).json()
api.wait_status(bob, att["id"], "ready")
with service_down("s3", "stop"):
pass
assert api.call("GET", f"/api/v1/attachments/{att['id']}/content", 200, token=bob["token"]).content == data
+224
View File
@@ -0,0 +1,224 @@
"""Unit tests of lab 5 without services: variant geometry and encoding (imaging.build, the same
code the worker runs in its child process), the job message schema, backoff with jitter and the
pipeline configuration."""
from __future__ import annotations
import io
import json
import sys
import uuid
from pathlib import Path
import pytest
from jsonschema import Draft202012Validator
from PIL import Image
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "src"))
sys.path.insert(0, str(ROOT / "student-tests"))
import imagegen # noqa: E402
from messenger import broker, imaging, jobs # noqa: E402
from messenger.config import ConfigError, Settings # noqa: E402
from messenger.pipeline import PIPELINES, center_square, fit # noqa: E402
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
SCHEMA = json.loads((ROOT / "contracts" / "jobs.schema.json").read_text(encoding="utf-8"))
LIMIT = 40_000_000
def variants(data: bytes, content_type: str = "image/png", version: int = 1) -> dict[str, imaging.Rendered]:
return {v.name: v for v in imaging.build(data, content_type, version, LIMIT)}
def decoded(v: imaging.Rendered) -> Image.Image:
img = Image.open(io.BytesIO(v.data))
img.load()
return img
# ------------------------------------------------------------------ geometry (contract rules)
@pytest.mark.parametrize("size, box, expected", [
((320, 200), 256, (256, 160)), # public fixture
((200, 320), 256, (160, 256)),
((100, 50), 256, (100, 50)), # never upscale
((256, 256), 256, (256, 256)),
((1000, 1), 256, (256, 1)), # 0.256 px -> minimum 1 px
((1, 1000), 256, (1, 256)),
((257, 255), 256, (256, 254)), # 255 * 256 / 257 = 254.0 (floor)
((3000, 2000), 1280, (1280, 853)), # 853.33 -> 853
])
def test_fit_rounds_down_without_upscaling(size, box, expected):
assert fit(*size, box) == expected
def test_center_square():
assert center_square(320, 200) == (60, 0, 260, 200)
assert center_square(7, 10) == (0, 1, 7, 8)
def test_public_fixture_variants_match_the_contract():
out = variants(SAMPLE)
assert list(out) == ["thumbnail", "crop", "optimized"]
assert (out["thumbnail"].content_type, decoded(out["thumbnail"]).format, decoded(out["thumbnail"]).size) == \
("image/jpeg", "JPEG", (256, 160))
assert (out["crop"].content_type, decoded(out["crop"]).size) == ("image/jpeg", (128, 128))
assert (out["optimized"].content_type, decoded(out["optimized"]).format, decoded(out["optimized"]).size) == \
("image/webp", "WEBP", (320, 200)) # fits 1280 already: no upscale
for v in out.values():
assert (v.width, v.height) == decoded(v).size
def test_small_image_is_not_upscaled_but_crop_is():
out = variants(imagegen.png(40, 30))
assert decoded(out["thumbnail"]).size == (40, 30)
assert decoded(out["optimized"]).size == (40, 30)
assert decoded(out["crop"]).size == (128, 128)
def test_big_image_is_bounded_by_1280():
out = variants(imagegen.png(3000, 2000))
assert decoded(out["optimized"]).size == (1280, 853)
assert decoded(out["thumbnail"]).size == (256, 170)
def test_exif_orientation_is_applied_and_dropped():
# 60x20 stored landscape with Orientation=6 (rotate 90 CW): displayed portrait 20x60.
img = Image.new("RGB", (60, 20), (200, 30, 30))
exif = Image.Exif()
exif[0x0112] = 6
buf = io.BytesIO()
img.save(buf, "JPEG", exif=exif.tobytes(), quality=95)
out = variants(buf.getvalue(), "image/jpeg")
assert decoded(out["thumbnail"]).size == (20, 60)
assert decoded(out["optimized"]).size == (20, 60)
for v in out.values():
assert not decoded(v).getexif(), v.name
def test_alpha_is_composited_on_white_for_jpeg_and_kept_for_webp():
img = Image.new("RGBA", (64, 64), (255, 0, 0, 0)) # fully transparent red
buf = io.BytesIO()
img.save(buf, "PNG")
out = variants(buf.getvalue())
thumb = decoded(out["thumbnail"]).convert("RGB")
assert min(thumb.getpixel((32, 32))) >= 250, "transparent pixels must become white, not red/black"
webp = decoded(out["optimized"])
assert webp.mode == "RGBA" and webp.getpixel((10, 10))[3] == 0
def test_metadata_is_not_copied():
img = Image.new("RGB", (300, 300), (10, 200, 10))
exif = Image.Exif()
exif[0x010F] = "SecretCamera" # Make
buf = io.BytesIO()
img.save(buf, "JPEG", exif=exif.tobytes(), icc_profile=b"\0" * 128, comment=b"private")
out = variants(buf.getvalue(), "image/jpeg")
for name in ("thumbnail", "crop"):
data = out[name].data
assert b"Exif" not in data and b"ICC_PROFILE" not in data and b"SecretCamera" not in data, name
assert b"EXIF" not in out["optimized"].data and b"ICCP" not in out["optimized"].data
@pytest.mark.parametrize("mode", ["RGBA", "P", "1", "L", "LA", "RGB"])
def test_png_modes_are_processed(mode):
out = variants(imagegen.png(33, 17, mode))
assert decoded(out["thumbnail"]).size == (33, 17)
def test_16_bit_grey_is_scaled_not_clipped():
img = Image.new("I;16", (8, 8), 32768) # 50 % grey in 16 bits
buf = io.BytesIO()
img.save(buf, "PNG")
out = variants(buf.getvalue())
value = decoded(out["thumbnail"]).convert("L").getpixel((4, 4))
assert 120 <= value <= 135
def test_pipeline_versions_differ_in_bytes_not_in_geometry():
v1, v2 = variants(SAMPLE, version=1), variants(SAMPLE, version=2)
for name in v1:
assert (v1[name].width, v1[name].height) == (v2[name].width, v2[name].height)
assert v1[name].sha256 != v2[name].sha256
assert variants(SAMPLE, version=1)["thumbnail"].sha256 == v1["thumbnail"].sha256 # deterministic
def test_pixel_limit_is_checked_before_decoding():
# 8001 x 5000 = 40.005 Mpx with only a few rows of data: refused from the header (TooLarge);
# 20000 x 10000 is refused even earlier by Pillow's own bomb check (> 2 x MAX_IMAGE_PIXELS).
with pytest.raises(imaging.TooLarge):
imaging.build(imagegen.png_bomb_header(8001, 5000), "image/png", 1, LIMIT)
with pytest.raises((imaging.TooLarge, Image.DecompressionBombError)):
imaging.build(imagegen.png_bomb_header(), "image/png", 1, LIMIT)
def test_child_process_protocol_round_trip():
out = list(variants(SAMPLE).values())
raw = json.dumps({"variants": [{"name": v.name, "content_type": v.content_type, "width": v.width,
"height": v.height, "size": len(v.data)} for v in out]}).encode() + b"\n"
raw += b"".join(v.data for v in out)
parsed = imaging.parse_output(raw)
assert [(p.name, p.sha256) for p in parsed] == [(v.name, v.sha256) for v in out]
with pytest.raises(imaging.ProcessingError):
imaging.parse_output(raw[:-1])
# ------------------------------------------------------------------ message format
def test_encoded_message_matches_jobs_schema_and_carries_ids_only():
import datetime as dt
raw = broker.encode(str(uuid.uuid4()), str(uuid.uuid4()), 1, 2, dt.datetime.now(dt.timezone.utc))
body = json.loads(raw)
assert not list(Draft202012Validator(SCHEMA, format_checker=Draft202012Validator.FORMAT_CHECKER).iter_errors(body))
assert set(body) == {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"}
assert broker.decode(raw) == body
@pytest.mark.parametrize("change", [
{"schema_version": 2}, {"type": "other"}, {"job_id": "not-a-uuid"}, {"attempt": 0}, {"attempt": True},
{"pipeline_version": "1"}, {"created_at": "yesterday"}, {"url": "http://evil"}, {"object_key": "a/b"},
{"traceparent": "bad"},
])
def test_invalid_messages_are_rejected(change):
body = json.loads(broker.encode(str(uuid.uuid4()), str(uuid.uuid4()), 1, 1,
__import__("datetime").datetime(2026, 1, 1, tzinfo=__import__("datetime").timezone.utc)))
body.update(change)
with pytest.raises(broker.BadMessage):
broker.decode(json.dumps(body).encode())
# The contract schema refuses the same messages (date-time needs an optional jsonschema extra).
checker = Draft202012Validator.FORMAT_CHECKER
assert list(Draft202012Validator(SCHEMA, format_checker=checker).iter_errors(body)) or "created_at" in change
def test_garbage_is_rejected():
for raw in (b"", b"[]", b"{", b"\xff", b"x" * 5000):
with pytest.raises(broker.BadMessage):
broker.decode(raw)
# ------------------------------------------------------------------ backoff and configuration
def test_backoff_is_full_jitter_and_capped():
assert jobs.backoff_delay(1, 2, 60, rnd=lambda: 1.0) == 2
assert jobs.backoff_delay(3, 2, 60, rnd=lambda: 1.0) == 8
assert jobs.backoff_delay(10, 2, 60, rnd=lambda: 1.0) == 60
assert jobs.backoff_delay(4, 2, 60, rnd=lambda: 0.0) == 0
samples = [jobs.backoff_delay(3, 2, 60) for _ in range(500)]
assert 0 <= min(samples) < 2 and 6 < max(samples) <= 8 # spread over the whole window
def test_pipeline_settings(monkeypatch):
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
monkeypatch.setenv("S3_ACCESS_KEY_ID", "AKTEST")
monkeypatch.setenv("S3_SECRET_ACCESS_KEY", "secret-for-unit-tests")
s = Settings.from_env()
assert (s.job_max_attempts, s.job_timeout_seconds, s.worker_concurrency, s.staging_retention_seconds) == (5, 60, 2, 86400)
assert s.s3_staging_bucket == "messenger-staging" and s.pipeline_version == 1
monkeypatch.setenv("FAULT_POINTS", "transient_error=3,slow")
s = Settings.from_env()
assert s.fault_points == {"transient_error", "slow"} and s.fault_value("transient_error") == 3
for name, value in (("PIPELINE_VERSION", "9"), ("JOB_MAX_ATTEMPTS", "0"), ("FAULT_POINTS", "slow=x"),
("S3_STAGING_BUCKET", "messenger-attachments"), ("JOB_RETRY_BASE_SECONDS", "100")):
monkeypatch.setenv(name, value)
with pytest.raises(ConfigError):
Settings.from_env()
monkeypatch.delenv(name)
assert set(PIPELINES) == {1, 2, 3}