Author SHA1 Message Date
Матвей 6bc0712c2c bug fix 2026-10-27 12:24:31 +03:00
Матвей a1bb6f8bde refactor 2026-10-26 15:49:31 +03:00
40 changed files with 17122 additions and 221 deletions
+2 -1
View File
@@ -11,7 +11,7 @@ SESSION_STORE=postgres
CACHE_URL_FILE=/run/secrets/cache_url
API_REPLICAS=2
IDEMPOTENCY_TTL_SECONDS=86400
S3_ENDPOINT=http://s3:9000
S3_ENDPOINT=http://s3:8333
S3_REGION=us-east-1
S3_BUCKET=messenger-attachments
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
@@ -25,3 +25,4 @@ JOB_MAX_ATTEMPTS=5
JOB_TIMEOUT_SECONDS=60
STAGING_RETENTION_SECONDS=86400
MAX_PENDING_JOBS=100
RENDER_MEMORY_MB=768
+73 -15
View File
@@ -1,18 +1,76 @@
## Лабораторная 5
## Лабораторная 5: асинхронная обработка изображений
Автор / группа: TODO
Целевая оценка (3/4/5): TODO
Трек 5, если заявлен: TODO
Автор / группа: Матвей Козырев / BVT2301.
Целевая оценка: 5. Трек 1 — «Очередь под перегрузкой».
Ветка решения: `solution/BVT2301-Kozyrev`.
Что реализовано и что перенесено: TODO
Команды запуска из чистого clone: TODO
Результаты проверок и ссылка на REPORT.md: TODO
Ограничения / известные ошибки: TODO
Источники и использование ИИ: TODO
Upload принимает исходный файл в устойчивое S3 staging и возвращает `202 queued` после фиксации attachment, job и outbox в PostgreSQL. Отдельный worker создаёт варианты изображения; клиент получает состояние через метаданные. Доказательства уровней 3–5 и ограничения исследования приведены в REPORT.md и evidence.
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
- [ ] Контракт и публичные тесты не ослаблены.
- [ ] make check и make test выполнены; приложен реальный вывод.
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
## Реализация
- Перенесена база lab4: FastAPI, PostgreSQL, сессии, чаты/сообщения, идемпотентность сообщений, приватное S3-хранилище SeaweedFS, две API-реплики за HAProxy.
- Добавлены RabbitMQ с persistent volume, transactional outbox и отдельные dispatcher/worker.
- Реализованы состояния `queued/processing/ready/failed`, thumbnail JPEG, crop JPEG 128×128 и optimized WebP.
- Добавлены ограниченные retries с backoff/jitter, классификация ошибок, lease recovery, защита от устаревших попыток, реестр failed и операторский replay. Некорректные сообщения направляются в DLQ.
- Рендер выполняется в отдельном процессе с timeout и Linux-лимитом памяти. Worker имеет heartbeat healthcheck; staging и непривязанные объекты очищаются с блокировкой активных writers.
- Добавлены глобальный лимит принятых jobs с ответом `429`, отдельные concurrency/prefetch и генератор исследования с измерением queue wait, времени до ready, throughput, RSS и проверкой восстановления.
## Запуск и проверка
Нужны работающий Docker Engine с Compose v2, Python 3.12+, uv и свободный порт `127.0.0.1:8080`. Из корня clone:
```sh
git switch solution/BVT2301-Kozyrev
python3 scripts/init-secrets.py
docker compose config --quiet
docker compose up -d --build
docker compose ps -a
curl --fail http://localhost:8080/health/ready
make test
```
Миграции и bootstrap bucket выполняются сервисами `migrate` и `s3-init`. Остановка с сохранением данных: `docker compose down`.
Локальные регрессии:
```sh
uv sync --locked --no-dev
make check
.venv/bin/python student-tests/pipeline_critical.py
.venv/bin/python student-tests/remaining_regressions.py
```
Выполнено локально: `make check`, `docker compose config --quiet`, `git diff --check`; 8 тестов критических ошибок и 7 дополнительных регрессионных тестов прошли. Часть сценариев использует mocks и не проверяет SQL на реальном PostgreSQL.
Подробные команды, результаты, архитектура и матрица критериев: [REPORT.md](../REPORT.md).
## Интеграционные проверки
- Публичный smoke, persistence и failover обеих API-реплик.
- Worker stop → upload 202 → сообщение с вложением → restart API/broker → ready.
- Дубли доставки; crash между COMMIT и publish; crash worker после S3 до COMMIT/ack; lease recovery.
- Исчерпание retry, permanent failure, реестр failed, явный replay и отказ replay для ready.
- Реальные SQL-проверки backoff, счётчика lease, fencing и watchdog зависших queued jobs.
- Linux memory/timeout, приватность S3, ACL вариантов, безопасная уборка stale-объектов.
- Трек 1: concurrency/prefetch 1/1, 2/2, 4/4 на двух размерах PNG; throughput, p95, queue wait, RSS, 429, drain и контрольный upload.
Повторяемые команды и результаты: [REPORT.md](../REPORT.md), [pipeline-integration.json](../evidence/pipeline-integration.json), [pipeline-invariants.json](../evidence/pipeline-invariants.json), [resilience.json](../evidence/resilience.json).
Исправлены запуск RabbitMQ с Docker secret, обход backoff/lease дублем и отсутствие повторной публикации для зависших queued jobs. Контракты и публичные тесты не менялись.
Ограничения: один Docker-host; closed-loop burst и polling; один прогон на профиль, без статистической оценки; RSS может учитывать shared pages повторно и пропускать пики. Failed staging сохраняется для replay. Чистый clone отдельно не запускался; исторические student-tests lab4 вне перечисленного набора не заявляются пройденными. Оценку определяет преподаватель.
## Источники и использование ИИ
Основа — README задания, обязательные контракты и публичные тесты; версии библиотек зафиксированы в `pyproject.toml`/`uv.lock`, образы — в `compose.yaml`/`Dockerfile`. Источники и детали перечислены в [REPORT.md](../REPORT.md).
Codex использовался для переноса кода, реализации, аудита, исправлений, тестов и документации. Mock-регрессии отделены от реальных интеграционных и нагрузочных результатов.
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
- [x] Контракт и публичные тесты не ослаблены.
- [x] make check и make test выполнены; приложен реальный вывод.
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
Проверка секретов: совпадений с локальными credentials и проверенными форматами ключей не обнаружено в отслеживаемых файлах и доступной Git-истории. Область и ограничения проверки: [evidence/checklist-review.txt](../evidence/checklist-review.txt).
+168 -23
View File
@@ -1,41 +1,186 @@
# Отчёт — лабораторная 5
- Автор, группа: Matvey Kozyrev, BVT2301
- Целевая оценка; выбранный трек 5, если нужен: 5, трек 1 «Очередь под перегрузкой»
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
> Проверка выполняется на реальном PostgreSQL/S3/RabbitMQ. Результаты отказов: [pipeline-integration.json](evidence/pipeline-integration.json), SQL/безопасности: [pipeline-invariants.json](evidence/pipeline-invariants.json), persistence/failover: [resilience.json](evidence/resilience.json). История первоначальных проверок: [checklist-review.txt](evidence/checklist-review.txt).
- Автор: Матвей Козырев, BVT2301.
- Целевая оценка: 5, трек 1 «Очередь под перегрузкой».
- Ветка: `solution/BVT2301-Kozyrev`. HEAD перед текущими исправлениями: `a1bb6f8` (`refactor`); результаты относятся к рабочему дереву, а не только этому commit. Ссылка на PR не предоставлена.
- Даты локальной проверки: 26–27 октября 2026 года.
- Статус: перечисленные ниже проверки уровней 3–4 и исследование трека 1 уровня 5 выполнены; результаты и границы проверки приложены. Это не автоматическое выставление оценки.
## Исходная база, источники и помощь ИИ
Из собственной lab4 перенесены API на FastAPI, PostgreSQL-миграции, сессии, идемпотентность сообщений, S3-адаптер, две API-реплики и HAProxy. Основание проверки: [README](README.md), [семантика API](contracts/README.md), [состояния вложений](contracts/attachment-states.md), [OpenAPI](contracts/openapi.json), [инфраструктура](contracts/infrastructure.json), [публичные тесты](tests/README.md).
Использован Codex для переноса исходников, подготовки реализации, аудита, исправлений и оформления отчёта. Локальные проверки не заменяют интеграционную демонстрацию. Справочные первоисточники задания: [RabbitMQ reliability](https://www.rabbitmq.com/docs/reliability), [publisher confirms и consumer acknowledgements](https://www.rabbitmq.com/docs/confirms).
Зависимости зафиксированы в [pyproject.toml](pyproject.toml) и [uv.lock](uv.lock): FastAPI 0.141.1, Uvicorn 0.40.0, asyncpg 0.31.0, argon2-cffi 25.1.0, boto3 1.43.115, Pillow 13.0.0, pika 1.3.2. Имя пакета пока сохранено от lab4.
## Запуск из чистого clone
Python 3.12, PostgreSQL 17.6, SeaweedFS 4.17, RabbitMQ 4.1 и HAProxy 3.0 запускаются через Compose. Для локального синтетического стенда: `python3 scripts/init-secrets.py`, затем `docker compose up -d --build`; дождаться `docker compose ps` со статусом healthy и выполнить `make test`. Локальные секреты создаются в игнорируемом `secrets/`. Остановка без удаления данных: `docker compose down`; удаление учебных данных выполняется оператором отдельно через `docker compose down -v`.
Нужны Git, Python 3.12+ для приложения, uv и работающий Docker Engine с Compose v2. REST доступен на `127.0.0.1:8080`; порт должен быть свободен, в том числе от стенда lab4. Используются синтетические данные.
В [Dockerfile](Dockerfile) и [Compose](compose.yaml) закреплены Python 3.12.12-slim, uv 0.11.28, PostgreSQL 17.6-alpine, SeaweedFS 4.17 с digest, RabbitMQ 4.1.2-alpine, HAProxy 3.0.11-alpine.
Из корня полученного clone:
```sh
git switch solution/BVT2301-Kozyrev
python3 scripts/init-secrets.py
docker compose config --quiet
docker compose up -d --build
docker compose ps -a
curl --fail http://localhost:8080/health/ready
make test
```
Локальные credentials создаются в игнорируемом `secrets/`. Их содержимое нельзя публиковать. Стандартный Compose использует значения по умолчанию; отдельный .env не обязателен. Сервис migrate применяет SQL из migrations, s3-init создаёт приватный bucket и проверяет запись. API и worker зависят от успешного завершения этих сервисов.
Эта инструкция пока не подтверждена запуском из чистого clone. Успешный `up -d` сам по себе не доказывает готовность: нужны проверка процессов, readiness и smoke. Worker использует heartbeat AMQP event loop; outbox/reconcile не наследуют HTTP healthcheck.
Локальные проверки:
```sh
uv sync --locked --no-dev
make check
.venv/bin/python student-tests/pipeline_critical.py
# Для полной OpenAPI-валидации:
uv pip install --python .venv/bin/python -r requirements-dev.txt
make validate PYTHON=.venv/bin/python
```
Остановка с сохранением volumes: `docker compose down`. Намеренный сброс учебных данных: `docker compose down -v`; удаляет volumes PostgreSQL, S3 и RabbitMQ данного проекта. В ходе проверки сброс не выполнялся.
## Архитектура и решения
PostgreSQL хранит метаданные, jobs и transactional outbox; SeaweedFS — private staging/final objects; RabbitMQ — durable сообщения; worker и outbox-dispatcher — отдельные процессы. До HTTP 202 API полностью принимает и валидирует bytes, сохраняет staging-object и в одной DB-транзакции метаданные + job + outbox event. Dispatcher публикует событие с publisher confirm и отмечает event после confirm, поэтому crash между COMMIT и publish восстанавливается без ручной job. Worker ack делает только после durable результата либо после финального failed. Обработка идемпотентна по attachment/pipeline/variant: повтор ready-job не меняет результат. Lease ограничен `JOB_TIMEOUT_SECONDS`; истёкшая processing-job возвращается в очередь dispatcher-ом. Retry ограничен `JOB_MAX_ATTEMPTS`, использует exponential backoff с jitter; исчерпанная job остаётся failed и её служебное сообщение попадает в DLQ. Явный replay: `docker compose run --rm outbox /app/.venv/bin/python -m src.replay <attachment_uuid>`.
Клиент → HAProxy → API → PostgreSQL + S3 staging. Фоновый путь: PostgreSQL outbox → dispatcher → RabbitMQ → worker → final S3 objects + метаданные PostgreSQL. Реализация: [attachments.py](src/attachments.py), [postgres.py](src/storage/postgres.py), [outbox.py](src/outbox.py), [broker.py](src/broker.py), [worker.py](src/worker.py).
На уровне 4 worker создаёт: thumbnail JPEG 256×256 без увеличения; crop JPEG 128×128, центрированный квадрат; optimized WebP до 1280×1280 без увеличения. JPEG quality=85, WebP quality=80; входные EXIF/metadata не сохраняются.
PostgreSQL хранит пользователей, чаты, сообщения, сессии, attachments, jobs и outbox. S3 хранит байты. Брокер передаёт служебные ID, без файлов и credentials.
## Доказательства критериев
Перед 202 API полностью принимает HTTP body, проверяет изображение, записывает исходник в staging и фиксирует attachment/job/outbox одной DB-транзакцией. S3 PUT не входит в DB-транзакцию: при rollback возможен непривязанный объект. Resize выполняет worker. Клиент получает состояние через GET метаданных; content неготового вложения возвращает 409.
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Трек 5: очередь под перегрузкой | `make track1 TRACK_ARGS="..."` | TODO: заполнить только результатом выполненного прогона | `evidence/track1-*.json` |
Dispatcher декодирует JSONB и публикует persistent сообщение с publisher confirm, затем отмечает event опубликованным. Crash после confirm до отметки допускает дубль. Восстановление после crash API между COMMIT и publish проверено с остановленным dispatcher: в БД остаётся неопубликованный outbox, после запуска задача достигает ready без создания новой job.
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
Watchdog повторно создаёт outbox-intent для queued-job, не захваченной за 60 секунд после публикации. Он не увеличивает attempt: это повтор доставки, а не новая попытка обработки. После намерения updated_at обновляется, поэтому повтор не происходит каждый цикл dispatcher. Это также восстанавливает доставку, если durable job существует, но брокер больше не содержит сообщения; дубли защищены состоянием job.
## Эксперименты и отказы
Worker захватывает только queued-job, для которой не действует отложенный retry. Просроченный processing восстанавливает dispatcher с увеличением attempt; дубль не продлевает lease и не обходит backoff. Завершение проверяет состояние, время захвата processing_started_at и срок lease. Попытки пишут по разным S3-ключам; только действующая попытка публикует свои ключи в БД. Отклонение устаревших completion/retry проверено на PostgreSQL. Логический ключ варианта — (attachment_id, pipeline_version, name); физические непривязанные объекты требуют уборки.
Гипотеза: увеличение worker concurrency сокращает p95 «202 → ready» до точки насыщения CPU/RAM; prefetch выше concurrency может повысить throughput ценой queue lag и RSS. Проверяются минимум три конфигурации: `1/1`, `2/2`, `4/4` (concurrency/prefetch) и несколько размеров входного PNG. Для каждой конфигурации используются одинаковые CPU/RAM limits Compose, одинаковое число изображений и не менее трёх прогонов после прогрева.
Ack выполняется после устойчивого результата или записи retry/failed; при сбое записи используется nack/requeue. Terminal-job повторно не обрабатывается. Это at-least-once доставка, не exactly-once. Реестр failed хранится в PostgreSQL; DLQ используется для некорректных сообщений.
Команда запуска профиля: `WORKER_CONCURRENCY=N WORKER_PREFETCH=P MAX_PENDING_JOBS=20 docker compose up -d --build`. Команда измерения: `make track1 TRACK_ARGS="--run-name cN-pP-sizeS --workers N --prefetch P --max-pending 20 --images 40 --concurrency 8 --size S"`. Скрипт сохраняет raw JSON с successful throughput, p50/p95 времени принятия и ready, queue depth RabbitMQ и RSS worker. Значения будут внесены после реального прогона; сейчас их нет, так как Docker daemon недоступен.
Ошибка удаления staging после ready журналируется и не откатывает результат. Сервис reconcile раз в минуту удаляет непривязанные объекты старше retention из staging/originals/variants. Общая advisory-блокировка исключает удаление во время upload и работы worker. Staging failed-задач сохраняется для явного replay; автоматического удаления этих исходников нет. Lease recovery учитывает попытки; retry использует exponential backoff с jitter. Невалидное изображение и превышение памяти рендера переводят задачу в failed без повторов. Ошибки зависимостей и timeout повторяются с ограничением попыток.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
Явный операторский replay только failed-job:
## Ограничения и следующие шаги
```sh
docker compose run --rm outbox /app/.venv/bin/python -m src.replay ATTACHMENT_UUID
```
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
Replay сохраняет replayed_at; полного журнала операторских действий нет.
## Конфигурация и варианты изображений
| Параметр | Соответствие реализации |
| --- | --- |
| SESSION_TTL_SECONDS / IDEMPOTENCY_TTL_SECONDS | По умолчанию 3600 / 86400 секунд, PostgreSQL |
| S3_ENDPOINT | Compose и .env.example используют http://s3:8333 |
| DATABASE_URL_FILE, CURSOR_SECRET_FILE, S3/Broker *_FILE | Credentials подключаются через Compose secrets |
| MAX_UPLOAD_BYTES / MAX_IMAGE_PIXELS | 10 485 760 байт / 40 000 000 пикселей; 10 MiB = 10 × 1024 × 1024 байт |
| WORKER_CONCURRENCY / WORKER_PREFETCH | По умолчанию 2 / 2, потоки и prefetch |
| JOB_MAX_ATTEMPTS / JOB_TIMEOUT_SECONDS | По умолчанию 5 / 60; рендер идёт в отдельном subprocess, принудительно завершаемом по timeout |
| MAX_PENDING_JOBS | По умолчанию 100 queued/processing jobs; глобальная DB-блокировка при admission, отказ 429 |
| STAGING_RETENTION_SECONDS | Порог возраста непривязанных объектов для плановой уборки, по умолчанию 86400 секунд |
| OUTBOX_FAULT_AFTER_COMMIT / WORKER_FAULT_AFTER_S3_PUT | По умолчанию 0; включаются только отказными тестами. Worker падает один раз на контейнер, после записи вариантов до COMMIT/ack; маркер находится в /tmp |
| API_REPLICAS, SESSION_STORE, CACHE_URL_FILE | Не управляют текущим Compose: явно заданы api-a/api-b и PostgreSQL без Redis |
Worker применяет EXIF orientation, композитит alpha на белый, создаёт thumbnail JPEG до 256×256, центрированный crop JPEG 128×128, optimized WebP до 1280×1280. JPEG quality=85, WebP quality=80/method=4; явного переноса входных EXIF нет.
Округление исправлено: исходник 300×200 даёт 256×170; высота вычисляется как floor(200 × 256 / 300). Маленькие изображения не увеличиваются. Linux renderer ограничен RLIMIT_AS=768 MiB; worker-контейнер ограничен 4 GiB RAM и 2 CPU. RSS собирается отдельно, RLIMIT_AS ограничивает виртуальную память.
## Выполненные проверки и доказательства критериев
Локально прошли `make check`, полная OpenAPI-валидация и 15 регрессионных тестов (8 + 7). Контракт, README задания и публичные tests не изменены относительно skeleton `276dbda`. Mock-числа не используются как нагрузочные результаты.
На контейнерном стенде прошли публичный smoke, дополнительные проверки attachments, конкурентная идемпотентность и S3 permissions. Команды и первоначальный вывод: [checklist-review.txt](evidence/checklist-review.txt).
| Критерий README | Проверка и доказательство |
| --- | --- |
| 3: минимум lab4, durable upload 202 | Smoke, attachments, persistence; HTTP передаёт все байты, исходник после рестарта совпадает |
| 3: broker/worker, доставка, ack | Отдельные контейнеры; broker restart с volume; queued → ready после запуска worker |
| 3: состояния, оригинал, thumbnail | HTTP-сценарии, фактические форматы/размеры и неизменность оригинала |
| 3: retries, failed, идемпотентность | Исчерпание двух попыток в тестовой конфигурации, failed/replay; дубль ready не создаёт объектов |
| 3: worker stop → upload → сообщение → restart API/broker → ready | PASS в [pipeline-integration.json](evidence/pipeline-integration.json) |
| 4: crop/WebP и bytes/pixels/time/memory | Attachments проверяет границы bytes/pixels; invariants — варианты и Linux timeout; integration — Linux memory limit |
| 4: outbox, crash COMMIT/publish | Реальный exit API при остановленном outbox; существующая job достигает ready после восстановления |
| 4: backoff/jitter, классификация, failed/replay | Permanent invalid_image на первой попытке; transient retry исчерпывается; явный replay; SQL-тест запрещает обход backoff дублем |
| 4: crash после S3, lease, cleanup | Worker exit до COMMIT/ack; attempt=2; четыре stale-объекта удалены, четыре объекта актуального результата сохранены |
| 5: три настройки, разные изображения | Серия 1/1, 2/2, 4/4 для 512×512 и 2400×2400; результаты ниже |
| 5: backpressure и восстановление | Генератор требует 429, соблюдение лимита в замерах, ready всех принятых jobs, пустую очередь и успешный контрольный upload |
Основные источники: [pipeline-integration.json](evidence/pipeline-integration.json), [pipeline-invariants.json](evidence/pipeline-invariants.json), [resilience.json](evidence/resilience.json). Последний содержит состояния контейнеров до/после: сохранение данных проверяется вместе с фактом перезапуска, а не только возвратом hook=0. [job-contract.json](evidence/job-contract.json) подтверждает проверку 425 реальных outbox payloads по обязательной схеме, включая запрет дополнительных полей, и no-op повторной доставки полного сохранённого сообщения.
Последний публичный failover для обеих реплик: восстановление записи за 2,436 и 4,675 с при требовании ≤10 с; соответственно 113 и 95 подтверждённых записей, 1 и 2 неуспешные переходные попытки. Подтверждённые сообщения, исходный файл и прежняя сессия сохранились. Persistence прошёл с изменившимися StartedAt всех проверяемых API/хранилищ/worker/outbox.
Воспроизводимый запуск, строго последовательно на отдельном учебном стенде:
```sh
uv sync --locked --no-dev
uv pip install --python .venv/bin/python -r requirements-dev.txt
make check
make validate PYTHON=.venv/bin/python
make test PYTHON=.venv/bin/python
.venv/bin/python student-tests/attachments.py
.venv/bin/python student-tests/s3_permissions.py
.venv/bin/python student-tests/idempotency_concurrency.py
.venv/bin/python student-tests/pipeline_critical.py
.venv/bin/python student-tests/remaining_regressions.py
.venv/bin/python student-tests/pipeline_invariants.py
.venv/bin/python student-tests/pipeline_integration.py
.venv/bin/python student-tests/job_contract.py
.venv/bin/python scripts/verify-resilience.py
.venv/bin/python scripts/run-track1-profiles.py
.venv/bin/python scripts/record-environment.py
```
Отказные тесты временно останавливают/пересоздают сервисы и изменяют только свои синтетические вложения. В finally восстанавливают обычные настройки; volumes не удаляют. Проверка cleanup удалила только четыре явно выбранных непривязанных объекта аварийной попытки; актуальные объекты остались. Не запускайте эти тесты одновременно с нагрузкой.
## Эксперимент: очередь под перегрузкой
Гипотеза: увеличение concurrency/prefetch сокращает ожидание в очереди до насыщения CPU, но повышает потребление памяти; admission ограничивает принятую работу и позволяет восстановиться после burst.
Методика: [run-track1-profiles.py](scripts/run-track1-profiles.py) последовательно выставляет 1/1, 2/2, 4/4. Для каждого профиля выполняются два burst по 160 запросов с 16 клиентскими потоками: PNG 512×512 (1890 байт) и 2400×2400 (22196 байт). Изображения синтетические, с повторяемым рисунком; их сжатый размер не отражает стоимость декодирования. Лимит queued/processing — 32, worker — 2 CPU и 4 GiB RAM. Перед burst проверяются реальные настройки контейнеров и отсутствие pending jobs. Отдельного прогрева и статистических повторений нет: по одному прогону на комбинацию, не измерение предельной производительности.
Среда и хеши исходников: [environment.json](evidence/environment.json). Docker Desktop на macOS ARM64; VM имеет 10 CPU и 10 416 644 096 байт RAM. Это ресурсы VM, не выделенные worker.
Источники результатов: [1/1, 512](evidence/real-c1-p1-s512.json), [1/1, 2400](evidence/real-c1-p1-s2400.json), [2/2, 512](evidence/real-c2-p2-s512.json), [2/2, 2400](evidence/real-c2-p2-s2400.json), [4/4, 512](evidence/real-c4-p4-s512.json), [4/4, 2400](evidence/real-c4-p4-s2400.json).
| Concurrency/prefetch | PNG, px | 202 / 429 | Длительность, с | Ready/с | p95 ready, с | p95 queue wait, с | RSS max, MiB |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 1/1 | 512×512 | 33 / 127 | 25.89 | 1.275 | 24.481 | 23.709 | 134.0 |
| 1/1 | 2400×2400 | 37 / 123 | 35.50 | 1.042 | 30.436 | 29.505 | 240.0 |
| 2/2 | 512×512 | 34 / 126 | 16.24 | 2.093 | 14.519 | 13.572 | 157.9 |
| 2/2 | 2400×2400 | 44 / 116 | 25.81 | 1.705 | 18.617 | 17.474 | 406.4 |
| 4/4 | 512×512 | 32 / 128 | 15.49 | 2.066 | 14.970 | 13.602 | 286.6 |
| 4/4 | 2400×2400 | 40 / 120 | 24.31 | 1.646 | 18.508 | 16.166 | 518.4 |
Итого: 6 × 160 = 960 запросов, 220 приняты и завершены ready, 740 получили ожидаемый 429; failed, timeout и ошибки метрик — 0. Во всех шести прогонах очередь полностью опустела и контрольный upload достиг ready. Максимум pending в сэмплах — 32; на прогон получено 5–14 сэмплов.
Вывод для этой серии: 2/2 быстрее 1/1 на обоих размерах, но использует больше памяти. Переход 2/2 → 4/4 не увеличил измеренный throughput: 2,093 → 2,066 ready/с для 512 и 1,705 → 1,646 для 2400. При этом RSS вырос с 157,9 до 286,6 MiB и с 406,4 до 518,4 MiB соответственно. На лимите 2 CPU профиль 2/2 выглядит более экономным выбором для этой нагрузки; статистически доказанного оптимума по одному прогону нет. p95 включает накопление очереди, поэтому это не время одного изолированного resize.
Формулы: throughput = ready / elapsed_seconds; p95 — элемент ceil(0,95 × N) отсортированной выборки; queue wait = first_started_at − created_at в PostgreSQL; RSS MiB = max_sampled_rss_bytes / 1 048 576. Время ready измеряется от ответа 202 до наблюдения ready. В JSON сохранены p50/p95/p99, все запросы, длительность, замеры очереди и число отказов.
Это closed-loop burst: coordinated omission, polling и накладные расходы клиента ограничивают выводы. RSS — сумма RSS процессов worker, shared pages могут учитываться несколько раз; пики между замерами пропускаются. Сэмплы pending подтверждают наблюдаемый предел, но не заменяют атомарную admission-блокировку. Число принятых за весь прогон может превышать 32: завершённые jobs освобождают ёмкость. Ответы 429 ожидаемы и учитываются отдельно от транспортных ошибок и failed jobs.
## Исправления по результатам проверки
- RabbitMQ 4.1.2 отвергал RABBITMQ_DEFAULT_PASS_FILE. [Стартовый скрипт](infra/rabbitmq-secret-entrypoint.sh) читает Docker secret внутри контейнера и вызывает штатный entrypoint; пароль не записан в Compose.
- Дубль мог обойти backoff и повторно захватить просроченный processing без увеличения attempt. [Захват в PostgreSQL](src/storage/postgres.py) теперь разрешён только для queued без действующей задержки; lease восстанавливает dispatcher. Реальный SQL-тест покрывает обе ситуации и устаревшие completion/retry.
- После выключения Docker обнаружены queued jobs с published outbox при пустой очереди брокера. Причина исчезновения сообщений не установлена; установлен дефект восстановления: next_attempt_at=infinity исключал такие jobs из повторной публикации навсегда. Добавлен 60-секундный watchdog; реальный SQL-тест проверяет повторную публикацию без увеличения attempt и без создания события на каждом проходе.
- Добавлен отключённый по умолчанию одноразовый crash-hook worker после S3; нужны реальные проверки этой границы, а не только mocks.
## Ограничения
Один Docker-host, одна БД, брокер, S3 и LB не обеспечивают устойчивость к потере host/хранилищ. Проверены конкретные процессные отказы и перезапуски с сохранёнными volumes. At-least-once не означает exactly-once.
Failed staging сохраняется бессрочно для явного replay; автоматической политики удаления таких исходников нет. Полного аудита операторских действий нет, сохраняется replayed_at. Исторические student-tests lab4, не перечисленные в командах выше, не заявляются как пройденные.
Запуск из отдельного чистого clone не проверялся: сборка, миграции и bootstrap проверялись в текущем рабочем дереве. Изменения не закоммичены и PR автоматически не создан. Окончательную оценку определяет преподаватель с учётом защиты; успешные тесты не являются доказательством отсутствия любых ошибок.
+24 -2
View File
@@ -54,11 +54,13 @@ services:
image: rabbitmq:4.1.2-alpine
environment:
RABBITMQ_DEFAULT_USER: messenger
RABBITMQ_DEFAULT_PASS_FILE: /run/secrets/rabbitmq_password
entrypoint: ["/bin/sh", "/usr/local/bin/rabbitmq-secret-entrypoint.sh"]
command: ["rabbitmq-server"]
secrets:
- rabbitmq_password
volumes:
- rabbitmq_data:/var/lib/rabbitmq
- ./infra/rabbitmq-secret-entrypoint.sh:/usr/local/bin/rabbitmq-secret-entrypoint.sh:ro
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 5s
@@ -151,10 +153,13 @@ services:
memory: 128M
reconcile:
healthcheck:
disable: true
build:
context: .
entrypoint: ["/app/.venv/bin/python", "-m", "src.reconcile"]
profiles: ["maintenance"]
command: ["--apply", "--loop"]
restart: unless-stopped
environment:
DATABASE_URL_FILE: /run/secrets/database_url
CURSOR_SECRET_FILE: /run/secrets/cursor_secret
@@ -162,6 +167,7 @@ services:
S3_BUCKET: messenger-attachments
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_admin_key
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_admin_secret
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
secrets:
- database_url
- cursor_secret
@@ -185,6 +191,17 @@ services:
<<: *api
worker:
restart: unless-stopped
healthcheck:
test: ["CMD", "/app/.venv/bin/python", "-c", "import time,pathlib; assert time.time()-float(pathlib.Path('/tmp/worker-heartbeat').read_text()) < 15"]
interval: 5s
timeout: 3s
retries: 3
deploy:
resources:
limits:
cpus: "2.0"
memory: 4G
build:
context: .
command: ["/app/.venv/bin/python", "-m", "src.worker"]
@@ -198,6 +215,8 @@ services:
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
BROKER_URL_FILE: /run/secrets/broker_url
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
WORKER_FAULT_AFTER_S3_PUT: ${WORKER_FAULT_AFTER_S3_PUT:-0}
RENDER_MEMORY_MB: ${RENDER_MEMORY_MB:-768}
WORKER_PREFETCH: ${WORKER_PREFETCH:-2}
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
@@ -218,6 +237,8 @@ services:
stop_grace_period: 30s
outbox:
healthcheck:
disable: true
build:
context: .
command: ["/app/.venv/bin/python", "-m", "src.outbox"]
@@ -227,6 +248,7 @@ services:
CURSOR_SECRET_FILE: /run/secrets/cursor_secret
BROKER_URL_FILE: /run/secrets/broker_url
OUTBOX_DISPATCH_INTERVAL_SECONDS: "1"
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
secrets:
- database_url
- cursor_secret
+12
View File
@@ -3,3 +3,15 @@
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
## Проверки решения, 26–27 октября 2026
- [environment.json](environment.json): среда, лимиты, образы и хеши исходников рабочего дерева.
- [checklist-review.txt](checklist-review.txt): хронология проверок, включая первоначальные ошибки; ранние ограничения не описывают финальное состояние.
- [pipeline-integration.json](pipeline-integration.json): stop/restart, crash COMMIT/publish и S3/ack, lease, retry/replay, cleanup, Linux memory.
- [pipeline-invariants.json](pipeline-invariants.json): реальные SQL-инварианты, watchdog, ACL, форматы вариантов, cleanup locking, DLQ, timeout.
- [job-contract.json](job-contract.json): проверка реальных outbox payloads по обязательной схеме и redelivery полного сообщения.
- [resilience.json](resilience.json): stdout публичных persistence/failover и состояния контейнеров до/после.
- `real-c{1,2,4}-p{1,2,4}-s{512,2400}.json`: шесть профилей нагрузки; параметры, каждый запрос, метрики, backpressure и восстановление.
Методика, таблица результатов и ограничения: [REPORT.md](../REPORT.md). Mock-метрики локальных регрессий в исследование не включены. Данные всех пользователей/вложений синтетические; сессии и credentials не сохранялись.
+113
View File
@@ -0,0 +1,113 @@
PR checklist review, 2026-10-26
make check: PASS (offline skeleton check; application not tested).
python student-tests/pipeline_critical.py: 8 tests, OK.
python student-tests/remaining_regressions.py: 7 tests, OK.
docker compose config --quiet: exit 0.
git diff 276dbda -- README.md contracts tests: empty.
git ls-files secrets .env: empty.
git check-ignore .env secrets/postgres_password: both ignored.
Secret scan scope:
- 90 Git-tracked working-tree files.
- 128 blobs reachable through git rev-list --objects --all.
- Compared against 10 locally configured secret values, read without printing.
- Searched private-key headers, AWS keys, GitHub/OpenAI token formats,
JWT-shaped tokens, and literal PostgreSQL/AMQP/Redis credential URLs.
- No findings. Template substitutions in credential URLs were excluded.
- This is a scoped heuristic check, not proof that every possible secret format is absent.
Mock benchmark numbers printed by the regression suite are not load-test evidence.
Integration attempt:
- Started installed Docker Desktop; Docker Engine 29.8.0 became available.
- make validate PYTHON=.venv/bin/python: PASS, full OpenAPI 3.1 / JSON Schema.
- docker compose up -d --build: images built, exit 1 during startup.
- migrate: exited 0.
- s3-init: PASS: private S3 bucket ready; exited 0.
- broker (rabbitmq:4.1.2-alpine): exited 1.
error: RABBITMQ_DEFAULT_PASS_FILE is set but deprecated
error: deprecated environment variables detected
Please use a configuration file instead
- API, worker, outbox and load_balancer remained Created, not running.
- Public smoke and failure experiments cannot run until broker starts.
- Volumes were preserved. PostgreSQL, S3 and reconcile were left running.
Follow-up after RabbitMQ startup fix, 2026-10-26:
- Removed deprecated RABBITMQ_DEFAULT_PASS_FILE from Compose.
- Read password from Docker secret in infra/rabbitmq-secret-entrypoint.sh;
export inside container and exec stock entrypoint with rabbitmq-server.
- docker compose up -d: exit 0.
- docker compose ps -a: broker, api-a, api-b, worker, load_balancer,
postgres and s3 healthy; outbox/reconcile running; migrate/s3-init exited 0.
Actual check output (exit 0):
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
.venv/bin/python tests/smoke.py --base-url "http://localhost:8080"
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
.venv/bin/python student-tests/attachments.py (exit 0):
PASS: PNG/JPEG originals, metadata, attachment-only messages and ACL
PASS: filename, MIME, malformed image, byte/pixel and chunked limits
PASS: attachment scope, duplicates and idempotency normalization
PASS: inclusive 10 MiB and 40 million pixel boundaries
.venv/bin/python student-tests/pipeline_critical.py (exit 0):
Ran 8 tests in 0.012s
OK
.venv/bin/python student-tests/remaining_regressions.py (exit 0):
Ran 7 tests in 0.576s
OK
Mock benchmark output is excluded: it is not real load evidence.
Failure/restart experiments and real load profiles remain unverified.
Stack left running; no volumes deleted.
Follow-up verification, 2026-10-26/27:
- Real fault suite: evidence/pipeline-integration.json.
- Real SQL, Linux, ACL and cleanup locking checks: evidence/pipeline-invariants.json.
- Public persistence and both API failovers with before/after container states:
evidence/resilience.json. Initial isolated run passed; overlapping exploratory
restart/failover attempts are not counted as successful evidence.
- S3 permissions: PASS: API identity cannot create buckets; maintenance identity has separate admin access.
- Idempotency: PASS: concurrent idempotency through load balancer.
- After Docker was stopped, 10 queued jobs had published outbox records but
RabbitMQ reported 0 ready and 0 unacknowledged messages. Original disappearance
cause is not established. Added 60s unclaimed-job publication watchdog.
- Fixed redelivery bypassing retry delay / expired lease attempt accounting.
- Current-worktree secret scan: 107 tracked/nonignored files, 9 local single-line
secret values >=12 bytes and private-key/GitHub/AWS patterns; no findings.
This complements the earlier history scan; neither is a universal guarantee.
- Test cleanup deleted four explicitly selected orphan objects from its own
crashed attempt. Active result objects and all volumes were preserved.
Final real load series, 2026-10-27:
- Six runs: workers/prefetch 1/1, 2/2, 4/4; PNG 512 and 2400 square.
- Each run: 160 uploads, client concurrency 16, MAX_PENDING_JOBS=32.
- Total 960 requests = 220 accepted (all ready) + 740 expected HTTP 429.
- Each run: failed=0, timed_out=0, metric_errors=[], drained=true,
recovery_upload_ready=true. Observed pending never exceeded 32.
- Source records: real-c*-p*-s*.json; table/formulas/limitations in REPORT.md.
- Earlier small runs were exploratory and replaced by this comparable series.
- Job schema: 425 real outbox payloads validated; persisted redelivery is no-op.
Detailed result: job-contract.json.
- Offline check, full OpenAPI validation, 8 + 7 local regressions passed again
after the final PostgreSQL watchdog change. Mock throughput is not evidence.
- Final public persistence: PASS, actual service StartedAt values changed.
- Final public failovers: PASS for both API replicas. First recovery times:
2.436s (113 successful writes, 1 failed attempt) and
4.675s (95 successful writes, 2 failed attempts).
- Final public smoke after those failures: PASS.
Final confirmation on the watchdog build, 2026-10-27:
- All seven pipeline integration stages passed again; pipeline-integration.json
contains the final run, not the earlier exploratory attempts.
- Attachments, S3 permissions, concurrent idempotency and public smoke passed again.
- Worker metrics: pending=0, concurrency=2, prefetch=2.
- Working RabbitMQ queue: messages_ready=0, messages_unacknowledged=0.
- DLQ contains 3 deliberately malformed test messages (not pending image work).
- broker, worker, both APIs, PostgreSQL, S3 and LB healthy; outbox/reconcile running;
migrate and s3-init exited 0. Normal configuration restored; volumes preserved.
- Final working-tree secret scan: 108 files, 9 local values plus key patterns,
no findings. git diff --check passed; README/contracts/public tests unchanged.
+170
View File
@@ -0,0 +1,170 @@
{
"recorded_at_utc": "2026-10-27T09:21:55.484450+00:00",
"base_commit": "a1bb6f8bded13c0fae2a525dcdbda8d6a890b971",
"branch": "solution/BVT2301-Kozyrev",
"note": "Results apply to this working tree, not only the base commit. Per-profile load settings are recorded in real-c*-p*-s*.json.",
"host": "macOS-26.1-arm64-arm-64bit-Mach-O",
"docker": {
"server": "29.8.0",
"cpus": 10,
"memory_bytes": 10416644096
},
"compose_version": "5.5.1",
"sources_sha256": {
"Dockerfile": "efede941e2ccf21cd1e70ebbf8af7647209bd030b2962f9446bee497a2ed6a8c",
"Makefile": "46681d5c9aa3b09be285ce5b6db39bb9e3c4348e3918505f916b865b8831a681",
"compose.yaml": "5e1a5813ee0f663334214e243593edee3528e4d49cbe1c89fbb26a3a5ed50d89",
"infra/README.md": "0e804fa51debba4c38d3cc84abf4704897665e0335b272060363f03aadd6354f",
"infra/filer.toml": "ae3c01bf7708f5d4a319fdb454f753be0f137fe7c31269f1c413cbccc860f5c7",
"infra/haproxy.cfg": "23c9b869170633e3c6a8c41bbd3f1102bc97bf213e0d7cfed9d461af91216fd3",
"infra/rabbitmq-secret-entrypoint.sh": "94ab6376d9fa6e08452172f69cbf467735f6edd781e07d368041769e76b3ac19",
"migrations/001_initial.sql": "062e58f5535d1ab6cd89d2347479a2a6b08a09e04665f7428ce41f89b39a19d1",
"migrations/002_history_cache_version.sql": "826c8243bc148caaa7339070826a7c2928073315a40dba7fa5a3d7421d980a4d",
"migrations/003_idempotency.sql": "d650ea7c1379928a013e035977a77026d2b8b09ad5b2ea97eecb545e7450353a",
"migrations/004_attachments.sql": "d760453ba130c94c403f5b04222649fc131ab4d091edd0267ede901fdf82a79e",
"migrations/005_async_attachments.sql": "77d0e180bc5661a1824224bd24152992b55e3ec19afa8fcbde66e7ff49216f59",
"migrations/006_level4_reliability.sql": "de6a2c3ce574abda4ddea1835c30c2845dead50f1c33f705a3b82f381bc6d1fe",
"migrations/007_job_measurements.sql": "d520a39c5a98ed471faef8371da9521bab249a53e190a7a6719788da1242029d",
"pyproject.toml": "056adefdef2f9a924bbf8e05b680a0e2dac553a097b2f351d2daecfa0a168ed2",
"scripts/audit.py": "5c695c70058b24e975ceca310b2bdc879858081e5ce82b444ea9eab6b9c0d2ed",
"scripts/check_contract.py": "7c4402c2a6ab80d3b4676e1866d6ecc87b6daea14c080bcb9be9a7e8b959d671",
"scripts/init-secrets.py": "f83905a882c82a48e5f0c04fc83f839c43d0c1bc1f7b3cd74aa70e8562bce2af",
"scripts/record-environment.py": "3a97282e349f99e8245f757599ed45e72c240a9445b577a22fdf13a4d941010e",
"scripts/restart.example.sh": "0328246ba75defbced992104e986fde973f63e3830d83251eced5953263e944b",
"scripts/restart.sh": "2424309b58bf9670c0c39d52c0b02d0bbc5b3454b774106ee69ef323705e5170",
"scripts/run-track1-profiles.py": "7d59285bac1ce4db391eafaf47fd7d8e8904e4792ac6580fa48347ebcc7b0deb",
"scripts/stop-one.example.sh": "1bcf34394520b89d95b7605ec56675be799eea920e83cfbba306d5dc0a6d9811",
"scripts/stop-one.sh": "c69fdb1891e0c49f41d3892f2d108ecd38b2f59d505c8fe991023bb5c9b08a5e",
"scripts/track1.py": "c5edbd3c6aa68e3a9b638dab2572239806b8d4605b5feebaab6e05cd8ccb9fc7",
"scripts/validate_openapi.py": "4e981acbfc10dac58817bf922d5896e996798551fedc1b2385130e1cddb13d54",
"scripts/verify-persistence.py": "6c366bf4d85802bcffe65ae3d45d00736b184033313dabb60b80e1270d8874f1",
"scripts/verify-resilience.py": "13d9d056638fcfed6616ac159a5d149cfdd26f6090c51fabbb3ab0cde9ac8199",
"src/__init__.py": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b",
"src/attachments.py": "43421b711a5be717c49522688c2fc5035f5ddb7898d02006e51791e66861b26b",
"src/bootstrap_s3.py": "2c43f5540e63f004a88e08961a72293546fbc5210f46bc719b90b9f5c0f3f9bd",
"src/broker.py": "551fa504d9bfdf3871b1a1cada8210ad73bd75fef5c5a1737c958ec2d53a3587",
"src/config.py": "db51a87564d3e84feddc9e824e37088a0a164af38361e2d131db34de6ec66542",
"src/cursor.py": "a9192f2445042b8d4ddac57031718ef558990a52eb2922827074479b7f686775",
"src/errors.py": "07f8860b45cadd242d0d9f268c4b806e35353f33b11bbde0ab3d50acda86a80a",
"src/main.py": "6980cdbb09c3b356ff870ee7fc972d85e835c58228d3c0ea27de8a668dc41ece",
"src/migrate.py": "1d164c8921df2b5369e30b1f8936c2b71858c5279070f0fd593f62f66e1f0b7d",
"src/models.py": "924ace12fb9bcdd222ff58ea4d40cd57ba40290c8fbdb335c267ec35f3bad930",
"src/outbox.py": "3fbe66c516e16efa00982f6cd4c4c46fbe04d7f5f98f48d76cece3ae1911d9ad",
"src/pipeline_metrics.py": "61df2e1f5d802ac21d03a3a8e0a653a25b84d0cabfdcccd0aab6327bbb0da27d",
"src/reconcile.py": "e36163601f3acead6d698fbad747044b7026b1af07cdea5223486bf5e1b43d53",
"src/render.py": "a2eb4001d934b09f39cc555cf56c06159dd6b40a59bc6a8c3ba64ae2612dabe5",
"src/replay.py": "5490e6fd42052a6a0f1449bef3ddd4ffbe3f847141743e6b43e28c858d510dc1",
"src/routes.py": "d629efcdea1c0d2b2202a57ea6a1804164fb8cc220de3b32850c30bdf97bbf11",
"src/storage/__init__.py": "05ef66318c4c436eaafc493072640817219ab37bce464a265a2306233389064a",
"src/storage/postgres.py": "07de530b2287cbfb358fc677f71dbdd9b15387f7312a3d40df095cc853fe5ad4",
"src/storage/s3.py": "b9b36ab1e86d084b58bffc2f55b16d260d234b2beeb35f8461e9f05222d4b843",
"src/worker.py": "e72ac3629f7f2976571a9958fcb0590289d388c0b031c9529f342857731e3303",
"student-tests/attachment_resilience.py": "8a4ad367263a5d5a597fcd4a2a657c80946d19a3bbedeebdfffbf75f45531e5d",
"student-tests/attachments.py": "f80ef87aba3d409b5689e1597e40f15428d8e65211529cef2dbc4b853682e995",
"student-tests/idempotency_concurrency.py": "db5d139009e4660ac1801af45d10e24665aa81cba737731e527c0f5b4152231e",
"student-tests/job_contract.py": "4b65bae8500c2f6b40ce5faf5435e0dfbb98c71c7c17dd6789c505d923d30273",
"student-tests/pipeline_critical.py": "49a6ee8f64bd75c9890e4a9b7767595ddaa38af3a4abfc07131855ea7a1308f5",
"student-tests/pipeline_integration.py": "12dec32832afb4f7392188f6e265c0d51c0f0dc8b4adb221b9a979e6e6f07550",
"student-tests/pipeline_invariants.py": "49b846db34327fcbcabf4dc2f0a81359a0072a263ece262a435e28e4aca868af",
"student-tests/readiness_failover.py": "0ef8355d85be66597d7d44eb7308dcb58c6c9a174d18f360b2d6d22fdcfbed14",
"student-tests/readiness_unavailable.py": "46e3f680a3ff9cb79e95568004d97f1752dbdcd88fd4b5f160a9cc38af65a237",
"student-tests/reconcile.py": "9c82be28eb5a41b38c9ddd63dbf65d3edc238ca09ffa4612fc4b679d64487173",
"student-tests/reconcile_audit.py": "1bcca4da1030901e45c1369672c8363f9a5b08513c0270dc8a6f73b1f0b74221",
"student-tests/reconcile_benchmark.py": "9ae60097cb70e63baf5653559e727e02da246827a256e02580f03b5d47e1ca15",
"student-tests/remaining_regressions.py": "a5e61fd4a2c6a92d52e1b0d051b3931f699d8b0b2d73d2ce5c2553e313efe3e6",
"student-tests/review_regressions.py": "de58f63b2c794c2775247ddd3fccc523870ccbe673ffa404fdd566274d1d41de",
"student-tests/s3_permissions.py": "8c42c8ef3f7abb73bfdaa9d395874ae44041501f540213a1276c5a8bbe5e9c80",
"student-tests/session_expiry.py": "ba8ead4356e4d12c4047ac2b5704d3d3342f71c37b3c13f65a0a9d7c37186ad6",
"student-tests/upload_memory.py": "ed6c013b9e29a826191e1ca904e0546449f0e6ed9ecddbf5aa256d0768f64604",
"uv.lock": "908af5e1ce932a1fe9ccd60401c28957d001e846d8d9b524f2e688534373c9de"
},
"services": {
"postgres": {
"image": "postgres:17.6-alpine",
"image_id": "sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94",
"state": "running",
"health": "healthy",
"memory_limit_bytes": 536870912,
"nano_cpus_limit": 750000000,
"volumes": [
"mtusi2026lab5_postgres_data"
]
},
"s3": {
"image": "chrislusf/seaweedfs:4.17@sha256:186de7ef977a20343ee9a5544073f081976a29e2d29ecf8379891e7bf177fbe9",
"image_id": "sha256:186de7ef977a20343ee9a5544073f081976a29e2d29ecf8379891e7bf177fbe9",
"state": "running",
"health": "healthy",
"memory_limit_bytes": 536870912,
"nano_cpus_limit": 1000000000,
"volumes": [
"mtusi2026lab5_s3_data"
]
},
"broker": {
"image": "rabbitmq:4.1.2-alpine",
"image_id": "sha256:8f1a4555a52cb5bbd91fcacfed98f230a1762ef7a08cc05d7f711b8a31fb5ca5",
"state": "running",
"health": "healthy",
"memory_limit_bytes": 268435456,
"nano_cpus_limit": 500000000,
"volumes": [
"mtusi2026lab5_rabbitmq_data"
]
},
"worker": {
"image": "mtusi2026lab5-worker",
"image_id": "sha256:869ddc8aed23c7d0d6d387c7f2e88bdfdb3bbfc70d8dd2c2571508051da43132",
"state": "running",
"health": "healthy",
"memory_limit_bytes": 4294967296,
"nano_cpus_limit": 2000000000,
"volumes": []
},
"outbox": {
"image": "mtusi2026lab5-outbox",
"image_id": "sha256:6f97c6b53c9616356ea32cc60c27da36c5e6049e34ffdcce4e3a98d6ab255fb2",
"state": "running",
"health": null,
"memory_limit_bytes": 0,
"nano_cpus_limit": 0,
"volumes": []
},
"reconcile": {
"image": "mtusi2026lab5-reconcile",
"image_id": "sha256:b03833302fe18069ab432b09cf75a79ec80ee11d5640f2e441f308bcfcde9453",
"state": "running",
"health": null,
"memory_limit_bytes": 134217728,
"nano_cpus_limit": 250000000,
"volumes": []
},
"api-a": {
"image": "mtusi2026lab5-api-a",
"image_id": "sha256:dbe50ae4bd1c27d0c3861f3ecbeedc0c73101e7ac14ed0393cccf4114046f042",
"state": "running",
"health": "healthy",
"memory_limit_bytes": 536870912,
"nano_cpus_limit": 500000000,
"volumes": []
},
"api-b": {
"image": "mtusi2026lab5-api-b",
"image_id": "sha256:f0ce767b22b37349e57232dbb5fc6b17a0b16c75b60a39088eae16549800b1c7",
"state": "running",
"health": "healthy",
"memory_limit_bytes": 536870912,
"nano_cpus_limit": 500000000,
"volumes": []
},
"load_balancer": {
"image": "haproxy:3.0.11-alpine",
"image_id": "sha256:e49b7beb96f4dba79f9a671515b469a6e516a2b88ff0681a820b184bba1effbd",
"state": "running",
"health": "healthy",
"memory_limit_bytes": 134217728,
"nano_cpus_limit": 250000000,
"volumes": []
}
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"status": "PASS",
"validated_outbox_payloads": 425,
"extra_payload_fields": false,
"persisted_redelivery_noop": true
}
+38
View File
@@ -0,0 +1,38 @@
[
{
"test": "stopped worker, queued message, broker/API restart, ready",
"status": "PASS",
"attachment_id": "ec83e811-1507-40a3-9cec-d79d501e6a4f"
},
{
"test": "duplicate delivery and replay of ready are no-ops",
"status": "PASS",
"object_count": 4
},
{
"test": "crash after COMMIT before publish recovered from existing outbox",
"status": "PASS",
"attachment_id": "357956fa-c571-45fa-a0d9-18ce24f382eb"
},
{
"test": "worker crash after S3 before commit/ack, lease recovery",
"status": "PASS",
"attempt": 2,
"objects_before_cleanup": 8
},
{
"test": "targeted orphan cleanup preserves committed attempt",
"status": "PASS",
"deleted": 4
},
{
"test": "bounded transient retry, failed registry and explicit replay",
"status": "PASS",
"attempts_before_replay": 2
},
{
"test": "Linux renderer memory limit",
"status": "PASS",
"returncode": 21
}
]
+11
View File
@@ -0,0 +1,11 @@
[
"actual thumbnail/crop/WebP formats, dimensions and removed EXIF",
"anonymous S3 403 on existing object; variant ACL 404",
{
"maintenance_wait_seconds": 1.0019877920000226
},
"real SQL: queued watchdog republishes without attempt increment/flood; duplicate respects backoff; expired lease counted; stale completion/retry fenced",
"permanent invalid_image reaches failed on attempt 1",
"malformed broker message delivered to DLQ",
"Linux render subprocess killed/reaped on deadline"
]
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+359
View File
@@ -0,0 +1,359 @@
[
{
"mode": "persistence",
"returncode": 0,
"output": "Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.\nPASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.\n",
"before": {
"api-a": {
"id": "c3f5c47431e1",
"started_at": "2026-10-27T09:15:45.83814246Z",
"status": "running"
},
"api-b": {
"id": "378998cb6e67",
"started_at": "2026-10-27T09:15:45.995940169Z",
"status": "running"
},
"broker": {
"id": "15b4f76f796e",
"started_at": "2026-10-27T09:06:18.060378836Z",
"status": "running"
},
"load_balancer": {
"id": "75a26443cd80",
"started_at": "2026-10-27T09:06:40.813835416Z",
"status": "running"
},
"migrate": {
"id": "4752a39b2c74",
"started_at": "2026-10-27T09:10:25.395828423Z",
"status": "exited"
},
"outbox": {
"id": "9b88bcba1d4a",
"started_at": "2026-10-27T09:10:07.674024346Z",
"status": "running"
},
"postgres": {
"id": "e40600648a2a",
"started_at": "2026-10-27T09:06:17.86004142Z",
"status": "running"
},
"reconcile": {
"id": "e97099d7b46b",
"started_at": "2026-10-27T09:10:07.611048596Z",
"status": "running"
},
"s3": {
"id": "d9ccfafd22ca",
"started_at": "2026-10-27T09:06:17.939983378Z",
"status": "running"
},
"s3-init": {
"id": "3e40ef3cf827",
"started_at": "2026-10-27T09:10:25.451664548Z",
"status": "exited"
},
"worker": {
"id": "fc199d14fc86",
"started_at": "2026-10-27T09:15:45.913794835Z",
"status": "running"
}
},
"after": {
"api-a": {
"id": "c3f5c47431e1",
"started_at": "2026-10-27T09:16:27.015462382Z",
"status": "running"
},
"api-b": {
"id": "378998cb6e67",
"started_at": "2026-10-27T09:16:26.933943216Z",
"status": "running"
},
"broker": {
"id": "15b4f76f796e",
"started_at": "2026-10-27T09:16:07.882420138Z",
"status": "running"
},
"load_balancer": {
"id": "75a26443cd80",
"started_at": "2026-10-27T09:16:26.847483466Z",
"status": "running"
},
"migrate": {
"id": "4752a39b2c74",
"started_at": "2026-10-27T09:16:57.480130299Z",
"status": "exited"
},
"outbox": {
"id": "9b88bcba1d4a",
"started_at": "2026-10-27T09:16:29.790017884Z",
"status": "running"
},
"postgres": {
"id": "e40600648a2a",
"started_at": "2026-10-27T09:16:06.788383595Z",
"status": "running"
},
"reconcile": {
"id": "e97099d7b46b",
"started_at": "2026-10-27T09:16:29.811798967Z",
"status": "running"
},
"s3": {
"id": "d9ccfafd22ca",
"started_at": "2026-10-27T09:16:09.773875388Z",
"status": "running"
},
"s3-init": {
"id": "3e40ef3cf827",
"started_at": "2026-10-27T09:16:57.533971841Z",
"status": "exited"
},
"worker": {
"id": "fc199d14fc86",
"started_at": "2026-10-27T09:16:56.780625216Z",
"status": "running"
}
}
},
{
"mode": "failover",
"returncode": 0,
"output": "Executing explicit failover hook; hook output suppressed to avoid leaking secrets.\n{\"observed_instances_before\": 2, \"successful_writes\": 113, \"failed_attempts\": 1, \"first_recovery_seconds\": 2.436}\nPASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.\n",
"before": {
"api-a": {
"id": "c3f5c47431e1",
"started_at": "2026-10-27T09:16:27.015462382Z",
"status": "running"
},
"api-b": {
"id": "378998cb6e67",
"started_at": "2026-10-27T09:16:26.933943216Z",
"status": "running"
},
"broker": {
"id": "15b4f76f796e",
"started_at": "2026-10-27T09:16:07.882420138Z",
"status": "running"
},
"load_balancer": {
"id": "75a26443cd80",
"started_at": "2026-10-27T09:16:26.847483466Z",
"status": "running"
},
"migrate": {
"id": "4752a39b2c74",
"started_at": "2026-10-27T09:16:57.480130299Z",
"status": "exited"
},
"outbox": {
"id": "9b88bcba1d4a",
"started_at": "2026-10-27T09:16:29.790017884Z",
"status": "running"
},
"postgres": {
"id": "e40600648a2a",
"started_at": "2026-10-27T09:16:06.788383595Z",
"status": "running"
},
"reconcile": {
"id": "e97099d7b46b",
"started_at": "2026-10-27T09:16:29.811798967Z",
"status": "running"
},
"s3": {
"id": "d9ccfafd22ca",
"started_at": "2026-10-27T09:16:09.773875388Z",
"status": "running"
},
"s3-init": {
"id": "3e40ef3cf827",
"started_at": "2026-10-27T09:16:57.533971841Z",
"status": "exited"
},
"worker": {
"id": "fc199d14fc86",
"started_at": "2026-10-27T09:16:56.780625216Z",
"status": "running"
}
},
"after": {
"api-a": {
"id": "c3f5c47431e1",
"started_at": "2026-10-27T09:16:27.015462382Z",
"status": "exited"
},
"api-b": {
"id": "378998cb6e67",
"started_at": "2026-10-27T09:16:26.933943216Z",
"status": "running"
},
"broker": {
"id": "15b4f76f796e",
"started_at": "2026-10-27T09:16:07.882420138Z",
"status": "running"
},
"load_balancer": {
"id": "75a26443cd80",
"started_at": "2026-10-27T09:16:26.847483466Z",
"status": "running"
},
"migrate": {
"id": "4752a39b2c74",
"started_at": "2026-10-27T09:16:57.480130299Z",
"status": "exited"
},
"outbox": {
"id": "9b88bcba1d4a",
"started_at": "2026-10-27T09:16:29.790017884Z",
"status": "running"
},
"postgres": {
"id": "e40600648a2a",
"started_at": "2026-10-27T09:16:06.788383595Z",
"status": "running"
},
"reconcile": {
"id": "e97099d7b46b",
"started_at": "2026-10-27T09:16:29.811798967Z",
"status": "running"
},
"s3": {
"id": "d9ccfafd22ca",
"started_at": "2026-10-27T09:16:09.773875388Z",
"status": "running"
},
"s3-init": {
"id": "3e40ef3cf827",
"started_at": "2026-10-27T09:16:57.533971841Z",
"status": "exited"
},
"worker": {
"id": "fc199d14fc86",
"started_at": "2026-10-27T09:16:56.780625216Z",
"status": "running"
}
}
},
{
"mode": "failover",
"returncode": 0,
"output": "Executing explicit failover hook; hook output suppressed to avoid leaking secrets.\n{\"observed_instances_before\": 2, \"successful_writes\": 95, \"failed_attempts\": 2, \"first_recovery_seconds\": 4.675}\nPASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.\n",
"before": {
"api-a": {
"id": "c3f5c47431e1",
"started_at": "2026-10-27T09:17:21.770393088Z",
"status": "running"
},
"api-b": {
"id": "378998cb6e67",
"started_at": "2026-10-27T09:16:26.933943216Z",
"status": "running"
},
"broker": {
"id": "15b4f76f796e",
"started_at": "2026-10-27T09:16:07.882420138Z",
"status": "running"
},
"load_balancer": {
"id": "75a26443cd80",
"started_at": "2026-10-27T09:16:26.847483466Z",
"status": "running"
},
"migrate": {
"id": "4752a39b2c74",
"started_at": "2026-10-27T09:16:57.480130299Z",
"status": "exited"
},
"outbox": {
"id": "9b88bcba1d4a",
"started_at": "2026-10-27T09:16:29.790017884Z",
"status": "running"
},
"postgres": {
"id": "e40600648a2a",
"started_at": "2026-10-27T09:16:06.788383595Z",
"status": "running"
},
"reconcile": {
"id": "e97099d7b46b",
"started_at": "2026-10-27T09:16:29.811798967Z",
"status": "running"
},
"s3": {
"id": "d9ccfafd22ca",
"started_at": "2026-10-27T09:16:09.773875388Z",
"status": "running"
},
"s3-init": {
"id": "3e40ef3cf827",
"started_at": "2026-10-27T09:16:57.533971841Z",
"status": "exited"
},
"worker": {
"id": "fc199d14fc86",
"started_at": "2026-10-27T09:16:56.780625216Z",
"status": "running"
}
},
"after": {
"api-a": {
"id": "c3f5c47431e1",
"started_at": "2026-10-27T09:17:21.770393088Z",
"status": "running"
},
"api-b": {
"id": "378998cb6e67",
"started_at": "2026-10-27T09:16:26.933943216Z",
"status": "exited"
},
"broker": {
"id": "15b4f76f796e",
"started_at": "2026-10-27T09:16:07.882420138Z",
"status": "running"
},
"load_balancer": {
"id": "75a26443cd80",
"started_at": "2026-10-27T09:16:26.847483466Z",
"status": "running"
},
"migrate": {
"id": "4752a39b2c74",
"started_at": "2026-10-27T09:16:57.480130299Z",
"status": "exited"
},
"outbox": {
"id": "9b88bcba1d4a",
"started_at": "2026-10-27T09:16:29.790017884Z",
"status": "running"
},
"postgres": {
"id": "e40600648a2a",
"started_at": "2026-10-27T09:16:06.788383595Z",
"status": "running"
},
"reconcile": {
"id": "e97099d7b46b",
"started_at": "2026-10-27T09:16:29.811798967Z",
"status": "running"
},
"s3": {
"id": "d9ccfafd22ca",
"started_at": "2026-10-27T09:16:09.773875388Z",
"status": "running"
},
"s3-init": {
"id": "3e40ef3cf827",
"started_at": "2026-10-27T09:16:57.533971841Z",
"status": "exited"
},
"worker": {
"id": "fc199d14fc86",
"started_at": "2026-10-27T09:16:56.780625216Z",
"status": "running"
}
}
}
]
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -eu
# RabbitMQ 4 no longer supports *_FILE. Keep the password in a Docker
# secret and export it only inside the running container, never in Compose.
RABBITMQ_DEFAULT_PASS="$(cat /run/secrets/rabbitmq_password)"
if [ -z "$RABBITMQ_DEFAULT_PASS" ]; then
echo "RabbitMQ password secret must not be empty" >&2
exit 1
fi
export RABBITMQ_DEFAULT_PASS
exec /usr/local/bin/docker-entrypoint.sh "$@"
+1
View File
@@ -0,0 +1 @@
ALTER TABLE attachment_jobs ADD COLUMN first_started_at timestamptz;
+2 -2
View File
@@ -22,7 +22,7 @@ report = {
'recorded_at_utc': datetime.now(timezone.utc).isoformat(),
'base_commit': command('git', 'rev-parse', 'HEAD'),
'branch': command('git', 'branch', '--show-current'),
'note': 'Results apply to this working tree, not only the base commit. Functional tests; no load benchmark.',
'note': 'Results apply to this working tree, not only the base commit. Per-profile load settings are recorded in real-c*-p*-s*.json.',
'host': platform.platform(),
'docker': json.loads(command('docker', 'info', '--format',
'{"server":"{{.ServerVersion}}","cpus":{{.NCPU}},"memory_bytes":{{.MemTotal}}}')),
@@ -30,7 +30,7 @@ report = {
'sources_sha256': {str(path.relative_to(root)): sha256(path.read_bytes()).hexdigest() for path in sorted(paths)},
'services': {},
}
for service in ('postgres', 's3', 'api-a', 'api-b', 'load_balancer'):
for service in ('postgres', 's3', 'broker', 'worker', 'outbox', 'reconcile', 'api-a', 'api-b', 'load_balancer'):
container = command('docker', 'compose', 'ps', '-q', service)
info = json.loads(command('docker', 'inspect', container))[0]
report['services'][service] = {
+2 -2
View File
@@ -6,5 +6,5 @@ cd "$(dirname "$0")/.."
docker compose restart postgres s3 broker
docker compose up -d --wait postgres s3 broker
docker compose run --rm --no-deps s3-init
docker compose restart worker api-a api-b load_balancer
docker compose up -d --wait worker api-a api-b load_balancer
docker compose restart worker outbox reconcile api-a api-b load_balancer
docker compose up -d --wait worker outbox reconcile api-a api-b load_balancer
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""Run real, sequential Docker profiles; restore normal settings on exit."""
import os
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
def main():
try:
for workers in (1, 2, 4):
env = dict(os.environ, WORKER_CONCURRENCY=str(workers),
WORKER_PREFETCH=str(workers), MAX_PENDING_JOBS='32')
subprocess.run(['docker', 'compose', 'up', '-d', '--no-deps', '--wait',
'worker', 'api-a', 'api-b'], cwd=ROOT, env=env, check=True)
for size in (512, 2400):
subprocess.run([sys.executable, 'scripts/track1.py',
'--run-name', f'real-c{workers}-p{workers}-s{size}',
'--workers', str(workers), '--prefetch', str(workers),
'--max-pending', '32', '--images', '160',
'--concurrency', '16', '--size', str(size),
'--require-backpressure'], cwd=ROOT, check=True)
finally:
subprocess.run(['docker', 'compose', 'up', '-d', '--no-deps', '--wait',
'worker', 'api-a', 'api-b'], cwd=ROOT, check=True)
if __name__ == '__main__':
main()
+175 -101
View File
@@ -1,13 +1,5 @@
#!/usr/bin/env python3
"""Repeatable level-5 queue-overload experiment.
Run a Compose profile first, for example:
WORKER_CONCURRENCY=2 MAX_PENDING_JOBS=20 docker compose up -d --build
.venv/bin/python scripts/track1.py --run-name c2-p2 --workers 2 --prefetch 2 --images 40 --size 1600
The script records client-observed acceptance/ready latency, RabbitMQ queue depth
and Docker RSS samples. It does not print credentials or session tokens.
"""
"""Closed-loop upload burst with concurrent readiness observations and drain proof."""
from concurrent.futures import ThreadPoolExecutor, as_completed
from io import BytesIO
import json
@@ -17,11 +9,10 @@ import subprocess
import sys
import threading
import time
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, arguments, check, run # noqa: E402
from client import Client, Failure, arguments, check, run
def percentile(values, point):
@@ -29,114 +20,197 @@ def percentile(values, point):
return round(values[max(0, math.ceil(len(values) * point) - 1)] * 1000, 3) if values else None
def docker_text(*args):
def command_json(*args):
result = subprocess.run(args, cwd=ROOT, text=True, capture_output=True, timeout=20)
if result.returncode:
raise Failure("metrics command failed: " + args[0])
try:
return subprocess.run(args, cwd=ROOT, text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
timeout=10, check=True).stdout.strip()
except (OSError, subprocess.SubprocessError):
return None
return json.loads(result.stdout)
except ValueError:
raise Failure("metrics command returned invalid JSON") from None
def metrics(chat_id):
return command_json("docker", "compose", "exec", "-T", "worker",
"/app/.venv/bin/python", "-m", "src.pipeline_metrics", chat_id)
def broker_depth():
text = docker_text("docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "list_queues", "name", "messages_ready", "messages_unacknowledged", "--formatter", "json")
if not text:
return None
try:
rows = json.loads(text)
return next((row for row in rows if row["name"] == "attachment.process.v1"), None)
except (ValueError, KeyError, TypeError):
return None
rows = command_json("docker", "compose", "exec", "-T", "broker",
"rabbitmqctl", "list_queues", "name", "messages_ready",
"messages_unacknowledged", "--formatter", "json")
return next(row for row in rows if row["name"] == "attachment.process.v1")
def worker_rss():
container = docker_text("docker", "compose", "ps", "-q", "worker")
if not container:
return None
text = docker_text("docker", "stats", "--no-stream", "--format", "{{json .}}", container)
if not text:
return None
try:
return json.loads(text).get("MemUsage")
except ValueError:
return None
def container_info(service):
result = subprocess.run(['docker', 'compose', 'ps', '-q', service], cwd=ROOT,
capture_output=True, text=True, timeout=10, check=True)
ids = result.stdout.split()
check(len(ids) == 1, 'expected exactly one container: ' + service)
return command_json('docker', 'inspect', ids[0])[0]
def main():
def configure(parser):
parser.add_argument("--run-name", required=True)
parser.add_argument("--workers", type=int, required=True, help="documented WORKER_CONCURRENCY setting")
parser.add_argument("--prefetch", type=int, required=True, help="documented RabbitMQ prefetch setting")
parser.add_argument("--max-pending", type=int, required=True, help="documented MAX_PENDING_JOBS setting")
parser.add_argument("--images", type=int, default=40)
parser.add_argument("--concurrency", type=int, default=4)
parser.add_argument("--size", type=int, default=1600, help="square synthetic PNG dimensions")
parser.add_argument("--max-ready-seconds", type=float, default=120)
parser.add_argument("--output", default=None)
args = arguments("Lab 5 track 1 image-pipeline experiment", configure)
check(1 <= args.workers <= 64 and 1 <= args.prefetch <= 1024 and 1 <= args.max_pending <= 100000, "invalid worker/prefetch/max-pending")
check(1 <= args.images <= 1000 and 1 <= args.concurrency <= 128 and 1 <= args.size <= 6000, "invalid workload")
def configure(p):
p.add_argument("--run-name", required=True)
p.add_argument("--workers", type=int, required=True)
p.add_argument("--prefetch", type=int, required=True)
p.add_argument("--max-pending", type=int, required=True)
p.add_argument("--images", type=int, default=40)
p.add_argument("--concurrency", type=int, default=8)
p.add_argument("--size", type=int, default=1600)
p.add_argument("--max-ready-seconds", type=float, default=180)
p.add_argument("--require-backpressure", action="store_true")
p.add_argument("--output")
args = arguments(__doc__, configure)
check(1 <= args.images <= 1000 and 1 <= args.concurrency <= 128, "invalid workload")
check(1 <= args.size <= 6000 and 0 < args.max_ready_seconds <= 3600, "invalid size/deadline")
check(args.workers > 0 and args.prefetch > 0 and args.max_pending > 0, "invalid profile")
from PIL import Image
image = Image.new("RGB", (args.size, args.size), "#427aa1")
raw = BytesIO(); image.save(raw, "PNG", optimize=True); data = raw.getvalue()
# Reproducible, nonuniform synthetic image; no real personal data.
row = bytes(v for x in range(args.size) for v in ((x * 13) % 256, (x * 37) % 256, (x * 71) % 256))
image = Image.frombytes("RGB", (args.size, args.size), row * args.size)
stream = BytesIO()
image.save(stream, "PNG")
data = stream.getvalue()
client = Client(args.base_url, args.ca_file, timeout=30)
alice, bob, _eve, chat = client.bootstrap()
alice, bob, _, chat = client.bootstrap()
baseline = metrics(chat["id"])
check(baseline["concurrency"] == args.workers and baseline["prefetch"] == args.prefetch,
"worker settings do not match requested profile")
check(baseline["pending"] == 0, "use an idle isolated stack")
for service in ("api-a", "api-b"):
env = dict(item.split('=', 1) for item in container_info(service)['Config']['Env'])
check(int(env['MAX_PENDING_JOBS']) == args.max_pending,
'running API MAX_PENDING_JOBS does not match profile')
resources = container_info('worker')['HostConfig']
path = "/api/v1/chats/" + chat["id"] + "/attachments?filename=track1.png"
barrier = threading.Barrier(args.concurrency)
queue_samples, rss_samples = [], []
stop_sampling = threading.Event()
def sampler():
while not stop_sampling.wait(1):
queue_samples.append({"seconds": round(time.monotonic() - started, 3), "queue": broker_depth()})
rss_samples.append({"seconds": round(time.monotonic() - started, 3), "rss": worker_rss()})
pending, records, samples, errors = {}, [], [], []
lock, finished = threading.Lock(), threading.Event()
started = time.monotonic()
def observe():
local = Client(args.base_url, args.ca_file, timeout=5)
while not finished.wait(.1):
with lock:
batch = list(pending.items())
for key, record in batch:
if finished.is_set():
break
try:
att = local.call("GET", "/api/v1/attachments/" + key, actor=bob, schema="Attachment")["json"]
if att["status"] in ("ready", "failed"):
with lock:
record["terminal"] = att["status"]
record["terminal_at"] = time.monotonic()
pending.pop(key, None)
except Failure:
continue
def sample():
while not finished.is_set():
try:
sample = metrics(chat["id"])
sample["queue"] = broker_depth()
sample["seconds"] = time.monotonic() - started
with lock:
samples.append(sample)
except (Failure, OSError, subprocess.TimeoutExpired) as exc:
with lock:
errors.append(type(exc).__name__)
if finished.wait(1):
break
observer = threading.Thread(target=observe, daemon=True)
sampler = threading.Thread(target=sample, daemon=True)
observer.start()
sampler.start()
def upload(index):
local = Client(args.base_url, args.ca_file, timeout=30)
barrier.wait()
started_at = time.monotonic()
before = time.monotonic()
try:
response = local.call("POST", path + "-" + str(index), 202, actor=alice, raw=data,
response = local.call("POST", path, (202, 429), actor=alice, raw=data,
headers={"Content-Type": "image/png"}, schema="Attachment")
return {"accepted": True, "id": response["json"]["id"], "accepted_seconds": time.monotonic() - started_at}
except Failure as error:
return {"accepted": False, "error": str(error), "accepted_seconds": time.monotonic() - started_at}
started = time.monotonic()
thread = threading.Thread(target=sampler, daemon=True); thread.start()
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
results = list(pool.map(upload, range(args.images)))
accepted = [item for item in results if item["accepted"]]
ready_latencies, failed_ready = [], 0
deadline = time.monotonic() + args.max_ready_seconds
pending = {item["id"]: started + item["accepted_seconds"] for item in accepted}
while pending and time.monotonic() < deadline:
for attachment_id, accepted_at in list(pending.items()):
try:
metadata = client.call("GET", "/api/v1/attachments/" + attachment_id, actor=bob, schema="Attachment")["json"]
except Failure:
continue
if metadata["status"] == "ready":
ready_latencies.append(time.monotonic() - accepted_at)
del pending[attachment_id]
elif metadata["status"] == "failed":
failed_ready += 1; del pending[attachment_id]
time.sleep(.2)
stop_sampling.set(); thread.join(timeout=2)
elapsed = time.monotonic() - started
received = time.monotonic()
record = {"index": index, "status": response["status"], "upload_seconds": received - before}
if response["status"] == 202:
record.update(id=response["json"]["id"], accepted_at=received)
with lock:
records.append(record)
if response["status"] == 202:
pending[record["id"]] = record
except Failure:
with lock:
records.append({"index": index, "status": "transport_or_http_error"})
try:
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
list(pool.map(upload, range(args.images)))
upload_finished = time.monotonic()
deadline = upload_finished + args.max_ready_seconds
while time.monotonic() < deadline:
with lock:
empty = not pending
if empty:
break
time.sleep(.1)
finally:
measured_end = time.monotonic()
finished.set()
observer.join(timeout=10)
sampler.join(timeout=45)
elapsed = measured_end - started
final = metrics(chat["id"])
queue = broker_depth()
for _ in range(20):
if queue["messages_ready"] == 0 and queue["messages_unacknowledged"] == 0:
break
time.sleep(.25)
queue = broker_depth()
accepted = [r for r in records if r["status"] == 202]
ready = [r for r in accepted if r.get("terminal") == "ready"]
latencies = [r["terminal_at"] - r["accepted_at"] for r in ready]
waits = [r["queue_wait_seconds"] for r in final["jobs"] if r["queue_wait_seconds"] is not None]
drained = (bool(accepted) and len(ready) == len(accepted) and final["pending"] == 0
and queue["messages_ready"] == 0 and queue["messages_unacknowledged"] == 0)
recovery = False
if drained:
try:
att, _ = client.attachment(alice, chat)
client.wait_ready(bob, att, wait_seconds=args.max_ready_seconds)
recovery = True
except Failure:
pass
rejected = sum(r["status"] == 429 for r in records)
report = {
"track": "queue-overload", "run_name": args.run_name,
"settings": {"worker_concurrency": args.workers, "prefetch": args.prefetch, "max_pending_jobs": args.max_pending},
"workload": {"images": args.images, "client_concurrency": args.concurrency, "png_dimensions": [args.size, args.size], "input_bytes": len(data)},
"results": {"elapsed_seconds": round(elapsed, 3), "accepted": len(accepted), "rejected_or_failed": args.images - len(accepted), "ready": len(ready_latencies), "failed": failed_ready, "timed_out": len(pending), "throughput_ready_per_second": round(len(ready_latencies) / elapsed, 4), "accept_latency_ms": {"p50": percentile([x["accepted_seconds"] for x in accepted], .5), "p95": percentile([x["accepted_seconds"] for x in accepted], .95)}, "time_to_ready_ms": {"p50": percentile(ready_latencies, .5), "p95": percentile(ready_latencies, .95)}},
"queue_samples": queue_samples, "worker_rss_samples": rss_samples,
"limitations": "Closed-loop client; queue/RSS samples are null when Docker CLI is unavailable. p95 covers ready tasks only.",
"run_name": args.run_name,
"settings": {"workers": baseline["concurrency"], "prefetch": baseline["prefetch"],
"max_pending": args.max_pending,
"worker_limits": {key: resources[key] for key in ('Memory', 'NanoCpus')}},
"workload": {"images": args.images, "concurrency": args.concurrency,
"size": args.size, "bytes": len(data), "type": "closed-loop burst"},
"results": {"accepted": len(accepted), "rejected_429": rejected, "ready": len(ready),
"failed": sum(r.get("terminal") == "failed" for r in accepted),
"timed_out": len(pending), "elapsed_seconds": elapsed,
"ready_per_second": len(ready) / elapsed,
"ready_latency_ms": {str(p): percentile(latencies, p) for p in (.5, .95, .99)},
"queue_wait_ms": {str(p): percentile(waits, p) for p in (.5, .95, .99)},
"max_sampled_rss_bytes": max((s["rss_bytes"] for s in samples), default=None),
"max_sampled_pending": max((s["pending"] for s in samples), default=None),
"sample_count": len(samples),
"drained": drained, "recovery_upload_ready": recovery},
"records": [{k: v for k, v in r.items() if k not in ("accepted_at", "terminal_at")} |
({"ready_seconds": r["terminal_at"] - r["accepted_at"]} if "terminal_at" in r else {})
for r in records],
"samples": samples, "metric_errors": errors,
"limitations": "Closed-loop; ready time is polling upper bound. RSS is sum of worker/container processes, shared pages may be counted twice. Sampling may miss peaks. Queue wait is first claim minus durable job creation.",
}
text = json.dumps(report, ensure_ascii=False, indent=2)
destination = Path(args.output or (ROOT / "evidence" / (args.run_name + ".json")))
destination.parent.mkdir(parents=True, exist_ok=True); destination.write_text(text + "\n", encoding="utf-8")
print(text)
check(bool(accepted), "no accepted uploads")
target = Path(args.output or ROOT / "evidence" / (args.run_name + ".json"))
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report["results"], indent=2))
check(not errors and bool(samples), "incomplete metrics; result saved but not valid evidence")
check(all(s['pending'] <= args.max_pending for s in samples), "admission limit exceeded")
check(all(r["status"] in (202, 429) for r in records), "unexpected HTTP/transport failures")
check(drained and recovery, "pipeline did not drain/recover; see saved result")
if args.require_backpressure:
check(rejected > 0, "backpressure was not observed")
if __name__ == "__main__":
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""Sequential public tests with safe container-state evidence; no credentials."""
import json
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
def states():
ids = subprocess.check_output(['docker', 'compose', 'ps', '-aq'], text=True).split()
rows = json.loads(subprocess.check_output(['docker', 'inspect', *ids], text=True))
return {r['Config']['Labels']['com.docker.compose.service']:
{'id': r['Id'][:12], 'started_at': r['State']['StartedAt'], 'status': r['State']['Status']}
for r in rows}
def main():
results, stopped = [], set()
try:
for mode in ['persistence'] + ['failover'] * 6:
before = states()
hook = 'restart' if mode == 'persistence' else 'stop-one'
result = subprocess.run([sys.executable, 'tests/resilience.py', '--mode', mode,
'--action-script', 'scripts/' + hook + '.sh'],
text=True, capture_output=True, timeout=200)
after = states()
results.append(dict(mode=mode, returncode=result.returncode,
output=result.stdout + result.stderr, before=before, after=after))
(ROOT / 'evidence/resilience.json').write_text(json.dumps(results, indent=2) + '\n')
print(result.stdout + result.stderr, flush=True)
assert result.returncode == 0, 'public resilience failed'
if mode == 'persistence':
for service in ('postgres', 's3', 'broker', 'worker', 'outbox', 'api-a', 'api-b'):
assert before[service]['started_at'] != after[service]['started_at'], service
else:
stopped.update(s for s in ('api-a', 'api-b') if after[s]['status'] == 'exited')
subprocess.run(['docker', 'compose', 'up', '-d', '--no-deps', '--wait', 'api-a', 'api-b'], check=True)
if len(stopped) == 2:
break
assert len(stopped) == 2, 'did not exercise both API replicas'
finally:
subprocess.run(['docker', 'compose', 'up', '-d', '--no-deps', '--wait', 'api-a', 'api-b'], check=True)
if __name__ == '__main__':
main()
+8 -6
View File
@@ -83,10 +83,6 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
attachment_id, job_id = uuid4(), uuid4()
key = f"staging/{attachment_id}/original"
async with store.attachment_transaction() as connection:
await s3.put(key, file, size, content_type)
# Disabled by default; models a crash after PUT, before INSERT.
if os.environ.get("UPLOAD_FAULT_AFTER_S3_PUT") == "1":
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
try:
max_pending = int(os.environ.get("MAX_PENDING_JOBS", "100"))
except ValueError as error:
@@ -94,6 +90,9 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
if max_pending < 1:
raise ApiError(503, "unavailable", "Некорректный лимит очереди")
await store.ensure_attachment_queue_capacity(connection, max_pending)
await s3.put(key, file, size, content_type)
if os.environ.get("UPLOAD_FAULT_AFTER_S3_PUT") == "1":
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
attachment = await store.create_attachment(
attachment_id, chat_id, user["id"], filename, content_type,
size, digest.hexdigest(), key, job_id, connection=connection,
@@ -130,9 +129,12 @@ async def download(attachment_id: UUID, request: Request,
if not matching:
raise ApiError(404, "not_found", "Вариант не найден")
item = matching[0]
suffix = {"thumbnail": "thumbnail.jpg", "crop": "crop.jpg", "optimized": "optimized.webp"}[variant]
object_key = await store.pool.fetchval(
'SELECT object_key FROM attachment_variants WHERE attachment_id=$1 AND pipeline_version=$2 AND name=$3',
attachment_id, attachment['pipeline_version'], variant,
)
data = await request.app.state.s3.download_key(
f"variants/{attachment_id}/{suffix}", item["size_bytes"], item["sha256"]
object_key, item["size_bytes"], item["sha256"]
)
content_type = item["content_type"]
return Response(data, media_type=content_type,
+5 -2
View File
@@ -51,7 +51,7 @@ async def publish(payload: dict) -> None:
async def publish_dlq(payload: dict) -> None:
payload = {**payload, "failure": "retry_exhausted"}
payload = {**payload, "failure": payload.get('failure', 'retry_exhausted')}
try:
await run_in_threadpool(_publish_to, DLQ, payload)
except (pika.exceptions.AMQPError, OSError, ValueError) as error:
@@ -61,9 +61,12 @@ async def publish_dlq(payload: dict) -> None:
def _publish_to(queue: str, payload: dict) -> None:
connection = _connection()
try:
connection.channel().basic_publish(
channel = connection.channel()
channel.confirm_delivery()
channel.basic_publish(
exchange="", routing_key=queue, body=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
properties=pika.BasicProperties(delivery_mode=pika.DeliveryMode.Persistent, content_type="application/json"),
mandatory=True,
)
finally:
connection.close()
+1
View File
@@ -22,6 +22,7 @@ _CONFIGURATION_KEYS = {
"MAX_UPLOAD_BYTES", "MAX_IMAGE_PIXELS",
"UPLOAD_CONCURRENCY", "UPLOAD_TIMEOUT_SECONDS", "UPLOAD_FAULT_AFTER_S3_PUT",
"WORKER_CONCURRENCY", "JOB_MAX_ATTEMPTS", "JOB_TIMEOUT_SECONDS", "STAGING_RETENTION_SECONDS",
"WORKER_PREFETCH", "MAX_PENDING_JOBS", "RENDER_MEMORY_MB",
}
+1 -1
View File
@@ -18,7 +18,7 @@ async def run() -> None:
try:
while True:
try:
await store.schedule_due_jobs()
await store.schedule_due_jobs(int(os.environ.get('JOB_MAX_ATTEMPTS', '5')))
for event in await store.due_outbox_events():
await publish(event["payload"])
await store.mark_outbox_published(event["id"])
+37
View File
@@ -0,0 +1,37 @@
"""Operator-only metrics for one synthetic chat; never exposes credentials."""
import asyncio
import json
import os
from pathlib import Path
import sys
from uuid import UUID
from .config import load_settings
from .storage.postgres import PostgresStore
async def main(chat):
store = PostgresStore(load_settings().database_url)
await store.connect()
try:
rows = await store.pool.fetch('SELECT a.id, a.status, extract(epoch from (j.first_started_at-j.created_at))::float8 AS queue_wait_seconds FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE a.chat_id=$1', chat)
jobs = [dict(row, id=str(row['id'])) for row in rows]
pending = await store.pool.fetchval("SELECT count(*) FROM attachment_jobs WHERE status IN ('queued','processing')")
finally:
await store.close()
rss = 0
for path in Path('/proc').glob('[0-9]*/status'):
try:
if int(path.parent.name) == os.getpid():
continue
for line in path.read_text().splitlines():
if line.startswith('VmRSS:'):
rss += int(line.split()[1]) * 1024
except (OSError, ValueError):
pass
print(json.dumps({'jobs': jobs, 'pending': pending, 'rss_bytes': rss,
'concurrency': int(os.environ['WORKER_CONCURRENCY']),
'prefetch': int(os.environ['WORKER_PREFETCH'])}))
if __name__ == '__main__':
asyncio.run(main(UUID(sys.argv[1])))
+20 -5
View File
@@ -9,6 +9,7 @@ import argparse
import asyncio
from datetime import datetime, timedelta, timezone
import json
import os
from time import perf_counter
from .config import load_settings
@@ -33,7 +34,11 @@ async def scan(args, db, s3) -> dict:
# Age is measured at scan start, not after a potentially slow inventory.
cutoff = datetime.now(timezone.utc) - timedelta(seconds=args.grace_seconds)
started = perf_counter()
objects, s3_pages = await s3.list_with_pages("originals/")
objects, s3_pages = {}, 0
for prefix in ('staging/', 'originals/', 'variants/'):
entries, pages = await s3.list_with_pages(prefix)
objects.update(entries)
s3_pages += pages
listed_at = perf_counter()
metadata = await db.attachment_keys()
metadata_at = perf_counter()
@@ -74,15 +79,25 @@ async def scan(args, db, s3) -> dict:
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--apply", action="store_true", help="delete only aged orphan objects")
parser.add_argument("--grace-seconds", type=int, default=3600)
parser.add_argument("--grace-seconds", type=int, default=int(os.environ.get('STAGING_RETENTION_SECONDS', '86400')))
parser.add_argument('--loop', action='store_true')
parser.add_argument("--object-key", action="append", default=[],
help="restrict apply to these exact keys; repeatable, inventory stays complete")
args = parser.parse_args()
if not 0 <= args.grace_seconds <= 7 * 24 * 3600:
parser.error("--grace-seconds must be 0..604800")
if any(not key.startswith("originals/") for key in args.object_key):
parser.error("--object-key must start with originals/")
print(json.dumps(asyncio.run(run(args)), ensure_ascii=False, sort_keys=True))
if any(not key.startswith(('originals/', 'staging/', 'variants/')) for key in args.object_key):
parser.error('unsupported object prefix')
if args.loop:
import time
while True:
try:
print(json.dumps(asyncio.run(run(args)), ensure_ascii=False, sort_keys=True))
except Exception:
print('cleanup deferred: dependency unavailable', flush=True)
time.sleep(60)
else:
print(json.dumps(asyncio.run(run(args)), ensure_ascii=False, sort_keys=True))
if __name__ == "__main__":
+27
View File
@@ -0,0 +1,27 @@
"""Isolated image renderer. Parent enforces wall time and kills this process."""
import os
import pickle
import sys
def main():
if sys.platform == 'linux':
import resource
limit = int(os.environ.get('RENDER_MEMORY_MB', '768')) * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
from .worker import variants
from PIL import UnidentifiedImageError, Image
try:
data = sys.stdin.buffer.read(10485761)
if len(data) > 10485760:
raise ValueError('bytes limit')
result = variants(data, int(os.environ.get('MAX_IMAGE_PIXELS', '40000000')))
pickle.dump(result, sys.stdout.buffer)
except MemoryError:
sys.exit(21)
except (ValueError, OSError, SyntaxError, UnidentifiedImageError, Image.DecompressionBombError):
sys.exit(20)
if __name__ == '__main__':
main()
+49 -29
View File
@@ -247,6 +247,11 @@ class PostgresStore:
)
if count != len(attachment_ids):
raise ApiError(404, "not_found", "Вложение не найдено")
failed = await connection.fetchval(
"SELECT 1 FROM attachments WHERE id=ANY($1::uuid[]) AND status='failed' LIMIT 1", attachment_ids
)
if failed:
raise ApiError(409, 'conflict', 'Вложение завершилось ошибкой')
claimed = await connection.fetchrow(
"INSERT INTO idempotency_records (user_id, method, path, idempotency_key, request_hash) "
"VALUES ($1, 'POST', $2, $3, $4) ON CONFLICT DO NOTHING RETURNING message_id",
@@ -384,28 +389,37 @@ class PostgresStore:
try:
async with self.pool.acquire() as connection, connection.transaction():
row = await connection.fetchrow(
"SELECT a.*, j.job_id, j.attempt, j.lease_until FROM attachments a JOIN attachment_jobs j ON j.attachment_id = a.id "
"SELECT a.*, j.job_id, j.attempt, j.lease_until, "
"(j.next_attempt_at <> 'infinity'::timestamptz AND j.next_attempt_at > now()) AS retry_waiting "
"FROM attachments a JOIN attachment_jobs j ON j.attachment_id = a.id "
"WHERE a.id = $1 FOR UPDATE", attachment_id
)
if row is None or row["status"] in {"ready", "failed"}:
return None
if row["status"] == "processing" and row["lease_until"] is not None and row["lease_until"] > datetime.now(timezone.utc):
# Only the dispatcher recovers an expired lease and increments
# its attempt. Redelivery must not renew it or bypass backoff.
if row is None or row["status"] != "queued" or row["retry_waiting"]:
return None
await connection.execute(
"UPDATE attachments SET status = 'processing', processing_started_at = now(), updated_at = now() WHERE id = $1",
attachment_id,
)
await connection.execute(
"UPDATE attachment_jobs SET status = 'processing', lease_until = now() + $2 * interval '1 second', updated_at = now() WHERE attachment_id = $1",
"UPDATE attachment_jobs SET status = 'processing', first_started_at=COALESCE(first_started_at, now()), lease_until = now() + $2 * interval '1 second', updated_at = now() WHERE attachment_id = $1",
attachment_id, lease_seconds,
)
return dict(row)
result = dict(row)
result['claim_time'] = await connection.fetchval('SELECT processing_started_at FROM attachments WHERE id=$1', attachment_id)
return result
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def complete_attachment_job(self, attachment_id: UUID, original_key: str, variants: list[dict]) -> None:
async def complete_attachment_job(self, attachment_id: UUID, original_key: str, variants: list[dict], claim_time) -> bool:
try:
async with self.pool.acquire() as connection, connection.transaction():
valid = await connection.fetchval(
"SELECT 1 FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE a.id=$1 AND a.status='processing' AND a.processing_started_at=$2 AND j.lease_until > now() FOR UPDATE", attachment_id, claim_time
)
if not valid:
return False
for variant in variants:
await connection.execute(
"INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256) "
@@ -418,28 +432,20 @@ class PostgresStore:
attachment_id, original_key,
)
await connection.execute("UPDATE attachment_jobs SET status = 'ready', lease_until = NULL, updated_at = now() WHERE attachment_id = $1", attachment_id)
return True
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def fail_attachment_job(self, attachment_id: UUID, code: str) -> None:
try:
await self.pool.execute(
"UPDATE attachments SET status = 'failed', error_code = $2, updated_at = now() WHERE id = $1", attachment_id, code
)
await self.pool.execute(
"UPDATE attachment_jobs SET status = 'failed', last_error = $2, updated_at = now() WHERE attachment_id = $1", attachment_id, code
)
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def retry_attachment_job(self, attachment_id: UUID, max_attempts: int, delay_seconds: float) -> bool:
async def retry_attachment_job(self, attachment_id: UUID, max_attempts: int, delay_seconds: float, claim_time, permanent_code=None) -> bool:
"""Return true only when a bounded at-least-once retry was recorded."""
try:
async with self.pool.acquire() as connection, connection.transaction():
job = await connection.fetchrow(
"SELECT attempt FROM attachment_jobs WHERE attachment_id = $1 FOR UPDATE", attachment_id
"SELECT j.attempt FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.id=$1 AND a.status='processing' AND a.processing_started_at=$2 FOR UPDATE", attachment_id, claim_time
)
if job is not None and job["attempt"] < max_attempts:
if job is None:
return False
if permanent_code is None and job["attempt"] < max_attempts:
await connection.execute(
"UPDATE attachment_jobs SET attempt = attempt + 1, status = 'queued', last_error = 'processing_failed', lease_until = NULL, next_attempt_at = now() + $2 * interval '1 second', updated_at = now() WHERE attachment_id = $1",
attachment_id, delay_seconds,
@@ -448,14 +454,16 @@ class PostgresStore:
"UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1", attachment_id
)
return True
await self.fail_attachment_job(attachment_id, "retry_exhausted")
return False
code = permanent_code or 'retry_exhausted'
await connection.execute("UPDATE attachments SET status='failed', error_code=$2, updated_at=now() WHERE id=$1", attachment_id, code)
await connection.execute("UPDATE attachment_jobs SET status='failed', last_error=$2, lease_until=NULL, updated_at=now() WHERE attachment_id=$1", attachment_id, code)
return False
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def due_outbox_events(self, limit: int = 20) -> list[dict]:
try:
return [dict(row) for row in await self.pool.fetch(
return [{**dict(row), 'payload': json.loads(row['payload']) if isinstance(row['payload'], str) else row['payload']} for row in await self.pool.fetch(
"SELECT id, payload FROM attachment_outbox WHERE published_at IS NULL ORDER BY created_at LIMIT $1", limit
)]
except DB_ERRORS as error:
@@ -464,24 +472,36 @@ class PostgresStore:
async def mark_outbox_published(self, event_id: UUID) -> None:
await self.pool.execute("UPDATE attachment_outbox SET published_at = now(), attempts = attempts + 1 WHERE id = $1", event_id)
async def schedule_due_jobs(self) -> None:
async def schedule_due_jobs(self, max_attempts: int = 5) -> None:
"""Outbox dispatcher also restores expired leases and scheduled retries."""
try:
async with self.pool.acquire() as connection, connection.transaction():
rows = await connection.fetch(
"SELECT job_id, attachment_id, pipeline_version, attempt, status FROM attachment_jobs "
"WHERE (status = 'queued' AND next_attempt_at <= now()) OR (status = 'processing' AND lease_until < now()) "
"WHERE (status = 'queued' AND (next_attempt_at <= now() OR "
"(next_attempt_at = 'infinity'::timestamptz AND updated_at < now() - interval '60 seconds'))) "
"OR (status = 'processing' AND lease_until < now()) "
"FOR UPDATE SKIP LOCKED"
)
for row in rows:
row = dict(row)
if row["status"] == "processing":
if row['attempt'] >= max_attempts:
await connection.execute("UPDATE attachment_jobs SET status='failed', lease_until=NULL, last_error='retry_exhausted', updated_at=now() WHERE job_id=$1", row['job_id'])
await connection.execute("UPDATE attachments SET status='failed', error_code='retry_exhausted', updated_at=now() WHERE id=$1", row['attachment_id'])
continue
row['attempt'] += 1
await connection.execute(
"UPDATE attachment_jobs SET status = 'queued', lease_until = NULL, next_attempt_at = now(), last_error = 'lease_expired', updated_at = now() WHERE job_id = $1", row["job_id"]
"UPDATE attachment_jobs SET status = 'queued', attempt=$2, lease_until = NULL, next_attempt_at = now(), last_error = 'lease_expired', updated_at = now() WHERE job_id = $1", row["job_id"], row['attempt']
)
await connection.execute("UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1", row["attachment_id"])
payload = {"schema_version": 1, "job_id": str(row["job_id"]), "type": "attachment.process.v1", "attachment_id": str(row["attachment_id"]), "pipeline_version": row["pipeline_version"], "attempt": row["attempt"], "created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")}
await connection.execute("INSERT INTO attachment_outbox (id, job_id, payload) VALUES ($1, $2, $3::jsonb)", uuid4(), row["job_id"], json.dumps(payload, separators=(",", ":")))
await connection.execute("UPDATE attachment_jobs SET next_attempt_at = 'infinity' WHERE job_id = $1", row["job_id"])
# Refresh the watchdog on publication intent, not on claim.
# Unclaimed jobs are republished after 60s. At-least-once
# duplicates are safe, and a published-but-lost delivery
# can no longer strand durable accepted work forever.
await connection.execute("UPDATE attachment_jobs SET next_attempt_at = 'infinity', updated_at=now() WHERE job_id = $1", row["job_id"])
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
@@ -505,7 +525,7 @@ class PostgresStore:
async def attachment_keys(self) -> dict[str, UUID]:
"""Inventory used only by the maintenance reconciler."""
try:
rows = await self.pool.fetch("SELECT COALESCE(original_key, staging_key) AS object_key, id FROM attachments")
rows = await self.pool.fetch("SELECT staging_key AS object_key, id FROM attachments WHERE status <> 'ready' UNION ALL SELECT original_key, id FROM attachments WHERE original_key IS NOT NULL UNION ALL SELECT object_key, attachment_id AS id FROM attachment_variants")
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
return {row["object_key"]: row["id"] for row in rows}
+105 -26
View File
@@ -6,8 +6,13 @@ import json
import logging
import os
import random
import pickle
import subprocess
import sys
import time
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
from uuid import UUID
from uuid import UUID, uuid4
from PIL import Image, ImageOps
@@ -19,6 +24,32 @@ from .storage.s3 import S3Settings, S3Store
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s worker %(message)s")
class PermanentFailure(Exception):
pass
def fit(image, bound):
longest = max(image.size)
if longest <= bound:
return image.copy()
return image.resize((max(1, image.width * bound // longest),
max(1, image.height * bound // longest)), Image.Resampling.LANCZOS)
def render_isolated(data, timeout):
try:
result = subprocess.run([sys.executable, '-m', 'src.render'], input=data,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout)
except subprocess.TimeoutExpired as error:
raise TimeoutError('render deadline exceeded') from error
if result.returncode in (20, 21):
raise PermanentFailure('invalid_image' if result.returncode == 20 else 'image_resource_limit')
if result.returncode:
raise RuntimeError('renderer exited')
# Only our own child process produces this payload; no external pickle input.
return pickle.loads(result.stdout)
def thumbnail(data: bytes) -> tuple[bytes, int, int]:
with Image.open(BytesIO(data), formats=("PNG", "JPEG")) as source:
image = ImageOps.exif_transpose(source)
@@ -28,7 +59,7 @@ def thumbnail(data: bytes) -> tuple[bytes, int, int]:
image = background.convert("RGB")
else:
image = image.convert("RGB")
image.thumbnail((256, 256), Image.Resampling.LANCZOS)
image = fit(image, 256)
output = BytesIO()
image.save(output, format="JPEG", quality=85, optimize=True)
return output.getvalue(), image.width, image.height
@@ -44,8 +75,7 @@ def variants(data: bytes, max_pixels: int = 40_000_000) -> list[tuple[str, bytes
white.alpha_composite(image)
rgb = white.convert("RGB")
thumb = rgb.copy()
thumb.thumbnail((256, 256), Image.Resampling.LANCZOS)
thumb = fit(rgb, 256)
thumbnail_out = BytesIO(); thumb.save(thumbnail_out, "JPEG", quality=85, optimize=True)
side = min(rgb.width, rgb.height)
@@ -53,8 +83,7 @@ def variants(data: bytes, max_pixels: int = 40_000_000) -> list[tuple[str, bytes
crop = rgb.crop((left, top, left + side, top + side)).resize((128, 128), Image.Resampling.LANCZOS)
crop_out = BytesIO(); crop.save(crop_out, "JPEG", quality=85, optimize=True)
optimized = rgb.copy()
optimized.thumbnail((1280, 1280), Image.Resampling.LANCZOS)
optimized = fit(rgb, 1280)
optimized_out = BytesIO(); optimized.save(optimized_out, "WEBP", quality=80, method=4)
return [
("thumbnail", thumbnail_out.getvalue(), "image/jpeg", thumb.width, thumb.height),
@@ -64,26 +93,61 @@ def variants(data: bytes, max_pixels: int = 40_000_000) -> list[tuple[str, bytes
async def process(store: PostgresStore, s3: S3Store, payload: dict, lease_seconds: int) -> None:
# Excludes cleanup for the whole lifetime of S3 effects, including stale attempts.
async with store.attachment_transaction():
await process_locked(store, s3, payload, lease_seconds)
async def process_locked(store: PostgresStore, s3: S3Store, payload: dict, lease_seconds: int) -> None:
attachment_id = UUID(payload["attachment_id"])
attachment = await store.claim_attachment_job(attachment_id, lease_seconds)
if attachment is None:
return
original_key = f"originals/{attachment_id}"
payload['_claim_time'] = attachment['claim_time']
payload['attempt'] = attachment.get('attempt', payload.get('attempt', 1))
attempt_key = uuid4().hex
original_key = f"originals/{attachment_id}/{attempt_key}"
await s3.copy(attachment["staging_key"], original_key, attachment["content_type"])
original = await s3.download_key(attachment["staging_key"], attachment["size_bytes"], attachment["sha256"])
rendered = await asyncio.wait_for(
asyncio.to_thread(variants, original, s3.settings.max_pixels), timeout=lease_seconds
)
rendered = await asyncio.to_thread(render_isolated, original, lease_seconds)
metadata = []
for name, content, content_type, width, height in rendered:
extension = "webp" if name == "optimized" else "jpg"
object_key = f"variants/{attachment_id}/{name}.{extension}"
object_key = f"variants/{attachment_id}/{attempt_key}/{name}.{extension}"
await s3.put(object_key, BytesIO(content), len(content), content_type)
metadata.append({"name": name, "object_key": object_key, "content_type": content_type,
"size_bytes": len(content), "width": width, "height": height,
"sha256": sha256(content).hexdigest()})
await store.complete_attachment_job(attachment_id, original_key, metadata)
await s3.delete(attachment["staging_key"])
# Explicit, opt-in integration fault. Marker survives container restart,
# so one crash exercises lease recovery without a permanent crash loop.
if os.environ.get('WORKER_FAULT_AFTER_S3_PUT') == '1':
marker = Path('/tmp/worker-fault-after-s3')
try:
with marker.open('x') as stream:
stream.write(str(attachment_id))
except FileExistsError:
pass
else:
os._exit(70)
committed = await store.complete_attachment_job(attachment_id, original_key, metadata, attachment['claim_time'])
if committed:
try:
await s3.delete(attachment["staging_key"])
except Exception:
logging.warning('staging cleanup deferred attachment_id=%s', attachment_id)
def settle_delivery(channel, delivery_tag, future):
"""Only a successful durable disposition permits acknowledgement."""
try:
success = future.result() is True
except Exception:
success = False
if channel.is_open:
if success:
channel.basic_ack(delivery_tag)
else:
channel.basic_nack(delivery_tag, requeue=True)
def main() -> None:
@@ -104,46 +168,61 @@ def main() -> None:
s3.client.close()
await store.close()
async def schedule_retry(attachment_id, delay):
async def schedule_retry(attachment_id, delay, claim_time, permanent_code=None):
retry_store = PostgresStore(settings.database_url)
await retry_store.connect()
try:
return await retry_store.retry_attachment_job(
attachment_id, max(1, int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))), delay
attachment_id, max(1, int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))), delay, claim_time, permanent_code
)
finally:
await retry_store.close()
def handle(body):
payload = None
try:
payload = json.loads(body)
if not isinstance(payload, dict):
raise ValueError('job must be an object')
if payload["type"] != "attachment.process.v1" or payload["schema_version"] != 1:
raise ValueError("unexpected broker payload")
UUID(payload['attachment_id'])
UUID(payload['job_id'])
except (ValueError, KeyError, TypeError):
try:
asyncio.run(publish_dlq({'failure': 'invalid_job'}))
return True
except Exception:
return False
try:
asyncio.run(handle_async(payload))
except Exception:
logging.exception("job failed")
except Exception as error:
logging.warning("job failed attachment_id=%s", payload['attachment_id'])
if '_claim_time' not in payload:
return False
try:
attachment_id = UUID(payload["attachment_id"])
attempt = int(payload.get("attempt", 1))
delay = min(60.0, float(2 ** min(attempt, 6))) * random.uniform(0.5, 1.5)
retry = asyncio.run(schedule_retry(attachment_id, delay))
asyncio.run(schedule_retry(attachment_id, delay, payload['_claim_time'],
str(error) if isinstance(error, PermanentFailure) else None))
except Exception:
retry = False
if not retry:
try:
asyncio.run(publish_dlq(payload))
except Exception:
logging.exception("could not publish failed job to DLQ")
return None
return False
return True
def consume(ch, method, properties, body):
del properties
future = executor.submit(handle, body)
def acknowledged(_future):
connection.add_callback_threadsafe(lambda: ch.basic_ack(method.delivery_tag))
if connection.is_open:
connection.add_callback_threadsafe(lambda: settle_delivery(ch, method.delivery_tag, _future))
future.add_done_callback(acknowledged)
try:
def heartbeat():
Path('/tmp/worker-heartbeat').write_text(str(time.time()))
connection.call_later(2, heartbeat)
heartbeat()
with ThreadPoolExecutor(max_workers=workers, thread_name_prefix="attachment-worker") as executor:
channel.basic_consume(queue=QUEUE, on_message_callback=consume, auto_ack=False)
channel.start_consuming()
+7 -5
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Attachment contract checks against the running lab4 stack."""
"""Attachment contract checks against the running lab5 stack."""
import hashlib
import http.client
from io import BytesIO
@@ -23,16 +23,17 @@ def main():
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
png = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
def upload(data, mime='image/png', filename='photo.png', status=201, actor=alice):
def upload(data, mime='image/png', filename='photo.png', status=202, actor=alice):
return c.call('POST', path + quote(filename, safe=''), status, actor=actor, raw=data,
headers={'Content-Type': mime}, schema='Attachment' if status == 201 else None)
headers={'Content-Type': mime}, schema='Attachment' if status == 202 else None)
for fmt, mime in [('PNG', 'image/png'), ('JPEG', 'image/jpeg')]:
buf = BytesIO()
Image.new('RGB', (32, 20), 'blue').save(buf, fmt)
data = buf.getvalue()
att = upload(data, mime)['json']
check(att['variants'] == [] and att['status'] == 'ready', 'wrong attachment state')
check(att['variants'] == [] and att['status'] == 'queued', 'wrong attachment state')
att = c.wait_ready(bob, att)
check(att['sha256'] == hashlib.sha256(data).hexdigest(), 'wrong checksum')
content_path = '/api/v1/attachments/' + att['id']
check(c.call('GET', content_path, actor=bob, schema='Attachment')['json'] == att,
@@ -41,7 +42,7 @@ def main():
c.call('GET', content_path, 404, actor=eve)
c.call('GET', content_path + '/content', 404, actor=eve)
c.call('GET', content_path + '/content', 401)
c.call('GET', content_path + '/content?variant=thumbnail', 404, actor=bob)
c.call('GET', content_path + '/content?variant=thumbnail', actor=bob)
message = c.message(bob, chat, '', attachments=[att['id']])['json']
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages',
actor=alice, schema='MessagePage')['json']['items']
@@ -98,6 +99,7 @@ def main():
# Exact limits are accepted; original bytes (including PNG trailing data) survive.
exact = png + b'\0' * (10485760 - len(png))
att = upload(exact)['json']
c.wait_ready(bob, att)
check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == exact,
'10 MiB original changed')
buf = BytesIO()
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""Check real producer payloads and redeliver a complete persisted message."""
import json
import time
from jsonschema import Draft202012Validator, FormatChecker
from pipeline_integration import ROOT, Client, remote, duplicate, snapshot, wait, check
def main():
c = Client('http://localhost:8080', timeout=30)
actor, _, _, chat = c.bootstrap()
att, _ = c.attachment(actor, chat)
wait(c, actor, att)
payloads = remote('''rows = await db.pool.fetch('SELECT payload FROM attachment_outbox')
print(json.dumps([json.loads(row['payload']) if isinstance(row['payload'], str) else row['payload'] for row in rows]))''')
validator = Draft202012Validator(json.loads((ROOT / 'contracts/jobs.schema.json').read_text()), format_checker=FormatChecker())
for payload in payloads:
validator.validate(payload)
before = snapshot(att)
duplicate(att)
duplicate(att)
time.sleep(3)
check(snapshot(att) == before, 'persisted redelivery changed result')
result = dict(status='PASS', validated_outbox_payloads=len(payloads),
extra_payload_fields=False, persisted_redelivery_noop=True)
(ROOT / 'evidence/job-contract.json').write_text(json.dumps(result, indent=2) + '\n')
print(json.dumps(result))
if __name__ == '__main__':
main()
+107
View File
@@ -0,0 +1,107 @@
"""Offline regression checks for delivery and terminal-state safety."""
import asyncio
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from io import BytesIO
import json
from pathlib import Path
import sys
from types import SimpleNamespace
import unittest
from unittest.mock import AsyncMock, MagicMock, patch
from uuid import uuid4
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src.storage.postgres import PostgresStore
from src.worker import process_locked as process, settle_delivery
from concurrent.futures import Future
from src.broker import _publish_to
class CriticalTests(unittest.IsolatedAsyncioTestCase):
def test_failed_or_unrecorded_work_is_requeued(self):
for result in (False, None, RuntimeError('database unavailable')):
future, channel = Future(), MagicMock()
if isinstance(result, Exception):
future.set_exception(result)
else:
future.set_result(result)
settle_delivery(channel, 7, future)
channel.basic_ack.assert_not_called()
channel.basic_nack.assert_called_once_with(7, requeue=True)
def test_durable_success_is_acked(self):
future, channel = Future(), MagicMock()
future.set_result(True)
settle_delivery(channel, 7, future)
channel.basic_ack.assert_called_once_with(7)
channel.basic_nack.assert_not_called()
async def test_outbox_decodes_jsonb(self):
store = PostgresStore('unused')
store._pool = AsyncMock()
payload = {'type': 'attachment.process.v1', 'attachment_id': str(uuid4())}
store.pool.fetch.return_value = [{'id': uuid4(), 'payload': json.dumps(payload)}]
event, = await store.due_outbox_events()
self.assertEqual(json.loads(json.dumps(event['payload'])), payload)
async def run_processing(self, committed):
store, s3 = AsyncMock(), AsyncMock()
stamp = datetime.now(timezone.utc)
store.claim_attachment_job.return_value = {
'claim_time': stamp, 'staging_key': 'staging/test',
'content_type': 'image/png', 'size_bytes': 1, 'sha256': 'unused',
}
store.complete_attachment_job.return_value = committed
s3.settings = SimpleNamespace(max_pixels=40000000)
s3.download_key.return_value = b'fixture'
s3.delete.side_effect = RuntimeError('storage temporarily unavailable')
payload = {'attachment_id': str(uuid4())}
with patch('src.worker.render_isolated', return_value=[('thumbnail', b'jpeg', 'image/jpeg', 1, 1)]):
await process(store, s3, payload, 60)
self.assertEqual(store.complete_attachment_job.call_args.args[-1], stamp)
return store, s3
async def test_cleanup_error_does_not_retry_ready(self):
store, s3 = await self.run_processing(True)
s3.delete.assert_awaited_once()
store.retry_attachment_job.assert_not_awaited()
async def test_stale_completion_keeps_staging(self):
_, s3 = await self.run_processing(False)
s3.delete.assert_not_awaited()
async def test_stale_claim_cannot_publish_metadata(self):
store = PostgresStore('unused')
connection = AsyncMock()
connection.fetchval.return_value = None
@asynccontextmanager
async def context():
yield connection
connection.transaction = context
store._pool = SimpleNamespace(acquire=context)
self.assertFalse(await store.complete_attachment_job(uuid4(), 'original', [], datetime.now(timezone.utc)))
connection.execute.assert_not_awaited()
async def test_retry_of_terminal_or_stale_attempt_is_noop(self):
store = PostgresStore('unused')
connection = AsyncMock()
connection.fetchrow.return_value = None
@asynccontextmanager
async def context():
yield connection
connection.transaction = context
store._pool = SimpleNamespace(acquire=context)
self.assertFalse(await store.retry_attachment_job(uuid4(), 5, 1, datetime.now(timezone.utc)))
connection.execute.assert_not_awaited()
def test_dlq_waits_for_publisher_confirm(self):
connection = MagicMock()
with patch('src.broker._connection', return_value=connection):
_publish_to('dlq', {'failure': 'invalid_job'})
connection.channel.return_value.confirm_delivery.assert_called_once()
self.assertTrue(connection.channel.return_value.basic_publish.call_args.kwargs['mandatory'])
if __name__ == '__main__':
unittest.main()
+205
View File
@@ -0,0 +1,205 @@
#!/usr/bin/env python3
"""Destructive-to-availability tests on the local lab stack; volumes preserved.
Only synthetic attachments created here are mutated. Tokens stay in memory.
Run sequentially, never alongside load or another fault test.
"""
import json
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, check
RESULTS = []
def compose(*args, env=None, source=None):
result = subprocess.run(['docker', 'compose', *args], cwd=ROOT,
env=dict(os.environ, **(env or {})), input=source,
text=True, capture_output=True, timeout=150)
check(result.returncode == 0, 'compose failed: ' + ' '.join(args[:4]) + '\n' + result.stderr[-1000:])
return result.stdout.strip()
def remote(body, **values):
source = '''import asyncio, json, os
from uuid import UUID
from src.config import load_settings
from src.storage.postgres import PostgresStore
from src.storage.s3 import S3Store, S3Settings
from src.broker import publish
V = json.loads(%r)
async def main():
db = PostgresStore(load_settings().database_url)
await db.connect()
s3 = S3Store(S3Settings.load())
try:
%s
finally:
s3.client.close()
await db.close()
asyncio.run(main())
''' % (json.dumps(values), '\n'.join(' ' + line for line in body.splitlines()))
return json.loads(compose('exec', '-T', 'api-a', '/app/.venv/bin/python', '-', source=source))
def record(name, **facts):
RESULTS.append(dict(test=name, status='PASS', **facts))
print('PASS: ' + name, flush=True)
(ROOT / 'evidence/pipeline-integration.json').write_text(json.dumps(RESULTS, indent=2) + '\n')
def ready(c):
deadline = time.monotonic() + 90
successes = 0
while time.monotonic() < deadline:
try:
c.call('GET', '/health/ready')
successes += 1
if successes >= 5:
return
time.sleep(.5)
except Failure:
successes = 0
time.sleep(.5)
raise Failure('API did not recover')
def wait(c, actor, att, status='ready', timeout=120):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
value = c.call('GET', '/api/v1/attachments/' + att['id'], actor=actor, schema='Attachment')['json']
except Failure:
time.sleep(.25)
continue
if value['status'] == status:
return value
check(value['status'] != 'failed' or status == 'failed', 'unexpected failed attachment')
time.sleep(.25)
raise Failure('attachment did not reach ' + status)
def snapshot(att):
return remote('''row = await db.pool.fetchrow("SELECT a.status, j.attempt, j.job_id, a.original_key, a.staging_key FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE a.id=$1", UUID(V['id']))
objects = sorted(list(await s3.list('originals/' + V['id'] + '/')) + list(await s3.list('variants/' + V['id'] + '/')))
print(json.dumps(dict(row) | {'objects': objects}, default=str))''', id=att['id'])
def duplicate(att):
return remote('''payload = await db.pool.fetchval("SELECT o.payload FROM attachment_outbox o JOIN attachment_jobs j ON j.job_id=o.job_id WHERE j.attachment_id=$1 ORDER BY o.created_at LIMIT 1", UUID(V['id']))
await publish(json.loads(payload) if isinstance(payload, str) else payload)
print('true')''', id=att['id'])
def main():
c = Client('http://localhost:8080', timeout=30)
alice, bob, _, chat = c.bootstrap()
# No worker: HTTP admission and message creation must remain asynchronous.
compose('stop', '-t', '2', 'worker')
att, data = c.attachment(alice, chat)
check(att['status'] == 'queued', 'upload is not queued with stopped worker')
c.message(alice, chat, 'queued attachment', attachments=[att['id']])
time.sleep(2)
compose('restart', 'broker')
compose('up', '-d', '--no-deps', '--wait', 'broker')
compose('restart', 'api-a', 'api-b')
ready(c)
compose('start', 'worker')
completed = wait(c, bob, att)
check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == data, 'original changed')
check({v['name'] for v in completed['variants']} == {'thumbnail', 'crop', 'optimized'}, 'variants missing')
record('stopped worker, queued message, broker/API restart, ready', attachment_id=att['id'])
before = snapshot(att)
duplicate(att)
duplicate(att)
time.sleep(3)
check(snapshot(att) == before, 'duplicate changed result or created S3 objects')
refused = remote("print(json.dumps(await db.replay_failed_attachment(UUID(V['id']))))", id=att['id'])
check(refused is False, 'ready replay accepted')
record('duplicate delivery and replay of ready are no-ops', object_count=len(before['objects']))
# Pause publication so the API crash is demonstrably before any publish.
compose('stop', '-t', '2', 'outbox')
compose('up', '-d', '--no-deps', '--wait', 'api-a', 'api-b', env={'OUTBOX_FAULT_AFTER_COMMIT': '1'})
ready(c)
fault_actor, _, _, fault_chat = c.bootstrap()
try:
c.attachment(fault_actor, fault_chat)
raise AssertionError('crash hook did not interrupt upload')
except Failure:
pass
compose('up', '-d', '--no-deps', '--wait', 'api-a', 'api-b')
ready(c)
row = remote('''rows = await db.pool.fetch("SELECT a.id, o.published_at FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id JOIN attachment_outbox o ON o.job_id=j.job_id WHERE a.chat_id=$1", UUID(V['chat']))
assert len(rows) == 1 and rows[0]['published_at'] is None
print(json.dumps({'id': str(rows[0]['id'])}))''', chat=fault_chat['id'])
compose('start', 'outbox')
wait(c, fault_actor, row)
record('crash after COMMIT before publish recovered from existing outbox', attachment_id=row['id'])
compose('up', '-d', '--no-deps', '--wait', 'worker', env={'WORKER_FAULT_AFTER_S3_PUT': '1', 'JOB_TIMEOUT_SECONDS': '10'})
att, _ = c.attachment(alice, chat)
wait(c, alice, att)
snap = snapshot(att)
check(snap['attempt'] >= 2 and len(snap['objects']) >= 8, 'side effect crash/lease retry not observed')
marker = compose('exec', '-T', 'worker', 'cat', '/tmp/worker-fault-after-s3')
check(marker == att['id'], 'wrong fault target')
record('worker crash after S3 before commit/ack, lease recovery', attempt=snap['attempt'], objects_before_cleanup=len(snap['objects']))
compose('up', '-d', '--no-deps', '--wait', 'worker')
# Select only this test's unreferenced attempt keys for cleanup.
cleaned = remote('''from argparse import Namespace
from src.reconcile import run
keys = V['keys']
result = await run(Namespace(apply=True, grace_seconds=0, object_key=keys))
print(json.dumps(result['deleted']))''', keys=snap['objects'])
check(len(cleaned) == 4, 'stale attempt objects not cleaned safely')
check(len(snapshot(att)['objects']) == 4, 'live attempt affected by cleanup')
wait(c, alice, att)
record('targeted orphan cleanup preserves committed attempt', deleted=len(cleaned))
# Lose only this synthetic staging object to exercise transient retry exhaustion.
compose('stop', '-t', '2', 'worker')
att, data = c.attachment(alice, chat)
remote("await s3.delete('staging/' + V['id'] + '/original')\nprint('true')", id=att['id'])
compose('up', '-d', '--no-deps', '--wait', 'worker', env={'JOB_MAX_ATTEMPTS': '2'})
failed = wait(c, alice, att, 'failed')
snap = snapshot(att)
check(snap['attempt'] == 2 and failed['error_code'] == 'retry_exhausted', 'unbounded/wrong retry')
# Restore exactly the bytes originally accepted, then explicit failed-only replay.
import base64
replayed = remote('''from io import BytesIO
import base64
content = base64.b64decode(V['data'])
await s3.put('staging/' + V['id'] + '/original', BytesIO(content), len(content), 'image/png')
print(json.dumps(await db.replay_failed_attachment(UUID(V['id']))))''', id=att['id'], data=base64.b64encode(data).decode())
check(replayed, 'failed replay refused')
wait(c, alice, att)
record('bounded transient retry, failed registry and explicit replay', attempts_before_replay=snap['attempt'])
compose('up', '-d', '--no-deps', '--wait', 'worker')
# Real Linux child with deliberately insufficient address space.
memory = remote('''import subprocess
from io import BytesIO
from PIL import Image
buf = BytesIO(); Image.new('RGB', (2400, 2400)).save(buf, 'PNG')
env = dict(os.environ, RENDER_MEMORY_MB='120')
p = subprocess.run(['/app/.venv/bin/python', '-m', 'src.render'], input=buf.getvalue(), capture_output=True, env=env, timeout=30)
print(json.dumps({'returncode': p.returncode}))''')
check(memory['returncode'] == 21, 'Linux memory limit did not produce bounded resource failure')
record('Linux renderer memory limit', **memory)
if __name__ == '__main__':
try:
main()
finally:
compose('up', '-d', '--no-deps', '--wait', 'api-a', 'api-b', 'worker', 'outbox')
+141
View File
@@ -0,0 +1,141 @@
#!/usr/bin/env python3
"""Real PostgreSQL/S3/RabbitMQ invariant and security checks, synthetic data only."""
import json
from pathlib import Path
import time
from pipeline_integration import Client, check, compose, remote, wait, ROOT
def main():
results = []
c = Client('http://localhost:8080', timeout=30)
alice, bob, eve, chat = c.bootstrap()
att, _ = c.attachment(alice, chat)
wait(c, bob, att)
from io import BytesIO
from PIL import Image
for name, fmt, bound in (('thumbnail', 'JPEG', 256), ('crop', 'JPEG', 128), ('optimized', 'WEBP', 1280)):
content = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=' + name, actor=bob)['bytes']
with Image.open(BytesIO(content)) as image:
check(image.format == fmt and max(image.size) <= bound and not image.getexif(), 'variant format/size/EXIF')
if name == 'crop':
check(image.size == (128, 128), 'crop dimensions')
results.append('actual thumbnail/crop/WebP formats, dimensions and removed EXIF')
# Verify actual private object key, not a nonexistent legacy key.
private = remote('''import urllib.request, urllib.error
key = await db.pool.fetchval('SELECT original_key FROM attachments WHERE id=$1', UUID(V['id']))
try:
urllib.request.urlopen('http://s3:8333/' + s3.settings.bucket + '/' + key, timeout=5)
except urllib.error.HTTPError as error:
assert error.code == 403, error.code
else:
raise AssertionError('anonymous object leaked')
print('true')''', id=att['id'])
check(private, 'private S3 check failed')
for variant in ('thumbnail', 'crop', 'optimized'):
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=' + variant, 404, actor=eve)
results.append('anonymous S3 403 on existing object; variant ACL 404')
lock = remote('''import time
entered = asyncio.Event()
async def writer():
async with db.attachment_transaction():
entered.set()
await asyncio.sleep(1)
task = asyncio.create_task(writer())
await entered.wait()
started = time.monotonic()
async with db.attachment_transaction(maintenance=True):
waited = time.monotonic() - started
await task
assert waited >= .9, waited
print(json.dumps({'maintenance_wait_seconds': waited}))''')
results.append(lock)
# Poison staging only for a newly created synthetic attachment and update its
# digest so invalid-image classification (not transport checksum) is exercised.
compose('stop', '-t', '2', 'worker')
guarded, _ = c.attachment(alice, chat)
fence = remote('''key = UUID(V['id'])
job_id = await db.pool.fetchval('SELECT job_id FROM attachment_jobs WHERE attachment_id=$1', key)
before = await db.pool.fetchval('SELECT count(*) FROM attachment_outbox WHERE job_id=$1', job_id)
await db.pool.execute("UPDATE attachment_jobs SET updated_at=now()-interval '61 seconds' WHERE attachment_id=$1", key)
await db.schedule_due_jobs()
after = await db.pool.fetchval('SELECT count(*) FROM attachment_outbox WHERE job_id=$1', job_id)
assert after == before + 1, 'unclaimed published job stranded'
assert await db.pool.fetchval('SELECT attempt FROM attachment_jobs WHERE attachment_id=$1', key) == 1
await db.schedule_due_jobs()
assert await db.pool.fetchval('SELECT count(*) FROM attachment_outbox WHERE job_id=$1', job_id) == after, 'watchdog floods outbox'
first = await db.claim_attachment_job(key, 30)
assert first is not None
assert await db.retry_attachment_job(key, 5, 30, first['claim_time'])
assert await db.claim_attachment_job(key, 30) is None, 'duplicate bypassed retry delay'
await db.pool.execute("UPDATE attachment_jobs SET next_attempt_at=now() WHERE attachment_id=$1", key)
await db.schedule_due_jobs()
second = await db.claim_attachment_job(key, 30)
assert second is not None and second['attempt'] == 2
assert not await db.complete_attachment_job(key, 'invalid-stale-key', [], first['claim_time'])
assert not await db.retry_attachment_job(key, 5, 0, first['claim_time'])
await db.pool.execute("UPDATE attachment_jobs SET lease_until=now()-interval '1 second' WHERE attachment_id=$1", key)
assert await db.claim_attachment_job(key, 30) is None, 'duplicate bypassed lease attempt accounting'
await db.schedule_due_jobs()
third = await db.claim_attachment_job(key, 30)
assert third['attempt'] == 3
assert await db.retry_attachment_job(key, 5, 0, third['claim_time'])
print('true')''', id=guarded['id'])
check(fence, 'SQL fencing/backoff invariant')
results.append('real SQL: queued watchdog republishes without attempt increment/flood; duplicate respects backoff; expired lease counted; stale completion/retry fenced')
att, _ = c.attachment(alice, chat)
remote('''from io import BytesIO
from hashlib import sha256
data = b'invalid image payload'
await s3.put('staging/' + V['id'] + '/original', BytesIO(data), len(data), 'image/png')
await db.pool.execute('UPDATE attachments SET size_bytes=$2, sha256=$3 WHERE id=$1', UUID(V['id']), len(data), sha256(data).hexdigest())
print('true')''', id=att['id'])
compose('start', 'worker')
wait(c, alice, guarded)
failed = wait(c, alice, att, 'failed')
check(failed['error_code'] == 'invalid_image', 'permanent classification failed')
attempt = remote("print(await db.pool.fetchval('SELECT attempt FROM attachment_jobs WHERE attachment_id=$1', UUID(V['id'])))", id=att['id'])
check(attempt == 1, 'permanent error retried')
results.append('permanent invalid_image reaches failed on attempt 1')
# DLQ uses confirmed persistent publication; count change avoids consuming
# messages belonging to a different test.
dlq = remote('''from src.broker import _connection, _publish, DLQ
connection = _connection(); channel = connection.channel()
before = channel.queue_declare(queue=DLQ, durable=True).method.message_count
connection.close()
_publish({'malformed': True})
print(json.dumps({'before': before}))''')
deadline = time.monotonic() + 20
while time.monotonic() < deadline:
count = remote('''from src.broker import _connection, DLQ
connection = _connection()
print(connection.channel().queue_declare(queue=DLQ, durable=True).method.message_count)
connection.close()''')
if count > dlq['before']:
break
time.sleep(.5)
check(count == dlq['before'] + 1, 'invalid job not delivered to DLQ')
results.append('malformed broker message delivered to DLQ')
# Actual Linux child timeout: no renderer can finish within this deadline.
timeout = remote('''from src.worker import render_isolated
try:
render_isolated(b'x', .000001)
except TimeoutError:
print('true')
else:
raise AssertionError('timeout not enforced')''')
check(timeout, 'timeout missing')
results.append('Linux render subprocess killed/reaped on deadline')
(ROOT / 'evidence/pipeline-invariants.json').write_text(json.dumps(results, indent=2) + '\n')
print(json.dumps(results, indent=2), flush=True)
if __name__ == '__main__':
try:
main()
finally:
compose('up', '-d', '--no-deps', '--wait', 'worker')
+127
View File
@@ -0,0 +1,127 @@
"""Contract, isolated-render and benchmark regressions without Docker."""
import asyncio
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
import importlib.util
from io import BytesIO
import json
from pathlib import Path
import sys
import tempfile
import threading
import time
from types import SimpleNamespace
import unittest
from unittest.mock import AsyncMock, patch
from uuid import uuid4
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from PIL import Image
from src.worker import variants, render_isolated, PermanentFailure
from src.storage.postgres import PostgresStore
from src.reconcile import scan
from src.errors import ApiError
def png(width, height):
buffer = BytesIO()
Image.new('RGBA', (width, height), (255, 0, 0, 0)).save(buffer, 'PNG')
return buffer.getvalue()
class Regressions(unittest.IsolatedAsyncioTestCase):
async def test_failed_attachment_is_rejected(self):
store, connection = PostgresStore('unused'), AsyncMock()
connection.fetchval.side_effect = [1, 1, 1]
@asynccontextmanager
async def context():
yield connection
connection.transaction = context
store._pool = SimpleNamespace(acquire=context)
with self.assertRaises(ApiError) as error:
await store.create_message_idempotent(uuid4(), uuid4(), '', 'key', 86400, [uuid4()])
self.assertEqual(error.exception.status_code, 409)
connection.fetchrow.assert_not_awaited()
def test_floor_and_small_images(self):
self.assertEqual(variants(png(300, 200))[0][3:], (256, 170))
self.assertEqual(variants(png(200, 300))[0][3:], (170, 256))
self.assertEqual(variants(png(10, 8))[0][3:], (10, 8))
for name, data, mime, width, height in variants(png(300, 200)):
with Image.open(BytesIO(data)) as image:
self.assertEqual(image.size, (width, height))
self.assertTrue(all(value > 240 for value in image.convert('RGB').getpixel((0, 0))))
def test_renderer_success_and_permanent_error(self):
self.assertEqual(render_isolated(png(300, 200), 10)[0][3:], (256, 170))
with self.assertRaises(PermanentFailure):
render_isolated(b'not an image', 10)
def test_renderer_is_killed_on_deadline(self):
started = time.monotonic()
with self.assertRaises(TimeoutError):
render_isolated(png(300, 200), .0001)
self.assertLess(time.monotonic() - started, 2)
async def test_cleanup_retains_active_and_failed_staging(self):
old = datetime.now(timezone.utc) - timedelta(days=2)
db, s3 = AsyncMock(), AsyncMock()
db.attachment_keys.return_value = {'staging/active': uuid4(), 'staging/failed': uuid4(), 'originals/ready': uuid4()}
s3.list_with_pages.side_effect = [({'staging/active': old, 'staging/failed': old, 'staging/orphan': old}, 1),
({'originals/ready': old}, 1), ({'variants/orphan': old}, 1)]
report = await scan(SimpleNamespace(grace_seconds=60, apply=True, object_key=[]), db, s3)
self.assertEqual(report['deleted'], ['staging/orphan', 'variants/orphan'])
async def test_permanent_failure_is_atomic_and_not_retried(self):
store = PostgresStore('unused')
connection = AsyncMock()
connection.fetchrow.return_value = {'attempt': 1}
@asynccontextmanager
async def context():
yield connection
connection.transaction = context
store._pool = SimpleNamespace(acquire=context)
result = await store.retry_attachment_job(uuid4(), 5, 1, datetime.now(timezone.utc), 'invalid_image')
self.assertFalse(result)
self.assertEqual(connection.execute.await_count, 2)
for call in connection.execute.call_args_list:
self.assertIn("status='failed'", call.args[0])
self.assertEqual(call.args[2], 'invalid_image')
def test_benchmark_partial_batch_and_recovery(self):
spec = importlib.util.spec_from_file_location('track1', ROOT / 'scripts/track1.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
jobs, lock = {}, threading.Lock()
class FakeClient:
def __init__(self, *args, **kwargs): pass
def bootstrap(self): return {}, {}, {}, {'id': str(uuid4())}
def call(self, method, path, *args, **kwargs):
if method == 'POST':
key = str(uuid4())
with lock: jobs[key] = {'id': key, 'status': 'ready', 'queue_wait_seconds': .01}
return {'status': 202, 'json': {'id': key}}
return {'json': {'status': 'ready'}}
def attachment(self, *args): return {}, b''
def wait_ready(self, *args, **kwargs): return {}
def metrics(_):
with lock:
return {'jobs': list(jobs.values()), 'pending': 0, 'rss_bytes': 1000, 'concurrency': 2, 'prefetch': 2}
with tempfile.TemporaryDirectory() as directory:
destination = str(Path(directory) / 'result.json')
args = SimpleNamespace(run_name='test', workers=2, prefetch=2, max_pending=20, images=10,
concurrency=8, size=8, max_ready_seconds=2, require_backpressure=False,
output=destination, base_url=None, ca_file=None)
info = {'Config': {'Env': ['MAX_PENDING_JOBS=20']}, 'HostConfig': {'Memory': 4096, 'NanoCpus': 2}}
with patch.object(module, 'arguments', return_value=args), patch.object(module, 'Client', FakeClient), \
patch.object(module, 'metrics', side_effect=metrics), patch.object(module, 'container_info', return_value=info), \
patch.object(module, 'broker_depth', return_value={'messages_ready': 0, 'messages_unacknowledged': 0}):
module.main()
report = json.loads(Path(destination).read_text())
self.assertEqual(report['results']['ready'], 10)
self.assertTrue(report['results']['recovery_upload_ready'])
if __name__ == '__main__':
unittest.main()
+1 -1
View File
@@ -20,7 +20,7 @@ def main():
client = Client(args.base_url, args.ca_file)
alice, _bob, _eve, chat = client.bootstrap()
data = (ROOT / "tests/fixtures/sample.png").read_bytes()
client.call("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=permission.png", 201,
client.call("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=permission.png", 202,
actor=alice, raw=data, headers={"Content-Type": "image/png"}, schema="Attachment")
bucket = "permission-probe-" + uuid.uuid4().hex
code = """from botocore.exceptions import ClientError