diff --git a/evidence/review-fixes-2026-11-06/RESULTS.md b/evidence/review-fixes-2026-11-06/RESULTS.md new file mode 100644 index 00000000..4be9241d --- /dev/null +++ b/evidence/review-fixes-2026-11-06/RESULTS.md @@ -0,0 +1,89 @@ +# Исправления major после первого ревью ЛР5 + +Исходный snapshot: `544b9c78d39d0e9dd07f841894c390895896605a`. +Этап выполнялся в основном репозитории, в существующем `.venv`, без установки окружений, +Docker, нагрузки, фоновых процессов и публикации. REPORT оформляет отдельный агент. + +## Что исправлено + +1. В `infra/rabbitmq/definitions.json` рабочая очередь получила `delivery-limit=-1`. + При ошибке PostgreSQL до claim consumer продолжает delayed nack с теми же `job_id`/`attempt`; + брокер больше не должен отправлять сообщение в DLQ по числу доставок. `JOB_MAX_ATTEMPTS=5`, + backoff/jitter после claim, reject невалидных сообщений в DLX и ack после COMMIT сохранены. + Поддержка политики сверена с [документацией RabbitMQ 4.1](https://www.rabbitmq.com/docs/4.1/quorum-queues#poison-message-handling) + и [исходником RabbitMQ v4.1.8](https://github.com/rabbitmq/rabbitmq-server/blob/v4.1.8/deps/rabbit/src/rabbit_quorum_queue.erl) + (`args_policy_lookup`, `resolve_delivery_limit`). Это проверка кода/документации, не запуск брокера. +2. `flatten` учитывает PNG tRNS в RGB/L/1/P и точное значение 16-битного grayscale до нормализации. + Все три варианта обеих версий имеют белые прозрачные области и сохраняют непрозрачные пиксели. + Соседние grayscale 12345/12346 проверены отдельно, чтобы нормализация не создала ложную прозрачность. + +## Выполненные проверки + +| Команда | Наблюдение | Файл | +| --- | --- | --- | +| `PYTHONPATH=src:student-tests .venv/bin/python -m pytest --confcutdir=student-tests/unit student-tests/unit/test_renderer.py student-tests/unit/test_worker_delivery.py -q --tb=short` до исправления | 9 failed, 25 passed: RGB/L/1/16-bit и delivery-limit | `regressions-before.txt` | +| Та же команда с добавлением `student-tests/unit/test_pipeline_domain.py` после первого исправления | 2 failed, 55 passed: ошибка 16-битной тестовой fixture, см. ниже | `regressions-fixture-error.txt` | +| `PYTHONPATH=src:student-tests .venv/bin/python -m pytest --confcutdir=student-tests/unit student-tests/unit/test_renderer.py student-tests/unit/test_worker_delivery.py student-tests/unit/test_pipeline_domain.py -q --tb=short` после исправления fixture | 57 passed, без загрузки общего conftest | `regressions-after.txt` | +| `PYTHONPATH=src:student-tests .venv/bin/python -m pytest --noconftest student-tests/api/test_bounded_contexts.py -q --tb=short` | 20 passed: зоны, транспорт, SQLAlchemy | `boundaries.txt` | +| `make check` | PASS, приложение не тестировалось | `check.txt` | +| `make validate` | PASS OpenAPI/JSON Schema | `validate.txt` | +| `make lint` | PASS ruff check/format и ty | `lint.txt` | +| `openspec validate --all --strict` до архивации | 23 passed, 0 failed | `openspec.txt` | +| `git diff --check` | exit 0 | `diff.txt` | + +В offline consumer-тесте 12 ошибок приводят к 12 nack и нулю ack/reject, затем успешный +bus-вызов даёт один ack; все 13 вызовов получают одно и то же задание. Пауза заменена AsyncMock. +Это не моделирует сервер RabbitMQ, реальное подключение к БД или COMMIT. + +Промежуточная fixture создавала правую половину `I;16` через `paste(12346, box)`, получая +14906 из-за семантики Pillow для скалярной заливки. Заменена на вставку `Image.new('I;16', …, 12346)` +с явной проверкой исходного пикселя. Производственный код для исправления этого теста не менялся. +Неуспешные логи сохранены и не считаются PASS. + +Дополнительно в одном offline Python-процессе исходный модуль из +`git show 544b9c78d39d0e9dd07f841894c390895896605a:src/messenger/attachments/infrastructure/images.py` +загружен в отдельный `ModuleType` и сопоставлен с текущим `render_variants`: +9 fixture × 2 версии × 3 варианта = **54 побайтно одинаковых варианта**. +Проверены sample, RGB/CMYK JPEG, RGBA/LA PNG, P с/без transparency, L и I;16 без tRNS. +Хеши — `unchanged-rendering.json`. Это подтверждает сохранение этих путей рендера, не throughput. +Точные SHA-256 затронутых файлов и exit codes — `checks.json`. + +## Обязательные проверки финального агента + +Эти проверки **НЕ запускались**. Архивация OpenSpec закрывает реализацию и offline-часть, +а не динамическую квалификацию исправления. + +1. На разрешённом стенде RabbitMQ **4.1.8**, с существующим volume, применить definitions без + пересоздания очередей/удаления данных. Сохранить `rabbitmqctl list_policies -p messenger` + и эффективную policy очереди `attachments.process`, исходную глубину DLQ. Убедиться в `delivery-limit=-1`. + Старые сообщения, уже попавшие в DLQ, смена политики автоматически не возвращает. +2. Выполнить `make student-test PYTEST_ARGS='student-tests/adapters/test_rabbitmq.py -q'`: + real-broker тест теперь включает 1 и 12 инфраструктурных ошибок, ждёт завершения и проверяет, + что DLQ не выросла. Также проверить reject невалидного сообщения, publisher confirms и права worker. +3. Проверить полную цепочку с настоящим отказом БД: остановить worker, upload → `202 queued`, + дождаться опубликованного outbox, остановить PostgreSQL **своего project**, запустить worker, + получить более 10 записей `job.requeued`, восстановить PostgreSQL. Без replay получить `ready` + с прежними `job_id`/`attempt`, одним набором вариантов, совпадающими хешами и неизменной DLQ. + Сохранить ID, сырые логи и `docker ps -a` для фактически остановленных контейнеров. +4. Через LB загрузить RGB/L/1/16-bit PNG с tRNS, получить `202 → ready`, проверить белые/непрозрачные + контрольные пиксели, метаданные и хеши thumbnail/crop/optimized для pipeline v1 и v2. + Проверить tRNS-путь на пределе 40 Мпикс под Linux с заданными лимитами памяти/времени. +5. Повторить затронутые сценарии pipeline: invalid-message/DLQ, retry-exhaustion/replay, + crash до/после COMMIT и ack, duplicate/reorder/lease fencing, v1/v2, инварианты single_effect, + bounded_attempts/no_lost_202. Достаточны адресные серии suite с сохранением их команд и условий; + прежние пригодные нагрузочные серии для изображений без tRNS этим изменением не аннулированы. + +Имена конкретных сценариев suite доступны в `scripts/pipeline_suite.py`; перед финальным запуском +использовать его штатные `--only`/`--output`. Прогоны public smoke/persistence/failover повторять, +если финальный аудит найдёт отсутствующее или затронутое подтверждение; прежние данные не стирать. + +## Ограничения для отдельного REPORT + +Пять minor первого ревью сохранены в `findings.json`. Они не исправлялись и не блокируют следующий +этап. В частности, `crash_publish_confirm` доказывает сбой после confirm до отметки outbox, старый +limits exit 1 не является PASS, reconcile_track для ЛР5 непригоден, failed upgrade не повторяется +отдельно, а спорные длительности track2 исключены из выводов о производительности. + +Неограниченные инфраструктурные redelivery сохраняют сообщение при длительном отказе БД ценой +повторных попыток/записей журнала; постоянные ошибки после claim остаются ограниченными. +Для 16-битного tRNS добавляется маска 1 байт/пиксель и LUT 65536 значений; её пределы требуют Linux-прогона. diff --git a/evidence/review-fixes-2026-11-06/boundaries.txt b/evidence/review-fixes-2026-11-06/boundaries.txt new file mode 100644 index 00000000..6c609b49 --- /dev/null +++ b/evidence/review-fixes-2026-11-06/boundaries.txt @@ -0,0 +1,2 @@ +.................... [100%] +20 passed in 0.15s diff --git a/evidence/review-fixes-2026-11-06/check.txt b/evidence/review-fixes-2026-11-06/check.txt new file mode 100644 index 00000000..9a553306 --- /dev/null +++ b/evidence/review-fixes-2026-11-06/check.txt @@ -0,0 +1,2 @@ +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. diff --git a/evidence/review-fixes-2026-11-06/checks.json b/evidence/review-fixes-2026-11-06/checks.json new file mode 100644 index 00000000..c66930e0 --- /dev/null +++ b/evidence/review-fixes-2026-11-06/checks.json @@ -0,0 +1,55 @@ +{ + "baseline_sha": "544b9c78d39d0e9dd07f841894c390895896605a", + "checks": [ + { + "command": [ + "make", + "check" + ], + "exit_code": 0, + "output": "check.txt" + }, + { + "command": [ + "make", + "validate" + ], + "exit_code": 0, + "output": "validate.txt" + }, + { + "command": [ + "make", + "lint" + ], + "exit_code": 0, + "output": "lint.txt" + }, + { + "command": [ + "openspec", + "validate", + "--all", + "--strict" + ], + "exit_code": 0, + "output": "openspec.txt" + }, + { + "command": [ + "git", + "diff", + "--check" + ], + "exit_code": 0, + "output": "diff.txt" + } + ], + "sha256": { + "src/messenger/attachments/infrastructure/images.py": "987f1e2d638412fcb4062924245314d1f16ffb8f3600c111867a5e21127f8257", + "infra/rabbitmq/definitions.json": "91c430622ed4f4d9c446d9c81b70d1b431fbad87c18b3dedd1feb34454d4b2a8", + "student-tests/unit/test_worker_delivery.py": "3b14dfbc40ca704c67b6f18bba37045dfeab1f45447ec89655e1f260ff33c2d1", + "student-tests/unit/test_renderer.py": "4c70ee4fac2b7430d21682d05e5381b4867f522cec5b764c92c781d9d9e78a92", + "student-tests/adapters/test_rabbitmq.py": "d18b135dc387077d9e165169a1b04050c9241349a7bafc2cd92fdf3227593def" + } +} diff --git a/evidence/review-fixes-2026-11-06/diff.txt b/evidence/review-fixes-2026-11-06/diff.txt new file mode 100644 index 00000000..e69de29b diff --git a/evidence/review-fixes-2026-11-06/findings.json b/evidence/review-fixes-2026-11-06/findings.json new file mode 100644 index 00000000..2d42a030 --- /dev/null +++ b/evidence/review-fixes-2026-11-06/findings.json @@ -0,0 +1,27 @@ +[ + { + "severity": "minor", + "file": "src/messenger/attachments/application/pipeline.py:230", + "problem": "Сохранено из ревью 544b9c78d39d0e9dd07f841894c390895896605a: after_publish_before_confirm вызывается после publish(), уже проверившего Basic.Ack. crash_publish_confirm доказывает сбой после confirm до COMMIT outbox, а не потерю подтверждения." + }, + { + "severity": "minor", + "file": "scripts/limits.py:10", + "problem": "Сохранено из первого ревью: S3_CLIENT_SECRETS не отсортирован, сравнение с sorted(secrets) даёт ложные FAIL. evidence/sqlalchemy-2026-11-06/grade3/limits.txt содержит exit_code=1; этот запуск нельзя обозначать PASS." + }, + { + "severity": "minor", + "file": "scripts/reconcile_track.py:396", + "problem": "Сохранено из первого ревью: демонстратор ожидает upload 201 и attachments/, поэтому непригоден для квалификации ЛР5 с 202 queued. Текущие pipeline evidence его не используют." + }, + { + "severity": "minor", + "file": "src/messenger/attachments/application/pipeline.py:333", + "problem": "Сохранено из первого ревью: failed upgrade v2 при опубликованной ready v1 нельзя отдельно повторить через replay/reprocess. V1 остаётся доступной; подтверждение исходного ревью — test_failed_new_version_keeps_ready_original." + }, + { + "severity": "minor", + "file": "evidence/forward-final-2026-11-06/clock-observation.json", + "problem": "Сохранено из первого ревью: в повторах 2/3 UTC-интервалы расходятся с elapsed (1161.195/186.458 с и 571.513/180.259 с). Причина не установлена; длительности исключены из выводов о производительности." + } +] diff --git a/evidence/review-fixes-2026-11-06/lint.txt b/evidence/review-fixes-2026-11-06/lint.txt new file mode 100644 index 00000000..4f6fd16f --- /dev/null +++ b/evidence/review-fixes-2026-11-06/lint.txt @@ -0,0 +1,6 @@ +.venv/bin/ruff check src student-tests scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py scripts/make_images.py scripts/pipeline_suite.py scripts/pipeline_evidence.py +All checks passed! +.venv/bin/ruff format --check src student-tests scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py scripts/make_images.py scripts/pipeline_suite.py scripts/pipeline_evidence.py +195 files already formatted +.venv/bin/ty check src student-tests alembic +All checks passed! diff --git a/evidence/review-fixes-2026-11-06/openspec.txt b/evidence/review-fixes-2026-11-06/openspec.txt new file mode 100644 index 00000000..0fc7080e --- /dev/null +++ b/evidence/review-fixes-2026-11-06/openspec.txt @@ -0,0 +1,25 @@ +✓ spec/lab1-event-publication +✓ spec/lab1-messenger-chats +✓ spec/lab1-messenger-history +✓ spec/lab1-messenger-identity +✓ spec/lab1-service-operability +✓ spec/lab2-auth-sessions +✓ spec/lab2-dependency-failures +✓ spec/lab2-history-index +✓ spec/lab2-persistent-storage +✓ spec/lab2-session-cache +✓ spec/lab3-failover-operations +✓ spec/lab3-idempotent-messages +✓ spec/lab3-load-balancing +✓ spec/lab4-attachments +✓ spec/lab4-object-storage +✓ spec/lab4-storage-reconciler +✓ spec/lab4-upload-resilience +✓ spec/lab5-attachment-pipeline +✓ change/lab5-critical-review-fixes +✓ spec/lab5-image-variants +✓ spec/lab5-job-delivery +✓ spec/lab5-job-recovery +✓ spec/lab5-versioned-pipeline +Totals: 23 passed, 0 failed (23 items) +- Validating... diff --git a/evidence/review-fixes-2026-11-06/regressions-after.txt b/evidence/review-fixes-2026-11-06/regressions-after.txt new file mode 100644 index 00000000..3965b76f --- /dev/null +++ b/evidence/review-fixes-2026-11-06/regressions-after.txt @@ -0,0 +1,2 @@ +......................................................... [100%] +57 passed in 0.32s diff --git a/evidence/review-fixes-2026-11-06/regressions-before.txt b/evidence/review-fixes-2026-11-06/regressions-before.txt new file mode 100644 index 00000000..cc14b354 --- /dev/null +++ b/evidence/review-fixes-2026-11-06/regressions-before.txt @@ -0,0 +1,73 @@ +...........FFFFFF..FF.........F... [100%] +=================================== FAILURES =================================== +_ test_png_trns_is_white_without_changing_opaque_pixels[RGB-transparent0-opaque0-expected0-1] _ +student-tests/unit/test_renderer.py:119: in test_png_trns_is_white_without_changing_opaque_pixels + assert image.getpixel((5, image.height // 2)) == (255, 255, 255) +E assert (254, 0, 0) == (255, 255, 255) +E +E At index 0 diff: 254 != 255 +E Use -v to get more diff +_ test_png_trns_is_white_without_changing_opaque_pixels[RGB-transparent0-opaque0-expected0-2] _ +student-tests/unit/test_renderer.py:119: in test_png_trns_is_white_without_changing_opaque_pixels + assert image.getpixel((5, image.height // 2)) == (255, 255, 255) +E assert (254, 0, 0) == (255, 255, 255) +E +E At index 0 diff: 254 != 255 +E Use -v to get more diff +__ test_png_trns_is_white_without_changing_opaque_pixels[L-0-96-expected1-1] ___ +student-tests/unit/test_renderer.py:119: in test_png_trns_is_white_without_changing_opaque_pixels + assert image.getpixel((5, image.height // 2)) == (255, 255, 255) +E assert (0, 0, 0) == (255, 255, 255) +E +E At index 0 diff: 0 != 255 +E Use -v to get more diff +__ test_png_trns_is_white_without_changing_opaque_pixels[L-0-96-expected1-2] ___ +student-tests/unit/test_renderer.py:119: in test_png_trns_is_white_without_changing_opaque_pixels + assert image.getpixel((5, image.height // 2)) == (255, 255, 255) +E assert (0, 0, 0) == (255, 255, 255) +E +E At index 0 diff: 0 != 255 +E Use -v to get more diff +__ test_png_trns_is_white_without_changing_opaque_pixels[1-0-255-expected2-1] __ +student-tests/unit/test_renderer.py:119: in test_png_trns_is_white_without_changing_opaque_pixels + assert image.getpixel((5, image.height // 2)) == (255, 255, 255) +E assert (0, 0, 0) == (255, 255, 255) +E +E At index 0 diff: 0 != 255 +E Use -v to get more diff +__ test_png_trns_is_white_without_changing_opaque_pixels[1-0-255-expected2-2] __ +student-tests/unit/test_renderer.py:119: in test_png_trns_is_white_without_changing_opaque_pixels + assert image.getpixel((5, image.height // 2)) == (255, 255, 255) +E assert (0, 0, 0) == (255, 255, 255) +E +E At index 0 diff: 0 != 255 +E Use -v to get more diff +_ test_png_trns_is_white_without_changing_opaque_pixels[I;16-12345-12346-expected4-1] _ +student-tests/unit/test_renderer.py:119: in test_png_trns_is_white_without_changing_opaque_pixels + assert image.getpixel((5, image.height // 2)) == (255, 255, 255) +E assert (48, 48, 48) == (255, 255, 255) +E +E At index 0 diff: 48 != 255 +E Use -v to get more diff +_ test_png_trns_is_white_without_changing_opaque_pixels[I;16-12345-12346-expected4-2] _ +student-tests/unit/test_renderer.py:119: in test_png_trns_is_white_without_changing_opaque_pixels + assert image.getpixel((5, image.height // 2)) == (255, 255, 255) +E assert (48, 48, 48) == (255, 255, 255) +E +E At index 0 diff: 48 != 255 +E Use -v to get more diff +_ test_infrastructure_requeues_preserve_the_message_and_dead_letter_rejections _ +student-tests/unit/test_worker_delivery.py:21: in test_infrastructure_requeues_preserve_the_message_and_dead_letter_rejections + assert policy["definition"]["delivery-limit"] == -1 +E assert 10 == -1 +=========================== short test summary info ============================ +FAILED student-tests/unit/test_renderer.py::test_png_trns_is_white_without_changing_opaque_pixels[RGB-transparent0-opaque0-expected0-1] +FAILED student-tests/unit/test_renderer.py::test_png_trns_is_white_without_changing_opaque_pixels[RGB-transparent0-opaque0-expected0-2] +FAILED student-tests/unit/test_renderer.py::test_png_trns_is_white_without_changing_opaque_pixels[L-0-96-expected1-1] +FAILED student-tests/unit/test_renderer.py::test_png_trns_is_white_without_changing_opaque_pixels[L-0-96-expected1-2] +FAILED student-tests/unit/test_renderer.py::test_png_trns_is_white_without_changing_opaque_pixels[1-0-255-expected2-1] +FAILED student-tests/unit/test_renderer.py::test_png_trns_is_white_without_changing_opaque_pixels[1-0-255-expected2-2] +FAILED student-tests/unit/test_renderer.py::test_png_trns_is_white_without_changing_opaque_pixels[I;16-12345-12346-expected4-1] +FAILED student-tests/unit/test_renderer.py::test_png_trns_is_white_without_changing_opaque_pixels[I;16-12345-12346-expected4-2] +FAILED student-tests/unit/test_worker_delivery.py::test_infrastructure_requeues_preserve_the_message_and_dead_letter_rejections +9 failed, 25 passed in 0.35s diff --git a/evidence/review-fixes-2026-11-06/regressions-fixture-error.txt b/evidence/review-fixes-2026-11-06/regressions-fixture-error.txt new file mode 100644 index 00000000..ee7fbef2 --- /dev/null +++ b/evidence/review-fixes-2026-11-06/regressions-fixture-error.txt @@ -0,0 +1,16 @@ +...................FF.................................... [100%] +=================================== FAILURES =================================== +_ test_png_trns_is_white_without_changing_opaque_pixels[I;16-12345-12346-expected4-1] _ +student-tests/unit/test_renderer.py:122: in test_png_trns_is_white_without_changing_opaque_pixels + assert all(abs(a - b) <= 3 for a, b in zip(pixel, expected, strict=True)) +E assert False +E + where False = all(. at 0x10707d120>) +_ test_png_trns_is_white_without_changing_opaque_pixels[I;16-12345-12346-expected4-2] _ +student-tests/unit/test_renderer.py:122: in test_png_trns_is_white_without_changing_opaque_pixels + assert all(abs(a - b) <= 3 for a, b in zip(pixel, expected, strict=True)) +E assert False +E + where False = all(. at 0x10707e2f0>) +=========================== short test summary info ============================ +FAILED student-tests/unit/test_renderer.py::test_png_trns_is_white_without_changing_opaque_pixels[I;16-12345-12346-expected4-1] +FAILED student-tests/unit/test_renderer.py::test_png_trns_is_white_without_changing_opaque_pixels[I;16-12345-12346-expected4-2] +2 failed, 55 passed in 0.34s diff --git a/evidence/review-fixes-2026-11-06/unchanged-rendering.json b/evidence/review-fixes-2026-11-06/unchanged-rendering.json new file mode 100644 index 00000000..03257967 --- /dev/null +++ b/evidence/review-fixes-2026-11-06/unchanged-rendering.json @@ -0,0 +1,168 @@ +{ + "baseline_sha": "544b9c78d39d0e9dd07f841894c390895896605a", + "result": "PASS", + "cases": [ + { + "fixture": "sample", + "pipeline_version": 1, + "variants": { + "thumbnail": "7bc40bf315c8e18e907889b23514d978be213a44223d64b737290188ee808594", + "crop": "97bf1400b30a28c19420a30161c944f57b5e7d613533b76afe6ab2531cba0143", + "optimized": "1090d84ed8411226010ae498b08e1b9e6d81c8eee02ee77143a0dc327b894beb" + } + }, + { + "fixture": "sample", + "pipeline_version": 2, + "variants": { + "thumbnail": "fa0db661078d4da91b241edc8b416de7755db9c9c79ae704a620ca7ad534e308", + "crop": "5b6fb2a66216f8ca038542acdd8482fca9d1ad79193d60ae74de3989048ec0a4", + "optimized": "fe520c978bd45fc8f1b85863dc9dc6fc98954b45d7fe803e8e4c6b681ddc1957" + } + }, + { + "fixture": "RGB", + "pipeline_version": 1, + "variants": { + "thumbnail": "28b0b092da0f4313332e7f58d2dd6e034c2a38d85c11e25a14e4cc31c7668c36", + "crop": "a7cfd98a348315426838146dbf7fb6cd7ea6fc54f2a1592d56237afe1046f606", + "optimized": "be8caf69fbbf3f646d4740292539d9e0b1de7505e4680c338077e484587160c7" + } + }, + { + "fixture": "RGB", + "pipeline_version": 2, + "variants": { + "thumbnail": "ff097b7c5dafd8b71338e4e4dd24bf3228ee7696e4ef1379f540de74710a5af3", + "crop": "c21b40cfe64d62de988e486561ae8f0deea620908815cdeda9a5a59eea311a02", + "optimized": "fedebf785bddbf2e97e52752bb6c1b21624b6d5b7914d4d110cb483ed4a5d346" + } + }, + { + "fixture": "CMYK", + "pipeline_version": 1, + "variants": { + "thumbnail": "ac5daf302b42a618e045732a586dd4d9945b769c9a8caa94bc2839ccfe298a5b", + "crop": "48d4de523377b98cf270e9345ff04e5c019b0763d0bc94f32611122ff1856fed", + "optimized": "bee9468dbcad822590916056bfa3767c35b897ce60f44499b1f39e67b891b833" + } + }, + { + "fixture": "CMYK", + "pipeline_version": 2, + "variants": { + "thumbnail": "cb3972a0ea283d66bc0b5dfc8feb36281331643f0f3ed9db2d70e8956718dd6c", + "crop": "a8ff9b14ffa3ac3988eda569a39c9a6f7d56a56d509b21cbe972ebab648317da", + "optimized": "ea6f686cd1c2e483931a97ea94ded0c344339609f0d9afcbbdfe157507ae9b0a" + } + }, + { + "fixture": "RGBA", + "pipeline_version": 1, + "variants": { + "thumbnail": "6d7c38650088487bba025b4c98561d4b1c04406bb03c52c4a9184835f69abeef", + "crop": "ef07355eb9b8d8fe466be550c516377ba8a7c5b43609744653db23cb34df8646", + "optimized": "c006b2e2616bbce71269ff932b0a023d8925e733b32e7e222c2595b9cdada473" + } + }, + { + "fixture": "RGBA", + "pipeline_version": 2, + "variants": { + "thumbnail": "9fead8d0bfffdb7a2f68777d357d843f5ab4f2393491e1756badfa68f0120d5b", + "crop": "e5ac07fd10c308b5d314deb893cf0c010de8a934959d576516c8f6323dca0d49", + "optimized": "c3b4f1b532c6689d4f056e020749243d81bd79eae603d0148bafad38c0ba29a0" + } + }, + { + "fixture": "LA", + "pipeline_version": 1, + "variants": { + "thumbnail": "93da2f71167ac8929e41ba5cb354a1fb4564b33010888c7e7e7dfa6f93472640", + "crop": "672dacf96ca8abdcd70664de71bfd0540d26b018d99e216c7e2a0ed994ba19cf", + "optimized": "eeed993fc15f9e6234f7184cd243e09b382884d48ac557016480d28d02877fed" + } + }, + { + "fixture": "LA", + "pipeline_version": 2, + "variants": { + "thumbnail": "94ea37336fe9457bcadfe98333142d37007863c30bc1b261524a856dfe9b9787", + "crop": "854e3d20ab31d217525ae5997144e0b498cef1fc22bca3707dbc74cdd3343dbf", + "optimized": "dd0af1c14848abf14e41b364eb576615b88da373734ef44c6446ce12431833c3" + } + }, + { + "fixture": "P", + "pipeline_version": 1, + "variants": { + "thumbnail": "cdadbef863c5819a1bd7a03bb67c8fa22be4b26fe3709fb66006429459585e41", + "crop": "4fb3b365a5278998ed1e11afc2d4d5deca2c06ebd5c45b28eaeebb56619343b4", + "optimized": "292ee17f29c203733ba10623a751d1a786befeb84dd8d53c48b30b1964dc58df" + } + }, + { + "fixture": "P", + "pipeline_version": 2, + "variants": { + "thumbnail": "96ea77f747af17185f3b8ff64c0d4280df4130c5b64f7ed6af18b56ab6c97409", + "crop": "4703e8731b7d52cf95d7e6db1ba2c000aa9a0f9aa3b851b31a24a7be4bcf7281", + "optimized": "4126871c04e218d2219b8db7a1aa1f650fcb0869d563d8dc8b2170369002b1a0" + } + }, + { + "fixture": "L", + "pipeline_version": 1, + "variants": { + "thumbnail": "97670517bb36708901f9ed484ea66c5637597059871f73508233e44911e0f0c8", + "crop": "fbbf2c3d52ac9797b96cae8185591d5eeee051c0294c4b2a2654cde711499b36", + "optimized": "ce9bf66572832bc634564343e604866518dd665c86c9fbe079943db1de717840" + } + }, + { + "fixture": "L", + "pipeline_version": 2, + "variants": { + "thumbnail": "5dcd5590c17fb7f2eb647f17bcdeb510c97dfe56bb1ccfb2264fcb4646475848", + "crop": "792f7709fa29acd44ead9a90322fa6c14e344105f4db4b5f8744cfaf33eaf51e", + "optimized": "0ebefcaf44fb7fc0b330a34826a419fc7fbc88a15ba805873b4fdf6fa1e662b8" + } + }, + { + "fixture": "I;16", + "pipeline_version": 1, + "variants": { + "thumbnail": "59472ec8f914eb4502ffd2591a59ac68b05cccefeedc678f5ad2919cd2c6a3a2", + "crop": "91eed7d7e1f422bfc3827903cc6801a37387d642a1b4fcc08e23b2de4840a3d7", + "optimized": "43938a0dc7ba6e835d20c40b8293309b3bad9677eba406cf77b8011f8dcd2b63" + } + }, + { + "fixture": "I;16", + "pipeline_version": 2, + "variants": { + "thumbnail": "13ea6ae5bd526b8b0ad4e88ff72498ff48c6d50f8d12e81ad6773a1eaa9fc177", + "crop": "2d5dbe60802e4aa1c3ff20c112df454c70a12e2c9fccc99137802a5556e270bf", + "optimized": "25badf5c956bd1f36fc4ce2fdfff541e03191c12a54eab6f4d9be6942fd69053" + } + }, + { + "fixture": "P-transparent", + "pipeline_version": 1, + "variants": { + "thumbnail": "85e14fe759886d5d9585503889ce2838048fa6c00157c8f8aa179d2253d13dc2", + "crop": "1b88218fd7e3ff00d6fa3e4bb732411617126591b2b6837aecdcaef426327eda", + "optimized": "c460bd3f650faca539921742e03810591f2c81179eb3d46313a21c6ea7884448" + } + }, + { + "fixture": "P-transparent", + "pipeline_version": 2, + "variants": { + "thumbnail": "f83468520aba20e724ed58d892a3d17882f3323f1be94eef371193d200812f9e", + "crop": "45eac1bd54dba273142a01a3f01a1530787db5a9fe04aa2483862256dbf16132", + "optimized": "b52d93eeb4ae525d61a463bce9a00ccd554de0e9519b1e1e122afe47a3a4def5" + } + } + ] +} diff --git a/evidence/review-fixes-2026-11-06/validate.txt b/evidence/review-fixes-2026-11-06/validate.txt new file mode 100644 index 00000000..37e81884 --- /dev/null +++ b/evidence/review-fixes-2026-11-06/validate.txt @@ -0,0 +1,2 @@ +.venv/bin/python scripts/validate_openapi.py +PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. diff --git a/infra/rabbitmq/definitions.json b/infra/rabbitmq/definitions.json index c4f9ec1b..1cf04607 100644 --- a/infra/rabbitmq/definitions.json +++ b/infra/rabbitmq/definitions.json @@ -26,7 +26,7 @@ "dead-letter-exchange": "attachments.dlx", "dead-letter-strategy": "at-least-once", "overflow": "reject-publish", - "delivery-limit": 10 + "delivery-limit": -1 } }, { diff --git a/openspec/changes/lab5-critical-review-fixes/tasks.md b/openspec/changes/lab5-critical-review-fixes/tasks.md index 80292673..ffa83748 100644 --- a/openspec/changes/lab5-critical-review-fixes/tasks.md +++ b/openspec/changes/lab5-critical-review-fixes/tasks.md @@ -1,15 +1,15 @@ ## 1. Доставка уровня «3» -- [ ] 1.1 Изменить политику рабочей очереди для инфраструктурных повторов, сохранив DLX и конечные application retries. -- [ ] 1.2 Добавить offline-регрессию consumer и политики; расширить реальный RabbitMQ-тест до 12 ошибок, не запуская Docker. Проверить offline consumer через pytest. +- [x] 1.1 Изменить политику рабочей очереди для инфраструктурных повторов, сохранив DLX и конечные application retries. +- [x] 1.2 Добавить offline-регрессию consumer и политики; расширить реальный RabbitMQ-тест до 12 ошибок, не запуская Docker. Проверить offline consumer через pytest. ## 2. Прозрачность вариантов уровней «3»/«4» и версий трека «5» -- [ ] 2.1 Исправить tRNS в Pillow до композиции на белый фон, сохранив непрозрачные оттенки. -- [ ] 2.2 Добавить и выполнить offline-регрессии всех вариантов v1/v2 для RGB/L/1/16-bit PNG, а также прежние renderer/domain тесты. +- [x] 2.1 Исправить tRNS в Pillow до композиции на белый фон, сохранив непрозрачные оттенки. +- [x] 2.2 Добавить и выполнить offline-регрессии всех вариантов v1/v2 для RGB/L/1/16-bit PNG, а также прежние renderer/domain тесты. ## 3. Проверки и передача -- [ ] 3.1 Выполнить make check, make validate, make lint и строгую валидацию OpenSpec; сохранить реальные результаты offline-проверок. -- [ ] 3.2 Зафиксировать обязательные динамические проверки для финального агента и прежние minor для отчёта; не объявлять их исправленными или проверенными. +- [x] 3.1 Выполнить make check, make validate, make lint и строгую валидацию OpenSpec; сохранить реальные результаты offline-проверок. +- [x] 3.2 Зафиксировать обязательные динамические проверки для финального агента и прежние minor для отчёта; не объявлять их исправленными или проверенными. - [ ] 3.3 Синхронизировать specs и архивировать завершённый цикл с датой и lab: 5; проверить отсутствие активного change. diff --git a/src/messenger/attachments/infrastructure/images.py b/src/messenger/attachments/infrastructure/images.py index 2141ea6f..81d40e65 100644 --- a/src/messenger/attachments/infrastructure/images.py +++ b/src/messenger/attachments/infrastructure/images.py @@ -88,10 +88,13 @@ class PillowImageInspector: def flatten(image: Image.Image) -> Image.Image: if image.mode in WIDE_MODES: - image = image.convert("I").point(lambda value: value / 256, "L") - if image.mode == "P": - image = image.convert("RGBA" if "transparency" in image.info else "RGB") - if image.mode in ALPHA_MODES: + image = image.convert("I") + if (transparent := image.info.pop("transparency", None)) is not None: + mask = [0] * 65536 + mask[transparent] = 255 + image.paste(65535, mask=image.point(mask, "L")) + image = image.point(lambda value: value / 256, "L") + if image.mode in ALPHA_MODES or "transparency" in image.info: image = image.convert("RGBA") if image.mode == "RGBA": background = Image.new("RGB", image.size, "white") diff --git a/student-tests/adapters/test_rabbitmq.py b/student-tests/adapters/test_rabbitmq.py index 5f24a3d5..ecbf5159 100644 --- a/student-tests/adapters/test_rabbitmq.py +++ b/student-tests/adapters/test_rabbitmq.py @@ -242,14 +242,20 @@ async def test_message_off_the_schema_goes_to_the_dead_letter_queue( assert depth(rabbitmq, "attachments.process") == 0 -async def test_failed_processing_is_requeued_and_retried(rabbitmq: dict[str, Any]) -> None: +@pytest.mark.parametrize("failures", [1, 12]) +async def test_failed_processing_is_requeued_and_retried( + rabbitmq: dict[str, Any], failures: int +) -> None: recorder, sent = Recorder(), job() - recorder.failures = 1 + recorder.failures = failures + before = depth(rabbitmq, "attachments.process.dlq") async with publisher(rabbitmq) as jobs: await jobs.publish(sent.id, body(sent.payload())) async with worker(rabbitmq, recorder): - await wait_for(lambda: recorder.jobs) + await wait_for(lambda: recorder.jobs, seconds=40) + await wait_for(lambda: depth(rabbitmq, "attachments.process") == 0) assert recorder.jobs == [sent] + assert depth(rabbitmq, "attachments.process.dlq") == before async def test_worker_account_cannot_publish(rabbitmq: dict[str, Any]) -> None: diff --git a/student-tests/unit/test_renderer.py b/student-tests/unit/test_renderer.py index c7367ae0..cfb4190d 100644 --- a/student-tests/unit/test_renderer.py +++ b/student-tests/unit/test_renderer.py @@ -5,7 +5,12 @@ from PIL import Image from messenger.attachments.application.ports import Rendition from messenger.attachments.domain.errors import ImageTooDemanding, UnreadableImage -from messenger.attachments.infrastructure.images import RenderLimits, render_variants +from messenger.attachments.domain.values import ImageKind +from messenger.attachments.infrastructure.images import ( + PillowImageInspector, + RenderLimits, + render_variants, +) from pictures import SAMPLE LIMITS = RenderLimits(max_bytes=10_485_760, max_pixels=40_000_000) @@ -22,8 +27,8 @@ def encoded(image: Image.Image, kind: str = "PNG", **options: object) -> bytes: return buffer.getvalue() -def rendered(data: bytes) -> dict[str, Image.Image]: - renditions: list[Rendition] = render_variants(data, LIMITS) +def rendered(data: bytes, version: int = 1) -> dict[str, Image.Image]: + renditions: list[Rendition] = render_variants(data, LIMITS, version) assert [rendition.name for rendition in renditions] == ["thumbnail", "crop", "optimized"] images = {} for rendition in renditions: @@ -87,6 +92,37 @@ def test_palette_transparency_is_composed_on_white() -> None: assert image.convert("RGB").getpixel((5, 5)) == (255, 255, 255) +@pytest.mark.parametrize("version", [1, 2]) +@pytest.mark.parametrize( + ("mode", "transparent", "opaque", "expected"), + [ + ("RGB", (255, 0, 0), (32, 96, 160), (32, 96, 160)), + ("L", 0, 96, (96, 96, 96)), + ("1", 0, 255, (255, 255, 255)), + ("1", 255, 0, (0, 0, 0)), + ("I;16", 12345, 12346, (48, 48, 48)), + ], +) +async def test_png_trns_is_white_without_changing_opaque_pixels( + version: int, + mode: str, + transparent: int | tuple[int, int, int], + opaque: int | tuple[int, int, int], + expected: tuple[int, int, int], +) -> None: + source = Image.new(mode, (64, 64), transparent) + source.paste(Image.new(mode, (32, 64), opaque), (32, 0)) + assert source.getpixel((58, 32)) == opaque + data = encoded(source, transparency=transparent) + info = await PillowImageInspector(LIMITS.max_pixels, 1).inspect(data, ImageKind.PNG) + assert (info.width, info.height) == (64, 64) + for image in rendered(data, version).values(): + assert image.getpixel((5, image.height // 2)) == (255, 255, 255) + pixel = image.getpixel((image.width - 6, image.height // 2)) + assert isinstance(pixel, tuple) + assert all(abs(a - b) <= 3 for a, b in zip(pixel, expected, strict=True)) + + @pytest.mark.parametrize( ("orientation", "thumbnail", "optimized"), [(6, (128, 256), (200, 400)), (3, (256, 128), (400, 200))], diff --git a/student-tests/unit/test_worker_delivery.py b/student-tests/unit/test_worker_delivery.py new file mode 100644 index 00000000..86eb8292 --- /dev/null +++ b/student-tests/unit/test_worker_delivery.py @@ -0,0 +1,63 @@ +import asyncio +import json +from datetime import UTC, datetime +from pathlib import Path +from unittest.mock import AsyncMock, Mock, call +from uuid import uuid4 + +import pytest + +from messenger.attachments.application.commands import ProcessJob +from messenger.attachments.domain.jobs import Job, Outcome +from messenger.attachments.entrypoints.worker import REQUEUE_DELAY_SECONDS, handle_job +from messenger.shared.application.errors import Unavailable + + +def test_infrastructure_requeues_preserve_the_message_and_dead_letter_rejections() -> None: + path = Path(__file__).resolve().parents[2] / "infra/rabbitmq/definitions.json" + definitions = json.loads(path.read_text()) + policy = next(p for p in definitions["policies"] if p["name"] == "attachments-process") + queue = next(q for q in definitions["queues"] if q["name"] == "attachments.process") + assert policy["definition"]["delivery-limit"] == -1 + assert "x-delivery-limit" not in queue["arguments"] + assert policy["definition"]["dead-letter-exchange"] == "attachments.dlx" + assert policy["definition"]["dead-letter-strategy"] == "at-least-once" + + +async def test_database_outage_never_acks_and_recovery_keeps_job_and_attempt( + monkeypatch: pytest.MonkeyPatch, +) -> None: + job = Job(uuid4(), uuid4(), 1, 1, datetime.now(UTC)) + message = AsyncMock(body=json.dumps(job.payload()).encode()) + bus, logger, sleep = AsyncMock(), Mock(), AsyncMock() + monkeypatch.setattr("messenger.attachments.entrypoints.worker.asyncio.sleep", sleep) + bus.execute.side_effect = [Unavailable("database unavailable")] * 12 + [Outcome.DONE] + for _ in range(12): + await handle_job(message, bus, logger) + message.ack.assert_not_awaited() + message.reject.assert_not_awaited() + assert message.nack.await_args_list == [call(requeue=True)] * 12 + assert sleep.await_args_list == [call(REQUEUE_DELAY_SECONDS)] * 12 + await handle_job(message, bus, logger) + message.ack.assert_awaited_once_with() + assert bus.execute.await_args_list == [call(ProcessJob(job))] * 13 + + +async def test_invalid_message_is_dead_lettered_without_calling_the_bus() -> None: + message, bus = AsyncMock(body=b"{}"), AsyncMock() + await handle_job(message, bus, Mock()) + message.reject.assert_awaited_once_with(requeue=False) + message.ack.assert_not_awaited() + message.nack.assert_not_awaited() + bus.execute.assert_not_awaited() + + +async def test_cancelled_handler_leaves_delivery_unacknowledged() -> None: + job = Job(uuid4(), uuid4(), 1, 1, datetime.now(UTC)) + message, bus = AsyncMock(body=json.dumps(job.payload()).encode()), AsyncMock() + bus.execute.side_effect = asyncio.CancelledError + with pytest.raises(asyncio.CancelledError): + await handle_job(message, bus, Mock()) + message.ack.assert_not_awaited() + message.nack.assert_not_awaited() + message.reject.assert_not_awaited()