Files
mtusi2026lab2/openspec/changes/add-lab5-async-attachments/tasks.md
T
ArtyomandClaude Opus 5.5 a55bc716c4 Record level 3 evidence and fill in the report
Every grade 3 item of lab 5 is proven on a stand raised from empty
volumes at fe26938: the public smoke passes with 202 queued and a real
256x160 JPEG thumbnail; the suite runs its six grade 3 scenarios and
eight invariants green, including worker down with both API replicas,
the relay and the broker restarted while the job stays in the queue,
a redelivered finished job that changes nothing, an S3 outage that
recovers on attempt 2 and five transient failures that end in
retry_exhausted; the stand evidence shows the queued job with
delivery mode 2, the job id as message id and exactly the contract
fields, 409 before ready and a clean SIGTERM of the relay and the
worker; persistence restarts all eight services with their volumes,
failover keeps 134 writes without errors, and the lab 4 scenarios,
S3 checks, upload faults and container policy still pass.

The report describes the clean clone start, the processes and the
source of truth, what is stored at the moment of 202, the outbox and
relay, the claim, fencing and ack order of the worker, the retry
policy, the failure windows, the broker topology and permissions, the
roles table and the mapping of .env.example.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 01:31:07 +03:00

6.8 KiB
Raw Blame History

1. Схема

  • 1.1 Миграция 0004_jobs.sql: статусы queued/processing/failed, staging_key, original_key, published_version, error_code у attachments (перенос object_key лабы 4), таблицы attachment_variants, jobs, outbox, job_events, частичные индексы outbox_pending_idx, jobs_lease_idx, attachments_staged_idx
  • 1.2 Проверка группы: тест миграций — версия 0004, повтор без изменений, колонки из .prep/lab5/tools/schema.reference.sql на месте, дубль ключа эффекта отклоняется первичным ключом

2. Зона attachments: домен и приложение

  • 2.1 Домен: статусы queued/processing/failed, Attachment.enqueue, Variant, геометрия fit, Job и его сообщение по jobs.schema.json, Lease, RetryPolicy, FailureCode, Outcome, события AttachmentQueued, AttachmentReady, AttachmentFailed, JobRescheduled, ошибка AttachmentNotReady
  • 2.2 Порты: ObjectStorage.read/copy, VariantRenderer, JobPublisher, Faults, репозитории jobs и outbox в AttachmentsUnitOfWork, AttachmentDirectory.visible
  • 2.3 Upload: queued вместо ready, задание и outbox в той же транзакции; запросы GetAttachment/OpenAttachment с 409 до ready и вариантами опубликованной версии
  • 2.4 Обработчики ProcessJob (захват, staging → оригинал, рендер, запись вариантов, фиксация с fencing, повтор/финальная ошибка), PublishOutbox, RecoverExpiredLeases, CleanStaging
  • 2.5 Проверка группы: unit-тесты fit, RetryPolicy, сообщения задания против contracts/jobs.schema.json

3. Зона attachments: инфраструктура

  • 3.1 PostgreSQL: вложение с ключами и вариантами, задания, outbox, события, захват аренды, фиксация с fencing и published_version < v, повтор, финальная ошибка, истёкшие аренды, staging к уборке
  • 3.2 S3: read и copy; Pillow: PillowVariantRenderer (EXIF orientation, 16 бит, alpha на белом, fit, JPEG без метаданных, классификация invalid_image)
  • 3.3 FastStream: адаптер JobPublisher (exchange без объявления, persist, mandatory, confirm, message_id), FAULT_POINT с точкой transient_error; зависимости faststream[rabbit], dishka-faststream в uv.lock
  • 3.4 Проверка группы: тест рендера (fixture 320×200 → 256×160, RGBA на белом, EXIF 6, 17×1000 → 4×256, битые данные → invalid_image)

4. Точки входа и сборка процессов

  • 4.1 HTTP: 202 upload, variant из четырёх значений, 409, схема AttachmentOut со статусом и вариантами, реестр ошибок, журнал
  • 4.2 PipelineSettings, PipelineProvider, точка входа worker (FastStream-подписчик, проверка сообщения, ack/reject/nack), циклы relay, heartbeat
  • 4.3 Сборки relay.py и worker.py, тест графа импортов: сборки процессов знают одну зону, shared/ не импортирует FastStream
  • 4.4 Проверка группы: тесты pipeline против одноразового PostgreSQL с памятью вместо S3 — ready, дубль после ready без новых строк, параллельные копии, временная ошибка → queued и новая строка outbox, исчерпание → retry_exhausted, invalid_image без повторов, fencing чужой аренды, возврат истёкшей аренды, уборка staging, публикация outbox

5. Связь зон

  • 5.1 messaging: порт AttachmentStates, ошибка AttachmentUnavailable → 409, проверка только для первого исполнения (повтор по ключу возвращает исходный ответ)
  • 5.2 main.py: адаптер порта поверх AttachmentDirectory, версия 1.5.0
  • 5.3 Проверка группы: API-тесты — 202 queued, 409 на /content до ready, 400 на неизвестный variant, 404 на crop, сообщение с queued — 201, с failed — 409

6. Стенд

  • 6.1 infra/rabbitmq/, infra/s3/worker-policy.json, infra/compose.faults.yaml из .prep/lab5; пользователь worker в infra/s3/init.sh
  • 6.2 compose.yaml: broker, relay, worker, volume broker-data, секреты брокера и S3-ключа worker; scripts/broker-secrets.sh в make secrets; .env.example (BROKER_MANAGEMENT_PORT, JOB_BACKOFF_BASE_SECONDS, OUTBOX_POLL_SECONDS, SWEEP_INTERVAL_SECONDS)
  • 6.3 Хуки: restart.sh с relay, worker и broker; worker.sh, broker.sh
  • 6.4 Проверка группы: docker compose config --quiet, make up из чистого состояния, все сервисы healthy, топология и consumer с prefetch_count, опубликованы только lb и UI брокера на 127.0.0.1

7. Сценарии и обвязка

  • 7.1 scripts/pipeline_suite.py, scripts/make_images.py из .prep/lab5; цели Makefile queues, worker-stop, worker-start, broker-restart, suite-preflight, level3, topology; ruff для новых scripts/*.py
  • 7.2 CI-job под лабу 5: брокер, relay и worker в стенде, сценарии уровня «3»
  • 7.3 Проверка группы: make test, make test-persistence ACTION_SCRIPT=scripts/restart.sh, make test-failover ACTION_SCRIPT=scripts/stop-one.sh с make restore, make suite-preflight, make level3

8. Отчёт

  • 8.1 evidence/: smoke, persistence и failover с состояниями контейнеров, level3, topology, student-tests, contract-checks, окружение
  • 8.2 REPORT.md: запуск из чистого clone, архитектура и решения, таблица ролей, соответствие переменных .env.example, строки уровня «3», таблица отказов уровня «3»
  • 8.3 Проверка группы: make check, make validate, make lint, make student-test зелёные