ЛР5: закрыть review края broker, staging replay и полной валидации изображений

This commit is contained in:
2026-11-06 20:19:50 +03:00
parent 7f51c6ac3b
commit 0487d685ec
28 changed files with 2131 additions and 113 deletions
+17 -11
View File
@@ -43,15 +43,17 @@ PostgreSQL — источник истины: users/chats/members/messages/sessi
Dispatcher XADD → mark published в транзакции. Crash между этими действиями даёт допустимый дубль. При AOF always XADD-ответ — наша граница приёма брокером, XACK — подтверждение обработки уведомления после устойчивого результата/сохранённого следующего состояния.
Broker envelope ограничен8KiB UTF-8 bytes; глубокий/слишком большой JSON и неканонический UUID URN безопасно отклоняются доSQL, uppercase канонические UUID нормализуются. JSON HTTP routes принимают UTF-8, UTF-16/32 не проходят даже при автодетекте Python. Binaryupload не затронут.
Worker атомарно записывает processing, attempt, случайный lease_id и deadline. Истёкший lease восстанавливает dispatcher. Ready публикуется лишь после всех четырёх объектов и проверки актуальных state/lease_id/pipeline_version под row locks. Ключ эффекта `(attachment_id,pipeline_version,variant)`, S3 prefix серверный и versioned. Дубликат ready — no-op; старая версия не меняет новое состояние. **At-least-once доставка с идемпотентным эффектом не означает exactly-once доставку.**
Временные ошибки: backoff1/2/4/8… максимум30s + jitter0–0.5s, по умолчанию JOB_MAX_ATTEMPTS=5. Постоянная ошибка — failed сразу, исчерпание — retry_exhausted. Failed_jobs и job_audit дают реестр ошибок и историю replay. Replay разрешён только failed с существующим источником, добавляет ограниченный budget и сохраняет job_id. Обычный pipeline1 использует WebP quality80; операторская версия2 — quality75. Reprocess queued выбирает staging, ready — опубликованный original; отсутствующий источник даёт отказ до изменения состояния.
Временные ошибки: backoff1/2/4/8… максимум30s + jitter0–0.5s, по умолчанию JOB_MAX_ATTEMPTS=5. Постоянная ошибка — failed сразу, исчерпание — retry_exhausted. Failed_jobs и job_audit дают реестр ошибок и историю replay. Replay разрешён только failed с существующим источником, добавляет ограниченный budget и сохраняет job_id. Обычный pipeline1 использует WebP quality80; операторская версия2 — quality75. Reprocess queued выбирает staging, ready — опубликованный original; отсутствующий источник даёт отказ до изменения состояния. Если worker ещё не очистил прежний staging после COMMITready, reprocess удаляет его под тем же attachmentlock перед заменой ссылки; ошибка DELETE откатывает смену версии и сохраняет ready-original.
Сессии/пароли/ACL и идемпотентность сообщений предыдущих лаб сохранены. SHA256 digest случайного256-bit токена и абсолютное expiry находятся в PostgreSQL, пароли Argon2id. GET/content проверяют сессию и членство; queued/processing/failed content409. Original скачивается побайтно через API без redirect. Private bucket и отдельная backend-сеть, app S3 credentials ограничены bucket, admin только bootstrap.
## Изображения, ресурсы и очистка
- PNG/JPEG, max10MiB, max40Mpixel до decode, полная проверка PNG IDAT/JPEG. Дополнительный djpeg-strict с timeout5s отклоняет предупреждения libjpeg, включая half-scan с поддельным EOI.
- PNG/JPEG, max10MiB, max40Mpixel до decode, полная проверка PNG IDAT/JPEG. Полная проверка проходит в короткоживущем процессе: wall5s, CPU4s, LinuxAS512MiB. Строгий djpeg384m проверяет JPEG один раз без одновременного полного Pillow-canvas. PNG/APNG декодируется покадрово, общий canvasbudget40M; rawacTL/число кадров проверены, invalidlaterframe/zerocount→415, cumulativeoverlimit→413. У APNG производные берутся по первому кадру, а перед приёмом проверяются все кадры. Parent убивает всю processgroup при timeout/nonzero и не передаёт credentials в child environment.
- Один upload на API-процесс, excess429; чтение тела ограничено15s.
- Отдельный serial worker, prefetch/count1. Child processing: wall20s, CPU15s, address space700MiB. Worker896MiB/1CPU, tmpfs32MiB; crash/OOM оставляет durable source для bounded recovery. Обычный lease45s, fault-overlay8s.
- Thumbnail JPEG quality85, fit256 без upscale и с floor/min1; EXIF orientation, alpha на белый. Crop JPEG128×128 центрированный с допустимым upscale. WebP fit1280 без upscale, method4, quality80/75; производные без EXIF/ICC. Не обещается уменьшение каждого исходника.
@@ -81,23 +83,25 @@ uv run --locked python research/pixel_boundary.py
| Критерий | Проверка | Evidence |
|---|---|---|
| Контракт/smoke | make check validate; make test | checks-final.txt; smoke-final.txt |
| Собственные API/session/image tests | make student-test | tests-final.txt |
| Контракт/smoke | make check validate; make test | checks-review-final.txt; smoke-review-final.txt |
| Собственные API/session/image tests | make student-test | tests-review-final.txt |
| Независимые81HTTP-проверки | Отдельный root-драйвер | independent-http.json |
| Полный restart, прежний токен и original | make test-persistence | persistence-final.txt; persistence-runtime.json |
| API failover через общий LB | make test-failover | failover-final.json |
| Worker absent202, API/broker restart | Fault-suite | fault-study.json |
| COMMIT/publish, XADD/mark gap | Настоящий exit API/dispatcher | fault-study.json |
| Crash до/послеS3 и послеCOMMIT доack | Настоящий exit worker, lease recovery | fault-study.json |
| 20duplicates, queuedv2, stalev1afterv2 | Реальные broker и S3 | fault-study.json |
| Worker absent202, API/broker restart | Fault-suite | fault-study-review.json |
| COMMIT/publish, XADD/mark gap | Настоящий exit API/dispatcher | fault-study-review.json |
| Crash до/послеS3 и послеCOMMIT доack | Настоящий exit worker, lease recovery | fault-study-review.json |
| 20duplicates, queuedv2, stalev1afterv2 | Реальные broker и S3 | fault-study-review.json |
| Backoff, broker reorder, concurrentcleanup/replay | Дополнительный fault-driver | extra-invariants.json |
| Законные40M RGB/RGBA под лимитами | HTTP→worker→ready | pixel-boundary.json |
Итог локальной проверки: **133 собственных теста PASS за35,94s**, smoke/contract/schema/lint PASS. Основное исследование: **11 сценариев PASS за118.877s**; дополнительно **6 инвариантов PASS**: backoff, reorder, malformed deliveries, aged queued staging и два concurrentcleanup/replay. Два физических API проверены в 3 failover-прогонах. Все используемые хранилища реально перезапущены, volumes совпали; прежний токен и original сохранены. LB при отсутствии API возвращает JSON503 с matchingRequestId и без поддельногоInstanceId.
Итог повторной проверки перед публикацией: **179 собственных тестов PASS за52,52s**, smoke/contract/schema/lint PASS. Повторное основное исследование: **11 сценариев PASS за118.347s**; **9 дополнительных инвариантов PASS**. Среди новых регрессий:9 malformedbroker deliveries без workerrestart; единственное uppercaseUUID уведомление доводит queued job доready; реальный S3DELETEoutage сохраняет readyv1, последующий reprocessv2 и поздний cleanup не оставляют старый staging и не меняют v2content.
Граница40Mpixel достиглаready: RGB 1.8s, RGBA 1.98s, OOM=false под заданными лимитами; это не peakRSS и не SLA. Полное содержимое и времена доступны в evidence/.
Повторно проверены публичные замечания преподавателей, новых/изменённых в использованном снимке нет. Дополнительно исправлены обнаруженные собственным review глубокий JSON poison, UUID wire spelling и окно staging cleanup/reprocess. Валидные RGB36M/CMYK40M progressiveJPEG и APNG40M теперь проходят доready с побайтно неизменным original; invalidlaterframe, acTL0 и превышение суммарного canvasbudget отклоняются до202.
После fault-опыта ужесточён общий парсер cursor (ISOweek/basicISO/неверные даты →400); pipeline/outbox/storage-модули побайтно совпадают с испытанным образом. [Проверка runtime-source](evidence/runtime-source.json) сопоставляет реальные container bytes с репозиторием и fault-image. Все133теста выполнены на окончательном образе. PASS не выставляет оценку автоматически.
Последний отдельный RGB/RGBA40M прогон дал ready за 2.028s/2.265s, OOM=false; это не peakRSS и не SLA. Lifecycle ранее подтвердил реальный restart всех используемых хранилищ с прежним токеном и отказ обеих физических API; результаты сохранены и независимый cleanclone повторяет эти проверки.
Актуальное состояние source сверено с двумя API: [review-runtime-source.json](evidence/review-runtime-source.json). Повторные11+9 faultсценариев выполнялись после worker/jobs/UTF-8/shareddecoderfixes; затем изменились только общие failureguards validate_image (killpg/outputtype), проверенные окончательными179тестами и большими изображениями. Полное совпадение старого faultimage с финальным образом не заявляется. PASS не выставляет оценку автоматически.
## Ограничения
@@ -108,3 +112,5 @@ uv run --locked python research/pixel_boundary.py
## Источники
Исходные contracts/README.md, attachment-states.md, jobs.schema.json; [Valkey persistence](https://valkey.io/topics/persistence/), [PostgreSQL transactions](https://www.postgresql.org/docs/17/tutorial-transactions.html), [Pillow ImageOps](https://pillow.readthedocs.io/en/stable/reference/ImageOps.html). Замечания со ссылками — REVIEW_CHECKLIST.md.
Дополнительно после позднего worker/cleanup сверены фактические S3bytes всех четырёх результатов с SHA/size: [reprocess-content-review.json](evidence/reprocess-content-review.json). Финальный общий валидатор совпадает с проверенным ЛР4 по ASTwrapper и байтам childmodule: [shared-validator-review.json](evidence/shared-validator-review.json).
+15
View File
@@ -46,3 +46,18 @@
- Новая версия queued использует staging, ready — опубликованный оригинал.
- Размеры thumbnail рассчитываются явно с floor: 319×200 → 256×160.
- Старый worker не публикует метаданные поверх новой версии.
## Повторная проверка перед публикацией
Повторно прочитаны те же публичные замечания преподавателей; в обновлённом снимке новых или изменённых замечаний по ЛР5 не обнаружено. Отсутствие комментариев к другим PR не используется как доказательство корректности.
При повторном независимом разборе дополнительно найдены и покрываются регрессиями:
- Глубокий/слишком большой broker JSON: ограничение UTF-8 envelope до8KiB и безопасное отклонение RecursionError.
- Необычное написание UUID: URN отклоняется доSQL, канонические uppercaseUUID нормализуются, единственное такое уведомление должно завершить queued job.
- Окно ready COMMIT → reprocess → старый cleanup: прежний staging удаляется под attachment lock перед заменой ссылки. Ошибка S3 DELETE оставляет текущую ready-версию неизменной.
- Валидный большой progressive JPEG не должен ошибочно считаться повреждённым из-за малого decoderbudget; native decode выполняется до полной Pillow canvasallocation.
- У PNG/APNG проверяется содержимое всех кадров и общий pixelbudget, повреждение позднего кадра не переносится в asynchronous failed после202.
- JSON-запросы принимаются только в UTF-8, несмотря на автоматическое распознавание UTF-16/32 в json.loads(bytes); binaryupload исключён из этого guard.
Точные результаты повторного запуска находятся в evidence/ и REPORT.md.
+71
View File
@@ -0,0 +1,71 @@
Image mtusi-vasilev:lab5 Building
#1 [internal] load local bake definitions
#1 reading from stdin 1.78kB done
#1 DONE 0.0s
#2 [internal] load build definition from Dockerfile
#2 transferring dockerfile: 1.07kB done
#2 DONE 0.0s
#3 [internal] load metadata for docker.io/library/python:3.12-slim@sha256:646fb0bca3dd3ea1bcc6feb72c17ed16eed6e10cffc732fcc1478bd3e7f02d7b
#3 DONE 0.0s
#4 [internal] load metadata for ghcr.io/astral-sh/uv:0.11.7
#4 DONE 0.0s
#5 [internal] load .dockerignore
#5 transferring context: 109B done
#5 DONE 0.0s
#6 [internal] load build context
#6 transferring context: 9.13kB done
#6 DONE 0.0s
#7 [build 1/5] FROM docker.io/library/python:3.12-slim@sha256:646fb0bca3dd3ea1bcc6feb72c17ed16eed6e10cffc732fcc1478bd3e7f02d7b
#7 resolve docker.io/library/python:3.12-slim@sha256:646fb0bca3dd3ea1bcc6feb72c17ed16eed6e10cffc732fcc1478bd3e7f02d7b done
#7 DONE 0.0s
#8 FROM ghcr.io/astral-sh/uv:0.11.7@sha256:240fb85ab0f263ef12f492d8476aa3a2e4e1e333f7d67fbdd923d00a506a516a
#8 resolve ghcr.io/astral-sh/uv:0.11.7@sha256:240fb85ab0f263ef12f492d8476aa3a2e4e1e333f7d67fbdd923d00a506a516a done
#8 DONE 0.0s
#9 [build 4/5] COPY pyproject.toml uv.lock ./
#9 CACHED
#10 [build 5/5] RUN uv sync --locked --no-dev --no-install-project --python /usr/local/bin/python
#10 CACHED
#11 [build 2/5] COPY --from=ghcr.io/astral-sh/uv:0.11.7 /uv /usr/local/bin/uv
#11 CACHED
#12 [build 3/5] WORKDIR /app
#12 CACHED
#13 [stage-1 3/6] WORKDIR /app
#13 CACHED
#14 [stage-1 2/6] RUN apt-get update && apt-get install -y --no-install-recommends libjpeg-turbo-progs=1:2.1.5-4 && rm -rf /var/lib/apt/lists/*
#14 CACHED
#15 [stage-1 4/6] COPY --from=build /app/.venv /app/.venv
#15 CACHED
#16 [stage-1 5/6] COPY src ./src
#16 DONE 0.0s
#17 [stage-1 6/6] COPY migrations ./migrations
#17 DONE 0.0s
#18 exporting to image
#18 exporting layers 0.0s done
#18 exporting manifest sha256:80ca299ae587b0ba967dd5b369852979a0f3f85dedbd55e38975ad3ad7ed2d24 done
#18 exporting config sha256:054b14251aab3f4b20e3d7139b8f22069bc1e4cab496457808da369b93ed075e done
#18 exporting attestation manifest sha256:520746f9a2893a44cff00d637b6859b3af44e31bae016b6a144e227c9c944d02 done
#18 exporting manifest list sha256:2a43094d66f44278456a1dd4b487da97287bc3935715b2b6a36535d60fb0b7d2 done
#18 naming to docker.io/library/mtusi-vasilev:lab5 done
#18 unpacking to docker.io/library/mtusi-vasilev:lab5 0.0s done
#18 DONE 0.1s
#19 resolving provenance for metadata file
#19 DONE 0.0s
Image mtusi-vasilev:lab5 Built
+4
View File
@@ -0,0 +1,4 @@
.venv/bin/python scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
.venv/bin/python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
+1
View File
@@ -0,0 +1 @@
PASS: backoff, reordered deliveries and both real cleanup/replay interleavings
+42 -21
View File
@@ -2,54 +2,54 @@
"scenarios": [
{
"name": "transient_retry_backoff_and_jitter",
"attachment_id": "3c819120-fb7c-45cc-9679-10ba0cacc003",
"attachment_id": "4d09ac73-dc77-4013-8368-c70947aac8b0",
"attempts": 3,
"observed_delays_seconds": [
1.256841,
2.218222
1.362641,
2.457416
],
"audit": [
{
"event": "accepted",
"attempt": 0,
"created_at": "2026-11-06T15:24:22.695787+00:00"
"created_at": "2026-11-06T16:10:48.759366+00:00"
},
{
"event": "claimed",
"attempt": 1,
"created_at": "2026-11-06T15:24:25.424362+00:00"
"created_at": "2026-11-06T16:10:51.436905+00:00"
},
{
"event": "retry_scheduled",
"attempt": 1,
"created_at": "2026-11-06T15:24:25.427909+00:00"
"created_at": "2026-11-06T16:10:51.440694+00:00"
},
{
"event": "claimed",
"attempt": 2,
"created_at": "2026-11-06T15:24:26.68475+00:00"
"created_at": "2026-11-06T16:10:52.803335+00:00"
},
{
"event": "retry_scheduled",
"attempt": 2,
"created_at": "2026-11-06T15:24:26.686074+00:00"
"created_at": "2026-11-06T16:10:52.816466+00:00"
},
{
"event": "claimed",
"attempt": 3,
"created_at": "2026-11-06T15:24:28.904296+00:00"
"created_at": "2026-11-06T16:10:55.273882+00:00"
},
{
"event": "published",
"attempt": 3,
"created_at": "2026-11-06T15:24:29.140377+00:00"
"created_at": "2026-11-06T16:10:55.520881+00:00"
}
],
"passed": true
},
{
"name": "broker_reorder_v2_v1_v2_no_regression",
"attachment_id": "3c819120-fb7c-45cc-9679-10ba0cacc003",
"attachment_id": "4d09ac73-dc77-4013-8368-c70947aac8b0",
"hashes": {
"original": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75",
"thumbnail": "b8e59b0cad429b1c49c27c4a1c79e52bfc23e2fab7c7238d18d5addd4df4b546",
@@ -69,43 +69,64 @@
"passed": true
},
{
"name": "six_poison_deliveries_rejected_without_worker_crash",
"attachment_id": "003a05f4-deb7-4253-b1d3-e3e678b64805",
"name": "nine_poison_deliveries_rejected_without_worker_crash",
"attachment_id": "12e51a70-4159-458c-8733-1eed92f40881",
"worker_before": {
"container_id": "de14445337ceb4b4e8df21155fc0c17a1546a04b891972bd8cdd53cdd7fe9e5c",
"container_id": "99d4d3aad44e120d24df5ae652a4aa731de31c1e4a8580f0c05409cbaab2e0a2",
"service": "worker",
"restart_count": 0,
"status": "running",
"exit_code": 0,
"started_at": "2026-11-06T15:24:24.553835426Z"
"started_at": "2026-11-06T16:10:50.624298554Z"
},
"worker_after": {
"container_id": "de14445337ceb4b4e8df21155fc0c17a1546a04b891972bd8cdd53cdd7fe9e5c",
"container_id": "99d4d3aad44e120d24df5ae652a4aa731de31c1e4a8580f0c05409cbaab2e0a2",
"service": "worker",
"restart_count": 0,
"status": "running",
"exit_code": 0,
"started_at": "2026-11-06T15:24:24.553835426Z"
"started_at": "2026-11-06T16:10:50.624298554Z"
},
"safe_log_events": 6,
"safe_log_events": 9,
"passed": true
},
{
"name": "uppercase_uuid_only_delivery_completes_queued_job",
"attachment_id": "24644ea4-c70f-447e-9bcf-fec51f495dd4",
"no_lowercase_publication": true,
"attempts": 1,
"passed": true
},
{
"name": "reprocess_staging_delete_outage_keeps_ready_version1",
"attachment_id": "a7724afb-9c2f-439f-a319-4270c426601f",
"reprocess_error": 503,
"source_and_final_content_intact": true,
"passed": true
},
{
"name": "ready_reprocess_before_old_cleanup_does_not_orphan_staging",
"attachment_id": "a7724afb-9c2f-439f-a319-4270c426601f",
"old_staging_absent": true,
"version2_metadata_and_content_unchanged": true,
"passed": true
},
{
"name": "eight_day_old_queued_metadata_never_expires_staging",
"attachment_id": "0fa10c93-7835-4078-9c4c-22045a840609",
"attachment_id": "e409c3ed-b6d5-491c-8f7b-006383119273",
"age_simulated_in_database": true,
"passed": true
},
{
"name": "cleanup_paused_before_delete_blocks_concurrent_replay",
"attachment_id": "66f6976c-1152-4b19-8274-ec25090d58c5",
"attachment_id": "08982860-9c59-44cb-a327-f5e9ce0e8858",
"while_locked_status": 503,
"after_source_expiry_status": 409,
"passed": true
},
{
"name": "replay_holds_lock_cleanup_cannot_delete_then_ready",
"attachment_id": "c84c5f9b-007c-45c0-b0c1-be9700968c04",
"attachment_id": "887b7e3b-0f3f-49e1-8862-afe822518407",
"cleanup_while_locked_status": 503,
"passed": true
}
+12
View File
@@ -0,0 +1,12 @@
PASS: accepted_202_worker_absent_api_broker_restart
PASS: api_crash_after_commit_before_publish
PASS: dispatcher_crash_after_broker_acceptance
PASS: worker_crash_before_effect
PASS: worker_crash_after_effect
PASS: worker_crash_after_result_commit
PASS: 20_concurrent_duplicate_deliveries
PASS: queued_reprocess_version2_uses_staging
PASS: stale_version1_after_version2_publish_rejected
PASS: failed_replay_before_cleanup_preserves_source_and_results
PASS: cleanup_before_replay_safe_refusal
PASS: all real fault scenarios; report evidence/fault-study-review.json
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
All checks passed!
29 files already formatted
+24
View File
@@ -0,0 +1,24 @@
{
"cases": [
{
"mode": "RGB",
"pixels": 40000000,
"size_bytes": 126351,
"attachment_id": "d146c349-b869-4fc2-9260-2e7030cbc689",
"seconds_to_ready": 2.028,
"status": "ready"
},
{
"mode": "RGBA",
"pixels": 40000000,
"size_bytes": 167472,
"attachment_id": "cb1d269b-82e7-434c-a909-d3af372c482a",
"seconds_to_ready": 2.265,
"status": "ready"
}
],
"worker_memory_limit": 939524096,
"worker_oom_killed": false,
"passed": true,
"limits": "Child RLIMIT_AS=700MiB, RLIMIT_CPU=15s, wall timeout=20s; this is not a peak RSS measurement."
}
+4 -4
View File
@@ -4,16 +4,16 @@
"mode": "RGB",
"pixels": 40000000,
"size_bytes": 126351,
"attachment_id": "179489ef-46ba-4535-97c1-4a9a6b21a744",
"seconds_to_ready": 1.8,
"attachment_id": "d146c349-b869-4fc2-9260-2e7030cbc689",
"seconds_to_ready": 2.028,
"status": "ready"
},
{
"mode": "RGBA",
"pixels": 40000000,
"size_bytes": 167472,
"attachment_id": "5cb068f4-9df0-4ea4-b21d-e9539ef58d2c",
"seconds_to_ready": 1.98,
"attachment_id": "cb1d269b-82e7-434c-a909-d3af372c482a",
"seconds_to_ready": 2.265,
"status": "ready"
}
],
+32
View File
@@ -0,0 +1,32 @@
{
"attachment_id": "a7724afb-9c2f-439f-a319-4270c426601f",
"pipeline_version": 2,
"after_old_worker_and_cleanup": true,
"checks": [
{
"name": "original",
"sha256": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75",
"size_bytes": 111817,
"matches": true
},
{
"name": "thumbnail",
"sha256": "b8e59b0cad429b1c49c27c4a1c79e52bfc23e2fab7c7238d18d5addd4df4b546",
"size_bytes": 5813,
"matches": true
},
{
"name": "crop",
"sha256": "fae35500205a78065cf7d589f121cc909b017e2a4cde882177e24f5608fb4c1f",
"size_bytes": 2462,
"matches": true
},
{
"name": "optimized",
"sha256": "0bb5b26524335872b2dfe977e2e364101870bfa4e223f4383ab00c34f6771735",
"size_bytes": 2148,
"matches": true
}
],
"passed": true
}
+34
View File
@@ -0,0 +1,34 @@
{
"instances": [
{
"container_id": "a753d11da1c6e15b6fa3f510e45159abca212cce1ea75047a978a7b3dcfb749c",
"image_id": "sha256:2a43094d66f44278456a1dd4b487da97287bc3935715b2b6a36535d60fb0b7d2",
"source_matches_repository": true
},
{
"container_id": "7ac775db02e181adbb150cb1f8d961f54899cc39ea876652c1ff8a43328d6bfa",
"image_id": "sha256:2a43094d66f44278456a1dd4b487da97287bc3935715b2b6a36535d60fb0b7d2",
"source_matches_repository": true
}
],
"runtime_source_sha256": {
"__init__.py": "9a72a49106367ca514cc6147d0e727e62c4d33fefd61572d209a5c9494551a2c",
"__main__.py": "ba9a59ad44ee8884cd65cf88d5ea15cbd7051b10f7c729043ddd44ca2f34defe",
"app.py": "b8b1495814c401e08fe864bcfaaa203162f254a39fea91c82863a5d7ae56cb64",
"attachments.py": "a10f28f9ce7355975c2509e6a360d1086f39d601a563706ad3bcb231da82228e",
"config.py": "e4d4aaf674ede8b5abdc361f77c7793ee94d8d7856030c28834eb7c95291b193",
"domain.py": "7bf6f177ab5bdeea09b303dc886160335d348f64f47912b9bba45355db378bef",
"image_pipeline.py": "3dcca5590704f1f9e8eca71dc28097930eac62701cf479aa8b7e3c71ca9b3551",
"image_validation.py": "d9aa8db65edaab88c9a76cf2e5459ad3028ba808579311aeb0d8c4f01f875720",
"jobctl.py": "41098fe1088960f6e62a3e3b6bd63e8b7f048b4561d82a994cf64574b939215d",
"jobs.py": "3105d13c0530ef9ba5ed19152a5e324382e553ce6a1c3d80f94752ed64e9e98f",
"migrate.py": "eb5cad7ac6abe38dd40b2db307d298b297abe9543b3928c36bab8ef06283664e",
"models.py": "c43769d2d4ba0369129a86bf80364a626ab91442f9b9020e6bc904e363a39665",
"postgres.py": "3fa443fae1dd078a01bc3e7403297a4e76f3dd06ec884f3518f95a1f80ffaa52",
"storage.py": "70b0fb157b285b674a7388a2bfe5c5a7feb8149a9266ac7ad035961d769008a5",
"storage_bootstrap.py": "b29a2a1f8864ec3425a7499b1752688f69d8f402f3881957e790ed4522d35589",
"worker.py": "7fa6df06ea8554850814b9d421e05903aac14179054168d8c462cd94faa96ca6"
},
"passed": true,
"fault_scope": "The repeated 11 fault scenarios and 9 extra invariants ran after worker/jobs/UTF-8/image-validation fixes. Only the shared validate_image wrapper's killpg/output failure guards were tightened afterward. The complete final 179-case suite and 40M image runs used this final image; no full-image identity with the preceding fault run is claimed."
}
+7
View File
@@ -0,0 +1,7 @@
{
"shared_lab4_commit": "f32e7e18a62594f93ae4c1c557c9ff0f344b8f40",
"wrapper_ast_identical": true,
"image_validation_sha256": "d9aa8db65edaab88c9a76cf2e5459ad3028ba808579311aeb0d8c4f01f875720",
"validation_module_identical": true,
"passed": true
}
+2
View File
@@ -0,0 +1,2 @@
python3 tests/smoke.py --base-url "http://127.0.0.1:8085"
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
+78
View File
@@ -0,0 +1,78 @@
Container mtusi-vasilev-lab5-s3-1 Running
Container mtusi-vasilev-lab5-storage-1 Running
Container mtusi-vasilev-lab5-postgres-1 Running
Container mtusi-vasilev-lab5-cache-1 Running
Container mtusi-vasilev-lab5-lb-1 Running
Container mtusi-vasilev-lab5-broker-1 Running
Container mtusi-vasilev-lab5-migrate-1 Recreate
Container mtusi-vasilev-lab5-s3-bootstrap-1 Recreate
Container mtusi-vasilev-lab5-migrate-1 Recreated
Container mtusi-vasilev-lab5-dispatcher-1 Recreate
Container mtusi-vasilev-lab5-s3-bootstrap-1 Recreated
Container mtusi-vasilev-lab5-api-1 Recreate
Container mtusi-vasilev-lab5-api-2 Recreate
Container mtusi-vasilev-lab5-worker-1 Recreate
Container mtusi-vasilev-lab5-worker-1 Recreated
Container mtusi-vasilev-lab5-dispatcher-1 Recreated
Container mtusi-vasilev-lab5-api-1 Recreated
Container mtusi-vasilev-lab5-api-2 Recreated
Container mtusi-vasilev-lab5-storage-1 Waiting
Container mtusi-vasilev-lab5-postgres-1 Waiting
Container mtusi-vasilev-lab5-storage-1 Healthy
Container mtusi-vasilev-lab5-postgres-1 Healthy
Container mtusi-vasilev-lab5-s3-bootstrap-1 Starting
Container mtusi-vasilev-lab5-migrate-1 Starting
Container mtusi-vasilev-lab5-migrate-1 Started
Container mtusi-vasilev-lab5-migrate-1 Waiting
Container mtusi-vasilev-lab5-broker-1 Waiting
Container mtusi-vasilev-lab5-s3-bootstrap-1 Started
Container mtusi-vasilev-lab5-s3-bootstrap-1 Waiting
Container mtusi-vasilev-lab5-migrate-1 Waiting
Container mtusi-vasilev-lab5-broker-1 Waiting
Container mtusi-vasilev-lab5-s3-bootstrap-1 Waiting
Container mtusi-vasilev-lab5-migrate-1 Waiting
Container mtusi-vasilev-lab5-cache-1 Waiting
Container mtusi-vasilev-lab5-broker-1 Healthy
Container mtusi-vasilev-lab5-cache-1 Healthy
Container mtusi-vasilev-lab5-broker-1 Healthy
Container mtusi-vasilev-lab5-migrate-1 Exited
Container mtusi-vasilev-lab5-dispatcher-1 Starting
Container mtusi-vasilev-lab5-migrate-1 Exited
Container mtusi-vasilev-lab5-s3-bootstrap-1 Exited
Container mtusi-vasilev-lab5-worker-1 Starting
Container mtusi-vasilev-lab5-migrate-1 Exited
Container mtusi-vasilev-lab5-s3-bootstrap-1 Exited
Container mtusi-vasilev-lab5-api-1 Starting
Container mtusi-vasilev-lab5-worker-1 Started
Container mtusi-vasilev-lab5-api-1 Started
Container mtusi-vasilev-lab5-api-2 Starting
Container mtusi-vasilev-lab5-dispatcher-1 Started
Container mtusi-vasilev-lab5-api-2 Started
Container mtusi-vasilev-lab5-api-1 Waiting
Container mtusi-vasilev-lab5-api-2 Waiting
Container mtusi-vasilev-lab5-api-1 Healthy
Container mtusi-vasilev-lab5-api-2 Healthy
Container mtusi-vasilev-lab5-cache-1 Waiting
Container mtusi-vasilev-lab5-worker-1 Waiting
Container mtusi-vasilev-lab5-s3-1 Waiting
Container mtusi-vasilev-lab5-storage-1 Waiting
Container mtusi-vasilev-lab5-postgres-1 Waiting
Container mtusi-vasilev-lab5-api-1 Waiting
Container mtusi-vasilev-lab5-api-2 Waiting
Container mtusi-vasilev-lab5-s3-bootstrap-1 Waiting
Container mtusi-vasilev-lab5-migrate-1 Waiting
Container mtusi-vasilev-lab5-lb-1 Waiting
Container mtusi-vasilev-lab5-broker-1 Waiting
Container mtusi-vasilev-lab5-dispatcher-1 Waiting
Container mtusi-vasilev-lab5-broker-1 Healthy
Container mtusi-vasilev-lab5-worker-1 Healthy
Container mtusi-vasilev-lab5-lb-1 Healthy
Container mtusi-vasilev-lab5-migrate-1 Exited
Container mtusi-vasilev-lab5-storage-1 Healthy
Container mtusi-vasilev-lab5-cache-1 Healthy
Container mtusi-vasilev-lab5-postgres-1 Healthy
Container mtusi-vasilev-lab5-dispatcher-1 Healthy
Container mtusi-vasilev-lab5-s3-1 Healthy
Container mtusi-vasilev-lab5-s3-bootstrap-1 Exited
Container mtusi-vasilev-lab5-api-1 Healthy
Container mtusi-vasilev-lab5-api-2 Healthy
+4
View File
@@ -0,0 +1,4 @@
........................................................................ [ 40%]
........................................................................ [ 80%]
................................... [100%]
179 passed in 52.52s
+5 -1
View File
@@ -44,7 +44,7 @@ uv run --locked python research/extra_invariants.py
- Дополнительный драйвер останавливает cleanup после последней проверки перед DELETE под row lock и запускает настоящий concurrent replay; обратный interleaving также проверен. Lock timeout — безопасная ограниченная ошибка, а не обход блокировки.
- В broker явно доставляются v2/v1/v2 после публикации v2; метаданные, bytes и число эффектов остаются прежними.
- Две временные ошибки показывают реальный backoff перед третьей успешной попыткой.
- Некорректные UUID-типы, boolean schema version, неверная дата и не-UTF8 payload отклоняются без crash loop, затем нормальное задание завершается тем же процессом.
- Некорректные UUID-типы, boolean schema version, неверная дата, не-UTF8 payload, глубокий/слишком большой JSON и UUID URN отклоняются без crash loop. Единственное уведомление с uppercase UUID нормализуется и доводит queued job до ready без скрытой lowercase публикации.
- Возраст queued-вложения моделируется как восемь суток в БД; cleanup с нулевой retention сохраняет staging, после запуска worker тот же объект становится ready. Реальные восемь суток ожидания не заявляются.
## Границы доказательства
@@ -52,3 +52,7 @@ uv run --locked python research/extra_invariants.py
Это автоматические контролируемые локальные interleaving, не перебор всех возможных распределённых отказов. At-least-once доставка сохраняется: дубли нормальны, идемпотентен логический эффект. Exactly-once доставка не заявляется. Broker, PostgreSQL, S3 и host остаются одиночными точками отказа. AOF и volumes не заменяют независимые backup.
Время fault-suite зависит от рестартов, lease и warm filesystem, не является SLA обработки. Перегрузка и сравнение concurrency не исследуются: выбран трек 2, а не трек 1. Производительность измеряется только там, где явно указана методика.
## Дополнительное окно готовности и reprocess
Worker приостанавливается сразу после COMMIT ready до cleanup. Reprocess доходит до удаления старого staging под attachment lock; реальная остановка S3 gateway приводит к503 и откату смены версии. После восстановления тот же ready-original/варианты сохранены. Затем штатный повтор reprocess запускает v2, старый worker возобновляется, cleanup не оставляет прежний staging и не меняет v2content. Это проверяет ресурсный leak, который не покрывался более ранним сценарием старого worker до COMMIT.
+103 -5
View File
@@ -140,8 +140,8 @@ def main():
snippet = (
"import json; from messenger.jobs import broker_client,STREAM; b=broker_client(); "
f"base={{'schema_version':1,'job_id':'{v2['id']}','type':'attachment.process.v1','attachment_id':'{aid}','pipeline_version':2,'attempt':1,'created_at':'2026-11-06T00:00:00Z'}}; "
"bad=[json.dumps({**base,'job_id':123}),json.dumps({**base,'attachment_id':[]}),json.dumps({**base,'schema_version':True}),json.dumps({**base,'created_at':123}),bytes([255]),bytes([110,111,116,45,106,115,111,110])]; "
"[b.xadd(STREAM,{'body':payload}) for payload in bad]; print('6 malformed deliveries')"
"bad=[json.dumps({**base,'job_id':123}),json.dumps({**base,'attachment_id':[]}),json.dumps({**base,'schema_version':True}),json.dumps({**base,'created_at':123}),bytes([255]),b'not-json','['*2000+']'*2000,b' '*10000+b'{}',json.dumps({**base,'attachment_id':'urn:uuid:'+base['attachment_id']})]; "
"[b.xadd(STREAM,{'body':payload}) for payload in bad]; print('9 malformed deliveries')"
)
operation(snippet)
normal = upload()
@@ -150,14 +150,112 @@ def main():
assert worker_after["container_id"] == worker_before["container_id"]
assert worker_after["restart_count"] == worker_before["restart_count"]
logs = compose("logs", "--tail", "100", "worker").stdout
assert logs.count('"event": "invalid_delivery"') >= 6
assert logs.count('"event": "invalid_delivery"') >= 9
result["scenarios"].append(
{
"name": "six_poison_deliveries_rejected_without_worker_crash",
"name": "nine_poison_deliveries_rejected_without_worker_crash",
"attachment_id": normal,
"worker_before": worker_before,
"worker_after": worker_after,
"safe_log_events": 6,
"safe_log_events": 9,
"passed": True,
}
)
# The only notification for this queued job uses uppercase UUIDs. There
# is no lowercase dispatcher publication available to mask a lost job.
compose("stop", "worker", "dispatcher")
aid = upload()
jid = job(aid)["id"]
operation(
"import json; from messenger.jobs import broker_client,STREAM; "
f"body={{'schema_version':1,'job_id':'{jid.upper()}','type':'attachment.process.v1','attachment_id':'{aid.upper()}','pipeline_version':1,'attempt':1,'created_at':'2026-11-06T00:00:00Z'}}; "
"broker_client().xadd(STREAM,{'body':json.dumps(body)}); print('uppercase notification accepted by broker')"
)
sql(f"UPDATE job_outbox SET published_at=now() WHERE job_id='{jid}'")
compose("start", "worker")
ready(aid)
assert job(aid)["attempt"] == 1
compose("start", "dispatcher")
result["scenarios"].append(
{
"name": "uppercase_uuid_only_delivery_completes_queued_job",
"attachment_id": aid,
"no_lowercase_publication": True,
"attempts": 1,
"passed": True,
}
)
# A ready result can precede worker staging cleanup. First prove a real
# S3 DELETE outage rolls reprocess back; then retry and prove no orphan.
compose("stop", "worker")
aid = upload()
old_stage = sql(f"SELECT stage_key FROM attachments WHERE id='{aid}'", rows=True)[0][
"stage_key"
]
old_worker_barrier = fault("after_result_commit", aid, "pause")
compose("start", "worker")
wait_until(lambda: reached(old_worker_barrier))
version1 = ready(aid)
delete_barrier = fault("reprocess_before_staging_delete", aid, "pause")
with ThreadPoolExecutor(1) as executor:
replacing = executor.submit(
command,
COMPOSE
+ [
"exec",
"-T",
"--index",
"2",
"api",
"python",
"-m",
"messenger.jobctl",
"reprocess",
aid,
"--version",
"2",
],
False,
)
wait_until(lambda: reached(delete_barrier))
compose("stop", "s3")
sql(f"UPDATE test_faults SET released=true WHERE id={delete_barrier}")
refused = replacing.result(timeout=20)
assert refused.returncode == 1 and json.loads(refused.stdout)["status"] == 503
assert job(aid)["pipeline_version"] == 1 and job(aid)["state"] == "ready"
compose("start", "s3")
compose("up", "-d", "--no-recreate", "--wait", "api", "lb")
command([sys.executable, "scripts/wait_replicas.py", "2"])
assert ready(aid) == version1
assert operation(f"print(o.exists('{old_stage}'))") == "True"
result["scenarios"].append(
{
"name": "reprocess_staging_delete_outage_keeps_ready_version1",
"attachment_id": aid,
"reprocess_error": 503,
"source_and_final_content_intact": True,
"passed": True,
}
)
operation(f"print(j.reprocess('{aid}',2,o))")
compose("up", "-d", "--no-deps", "--scale", "worker=2", "worker")
version2 = ready(aid)
sql(f"UPDATE test_faults SET released=true WHERE id={old_worker_barrier}")
time.sleep(1)
operation("from messenger.jobctl import cleanup; print(cleanup(s,o,0,3600))")
assert operation(f"print(o.exists('{old_stage}'))") == "False"
assert ready(aid) == version2
for variant in ["original", "thumbnail", "crop", "optimized"]:
c.call("GET", f"/api/v1/attachments/{aid}/content?variant={variant}", actor=bob)
compose("up", "-d", "--no-deps", "--scale", "worker=1", "worker")
result["scenarios"].append(
{
"name": "ready_reprocess_before_old_cleanup_does_not_orphan_staging",
"attachment_id": aid,
"old_staging_absent": True,
"version2_metadata_and_content_unchanged": True,
"passed": True,
}
)
+12 -13
View File
@@ -1,4 +1,4 @@
"""Compare actual container source bytes to the repository and fault-study image."""
"""Verify final container source bytes without attributing old experiments to a new image."""
import hashlib
import json
@@ -8,16 +8,15 @@ from pathlib import Path
ids = subprocess.check_output(["docker", "compose", "ps", "-q", "api"], text=True).split()
assert ids
probe = "import hashlib,json,pathlib; p=pathlib.Path('/app/src/messenger'); print(json.dumps({x.name:hashlib.sha256(x.read_bytes()).hexdigest() for x in sorted(p.glob('*.py'))}))"
actual = json.loads(subprocess.check_output(["docker", "exec", ids[0], "python", "-c", probe], text=True))
expected = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(Path("src/messenger").glob("*.py"))}
assert actual == expected, "Runtime source differs from repository"
old = json.loads(Path("evidence/fault-runtime-source.json").read_text())
changed = sorted(name for name, digest in actual.items() if digest != old["source_sha256"].get(name))
assert set(changed) <= {"domain.py"}, changed
result = {"runtime_container_id": ids[0], "runtime_source_sha256": actual,
"fault_image_id": old["image_id"], "changed_after_fault_image": changed,
"pipeline_modules_identical": True,
"explanation": "Only shared cursor parsing was tightened after fault tests; complete final HTTP suite checks it. All pipeline/outbox/storage modules are byte-identical.",
"passed": True}
Path("evidence/runtime-source.json").write_text(json.dumps(result, indent=2))
print("PASS: runtime matches repository; fault-tested pipeline modules are identical")
instances = []
for cid in ids:
actual = json.loads(subprocess.check_output(["docker", "exec", cid, "python", "-c", probe], text=True))
assert actual == expected, "Runtime source differs from repository"
identity = json.loads(subprocess.check_output(["docker", "inspect", cid], text=True))[0]
instances.append({"container_id": cid, "image_id": identity["Image"], "source_matches_repository": True})
result = {"instances": instances, "runtime_source_sha256": expected,
"passed": True,
"fault_scope": "The repeated 11 fault scenarios and 9 extra invariants ran after worker/jobs/UTF-8/image-validation fixes. Only the shared validate_image wrapper's killpg/output failure guards were tightened afterward. The complete final 179-case suite and 40M image runs used this final image; no full-image identity with the preceding fault run is claimed."}
Path("evidence/review-runtime-source.json").write_text(json.dumps(result, indent=2))
print("PASS: both final API containers match repository source")
+19
View File
@@ -67,6 +67,23 @@ def error(request, status, message, headers=None):
)
async def invalid_json_encoding(request: Request):
path = request.url.path
if request.method != "POST" or not (
path in {"/api/v1/users", "/api/v1/chats"}
or re.fullmatch(r"/api/v1/chats/[^/]+/messages", path)
):
return False
raw = await request.body()
try:
raw.decode("utf-8")
except UnicodeDecodeError:
return True
# Literal NUL is invalid JSON; it also prevents json.loads(bytes) from
# autodetecting BOM-less UTF-16/32. Escaped JSON \u0000 remains valid.
return b"\x00" in raw
@app.middleware("http")
async def request_log(request: Request, call_next):
request.state.request_id = str(uuid4())
@@ -78,6 +95,8 @@ async def request_log(request: Request, call_next):
and await request.body()
):
response = error(request, 400, "Вход не принимает тело запроса")
elif await invalid_json_encoding(request):
response = error(request, 400, "JSON должен быть закодирован в UTF-8")
else:
response = await call_next(request)
except Exception:
+55 -55
View File
@@ -1,21 +1,21 @@
"""Durable asynchronous intake with full bounded validation before acceptance."""
import hashlib
import json
import os
import signal
import subprocess
import tempfile
import sys
import unicodedata
from pathlib import Path
from uuid import uuid4
from PIL import Image, UnidentifiedImageError
from .domain import Failure, timestamp
from .jobs import Jobs, fault
from .postgres import public
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
# Check dimensions before decoding. Pillow's own hard bomb threshold remains active.
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
PUBLIC_FIELDS = (
"id",
"chat_id",
@@ -42,61 +42,61 @@ def filename_valid(name):
def validate_image(fileobj, declared_type):
if declared_type not in {"image/png", "image/jpeg"}:
raise Failure(415, "Ожидается PNG или JPEG")
fileobj.seek(0)
encoded = fileobj.read(MAX_BYTES + 1)
if len(encoded) > MAX_BYTES:
raise Failure(413, "Файл больше 10 MiB")
try:
fileobj.seek(0)
with Image.open(fileobj) as image:
width, height = image.size
if width * height > MAX_PIXELS:
raise Failure(413, "Слишком много пикселей")
actual = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(image.format)
if actual != declared_type:
raise Failure(415, "Формат изображения не соответствует MIME")
image.verify()
# verify() alone does not decode IDAT/JPEG scan data.
fileobj.seek(0)
with Image.open(fileobj) as image:
image.load()
if actual == "image/jpeg":
# libjpeg emits a warning but Pillow accepts e.g. a half scan with a
# forged EOI. djpeg's nonzero warning exit rejects that corruption.
fileobj.seek(0)
fallback = None
with subprocess.Popen(
[sys.executable, "-m", "messenger.image_validation", declared_type],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
start_new_session=True,
env={
"PATH": os.environ.get("PATH", os.defpath),
"PYTHONPATH": str(Path(__file__).resolve().parents[1]),
"PYTHONDONTWRITEBYTECODE": "1",
"LANG": "C.UTF-8",
},
) as process:
try:
decoder_input = fileobj
try:
fileobj.fileno()
except (AttributeError, OSError):
# Internal callers may supply BytesIO; bound the fallback too.
fallback = tempfile.TemporaryFile()
copied = 0
while chunk := fileobj.read(64 * 1024):
copied += len(chunk)
if copied > MAX_BYTES:
raise Failure(413, "Файл больше 10 MiB") from None
fallback.write(chunk)
fallback.seek(0)
decoder_input = fallback
decoded = subprocess.run(
["djpeg", "-strict", "-maxmemory", "192m", "-outfile", "/dev/null"],
stdin=decoder_input,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
timeout=5,
check=False,
)
output, _ = process.communicate(input=encoded, timeout=5)
except subprocess.TimeoutExpired:
# The validator can itself run djpeg: kill its whole process group
# before releasing the upload slot, not only the Python parent.
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass # The child may have exited at the timeout boundary.
process.communicate()
raise Failure(415, "Изображение не прошло ограниченную проверку") from None
finally:
if fallback is not None:
fallback.close()
if decoded.returncode:
raise Failure(415, "Повреждённое изображение")
fileobj.seek(0)
return actual, width, height
except Image.DecompressionBombError:
raise Failure(413, "Слишком много пикселей") from None
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
if process.returncode:
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
raise Failure(415, "Изображение не прошло ограниченную проверку")
except OSError:
raise Failure(503, "Проверка изображения временно недоступна") from None
finally:
del encoded
try:
outcome = json.loads(output)
except (ValueError, UnicodeError):
raise Failure(415, "Повреждённое изображение") from None
if not isinstance(outcome, dict):
raise Failure(415, "Изображение не прошло ограниченную проверку")
if "error" in outcome:
status = outcome["error"]
if type(status) is not int or status not in {413, 415}:
status = 415
raise Failure(status, "Изображение не прошло ограниченную проверку")
values = outcome.get("ok")
if not isinstance(values, list) or len(values) != 3:
raise Failure(415, "Изображение не прошло ограниченную проверку")
fileobj.seek(0)
return tuple(values)
def metadata_public(row):
+146
View File
@@ -0,0 +1,146 @@
"""Short-lived bounded pixel validation; no DB, credentials or application imports."""
import json
import resource
import subprocess
import sys
from io import BytesIO
from PIL import Image, UnidentifiedImageError
from .domain import Failure
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
def inspect_image(fileobj, declared_type):
if declared_type not in {"image/png", "image/jpeg"}:
raise Failure(415, "Ожидается PNG или JPEG")
try:
fileobj.seek(0)
with Image.open(fileobj) as header:
width, height = header.size
if width * height > MAX_PIXELS:
raise Failure(413, "Слишком много пикселей")
actual = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(header.format)
if actual != declared_type:
raise Failure(415, "Формат изображения не соответствует MIME")
frames = getattr(header, "n_frames", 1)
default_image = bool(getattr(header, "default_image", False))
if width * height * frames > MAX_PIXELS:
raise Failure(413, "Слишком много пикселей во всех кадрах")
header.verify()
# Drop parsed metadata before the separate strict decoder process starts.
del header
if actual == "image/png":
# verify() checks CRC, but does not compare acTL's frame count with
# every fcTL. Do not let a forged count hide a corrupt later frame.
fileobj.seek(8)
controls = frame_controls = 0
declared_frames = None
animation_data = False
while True:
chunk_header = fileobj.read(8)
if len(chunk_header) != 8:
raise ValueError("Truncated PNG chunk")
length = int.from_bytes(chunk_header[:4], "big")
kind = chunk_header[4:]
controls += kind == b"acTL"
frame_controls += kind == b"fcTL"
animation_data |= kind == b"fdAT"
if kind == b"acTL":
if length != 8:
raise ValueError("Invalid acTL length")
declared_frames = int.from_bytes(fileobj.read(4), "big")
fileobj.seek(length, 1) # remaining payload plus CRC
else:
fileobj.seek(length + 4, 1)
if kind == b"IEND":
break
if controls:
if (
controls != 1
or not declared_frames
or frame_controls != declared_frames
or declared_frames + int(default_image) != frames
):
raise ValueError("Invalid APNG frame count")
elif frame_controls or animation_data:
raise ValueError("Animation chunks without acTL")
if actual == "image/jpeg":
# Validate scan warnings before allocating Pillow's decoded canvas.
# 384 MiB covers coefficient arrays for <=40M pixels and <=4 channels;
# keeping both full decoded buffers alive could exceed the API cgroup.
fileobj.seek(0)
# A bounded compressed copy avoids sharing buffered file-descriptor
# offsets with the child, and supports BytesIO callers as well.
encoded = fileobj.read(MAX_BYTES + 1)
if len(encoded) > MAX_BYTES:
raise Failure(413, "Файл больше 10 MiB")
try:
decoded = subprocess.run(
["djpeg", "-strict", "-maxmemory", "384m", "-outfile", "/dev/null"],
input=encoded,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
timeout=4,
check=False,
)
except subprocess.TimeoutExpired:
raise Failure(415, "Изображение не прошло ограниченную проверку") from None
finally:
del encoded
if decoded.returncode:
raise Failure(415, "Повреждённое изображение")
# djpeg has already decoded every JPEG pixel, streaming output rows.
# A second Pillow load would overlap full progressive coefficient
# arrays with a 160 MiB CMYK canvas and violate the API's 512 MiB cap.
fileobj.seek(0)
return actual, width, height
# Decode one frame at a time. Pillow may retain a previous APNG canvas
# for compositing, but no list/copies of every decoded frame is collected.
fileobj.seek(0)
with Image.open(fileobj) as image:
decoded_pixels = 0
for frame in range(frames):
if decoded_pixels + width * height > MAX_PIXELS:
raise Failure(413, "Слишком много пикселей во всех кадрах")
image.seek(frame)
decoded_pixels += image.size[0] * image.size[1]
if decoded_pixels > MAX_PIXELS:
raise Failure(413, "Слишком много пикселей во всех кадрах")
image.load()
# Image's context manager closes its input handle, not the decoded core.
# Releasing the object frees native canvases before hashing/S3 publication.
del image
fileobj.seek(0)
return actual, width, height
except Image.DecompressionBombError:
raise Failure(413, "Слишком много пикселей") from None
except (UnidentifiedImageError, OSError, ValueError, SyntaxError, EOFError):
raise Failure(415, "Повреждённое изображение") from None
def main():
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
resource.setrlimit(resource.RLIMIT_CPU, (4, 5))
if sys.platform == "linux":
resource.setrlimit(resource.RLIMIT_AS, (512 * 1024 * 1024, 512 * 1024 * 1024))
try:
data = sys.stdin.buffer.read(MAX_BYTES + 1)
if len(data) > MAX_BYTES:
raise Failure(413, "Файл больше 10 MiB")
result = inspect_image(BytesIO(data), sys.argv[1])
print(json.dumps({"ok": result}))
except Failure as exc:
print(json.dumps({"error": exc.status}))
except MemoryError:
print(json.dumps({"error": 415}))
except Exception:
print(json.dumps({"error": 415}))
if __name__ == "__main__":
main()
+7
View File
@@ -302,6 +302,13 @@ class Jobs:
source = a["object_key"] if a["status"] == "ready" else a["stage_key"]
if not source or not storage.exists(source):
raise Failure(409, "Источник больше недоступен")
if a["status"] == "ready" and a["stage_key"] and a["stage_key"].startswith("staging/"):
# A worker can be paused after publishing ready but before its
# staging cleanup. Do not orphan that key when choosing final v1
# as the new source. Delete stays under the same attachment lock;
# a storage failure leaves the ready version unchanged.
fault(self.store, "reprocess_before_staging_delete", attachment_id)
storage.delete(a["stage_key"])
conn.execute(
"UPDATE attachment_jobs SET state='superseded',updated_at=now() WHERE attachment_id=%s AND state IN ('queued','processing','failed')",
(attachment_id,),
+17 -3
View File
@@ -24,6 +24,7 @@ from .storage import ObjectStorage
logger = logging.getLogger("messenger.worker")
logging.basicConfig(level=logging.INFO, format="%(message)s")
stopping = False
MAX_JOB_BYTES = 8192
def stop(signum, frame):
@@ -105,7 +106,15 @@ def cleanup_ready(store, storage, attachment_id):
def validate_delivery(body):
data = json.loads(body)
if not isinstance(body, (str, bytes, bytearray)):
raise ValueError("invalid_job")
encoded = body.encode("utf-8") if isinstance(body, str) else body
if len(encoded) > MAX_JOB_BYTES:
raise ValueError("invalid_job")
try:
data = json.loads(encoded)
except RecursionError:
raise ValueError("invalid_job") from None
expected = {
"schema_version",
"job_id",
@@ -126,8 +135,13 @@ def validate_delivery(body):
raise ValueError("invalid_job")
if not isinstance(data["job_id"], str) or not isinstance(data["attachment_id"], str):
raise ValueError("invalid_job")
UUID(data["job_id"])
UUID(data["attachment_id"])
for field in ("job_id", "attachment_id"):
canonical = str(UUID(data[field]))
if data[field].lower() != canonical:
raise ValueError("invalid_job")
# RFC UUID hex is case-insensitive; PostgreSQL and state comparisons use
# the same canonical spelling, so a valid uppercase delivery is not lost.
data[field] = canonical
if type(data["pipeline_version"]) is not int or data["pipeline_version"] < 1:
raise ValueError("invalid_job")
if type(data["attempt"]) is not int or data["attempt"] < 1:
+229
View File
@@ -0,0 +1,229 @@
"""Full-range JPEG and bounded multi-frame PNG regressions."""
import os
import struct
import zlib
from io import BytesIO
import pytest
from client import Client
from PIL import Image
@pytest.fixture(scope="module")
def scenario():
c = Client(os.getenv("BASE_URL", "http://127.0.0.1:8085"))
return c, *c.bootstrap()
def upload(scenario, data, mime, expected):
c, alice, _, _, chat = scenario
result = c.call(
"POST",
f"/api/v1/chats/{chat['id']}/attachments?filename=edge.png",
202 if expected == 201 else expected,
actor=alice,
raw=data,
headers={"Content-Type": mime},
schema="Attachment" if expected == 201 else None,
)
if expected == 201:
result["json"] = c.wait_ready(alice, result["json"])
return result
def progressive_jpeg():
output = BytesIO()
image = Image.new("RGB", (6000, 6000), "blue")
try:
image.save(output, "JPEG", quality=90, progressive=True, subsampling=0)
finally:
image.close()
return output.getvalue()
def apng(size=(16, 16), default_image=False):
output = BytesIO()
first, second = Image.new("RGB", size, "red"), Image.new("RGB", size, "blue")
try:
first.save(
output,
"PNG",
save_all=True,
append_images=[second],
duration=100,
loop=0,
default_image=default_image,
)
finally:
first.close()
second.close()
return output.getvalue()
def broken_later_frame(data):
result, position = bytearray(data[:8]), 8
while position < len(data):
length = struct.unpack(">I", data[position : position + 4])[0]
kind = data[position + 4 : position + 8]
payload = data[position + 8 : position + 8 + length]
if kind == b"fdAT":
payload = payload[:4] + b"not-a-valid-deflate-stream"
result += (
struct.pack(">I", len(payload))
+ kind
+ payload
+ struct.pack(">I", zlib.crc32(kind + payload))
)
position += length + 12
return bytes(result)
def test_36m_progressive_jpeg_is_valid_and_unchanged(scenario):
data = progressive_jpeg()
attachment = upload(scenario, data, "image/jpeg", 201)["json"]
c, _, bob, _, _ = scenario
assert (
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)["bytes"] == data
)
def test_apng_corrupt_later_frame_is_rejected(scenario):
upload(scenario, broken_later_frame(apng()), "image/png", 415)
def test_valid_small_apng_is_accepted_and_unchanged(scenario):
data = apng()
attachment = upload(scenario, data, "image/png", 201)["json"]
c, _, bob, _, _ = scenario
assert (
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)["bytes"] == data
)
def test_apng_cumulative_canvas_limit(scenario):
# Two 25M-pixel canvases exceed the total 40M decode budget.
upload(scenario, apng((5000, 5000)), "image/png", 413)
def test_apng_forged_frame_count_cannot_hide_bad_frame(scenario):
data = bytearray(broken_later_frame(apng()))
position = 8
while position < len(data):
length = struct.unpack(">I", data[position : position + 4])[0]
kind = bytes(data[position + 4 : position + 8])
if kind == b"acTL":
data[position + 8 : position + 12] = struct.pack(">I", 1)
payload = bytes(data[position + 8 : position + 8 + length])
data[position + 8 + length : position + 12 + length] = struct.pack(
">I", zlib.crc32(kind + payload)
)
break
position += length + 12
upload(scenario, bytes(data), "image/png", 415)
def test_apng_zero_count_with_static_fallback_is_rejected(scenario):
# Pillow warns and falls back to one valid static PNG frame. The raw acTL
# count must still be rejected rather than trusting Pillow's n_frames=1.
data = apng()
result, position, controls = bytearray(data[:8]), 8, 0
while position < len(data):
length = int.from_bytes(data[position : position + 4], "big")
kind = data[position + 4 : position + 8]
payload = data[position + 8 : position + 8 + length]
position += length + 12
if kind == b"acTL":
payload = bytes(4) + payload[4:]
if kind == b"fcTL":
controls += 1
if controls > 1:
continue
if kind == b"fdAT":
continue
result += (
struct.pack(">I", len(payload))
+ kind
+ payload
+ struct.pack(">I", zlib.crc32(kind + payload))
)
upload(scenario, bytes(result), "image/png", 415)
def test_apng_exact_cumulative_limit_is_accepted(scenario):
upload(scenario, apng((4000, 5000)), "image/png", 201)
def test_40m_cmyk_progressive_jpeg_is_accepted(scenario):
output = BytesIO()
image = Image.new("CMYK", (8000, 5000), (0, 128, 128, 0))
try:
image.save(output, "JPEG", quality=90, progressive=True, subsampling=0)
finally:
image.close()
data = output.getvalue()
attachment = upload(scenario, data, "image/jpeg", 201)["json"]
c, _, bob, _, _ = scenario
assert (
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)["bytes"] == data
)
def test_repeated_large_image_sequence_stays_available(scenario):
# Formerly retained APNG canvases could overlap the next CMYK decoder.
c, _, bob, _, _ = scenario
data = apng((4000, 5000))
attachment = upload(scenario, data, "image/png", 201)["json"]
assert (
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)["bytes"] == data
)
del data
test_40m_cmyk_progressive_jpeg_is_accepted(scenario)
test_36m_progressive_jpeg_is_valid_and_unchanged(scenario)
data = BytesIO()
image = Image.new("RGB", (16, 16), "green")
image.save(data, "PNG")
image.close()
attachment = upload(scenario, data.getvalue(), "image/png", 201)["json"]
assert (
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)["bytes"]
== data.getvalue()
)
@pytest.mark.parametrize("progressive", [False, True])
def test_small_cmyk_jpeg(progressive, scenario):
output = BytesIO()
image = Image.new("CMYK", (24, 18), (0, 128, 128, 0))
image.save(output, "JPEG", progressive=progressive)
image.close()
upload(scenario, output.getvalue(), "image/jpeg", 201)
def test_invalid_zero_frame_count_is_rejected(scenario):
data = apng()
result, position, controls = bytearray(data[:8]), 8, 0
while position < len(data):
length = struct.unpack(">I", data[position : position + 4])[0]
kind = data[position + 4 : position + 8]
payload = data[position + 8 : position + 8 + length]
position += length + 12
if kind == b"fcTL":
controls += 1
if controls > 1:
continue
if kind == b"fdAT":
continue
if kind == b"acTL":
payload = bytes(4) + payload[4:]
result += (
struct.pack(">I", len(payload))
+ kind
+ payload
+ struct.pack(">I", zlib.crc32(kind + payload))
)
upload(scenario, bytes(result), "image/png", 415)
def test_valid_apng_default_image(scenario):
upload(scenario, apng(default_image=True), "image/png", 201)
+20
View File
@@ -50,3 +50,23 @@ def test_valid_trace_context():
"tracestate": "test=value",
}
assert validate_delivery(json.dumps(body)) == body
@pytest.mark.parametrize(
"body", ["[" * 2000 + "]" * 2000, "[" * 20000 + "]" * 20000, b" " * 8193 + b"{}"]
)
def test_deep_and_oversize_envelopes_reject_safely(body):
with pytest.raises(ValueError):
validate_delivery(body)
def test_uuid_uppercase_is_normalized_before_storage():
value = "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA"
parsed = validate_delivery(json.dumps({**VALID, "job_id": value, "attachment_id": value}))
assert parsed["job_id"] == parsed["attachment_id"] == value.lower()
@pytest.mark.parametrize("field", ["job_id", "attachment_id"])
def test_uuid_urn_is_rejected_before_storage(field):
with pytest.raises(ValueError):
validate_delivery(json.dumps({**VALID, field: "urn:uuid:" + VALID[field]}))
+169
View File
@@ -0,0 +1,169 @@
import base64
import codecs
import json
import os
import uuid
from uuid import uuid4
import pytest
from client import Client
ENCODINGS = [
"utf-16",
"utf-16-le",
"utf-16-be",
"utf-16-be-bom",
"utf-32",
"utf-32-le",
"utf-32-be",
"utf-32-be-bom",
]
def encoded(body, encoding):
text = json.dumps(body, ensure_ascii=False)
if encoding == "utf-16-be-bom":
return codecs.BOM_UTF16_BE + text.encode("utf-16-be")
if encoding == "utf-32-be-bom":
return codecs.BOM_UTF32_BE + text.encode("utf-32-be")
return text.encode(encoding)
@pytest.fixture(scope="module")
def encoding_scenario():
c = Client(os.environ["BASE_URL"])
return c, *c.bootstrap()
@pytest.mark.parametrize("encoding", ENCODINGS)
def test_non_utf8_registration_has_no_write(encoding_scenario, encoding):
c, *_ = encoding_scenario
body = {
"username": "enc_" + uuid.uuid4().hex[:14],
"display_name": "Никита\u0000имя",
"password": "Пароль:тестовый-12345",
}
c.call(
"POST",
"/api/v1/users",
400,
raw=encoded(body, encoding),
headers={"Content-Type": "application/json"},
)
# UNIQUE username proves the rejected request did not insert a user.
created = c.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
assert created["display_name"] == body["display_name"]
@pytest.mark.parametrize("encoding", ENCODINGS)
def test_non_utf8_chat_has_no_write(encoding_scenario, encoding):
c, alice, *_ = encoding_scenario
before = c.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]
body = {"title": "Чат\u0000" + uuid.uuid4().hex, "member_ids": [alice["id"]]}
c.call(
"POST",
"/api/v1/chats",
400,
actor=alice,
raw=encoded(body, encoding),
headers={"Content-Type": "application/json"},
)
after = c.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]
assert before == after
assert (
c.call("POST", "/api/v1/chats", 201, actor=alice, body=body, schema="Chat")["json"]["title"]
== body["title"]
)
@pytest.mark.parametrize("encoding", ENCODINGS)
def test_non_utf8_message_has_no_write(encoding_scenario, encoding):
c, alice, _, _, chat = encoding_scenario
path = f"/api/v1/chats/{chat['id']}/messages"
key = uuid.uuid4().hex
body = {"text": "Сообщение\u0000" + key}
c.call(
"POST",
path,
400,
actor=alice,
raw=encoded(body, encoding),
headers={"Content-Type": "application/json", "Idempotency-Key": key},
)
history = c.call("GET", path + "?limit=100", actor=alice, schema="MessagePage")["json"]["items"]
assert all(item["text"] != body["text"] for item in history)
good = c.call(
"POST",
path,
201,
actor=alice,
body=body,
headers={"Idempotency-Key": key},
schema="Message",
)["json"]
repeat = c.call(
"POST",
path,
201,
actor=alice,
body=body,
headers={"Idempotency-Key": key},
schema="Message",
)["json"]
assert good == repeat and good["text"] == body["text"]
@pytest.mark.parametrize("encoding", ["utf-8", "utf-8-sig"])
def test_valid_utf8_registration_and_login(encoding_scenario, encoding):
c, *_ = encoding_scenario
body = {
"username": "utf8_" + uuid.uuid4().hex[:14],
"display_name": "Юникод\u0000😀",
"password": "Пароль:тестовый-12345",
}
user = c.call(
"POST",
"/api/v1/users",
201,
raw=encoded(body, encoding),
headers={"Content-Type": "application/json"},
schema="User",
)["json"]
assert user["display_name"] == body["display_name"]
credential = base64.b64encode((body["username"] + ":" + body["password"]).encode()).decode()
session = c.call(
"POST",
"/api/v1/auth/sessions",
201,
headers={"Authorization": "Basic " + credential},
schema="Session",
)["json"]
assert session["user"] == user
def requests_for(alice, chat):
return [
(
"/api/v1/users",
{
"username": "utf_" + uuid4().hex[:12],
"display_name": "Имя\0",
"password": "synthetic-password-123",
},
),
("/api/v1/chats", {"title": "Чат\0", "member_ids": [alice["id"]]}),
(f"/api/v1/chats/{chat['id']}/messages", {"text": "Сообщение\0"}),
]
def test_utf8_and_escaped_nul_remain_valid(encoding_scenario):
c, alice, _, _, chat = encoding_scenario
for path, body in requests_for(alice, chat):
c.call(
"POST",
path,
201,
actor=alice,
raw=json.dumps(body, ensure_ascii=False).encode("utf-8"),
headers={"Content-Type": "application/json", "Idempotency-Key": uuid4().hex},
)