forked from mtusi2026/mtusi2026lab4
Compare commits
10
Commits
59b2f031bc
...
f32e7e18a6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f32e7e18a6 | ||
|
|
de36c967cc | ||
|
|
8de05d3899 | ||
|
|
ff17362bcd | ||
|
|
619155f1e0 | ||
|
|
9d9d425205 | ||
|
|
14c659fda4 | ||
|
|
1779b5f036 | ||
|
|
6ac558ee08 | ||
|
|
ca9570f495 |
+19
-19
@@ -1,20 +1,20 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
# Copying is optional: make up runs scripts/bootstrap.py and creates .env once.
|
||||
# Never put credentials in this file. Bootstrap writes ignored ./secrets/ files.
|
||||
PUBLIC_PORT=8084
|
||||
API_REPLICAS=2
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
S3_ENDPOINT=http://s3:9000
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
||||
MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
API_CPUS=0.5
|
||||
API_MEMORY=512m
|
||||
POOL_MAX_SIZE=8
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Optional custom tag; default is mtusi-vasilev:lab4.
|
||||
API_IMAGE=mtusi-vasilev:lab4
|
||||
|
||||
# Fixed internal topology in compose.yaml (comments, not .env overrides):
|
||||
# API binds 0.0.0.0:8080; only LB publishes 127.0.0.1:${PUBLIC_PORT}:8080.
|
||||
# PostgreSQL host=postgres, database/user=messenger; DATABASE_URL_FILE is mounted.
|
||||
# CACHE_URL_FILE points to redis://cache:6379/0, public user cards only.
|
||||
# S3_ENDPOINT=http://s3:8333, S3_BUCKET=messenger.
|
||||
# S3_ACCESS_KEY_FILE=/run/secrets/s3_access_key
|
||||
# S3_SECRET_KEY_FILE=/run/secrets/s3_secret_key
|
||||
# Bootstrap alone receives S3_ADMIN_ACCESS_KEY_FILE/S3_ADMIN_SECRET_KEY_FILE.
|
||||
# Storage backend/filer/master are on the isolated storage_backend network.
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
name: Application checks
|
||||
on: [push, pull_request]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
application:
|
||||
# Intended for an isolated hosted VM, never a runner sharing production Docker.
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
env:
|
||||
COMPOSE_PROJECT_NAME: ci-lab4-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
PUBLIC_PORT: '8084'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- run: python -m pip install uv==0.11.7
|
||||
- run: uv sync --locked
|
||||
- run: make up
|
||||
- run: make check validate PYTHON=.venv/bin/python
|
||||
- run: make test student-test
|
||||
- if: always()
|
||||
run: docker compose down --volumes --remove-orphans
|
||||
+1
-1
@@ -5,7 +5,7 @@ COPY pyproject.toml uv.lock ./
|
||||
RUN uv sync --locked --no-dev --no-install-project --python /usr/local/bin/python
|
||||
|
||||
FROM python:3.12-slim@sha256:646fb0bca3dd3ea1bcc6feb72c17ed16eed6e10cffc732fcc1478bd3e7f02d7b
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends libjpeg-turbo-progs && rm -rf /var/lib/apt/lists/*
|
||||
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/*
|
||||
ARG VCS_REF=uncommitted
|
||||
LABEL org.opencontainers.image.revision=$VCS_REF
|
||||
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=/app/src PATH=/app/.venv/bin:$PATH
|
||||
|
||||
@@ -1,37 +1,165 @@
|
||||
# Отчёт — лабораторная 4
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
**Васильев Никита, БВТ2301. Целевая оценка: 5. Трек 2 — согласованность двух хранилищ.**
|
||||
|
||||
Локальное выполнение без публикации PR. Отдельный application workflow описывает build/readiness/smoke/own tests на изолированной hosted VM; удалённый CI в рамках этой работы не запускался. Оригинальные README, COURSE, CONTRIBUTING, contracts и публичные tests сохранены. Собственный код ЛР3 перенесён в отдельный skeleton ЛР4; добавлены вложения и исследование согласованности. Использована помощь ИИ при реализации, тестировании и подготовке отчёта. Замечания преподавателей изучены заранее, ссылки и регрессии — в [REVIEW_NOTES.md](REVIEW_NOTES.md). Код и чужие измерения не заимствованы.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Нужны Docker Engine с Compose v2, Python 3.12 и uv, make. Для публичных тестов достаточно системного Python 3.9+. Host djpeg необязателен: один дополнительный unit-тест внутреннего BytesIO helper пропускается, если этого бинарника нет на хосте; HTTP-регрессии JPEG всегда выполняются против Docker, где decoder установлен и закреплён. API и все хранилища запускаются из этого репозитория; ручная установка PostgreSQL/S3 не нужна.
|
||||
|
||||
## Архитектура и решения
|
||||
```sh
|
||||
uv sync --locked --python 3.12
|
||||
make up
|
||||
make check validate PYTHON=.venv/bin/python
|
||||
make test
|
||||
make student-test
|
||||
```
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
`make up` создаёт локальные секреты один раз, сохраняет существующие значения, собирает образ, ждёт PostgreSQL, применяет миграции и идемпотентно создаёт приватный bucket. Затем запускаются две API-реплики и HAProxy. На хост опубликован только `127.0.0.1:8084` балансировщика; API и storage напрямую не публикуются.
|
||||
|
||||
## Доказательства критериев
|
||||
Обычная остановка с сохранением данных:
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
```sh
|
||||
make down
|
||||
```
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
Намеренное удаление учебных данных выполняется отдельно командой `docker compose down --volumes`; она не нужна для restart и не применяется к основному стенду при проверке сохранности.
|
||||
|
||||
## Эксперименты и отказы
|
||||
Полная проверка рестарта и отказа одной API:
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
```sh
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
docker compose up -d --wait --no-recreate
|
||||
```
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
После восстановления первой реплики failover повторяется для другой. Hook использует TARGET_INSTANCE_ID, читает действительный alias процесса и останавливает соответствующий контейнер. Сопоставление alias/контейнера и timestamps до/после фиксируются в evidence.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
Переменные: `PUBLIC_PORT=8084`, `API_REPLICAS=2`, `API_CPUS=0.5`, `API_MEMORY=512m`, `POOL_MAX_SIZE=8`, `SESSION_TTL_SECONDS=3600`. DSN, S3 access/secret keys читаются из файлов Compose secrets; app и admin keys разделены. `.env`, secrets и volumes не находятся в Git. `.env.example` содержит поддерживаемые переменные и комментарии с фиксированными внутренними адресами; реальные секреты генерирует scripts/bootstrap.py. Изменение S3 bucket/endpoint требует согласованного изменения Compose и bucket-scoped identity, а не только строки в .env.
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
## Версии и ограничения ресурсов
|
||||
|
||||
- Python 3.12, Python-зависимости закреплены в uv.lock (FastAPI 0.162.0, Pillow 12.3.0, boto3/botocore 1.43.125 и прочие).
|
||||
- Python base закреплён digest, uv в Docker 0.11.7. Native decoder libjpeg-turbo-progs 1:2.1.5-4 закреплён явно.
|
||||
- PostgreSQL 17.10-alpine: 1 CPU, 768 MiB, durable WAL settings включены.
|
||||
- Valkey 8.1.3-alpine: 0.5 CPU, 128 MiB; кэш публичных пользователей, не сессий.
|
||||
- HAProxy 3.2-alpine закреплён digest: 0.5 CPU, 128 MiB; stream forwarding без полного буферирования тела.
|
||||
- SeaweedFS 4.15 закреплён digest: backend 1 CPU/512 MiB, S3 gateway 0.5 CPU/256 MiB.
|
||||
- Каждая API: 0.5 CPU/512 MiB, один worker, non-root UID10001, read-only FS, tmpfs16MiB, drop capabilities, no-new-privileges.
|
||||
|
||||
При первоначальном переносе bytea-миграция несовместима со старым runtime ЛР2: такой переход требует maintenance window. Поочерёдная замена одинаковой версии с уже применённой схемой не требует повторной миграции.
|
||||
|
||||
## Архитектура и источник истины
|
||||
|
||||
```text
|
||||
Клиент → HAProxy → API × 2 → PostgreSQL (сессии/данные/метаданные/intent)
|
||||
↘ Valkey (кэш публичных карточек пользователей)
|
||||
↘ S3 gateway → Seaweed backend (bytes)
|
||||
```
|
||||
|
||||
Seaweed backend подключён только к отдельной `storage_backend` internal network. API к ней не подключается: filer/master/volume интерфейсы недоступны из общей API-сети. S3 gateway подключён к обеим сетям и предоставляет только S3-интерфейс на общей сети; публичных host ports у него нет. Admin identity присутствует только у gateway и bootstrap/research, API получает bucket-scoped Read/Write/List identity.
|
||||
|
||||
Readiness проверяет обязательные таблицы и столбцы PostgreSQL запросом WHERE false, затем доступность S3 bucket. Простого SELECT 1 недостаточно для обнаружения отсутствующей схемы.
|
||||
|
||||
Ни случайный UUID, ни приватный bucket не заменяют ACL: метаданные и content выдаются только после проверки PostgreSQL-сессии и членства в чате. Сессии не кэшируются. Валидный токен не открывает чужой чат. Оригинал скачивается через авторизованный API без redirect.
|
||||
|
||||
Сообщения сохраняют порядок attachment_ids в message_attachments.position. Идемпотентность из ЛР3 атомарно сохраняет сообщение, связи и точный ответ; перестановка вложений при том же ключе считается другим body. Пропущенный attachment_ids и [] эквивалентны. UTF-8 поля сообщений/имён хранятся lossless в bytea, включая NUL, который PostgreSQL text не принимает.
|
||||
|
||||
## Upload и download
|
||||
|
||||
1. Проверяются сессия, чат, filename, MIME.
|
||||
2. Тело читается частями в spool: первые 256 KiB в RAM, далее временный файл в ограниченном tmpfs. Максимум 10 MiB, таймаут чтения 15 секунд.
|
||||
3. По одному upload slot на API, лишняя работа получает 429/Retry-After. Сжатое содержимое передаётся короткоживущему процессу ограниченной копией до10MiB; второй10MiB-файл в tmpfs не создаётся. API не сохраняет декодированные пиксели между запросами.
|
||||
4. Child проверяет MIME и размеры до decode. Для PNG/APNG Pillow проверяет CRC и декодирует каждый кадр по очереди; общий бюджет всех canvas, включая default image, не более40млн пикселей. Raw acTL/fcTL сверяются, чтобы нулевое/поддельное число кадров не скрывало повреждение. Для JPEG после проверки метаданных строгий djpeg полностью декодирует пиксели построчно в/dev/null, с nativebudget384MiB и timeout4s. Второй полный Pillow.load JPEG не выполняется: он избыточен и у progressiveCMYK мог одновременно держать коэффициенты320MB и canvas160MB. Child Linux address-space limit512MiB, CPU4s; parent walltimeout5s завершает всю process group, включая native grandchildren. Ошибка/падение/таймаут декодера даёт415, превышение bytes/pixel budget413; недоступность запуска процесса503.
|
||||
5. После полной валидации фиксируется durable upload_intent. Под его row lock выполняются S3 PUT и транзакция ready metadata + удаление intent.
|
||||
6. Только успешное завершение COMMIT даёт 201 ready с variants=[] и error_code=null. SHA-256/size/MIME относятся к исходным bytes.
|
||||
|
||||
Filename не используется в object key. Отклоняются slash, backslash, все Unicode Cc (включая C0, C1 и DEL), пустые/пробельные имена и длина вне1..255. MIME сравнивается с фактическим PNG/JPEG. Download получает S3 stream заранее и отдаёт части по64KiB; отсутствие variant у ready возвращает404, failed content409. Ошибка S3 до начала ответа переводится в503. Если сеть оборвётся после отправки HTTP headers, клиент увидит оборванный поток и должен проверить размер/checksum.
|
||||
|
||||
Прерванный HTTP приём закрывает spool и освобождает slot до создания intent/объекта. Неопределённый COMMIT не приводит к немедленному удалению S3: возможно, ready уже зафиксирован. Остатки очищаются сверкой после grace.
|
||||
|
||||
## Согласованность и исследование на 5
|
||||
|
||||
Подробная гипотеза, окна отказа и команды находятся в [research/README.md](research/README.md).
|
||||
|
||||
Reconciler по умолчанию dry-run. Явный apply может удалять старые orphan objects и завершать очистку abandoned intent; live intent защищён row lock, свежие bytes — независимой проверкой LastModified. Перед мутацией выполняется актуальный HEAD, не используется только старый LIST snapshot. Пропавший оригинал старой ready metadata помечается failed/storage_missing, но запись и связи сообщений сохраняются. Валидные ready вложения не удаляются даже без сообщения.
|
||||
|
||||
```sh
|
||||
# Обычная сверка основного стенда — без изменений:
|
||||
docker compose run --rm --no-deps api python -m messenger.reconcile
|
||||
# Явное исправление после просмотра dry-run:
|
||||
docker compose run --rm --no-deps api python -m messenger.reconcile --apply --grace-seconds 3600
|
||||
# Изолированное исследование в новых временных БД и bucket:
|
||||
docker compose run --rm --no-deps research
|
||||
```
|
||||
|
||||
Проверяются реальные PG INSERT failure после PUT, ошибка подключения S3, потеря подтверждения после успешного COMMIT, PG DELETE failure после удаления S3, повторный dry-run после частичного удаления, S3 delete failure/recovery, fresh orphan, old intent с fresh bytes, live writer lock, missing used metadata. Временные исследовательские ресурсы удаляются в finally, рабочая messenger не очищается.
|
||||
|
||||
Стоимость обхода измеряется на10/100/1000 добавленных intact attachments, по3 dry-run, page_size100. Перед измерением все добавленные объекты выдерживаются за границу grace, чтобы fresh-skip не менял профиль работы. Точные размеры с учётом сохранённых fault fixtures находятся в JSON. Измеряются время и количество просмотренных объектов/метаданных; это SQL+S3 обход, не HTTP throughput.
|
||||
|
||||
После сохранённых измерений отдельно исправлены строгий RFC3339Z cursor, UTF-8 JSON guard и validation edge cases progressive JPEG/APNG. Сам reconciler, S3 adapter и схема этого эксперимента не изменились. Исходные hashes в raw JSON оставлены как снимок измеренного runtime, не переписаны под новые файлы. Финальные HTTP/unit регрессии и отдельные image-validation receipts проверяют последние изменения; они не выдаются за повторный замер исследования сверки.
|
||||
|
||||
### Результат исследовательского прогона
|
||||
|
||||
[reconcile-study.json](evidence/reconcile-study.json) содержит **30 успешных проверок**, девять замеров обхода и hashes runtime. Первый apply удалил остатки двух старых intent и orphan, пометил один missing original failed; повтор не сделал новых изменений. Проверены также ошибка DELETE после удаления bytes и последующий read-only dry-run. Временные БД и bucket удалены.
|
||||
|
||||
| Добавлено intact | Фактически просмотрено metadata | Медиана трёх обходов |
|
||||
|---:|---:|---:|
|
||||
| 10 | 13 | 0,023085 с |
|
||||
| 100 | 103 | 0,170581 с |
|
||||
| 1000 | 1003 | 1,581705 с |
|
||||
|
||||
Рост близок к росту числа HEAD/SQL round trips. Это локальная стоимость консервативного обхода; нет утверждения о линейности для любой БД/сети. Помимо добавленных строк остаются три intact fault fixtures; missing failed исключён из ready scan.
|
||||
|
||||
### Результат десяти конкурентных upload
|
||||
|
||||
`upload-memory-final.json` — исходный снимок до поздних исправлений валидатора. Его данные и hashes не переписаны. Отдельная новая image-validation проверка ниже проверяет текущий short-lived child на больших файлах; это другой сценарий, не подмена старого эксперимента.
|
||||
|
||||
|
||||
После рестарта API с сохранением старого токена проверены PNG 788100 и 8683594 байт. На каждом размере десять клиентов начали одновременно; **2 получили 201, 8 — контролируемый 429**, затем readiness200. У API и LB `oom=0`, `oom_kill=0`, процессы остались живы. Cgroup lifetime peaks: API 122773504 и122679296 байт, LB19656704 байт. Лимиты соответственно512/512/128MiB.
|
||||
|
||||
Before/after peaks не выросли: начальная загрузка приложения/Argon2 уже создала больший high-water. Поэтому опыт доказывает ограниченное поведение выбранной нагрузки без OOM, но не выделяет точную память одной загрузки и не доказывает экономию RAM самим spool.
|
||||
|
||||
### Поздняя проверка полного диапазона изображений
|
||||
|
||||
Повторное изучение замечаний обнаружило допустимый36M progressiveRGBJPEG, который прежний nativebudget192MiB отклонял, и APNG с повреждённым вторым кадром. Регрессия на отдельном Docker project до правки:3 failed/1 passed. После правки проверены большие RGB/CMYK progressiveJPEG, маленькиеCMYK baseline/progressive, полный APNG decode, повреждённый later frame, rawacTL0/forgedcount, default image,40M cumulative boundary и50M rejection. Последовательность APNG40M→CMYK40M→RGB36M→обычныйPNG возвращает201 с неизменными original bytes при API512MiB и безOOM. Пик/счётчики и текущие source hashes сохранены в отдельном receipt.
|
||||
|
||||
Полный собственный набор после основной правки:155 passed; child timeout/crash boundary дополнительно проверена пятью unit-тестами. Финальные smoke/schema/lint и целевые image-регрессии находятся в новых evidence с суффиксом image-fix.
|
||||
|
||||
## Проверки и доказательства
|
||||
|
||||
| Критерий | Сценарий | Доказательство |
|
||||
|---|---|---|
|
||||
| Контракт и схема | make check validate | evidence/contract-checks.txt |
|
||||
| Обязательный API, PNG/ACL/checksum/idempotency | make test | evidence/smoke-image-fix-final.txt |
|
||||
| Негативные/параллельные/Unicode/вложения/cursor | make student-test | evidence/tests-image-fix-final.txt |
|
||||
| Повреждённый JPEG с поддельным EOI | regression до исправления и полный тест после djpeg | evidence/attachments-before-strict-jpeg.txt; evidence/tests-image-fix-final.txt |
|
||||
| Независимая проверка реального HTTP | root external regression | Отдельная итоговая проверка общего пакета |
|
||||
| Десять одновременных upload | research/upload_memory.py | evidence/upload-memory-final.json |
|
||||
| Reconciler/fault-injection/стоимость | tools profile research | evidence/reconcile-study.json |
|
||||
| Сохранность данных/прежней сессии/файла | make test-persistence + реальные timestamps | evidence/persistence-final.txt; persistence-before-containers.json; persistence-after-containers.json |
|
||||
| Отказ каждой физической API | 4 публичных failover до покрытия двух разных контейнеров | evidence/failover-1.txt .. failover-4.txt; failover-hooks.jsonl |
|
||||
| Отказ именно загрузившей API и download другой | scripts/verify_attachment_failover.py | evidence/attachment-failover.json |
|
||||
| Приватный S3/ограниченные credentials/backend isolation/отказы/schema | scripts/verify_storage.py: 15 проверок | evidence/storage-checks.json |
|
||||
| JSON503 без выдуманного instance при отсутствии всех API | explicit stop all APIs | evidence/attachment-failover.json |
|
||||
|
||||
### Наблюдения отказов
|
||||
|
||||
Действительный upload обслужила одна API, затем она была остановлена по её X-Instance-Id. Другая API вернула те же исходные bytes через 2,318 секунды; сохранены оба alias и checksum. Публичные failover-прогоны допускают краткие ошибки обнаружения: точные успешные записи, failed_attempts и first_recovery_seconds находятся в четырёх raw outputs. После каждого отказа реплика восстановлена; audit доказывает остановку двух разных контейнеров, а не только смену заголовка.
|
||||
|
||||
При выключенном S3 direct API readiness и content возвращают503 в пределах сетевых таймаутов. После запуска оригинал совпадает. Paused PostgreSQL даёт503 с client-side deadline; после unpause прежняя сессия работает. Переименование message_requests делает readiness503, возврат схемы восстанавливает200. Когда LB не видит ни одной готовой API, он возвращает JSON503 с динамическим согласованным X-Request-Id и без фиктивного X-Instance-Id.
|
||||
|
||||
## Ограничения
|
||||
|
||||
- Один host, LB, PostgreSQL и Seaweed backend остаются точками отказа; две API-реплики не создают HA всех зависимостей.
|
||||
- Сверка может пометить потерянные bytes failed, но не восстановить их без backup. Здесь не настраивается внешнее резервное копирование S3.
|
||||
- Нет распределённого COMMIT через PostgreSQL и S3: остатки допустимы до grace/apply. Уникальные immutable server keys и intent делают выбранную очистку безопасной для штатного API; конкурентное ручное изменение администратором после HEAD находится вне этой гарантии.
|
||||
- Очереди обработки изображений нет: ЛР4 синхронная, thumbnail/crop/optimized относятся к ЛР5.
|
||||
- HTTP допустим для локального изолированного стенда с синтетическими данными. Удалённая передача секретов требует TLS.
|
||||
- Native decoder/libjpeg и Pillow ограничены memory/time/cgroup; корректность декодирования зависит от закреплённых библиотек. Проверены конкретные повреждения из замечаний,36M RGB progressive,40M CMYK progressive и последовательность APNG40M→CMYK40M→RGB36M→обычныйPNG при512MiB API безOOM. Кадры APNG валидируются все, а thumbnail следующей ЛР5 строится по первому кадру; такая политика не изменяет original bytes.
|
||||
- Client-side deadline ограничивает ожидание одного обращения к PostgreSQL, а не весь HTTP-путь; при неопределённом результате записи ключ идемпотентности защищает повтор сообщения. Upload не имеет такого ключа и не должен автоматически повторяться как будто это тот же объект.
|
||||
|
||||
## Источники
|
||||
|
||||
Оригинальные contracts/README и OpenAPI текущего skeleton, Docker Compose reference, документация PostgreSQL/psycopg, boto3 S3 client и SeaweedFS S3 configuration, Pillow Image API и libjpeg-turbo djpeg. Проверки кода опираются на сохранённые версии зависимостей и реальные ответы стенда.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Учтённые замечания преподавателей
|
||||
|
||||
Чужие PR использованы для изучения требований и типовых ошибок до реализации, не как источник кода или результатов. Отсутствие комментария не трактуется как доказательство правильности решения. Исходные комментарии доступны по ссылкам ниже; обзор собран 2026-11-06.
|
||||
|
||||
| Источник | Риск | Наше решение / проверка |
|
||||
|---|---|---|
|
||||
| [PR1](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/1#issuecomment-238) | Dry-run продолжает частичное удаление; missing/null в JSON принимаются | Каждая мутация только внутри apply; real DB DELETE fault → dry-run → repeat. Strict модели отличают обязательный text и массив attachment_ids |
|
||||
| [PR4](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/4#issuecomment-506), [PR7](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/7#issuecomment-571) | Повреждённые изображения, неверные byte/pixel лимиты, root credentials, S3 500/timeouts | Полное verify+decode, проверка размеров до decode, 10 MiB включительно через LB, bounded S3 calls, отдельные app/admin keys |
|
||||
| [PR8](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/8#issuecomment-572) | PNG palette 257 и недопустимый filter | Проверяет Pillow 12.3; отдельные воспроизведения |
|
||||
| [PR12](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/12#issuecomment-630) | Удаление S3 при неопределённом COMMIT | Никакого немедленного delete в catch; durable upload_intent, сверка после grace |
|
||||
| [PR13](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/13#issuecomment-735) | Пробельный filename, тест ACL без Idempotency-Key | Filename проверяется до I/O; тесты авторизации предъявляют действительный ключ |
|
||||
| [PR24](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/24#issuecomment-990), [PR25](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/25#issuecomment-1007), [PR49](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/49#issuecomment-1507) | JPEG без scan/половина JPEG с поддельным EOI; OOM LB | Pillow дополняется строгим djpeg с timeout; 10 конкурентных upload через HAProxy, memory.events/peak API и LB |
|
||||
| [PR27](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/27#issuecomment-1442), [PR15](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/15#issuecomment-1444) | Анонимный filer GET обходит приватный S3 | Storage backend в отдельной internal network; API видит только S3 gateway |
|
||||
| [PR22](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/22#issuecomment-1446) | Filename C0/C1/DEL, неверные 400/404/415, потеря порядка вложений | Unicode category Cc; контрактные коды; position в связях и сохранённый JSON ответа |
|
||||
| [PR21](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/21#issuecomment-1448) | Pending никогда не очищается | Старые intent удаляются с их остаточными объектами после grace; активная row lock защищает живой PUT |
|
||||
| [PR47](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/47#issuecomment-1508) | Pixel bomb неверный код; отсутствующий filename 422 | Dimension check до декодирования, DecompressionBombError→413; собственная query validation→400 |
|
||||
| [PR56](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/56#issuecomment-1550) | JSON null и повреждённые PNG/JPEG | Strict model + generated corrupt fixtures |
|
||||
| [PR60](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/60#issuecomment-1551) | Проверка только заголовка крупных файлов, NUL text, paused PostgreSQL | Полный decode во всём допустимом диапазоне; bytea для lossless UTF-8; client-side deadline connection |
|
||||
| [PR59](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/59#issuecomment-1552), [PR64](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/64#issuecomment-1576), [PR63](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/63#issuecomment-1625) | Серверный SQL timeout не срабатывает при pause БД | Клиентский I/O deadline закрывает неопределённое соединение; реальные pause/resume проверки |
|
||||
| [PR28](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/28#issuecomment-1555) | Username с завершающим LF | Полный re.fullmatch до INSERT |
|
||||
| [PR58](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/58#issuecomment-1573) | Игнорирование variant/status и воскресающая сессия из кэша | Проверки ready/variant перед GET; каждая сессия проверяется в PostgreSQL |
|
||||
|
||||
Дополнительно при сверке учитываются возраст объекта независимо от возраста intent, повторный HEAD перед мутацией вместо старого снимка LIST, сохранение используемых и свежих вложений и запрет сортировать attachment_ids при сравнении идемпотентного запроса. Детальные результаты находятся в REPORT.md и evidence.
|
||||
@@ -0,0 +1,37 @@
|
||||
# Схема PostgreSQL и связь с S3
|
||||
|
||||
Основной источник истины — PostgreSQL. В S3 находятся только исходные bytes вложения. Valkey содержит временные копии публичных пользователей, TTL60, без сессий и истории.
|
||||
|
||||
| Таблица | Ключи и назначение |
|
||||
|---|---|
|
||||
| users | UUID PK, username UNIQUE, Argon2id password_hash, UTF-8 display_name в bytea |
|
||||
| chats | UUID PK, UTF-8 title в bytea, server UTC created_at |
|
||||
| members | PK(chat_id,user_id), FK к chats/users, UNIQUE(chat_id,position) |
|
||||
| messages | UUID PK, FK(chat_id,sender_id)→members, UTF-8 text в bytea, UTC created_at |
|
||||
| message_requests | Уникальный scope(actor_id,chat_id,key), body_digest, точный JSON response в bytea, expires_at24h |
|
||||
| sessions | SHA-256 token_digest PK, user FK, абсолютный expires_at |
|
||||
| attachments | UUID PK, chat/owner FK, filename/MIME/size/SHA-256, status/error, created_at/updated_at, object_key UNIQUE |
|
||||
| message_attachments | PK(message_id,attachment_id), FK к message/attachment, UNIQUE(message_id,position), position0..9 |
|
||||
| upload_intents | UUID PK, object_key UNIQUE, created_at; durable запись до PUT |
|
||||
| attachment_reconcile_audit | Генерируемый PK, безопасный event, внутренний object_key и время apply |
|
||||
| schema_migrations | Имя SQL-файла PK и SHA-256 применённого содержимого |
|
||||
|
||||
## Миграции
|
||||
|
||||
1. 001_initial: базовые таблицы/ограничения/индексы ЛР2.
|
||||
2. 002_idempotency: общий результат POST message для всех API-реплик.
|
||||
3. 003_unicode_storage: lossless UTF-8 в bytea для полей, допускающих NUL; старому runtime нужна остановка на переход.
|
||||
4. 004_attachments: attachments, links, durable intents и audit.
|
||||
5. 005_attachment_only_message: допускает нулевую длину bytea text; API требует хотя бы одно вложение для пустого/пробельного текста.
|
||||
|
||||
Мигратор применяет файлы последовательно в транзакции под advisory lock. Повторный запуск пропускает неизменившиеся миграции; изменённый применённый файл вызывает ошибку.
|
||||
|
||||
## Индексы и транзакции
|
||||
|
||||
История читается keyset по `(chat_id,created_at,id)` с соответствующим B-tree. ID разрешает совпадения времени. Cursor scoped к чату и валидируется до SQL; он не создаёт snapshot между страницами.
|
||||
|
||||
`message_attachments_attachment_idx` помогает находить ссылки на вложение. `upload_intents_created_idx` поддерживает обход старых intent через `(created_at,id)` без OFFSET. Публичный порядок вложений берётся из position, не сортируется по UUID.
|
||||
|
||||
Создание чата с участниками атомарно. Отправка сообщения, проверка вложений того же чата под row lock, связи и сохранённый ответ идемпотентности выполняются одной транзакцией. Read-after-write обеспечивается чтением общего PostgreSQL, история не кэшируется.
|
||||
|
||||
Upload сначала фиксирует intent, затем держит его `FOR UPDATE` во время S3 PUT и финализации ready metadata. PostgreSQL и S3 не имеют общей транзакции. Неопределённый COMMIT не запускает delete; только консервативная сверка после grace может убрать abandoned остаток. Публичный API не раскрывает object_key, внутренние адреса или credentials.
|
||||
+2
-2
@@ -67,7 +67,7 @@ services:
|
||||
s3-bootstrap: {condition: service_completed_successfully}
|
||||
storage:
|
||||
image: chrislusf/seaweedfs:4.15@sha256:1593bd2a98964f5d4df83fa7db2b3d4ee7b20190813cc5bf8c3200e0e70d346e
|
||||
command: [server, -dir=/data, -ip=storage, -ip.bind=0.0.0.0, -filer, -volume.max=4, -volume.preStopSeconds=0, -master.volumeSizeLimitMB=64]
|
||||
command: [server, -dir=/data, -ip=storage, -ip.bind=0.0.0.0, -filer, -volume.max=32, -volume.preStopSeconds=0, -master.volumeSizeLimitMB=64]
|
||||
volumes: ["s3_data:/data", "./infra/filer.toml:/etc/seaweedfs/filer.toml:ro"]
|
||||
networks: [storage_backend]
|
||||
cpus: 1
|
||||
@@ -79,7 +79,7 @@ services:
|
||||
retries: 20
|
||||
s3:
|
||||
image: chrislusf/seaweedfs:4.15@sha256:1593bd2a98964f5d4df83fa7db2b3d4ee7b20190813cc5bf8c3200e0e70d346e
|
||||
command: [s3, -filer=storage:8888, -ip.bind=0.0.0.0, -config=/run/secrets/s3_config, -port=8333]
|
||||
command: [s3, -filer=storage:8888, -ip.bind=0.0.0.0, -config=/run/secrets/s3_config, -port=8333, -port.iceberg=0]
|
||||
secrets: [s3_config]
|
||||
networks: [default, storage_backend]
|
||||
depends_on:
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"uploader_instance": "2ce0bbc4-1cd3-4f73-95a0-e4ca5b2a752c",
|
||||
"download_instance": "52106d2a-9828-4995-8a50-02f0607c18da",
|
||||
"same_original_bytes": true,
|
||||
"sha256": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75",
|
||||
"elapsed_seconds": 2.3175257910043,
|
||||
"lb_no_backend": {
|
||||
"status": 503,
|
||||
"request_id": "0a7be913-caf6-490f-88a6-9407cda9391c",
|
||||
"no_fake_instance": true
|
||||
},
|
||||
"existing_session_recovers": true
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"uploader_instance": "2ce0bbc4-1cd3-4f73-95a0-e4ca5b2a752c", "download_instance": "52106d2a-9828-4995-8a50-02f0607c18da", "same_original_bytes": true, "sha256": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75", "elapsed_seconds": 2.3175257910043, "lb_no_backend": {"status": 503, "request_id": "0a7be913-caf6-490f-88a6-9407cda9391c", "no_fake_instance": true}, "existing_session_recovers": true}
|
||||
@@ -0,0 +1,43 @@
|
||||
..........................F [100%]
|
||||
=================================== FAILURES ===================================
|
||||
_____________________ test_truncated_jpeg_with_forged_eoi ______________________
|
||||
|
||||
scenario = (<client.Client object at 0x105defaa0>, {'id': '881b708c-1c42-4d33-a7ff-0a24d24180ed', 'user': {'id': '881b708c-1c42-4...-06T14:52:44.187538Z', 'member_ids': ['881b708c-1c42-4d33-a7ff-0a24d24180ed', 'e9f642b2-d052-420a-9f41-113bc79347fe']})
|
||||
|
||||
def test_truncated_jpeg_with_forged_eoi(scenario):
|
||||
import random
|
||||
|
||||
stream = BytesIO()
|
||||
Image.frombytes("RGB", (512, 512), random.Random(42).randbytes(512 * 512 * 3)).save(
|
||||
stream, "JPEG", quality=95
|
||||
)
|
||||
original = stream.getvalue()
|
||||
upload(scenario, data=original, name="real.jpg", mime="image/jpeg")
|
||||
> upload(
|
||||
scenario,
|
||||
data=original[: len(original) // 2] + b"\xff\xd9",
|
||||
name="broken.jpg",
|
||||
mime="image/jpeg",
|
||||
status=415,
|
||||
)
|
||||
|
||||
student-tests/test_attachments.py:195:
|
||||
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
|
||||
student-tests/test_attachments.py:30: in upload
|
||||
return c.call(
|
||||
tests/client.py:132: in call
|
||||
check(status in allowed, method + ' ' + path.split('?')[0] + ': expected ' + str(allowed) + ', received ' + str(status))
|
||||
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
|
||||
|
||||
condition = False
|
||||
message = 'POST /api/v1/chats/ed1d5486-a609-41e0-8066-e2abfcd078c0/attachments: expected [415], received 201'
|
||||
|
||||
def check(condition, message):
|
||||
if not condition:
|
||||
> raise Failure(message)
|
||||
E client.Failure: POST /api/v1/chats/ed1d5486-a609-41e0-8066-e2abfcd078c0/attachments: expected [415], received 201
|
||||
|
||||
tests/client.py:24: Failure
|
||||
=========================== short test summary info ============================
|
||||
FAILED student-tests/test_attachments.py::test_truncated_jpeg_with_forged_eoi
|
||||
1 failed, 26 passed in 0.93s
|
||||
@@ -0,0 +1,155 @@
|
||||
Image mtusi-vasilev:lab4 Building
|
||||
Image mtusi-vasilev:lab4 Building
|
||||
Image mtusi-vasilev:lab4 Building
|
||||
#1 [internal] load local bake definitions
|
||||
#1 reading from stdin 1.91kB done
|
||||
#1 DONE 0.0s
|
||||
|
||||
#2 [s3-bootstrap internal] load build definition from Dockerfile
|
||||
#2 transferring dockerfile: 1.07kB done
|
||||
#2 DONE 0.0s
|
||||
|
||||
#3 [migrate internal] load metadata for ghcr.io/astral-sh/uv:0.11.7
|
||||
#3 DONE 0.0s
|
||||
|
||||
#4 [s3-bootstrap internal] load metadata for docker.io/library/python:3.12-slim@sha256:646fb0bca3dd3ea1bcc6feb72c17ed16eed6e10cffc732fcc1478bd3e7f02d7b
|
||||
#4 DONE 0.0s
|
||||
|
||||
#5 [api internal] load .dockerignore
|
||||
#5 transferring context: 109B done
|
||||
#5 DONE 0.0s
|
||||
|
||||
#6 [migrate internal] load build context
|
||||
#6 transferring context: 32.99kB done
|
||||
#6 DONE 0.0s
|
||||
|
||||
#7 [s3-bootstrap 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 [migrate] FROM ghcr.io/astral-sh/uv:0.11.7@sha256:240fb85ab0f263ef12f492d8476aa3a2e4e1e333f7d67fbdd923d00a506a516a
|
||||
#8 resolve ghcr.io/astral-sh/uv:0.11.7@sha256:240fb85ab0f263ef12f492d8476aa3a2e4e1e333f7d67fbdd923d00a506a516a 0.0s done
|
||||
#8 DONE 0.0s
|
||||
|
||||
#9 [api 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/*
|
||||
#9 CACHED
|
||||
|
||||
#10 [api build 2/5] COPY --from=ghcr.io/astral-sh/uv:0.11.7 /uv /usr/local/bin/uv
|
||||
#10 CACHED
|
||||
|
||||
#11 [api build 5/5] RUN uv sync --locked --no-dev --no-install-project --python /usr/local/bin/python
|
||||
#11 CACHED
|
||||
|
||||
#12 [api build 4/5] COPY pyproject.toml uv.lock ./
|
||||
#12 CACHED
|
||||
|
||||
#13 [api stage-1 3/6] WORKDIR /app
|
||||
#13 CACHED
|
||||
|
||||
#14 [api build 3/5] WORKDIR /app
|
||||
#14 CACHED
|
||||
|
||||
#15 [s3-bootstrap stage-1 4/6] COPY --from=build /app/.venv /app/.venv
|
||||
#15 CACHED
|
||||
|
||||
#16 [s3-bootstrap stage-1 5/6] COPY src ./src
|
||||
#16 DONE 0.0s
|
||||
|
||||
#17 [api stage-1 6/6] COPY migrations ./migrations
|
||||
#17 DONE 0.0s
|
||||
|
||||
#18 [api] exporting to image
|
||||
#18 exporting layers 0.0s done
|
||||
#18 exporting manifest sha256:76e4717644b7216802f263cecdc39b1b8909111738b9595eb11d2a69fded5cf5 done
|
||||
#18 exporting config sha256:a5eb2b1b6617dc8eeb1b37ab4a36f375b33482ea9e0372bc6eafaa32b69354b6
|
||||
#18 exporting config sha256:a5eb2b1b6617dc8eeb1b37ab4a36f375b33482ea9e0372bc6eafaa32b69354b6 0.0s done
|
||||
#18 exporting attestation manifest sha256:052d9bea4bb919ea1aedd937166fb57f95b69f8b7afd94ff08013d8c3be404e3 0.0s done
|
||||
#18 exporting manifest list sha256:cfcd162da81cd5a5f1e6729a245b7c1fc814b5cbc1a543b2a50d0131dae5120b done
|
||||
#18 naming to docker.io/library/mtusi-vasilev:lab4 done
|
||||
#18 unpacking to docker.io/library/mtusi-vasilev:lab4 0.0s done
|
||||
#18 DONE 0.1s
|
||||
|
||||
#19 [s3-bootstrap] exporting to image
|
||||
#19 exporting layers 0.0s done
|
||||
#19 exporting manifest sha256:23e60390e8d2edca4c8664bda72b63b7fbfaab5ef91c09c9dc3dd09ccbf889dc done
|
||||
#19 exporting config sha256:808eb376512c2f8bd0148c5a1ac9a3ddbe2a34184cb7c3cb1e9a081955bae2a6 0.0s done
|
||||
#19 exporting attestation manifest sha256:e8977fb690c0b5986719e2e960dd939b8f9ccadc2b5a009370959a3d85e9390f 0.0s done
|
||||
#19 exporting manifest list sha256:593cdabf59cf1bf0ff446446a6138270a064bce3da5b08095b95096700da485d done
|
||||
#19 naming to docker.io/library/mtusi-vasilev:lab4 done
|
||||
#19 unpacking to docker.io/library/mtusi-vasilev:lab4 0.0s done
|
||||
#19 DONE 0.1s
|
||||
|
||||
#20 [migrate] exporting to image
|
||||
#20 exporting layers 0.0s done
|
||||
#20 exporting manifest sha256:85518f8cd6ca3f1af9a60e4b594d4dc02717b9ca2b402823eecebec387f67afe 0.0s done
|
||||
#20 exporting config sha256:e6cbef2d7963fb852a2fdd3d2012b69a4c9f0ab81e6dd65bc3d9a17cbb37561e 0.0s done
|
||||
#20 exporting attestation manifest sha256:70ce3b90e76d010cbd587cc1a2c3fa66e31a427c996cb86be9975765493529e5 0.0s done
|
||||
#20 exporting manifest list sha256:d8e01d722065f1b4b46706f834e2727124409d8c90dd9a707a2b97bd91600980 done
|
||||
#20 naming to docker.io/library/mtusi-vasilev:lab4 done
|
||||
#20 unpacking to docker.io/library/mtusi-vasilev:lab4 0.0s done
|
||||
#20 DONE 0.1s
|
||||
|
||||
#21 [api] resolving provenance for metadata file
|
||||
#21 DONE 0.0s
|
||||
|
||||
#22 [s3-bootstrap] resolving provenance for metadata file
|
||||
#22 DONE 0.0s
|
||||
|
||||
#23 [migrate] resolving provenance for metadata file
|
||||
#23 DONE 0.0s
|
||||
Image mtusi-vasilev:lab4 Built
|
||||
Image mtusi-vasilev:lab4 Built
|
||||
Image mtusi-vasilev:lab4 Built
|
||||
Container mtusi-vasilev-lab4-cache-1 Running
|
||||
Container mtusi-vasilev-lab4-postgres-1 Running
|
||||
Container mtusi-vasilev-lab4-s3-1 Running
|
||||
Container mtusi-vasilev-lab4-storage-1 Running
|
||||
Container mtusi-vasilev-lab4-lb-1 Running
|
||||
Container mtusi-vasilev-lab4-migrate-1 Recreate
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Recreate
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Recreated
|
||||
Container mtusi-vasilev-lab4-migrate-1 Recreated
|
||||
Container mtusi-vasilev-lab4-api-1 Recreate
|
||||
Container mtusi-vasilev-lab4-api-2 Recreate
|
||||
Container mtusi-vasilev-lab4-api-2 Recreated
|
||||
Container mtusi-vasilev-lab4-api-1 Recreated
|
||||
Container mtusi-vasilev-lab4-storage-1 Waiting
|
||||
Container mtusi-vasilev-lab4-postgres-1 Waiting
|
||||
Container mtusi-vasilev-lab4-postgres-1 Healthy
|
||||
Container mtusi-vasilev-lab4-migrate-1 Starting
|
||||
Container mtusi-vasilev-lab4-storage-1 Healthy
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Starting
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Started
|
||||
Container mtusi-vasilev-lab4-migrate-1 Started
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Waiting
|
||||
Container mtusi-vasilev-lab4-migrate-1 Waiting
|
||||
Container mtusi-vasilev-lab4-cache-1 Waiting
|
||||
Container mtusi-vasilev-lab4-cache-1 Healthy
|
||||
Container mtusi-vasilev-lab4-migrate-1 Exited
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Exited
|
||||
Container mtusi-vasilev-lab4-api-1 Starting
|
||||
Container mtusi-vasilev-lab4-api-1 Started
|
||||
Container mtusi-vasilev-lab4-api-2 Starting
|
||||
Container mtusi-vasilev-lab4-api-2 Started
|
||||
Container mtusi-vasilev-lab4-api-1 Waiting
|
||||
Container mtusi-vasilev-lab4-api-2 Waiting
|
||||
Container mtusi-vasilev-lab4-api-1 Healthy
|
||||
Container mtusi-vasilev-lab4-api-2 Healthy
|
||||
Container mtusi-vasilev-lab4-api-1 Waiting
|
||||
Container mtusi-vasilev-lab4-api-2 Waiting
|
||||
Container mtusi-vasilev-lab4-lb-1 Waiting
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Waiting
|
||||
Container mtusi-vasilev-lab4-migrate-1 Waiting
|
||||
Container mtusi-vasilev-lab4-cache-1 Waiting
|
||||
Container mtusi-vasilev-lab4-postgres-1 Waiting
|
||||
Container mtusi-vasilev-lab4-s3-1 Waiting
|
||||
Container mtusi-vasilev-lab4-storage-1 Waiting
|
||||
Container mtusi-vasilev-lab4-lb-1 Healthy
|
||||
Container mtusi-vasilev-lab4-migrate-1 Exited
|
||||
Container mtusi-vasilev-lab4-s3-1 Healthy
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Exited
|
||||
Container mtusi-vasilev-lab4-storage-1 Healthy
|
||||
Container mtusi-vasilev-lab4-postgres-1 Healthy
|
||||
Container mtusi-vasilev-lab4-cache-1 Healthy
|
||||
Container mtusi-vasilev-lab4-api-1 Healthy
|
||||
Container mtusi-vasilev-lab4-api-2 Healthy
|
||||
@@ -0,0 +1,214 @@
|
||||
Image mtusi-vasilev:lab4 Building
|
||||
Image mtusi-vasilev:lab4 Building
|
||||
Image mtusi-vasilev:lab4 Building
|
||||
#1 [internal] load local bake definitions
|
||||
#1 reading from stdin 1.91kB done
|
||||
#1 DONE 0.0s
|
||||
|
||||
#2 [api] FROM ghcr.io/astral-sh/uv:0.11.7@sha256:240fb85ab0f263ef12f492d8476aa3a2e4e1e333f7d67fbdd923d00a506a516a
|
||||
#2 resolve ghcr.io/astral-sh/uv:0.11.7@sha256:240fb85ab0f263ef12f492d8476aa3a2e4e1e333f7d67fbdd923d00a506a516a done
|
||||
#2 DONE 0.0s
|
||||
|
||||
#3 [api build 1/5] FROM docker.io/library/python:3.12-slim@sha256:646fb0bca3dd3ea1bcc6feb72c17ed16eed6e10cffc732fcc1478bd3e7f02d7b
|
||||
#3 resolve docker.io/library/python:3.12-slim@sha256:646fb0bca3dd3ea1bcc6feb72c17ed16eed6e10cffc732fcc1478bd3e7f02d7b 0.0s done
|
||||
#3 CACHED
|
||||
|
||||
#4 [s3-bootstrap build 5/5] RUN uv sync --locked --no-dev --no-install-project --python /usr/local/bin/python
|
||||
#4 CACHED
|
||||
|
||||
#5 [migrate internal] load build definition from Dockerfile
|
||||
#5 transferring dockerfile: 1.07kB done
|
||||
#5 DONE 0.0s
|
||||
|
||||
#6 [s3-bootstrap internal] load metadata for ghcr.io/astral-sh/uv:0.11.7
|
||||
#6 DONE 0.0s
|
||||
|
||||
#7 [s3-bootstrap internal] load metadata for docker.io/library/python:3.12-slim@sha256:646fb0bca3dd3ea1bcc6feb72c17ed16eed6e10cffc732fcc1478bd3e7f02d7b
|
||||
#7 DONE 0.0s
|
||||
|
||||
#8 [api internal] load .dockerignore
|
||||
#8 transferring context: 109B done
|
||||
#8 DONE 0.0s
|
||||
|
||||
#9 [api internal] load build context
|
||||
#9 transferring context: 56.14kB done
|
||||
#9 DONE 0.0s
|
||||
|
||||
#10 [api 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/*
|
||||
#10 0.316 Get:1 http://deb.debian.org/debian trixie InRelease [140 kB]
|
||||
#10 0.381 Get:2 http://deb.debian.org/debian trixie-updates InRelease [47.3 kB]
|
||||
#10 0.463 Get:3 http://deb.debian.org/debian-security trixie-security InRelease [43.4 kB]
|
||||
#10 0.591 Get:4 http://deb.debian.org/debian trixie/main arm64 Packages [9614 kB]
|
||||
#10 0.965 Get:5 http://deb.debian.org/debian trixie-updates/main arm64 Packages [1108 B]
|
||||
#10 1.030 Get:6 http://deb.debian.org/debian-security trixie-security/main arm64 Packages [299 kB]
|
||||
#10 1.575 Fetched 10.1 MB in 1s (6874 kB/s)
|
||||
#10 1.575 Reading package lists...
|
||||
#10 1.918 Reading package lists...
|
||||
#10 2.236 Building dependency tree...
|
||||
#10 2.328 Reading state information...
|
||||
#10 2.436 The following additional packages will be installed:
|
||||
#10 2.436 libjpeg62-turbo libturbojpeg0
|
||||
#10 2.461 The following NEW packages will be installed:
|
||||
#10 2.461 libjpeg-turbo-progs libjpeg62-turbo libturbojpeg0
|
||||
#10 2.543 0 upgraded, 3 newly installed, 0 to remove and 28 not upgraded.
|
||||
#10 2.543 Need to get 523 kB of archives.
|
||||
#10 2.543 After this operation, 1650 kB of additional disk space will be used.
|
||||
#10 2.543 Get:1 http://deb.debian.org/debian trixie/main arm64 libjpeg62-turbo arm64 1:2.1.5-4 [173 kB]
|
||||
#10 2.818 Get:2 http://deb.debian.org/debian trixie/main arm64 libturbojpeg0 arm64 1:2.1.5-4 [211 kB]
|
||||
#10 2.854 Get:3 http://deb.debian.org/debian trixie/main arm64 libjpeg-turbo-progs arm64 1:2.1.5-4 [140 kB]
|
||||
#10 2.985 debconf: unable to initialize frontend: Dialog
|
||||
#10 2.985 debconf: (TERM is not set, so the dialog frontend is not usable.)
|
||||
#10 2.985 debconf: falling back to frontend: Readline
|
||||
#10 2.985 debconf: unable to initialize frontend: Readline
|
||||
#10 2.985 debconf: (Can't locate Term/ReadLine.pm in @INC (you may need to install the Term::ReadLine module) (@INC entries checked: /etc/perl /usr/local/lib/aarch64-linux-gnu/perl/5.40.1 /usr/local/share/perl/5.40.1 /usr/lib/aarch64-linux-gnu/perl5/5.40 /usr/share/perl5 /usr/lib/aarch64-linux-gnu/perl-base /usr/lib/aarch64-linux-gnu/perl/5.40 /usr/share/perl/5.40 /usr/local/lib/site_perl) at /usr/share/perl5/Debconf/FrontEnd/Readline.pm line 8, <STDIN> line 3.)
|
||||
#10 2.985 debconf: falling back to frontend: Teletype
|
||||
#10 2.987 debconf: unable to initialize frontend: Teletype
|
||||
#10 2.987 debconf: (This frontend requires a controlling tty.)
|
||||
#10 2.987 debconf: falling back to frontend: Noninteractive
|
||||
#10 3.306 Fetched 523 kB in 0s (1191 kB/s)
|
||||
#10 3.316 Selecting previously unselected package libjpeg62-turbo:arm64.
|
||||
#10 3.316 (Reading database ... ␍(Reading database ... 5%␍(Reading database ... 10%␍(Reading database ... 15%␍(Reading database ... 20%␍(Reading database ... 25%␍(Reading database ... 30%␍(Reading database ... 35%␍(Reading database ... 40%␍(Reading database ... 45%␍(Reading database ... 50%␍(Reading database ... 55%␍(Reading database ... 60%␍(Reading database ... 65%␍(Reading database ... 70%␍(Reading database ... 75%␍(Reading database ... 80%␍(Reading database ... 85%␍(Reading database ... 90%␍(Reading database ... 95%␍(Reading database ... 100%␍(Reading database ... 5642 files and directories currently installed.)
|
||||
#10 3.318 Preparing to unpack .../libjpeg62-turbo_1%3a2.1.5-4_arm64.deb ...
|
||||
#10 3.320 Unpacking libjpeg62-turbo:arm64 (1:2.1.5-4) ...
|
||||
#10 3.337 Selecting previously unselected package libturbojpeg0:arm64.
|
||||
#10 3.337 Preparing to unpack .../libturbojpeg0_1%3a2.1.5-4_arm64.deb ...
|
||||
#10 3.338 Unpacking libturbojpeg0:arm64 (1:2.1.5-4) ...
|
||||
#10 3.354 Selecting previously unselected package libjpeg-turbo-progs.
|
||||
#10 3.354 Preparing to unpack .../libjpeg-turbo-progs_1%3a2.1.5-4_arm64.deb ...
|
||||
#10 3.355 Unpacking libjpeg-turbo-progs (1:2.1.5-4) ...
|
||||
#10 3.371 Setting up libturbojpeg0:arm64 (1:2.1.5-4) ...
|
||||
#10 3.373 Setting up libjpeg62-turbo:arm64 (1:2.1.5-4) ...
|
||||
#10 3.375 Setting up libjpeg-turbo-progs (1:2.1.5-4) ...
|
||||
#10 3.379 Processing triggers for libc-bin (2.41-12+deb13u3) ...
|
||||
#10 DONE 3.4s
|
||||
|
||||
#11 [migrate stage-1 3/6] WORKDIR /app
|
||||
#11 DONE 0.0s
|
||||
|
||||
#12 [s3-bootstrap stage-1 4/6] COPY --from=build /app/.venv /app/.venv
|
||||
#12 DONE 0.3s
|
||||
|
||||
#13 [migrate stage-1 4/6] COPY --from=build /app/.venv /app/.venv
|
||||
#13 CACHED
|
||||
|
||||
#14 [migrate build 4/5] COPY pyproject.toml uv.lock ./
|
||||
#14 CACHED
|
||||
|
||||
#15 [migrate build 5/5] RUN uv sync --locked --no-dev --no-install-project --python /usr/local/bin/python
|
||||
#15 CACHED
|
||||
|
||||
#16 [migrate build 2/5] COPY --from=ghcr.io/astral-sh/uv:0.11.7 /uv /usr/local/bin/uv
|
||||
#16 CACHED
|
||||
|
||||
#17 [migrate build 3/5] WORKDIR /app
|
||||
#17 CACHED
|
||||
|
||||
#18 [s3-bootstrap stage-1 5/6] COPY src ./src
|
||||
#18 DONE 0.0s
|
||||
|
||||
#19 [migrate stage-1 6/6] COPY migrations ./migrations
|
||||
#19 DONE 0.0s
|
||||
|
||||
#20 [s3-bootstrap] exporting to image
|
||||
#20 exporting layers
|
||||
#20 exporting layers 1.4s done
|
||||
#20 exporting manifest sha256:9c7beb537d46f62e0a0125cca10a389b079d69ff236f6ebf103c48a668fe48a9 0.0s done
|
||||
#20 exporting config sha256:4b06563cc9df4800046c57198947d33b3de7ce8ab5e489172a3b79fc1e32a206 0.0s done
|
||||
#20 exporting attestation manifest sha256:63b281e33599928fc2e05e1f503d3a248bd05c3891f609c6183515222d97762c 0.0s done
|
||||
#20 exporting manifest list sha256:02ba01cac8063d6d9d92a423e07a799cb887605f5c2d4c45b0cb2be678555f62 done
|
||||
#20 naming to docker.io/library/mtusi-vasilev:lab4 done
|
||||
#20 unpacking to docker.io/library/mtusi-vasilev:lab4
|
||||
#20 unpacking to docker.io/library/mtusi-vasilev:lab4 0.8s done
|
||||
#20 DONE 2.4s
|
||||
|
||||
#21 [api] exporting to image
|
||||
#21 exporting layers 1.4s done
|
||||
#21 exporting manifest sha256:e099f891bbc8556c8d165432df0607fb19fe94c118a41f07100c83a2070ed33a done
|
||||
#21 exporting config sha256:206eac1e185e7d2e0c51de40eefacd3451e957a541592b347742643f26d513f0 0.0s done
|
||||
#21 exporting attestation manifest sha256:048e39632ccadafe299f7ee0e9b14c6e510cc0cdadb3ad30646cb18620cccc7c 0.0s done
|
||||
#21 exporting manifest list sha256:fb1fa012b813c17f834b01a58e3dff5c48a7376b11942226426e0ed7637ef719 done
|
||||
#21 naming to docker.io/library/mtusi-vasilev:lab4 done
|
||||
#21 unpacking to docker.io/library/mtusi-vasilev:lab4 0.9s done
|
||||
#21 DONE 2.4s
|
||||
|
||||
#22 [migrate] exporting to image
|
||||
#22 exporting layers 1.4s done
|
||||
#22 exporting manifest sha256:b07d34138667c73e38e0a14aeaaab517a72d3f83e52fa9c5abf1b437802396f8 0.0s done
|
||||
#22 exporting config sha256:5c1fc0ea8ee20d8ba557b492b0700e78b506ac52aedf466d1258456061177fd8 0.0s done
|
||||
#22 exporting attestation manifest sha256:56327f9b7aaaa4d121696463d86e51cf52b698f7c9f7efcb989344541c33ac27 0.0s done
|
||||
#22 exporting manifest list sha256:1beedea111bd3f8f5de5a31b7a67b2013ffc9c0271b51313bb6968bcaea96f6e 0.0s done
|
||||
#22 naming to docker.io/library/mtusi-vasilev:lab4 done
|
||||
#22 unpacking to docker.io/library/mtusi-vasilev:lab4 0.9s done
|
||||
#22 DONE 2.5s
|
||||
|
||||
#23 [s3-bootstrap] resolving provenance for metadata file
|
||||
#23 DONE 0.0s
|
||||
|
||||
#24 [api] resolving provenance for metadata file
|
||||
#24 DONE 0.0s
|
||||
|
||||
#25 [migrate] resolving provenance for metadata file
|
||||
#25 DONE 0.0s
|
||||
Image mtusi-vasilev:lab4 Built
|
||||
Image mtusi-vasilev:lab4 Built
|
||||
Image mtusi-vasilev:lab4 Built
|
||||
Container mtusi-vasilev-lab4-migrate-1 Recreate
|
||||
Container mtusi-vasilev-lab4-s3-1 Recreate
|
||||
Container mtusi-vasilev-lab4-s3-1 Recreated
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Recreate
|
||||
Container mtusi-vasilev-lab4-migrate-1 Recreated
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Recreated
|
||||
Container mtusi-vasilev-lab4-api-1 Recreate
|
||||
Container mtusi-vasilev-lab4-api-2 Recreate
|
||||
Container mtusi-vasilev-lab4-api-1 Recreated
|
||||
Container mtusi-vasilev-lab4-api-2 Recreated
|
||||
Container mtusi-vasilev-lab4-storage-1 Starting
|
||||
Container mtusi-vasilev-lab4-cache-1 Starting
|
||||
Container mtusi-vasilev-lab4-postgres-1 Starting
|
||||
Container mtusi-vasilev-lab4-storage-1 Started
|
||||
Container mtusi-vasilev-lab4-storage-1 Waiting
|
||||
Container mtusi-vasilev-lab4-postgres-1 Started
|
||||
Container mtusi-vasilev-lab4-postgres-1 Waiting
|
||||
Container mtusi-vasilev-lab4-cache-1 Started
|
||||
Container mtusi-vasilev-lab4-storage-1 Healthy
|
||||
Container mtusi-vasilev-lab4-s3-1 Starting
|
||||
Container mtusi-vasilev-lab4-postgres-1 Healthy
|
||||
Container mtusi-vasilev-lab4-migrate-1 Starting
|
||||
Container mtusi-vasilev-lab4-s3-1 Started
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Starting
|
||||
Container mtusi-vasilev-lab4-migrate-1 Started
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Started
|
||||
Container mtusi-vasilev-lab4-cache-1 Waiting
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Waiting
|
||||
Container mtusi-vasilev-lab4-migrate-1 Waiting
|
||||
Container mtusi-vasilev-lab4-cache-1 Healthy
|
||||
Container mtusi-vasilev-lab4-migrate-1 Exited
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Exited
|
||||
Container mtusi-vasilev-lab4-api-1 Starting
|
||||
Container mtusi-vasilev-lab4-api-1 Started
|
||||
Container mtusi-vasilev-lab4-api-2 Starting
|
||||
Container mtusi-vasilev-lab4-api-2 Started
|
||||
Container mtusi-vasilev-lab4-api-1 Waiting
|
||||
Container mtusi-vasilev-lab4-api-2 Waiting
|
||||
Container mtusi-vasilev-lab4-api-1 Healthy
|
||||
Container mtusi-vasilev-lab4-api-2 Healthy
|
||||
Container mtusi-vasilev-lab4-lb-1 Starting
|
||||
Container mtusi-vasilev-lab4-lb-1 Started
|
||||
Container mtusi-vasilev-lab4-api-1 Waiting
|
||||
Container mtusi-vasilev-lab4-api-2 Waiting
|
||||
Container mtusi-vasilev-lab4-s3-1 Waiting
|
||||
Container mtusi-vasilev-lab4-postgres-1 Waiting
|
||||
Container mtusi-vasilev-lab4-migrate-1 Waiting
|
||||
Container mtusi-vasilev-lab4-cache-1 Waiting
|
||||
Container mtusi-vasilev-lab4-lb-1 Waiting
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Waiting
|
||||
Container mtusi-vasilev-lab4-storage-1 Waiting
|
||||
Container mtusi-vasilev-lab4-cache-1 Healthy
|
||||
Container mtusi-vasilev-lab4-migrate-1 Exited
|
||||
Container mtusi-vasilev-lab4-s3-1 Healthy
|
||||
Container mtusi-vasilev-lab4-s3-bootstrap-1 Exited
|
||||
Container mtusi-vasilev-lab4-storage-1 Healthy
|
||||
Container mtusi-vasilev-lab4-api-1 Healthy
|
||||
Container mtusi-vasilev-lab4-api-2 Healthy
|
||||
Container mtusi-vasilev-lab4-postgres-1 Healthy
|
||||
Container mtusi-vasilev-lab4-lb-1 Healthy
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,2 @@
|
||||
. [100%]
|
||||
1 passed in 1.66s
|
||||
@@ -0,0 +1,4 @@
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:8084"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 136, "failed_attempts": 2, "first_recovery_seconds": 1.543}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,4 @@
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:8084"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 125, "failed_attempts": 3, "first_recovery_seconds": 2.105}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,4 @@
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:8084"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 124, "failed_attempts": 3, "first_recovery_seconds": 2.213}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,4 @@
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:8084"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 124, "failed_attempts": 3, "first_recovery_seconds": 0.868}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,5 @@
|
||||
{"stopped_container": "255f6fa790fd2b2f5f308846391634c9ff7d308e1d6064085fda31f364b7a6d9", "instance_id": "41205fc8-2249-4028-8387-2a9bb6f40b74", "stopped_at": "2026-11-06T15:16:55.346421+00:00"}
|
||||
{"stopped_container": "255f6fa790fd2b2f5f308846391634c9ff7d308e1d6064085fda31f364b7a6d9", "instance_id": "730d80b7-0f1d-443f-b817-69b96c42257a", "stopped_at": "2026-11-06T15:17:18.680493+00:00"}
|
||||
{"stopped_container": "255f6fa790fd2b2f5f308846391634c9ff7d308e1d6064085fda31f364b7a6d9", "instance_id": "6e460a1c-fe88-4108-bc03-0f5f668e8a65", "stopped_at": "2026-11-06T15:17:42.685676+00:00"}
|
||||
{"stopped_container": "fb116950e109b2c4f68378be994e4fa685b1e32d5df70e4f4ba88b9aaac11734", "instance_id": "6a5a80d4-582a-47a1-9cef-0179b9a423b3", "stopped_at": "2026-11-06T15:18:05.937471+00:00"}
|
||||
{"stopped_container": "255f6fa790fd2b2f5f308846391634c9ff7d308e1d6064085fda31f364b7a6d9", "instance_id": "2ce0bbc4-1cd3-4f73-95a0-e4ca5b2a752c", "stopped_at": "2026-11-06T15:18:34.416070+00:00"}
|
||||
@@ -0,0 +1,2 @@
|
||||
...................... [100%]
|
||||
22 passed in 13.29s
|
||||
@@ -0,0 +1,82 @@
|
||||
FF.F [100%]
|
||||
=================================== FAILURES ===================================
|
||||
_______________ test_36m_progressive_jpeg_is_valid_and_unchanged _______________
|
||||
|
||||
scenario = (<client.Client object at 0x102ae4290>, {'id': 'ef1e6ee9-739a-4dfe-8b05-78bef274c542', 'user': {'id': 'ef1e6ee9-739a-4...-06T15:51:51.913231Z', 'member_ids': ['ef1e6ee9-739a-4dfe-8b05-78bef274c542', '830c471d-1354-43d3-9241-ef98ffc87c7c']})
|
||||
|
||||
def test_36m_progressive_jpeg_is_valid_and_unchanged(scenario):
|
||||
data = progressive_jpeg()
|
||||
> attachment = upload(scenario, data, "image/jpeg", 201)["json"]
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
student-tests/test_image_edges.py:73:
|
||||
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
|
||||
student-tests/test_image_edges.py:21: in upload
|
||||
return c.call(
|
||||
tests/client.py:132: in call
|
||||
check(status in allowed, method + ' ' + path.split('?')[0] + ': expected ' + str(allowed) + ', received ' + str(status))
|
||||
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
|
||||
|
||||
condition = False
|
||||
message = 'POST /api/v1/chats/e9b3f246-cba5-470b-b88f-35da5340b635/attachments: expected [201], received 415'
|
||||
|
||||
def check(condition, message):
|
||||
if not condition:
|
||||
> raise Failure(message)
|
||||
E client.Failure: POST /api/v1/chats/e9b3f246-cba5-470b-b88f-35da5340b635/attachments: expected [201], received 415
|
||||
|
||||
tests/client.py:24: Failure
|
||||
__________________ test_apng_corrupt_later_frame_is_rejected ___________________
|
||||
|
||||
scenario = (<client.Client object at 0x102ae4290>, {'id': 'ef1e6ee9-739a-4dfe-8b05-78bef274c542', 'user': {'id': 'ef1e6ee9-739a-4...-06T15:51:51.913231Z', 'member_ids': ['ef1e6ee9-739a-4dfe-8b05-78bef274c542', '830c471d-1354-43d3-9241-ef98ffc87c7c']})
|
||||
|
||||
def test_apng_corrupt_later_frame_is_rejected(scenario):
|
||||
> upload(scenario, broken_later_frame(apng()), "image/png", 415)
|
||||
|
||||
student-tests/test_image_edges.py:81:
|
||||
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
|
||||
student-tests/test_image_edges.py:21: in upload
|
||||
return c.call(
|
||||
tests/client.py:132: in call
|
||||
check(status in allowed, method + ' ' + path.split('?')[0] + ': expected ' + str(allowed) + ', received ' + str(status))
|
||||
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
|
||||
|
||||
condition = False
|
||||
message = 'POST /api/v1/chats/e9b3f246-cba5-470b-b88f-35da5340b635/attachments: expected [415], received 201'
|
||||
|
||||
def check(condition, message):
|
||||
if not condition:
|
||||
> raise Failure(message)
|
||||
E client.Failure: POST /api/v1/chats/e9b3f246-cba5-470b-b88f-35da5340b635/attachments: expected [415], received 201
|
||||
|
||||
tests/client.py:24: Failure
|
||||
______________________ test_apng_cumulative_canvas_limit _______________________
|
||||
|
||||
scenario = (<client.Client object at 0x102ae4290>, {'id': 'ef1e6ee9-739a-4dfe-8b05-78bef274c542', 'user': {'id': 'ef1e6ee9-739a-4...-06T15:51:51.913231Z', 'member_ids': ['ef1e6ee9-739a-4dfe-8b05-78bef274c542', '830c471d-1354-43d3-9241-ef98ffc87c7c']})
|
||||
|
||||
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)
|
||||
|
||||
student-tests/test_image_edges.py:95:
|
||||
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
|
||||
student-tests/test_image_edges.py:21: in upload
|
||||
return c.call(
|
||||
tests/client.py:132: in call
|
||||
check(status in allowed, method + ' ' + path.split('?')[0] + ': expected ' + str(allowed) + ', received ' + str(status))
|
||||
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
|
||||
|
||||
condition = False
|
||||
message = 'POST /api/v1/chats/e9b3f246-cba5-470b-b88f-35da5340b635/attachments: expected [413], received 201'
|
||||
|
||||
def check(condition, message):
|
||||
if not condition:
|
||||
> raise Failure(message)
|
||||
E client.Failure: POST /api/v1/chats/e9b3f246-cba5-470b-b88f-35da5340b635/attachments: expected [413], received 201
|
||||
|
||||
tests/client.py:24: Failure
|
||||
=========================== short test summary info ============================
|
||||
FAILED student-tests/test_image_edges.py::test_36m_progressive_jpeg_is_valid_and_unchanged
|
||||
FAILED student-tests/test_image_edges.py::test_apng_corrupt_later_frame_is_rejected
|
||||
FAILED student-tests/test_image_edges.py::test_apng_cumulative_canvas_limit
|
||||
3 failed, 1 passed in 2.41s
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"scenario": "APNG40M\u2192CMYK40M\u2192RGB36M\u2192ordinaryPNG, plus malformed frames/JPEG and repeated cases",
|
||||
"api_limit_bytes": 536870912,
|
||||
"containers": [
|
||||
{
|
||||
"id": "7b1331ef2f48894e180f55aa43a7fc926ebdb8119b70c6b12e6154ddd7718c41",
|
||||
"image": "sha256:0f1975a55bf57b7a413815f678e29d500924f18a1485e2e3000aa9b09c2e23ae",
|
||||
"current_bytes": 88059904,
|
||||
"peak_bytes": 426946560,
|
||||
"events": {
|
||||
"low": 0,
|
||||
"high": 0,
|
||||
"max": 0,
|
||||
"oom": 0,
|
||||
"oom_kill": 0,
|
||||
"oom_group_kill": 0
|
||||
},
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"limit_bytes": 536870912
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"api_limit_bytes": 536870912,
|
||||
"native_budget_mib": 384,
|
||||
"child_linux_as_mib": 512,
|
||||
"child_cpu_seconds": 4,
|
||||
"parent_wall_seconds": 5,
|
||||
"scenario": "APNG40M\u2192CMYK40M\u2192RGB36M\u2192ordinaryPNG plus malformed/full-range cases",
|
||||
"targeted_result": "22 passed in 13.29s",
|
||||
"full_suite_result": "155 passed in 50.44s",
|
||||
"final_source_hashes": {
|
||||
"src/messenger/__init__.py": "9a72a49106367ca514cc6147d0e727e62c4d33fefd61572d209a5c9494551a2c",
|
||||
"src/messenger/__main__.py": "ba9a59ad44ee8884cd65cf88d5ea15cbd7051b10f7c729043ddd44ca2f34defe",
|
||||
"src/messenger/app.py": "bea8bc70db73e99cb26a794db9549ff6d5ffc51951e587c44c36ea2656410e54",
|
||||
"src/messenger/attachments.py": "fb8735c19140c96b16ecdc7b643c175c8e418bfa9683a986d5c9c92617dc8082",
|
||||
"src/messenger/config.py": "e4d4aaf674ede8b5abdc361f77c7793ee94d8d7856030c28834eb7c95291b193",
|
||||
"src/messenger/domain.py": "7bf6f177ab5bdeea09b303dc886160335d348f64f47912b9bba45355db378bef",
|
||||
"src/messenger/image_validation.py": "d9aa8db65edaab88c9a76cf2e5459ad3028ba808579311aeb0d8c4f01f875720",
|
||||
"src/messenger/migrate.py": "eb5cad7ac6abe38dd40b2db307d298b297abe9543b3928c36bab8ef06283664e",
|
||||
"src/messenger/models.py": "c43769d2d4ba0369129a86bf80364a626ab91442f9b9020e6bc904e363a39665",
|
||||
"src/messenger/postgres.py": "8a9c0cd275bbb04604d94c1a0155176e9f0348d1e05abe2120c74b0b83f36f6c",
|
||||
"src/messenger/reconcile.py": "792e21f50e777458df367069694e5ff751817fff4dbec4276e4d73e9c64a2fd7",
|
||||
"src/messenger/storage.py": "70b0fb157b285b674a7388a2bfe5c5a7feb8149a9266ac7ad035961d769008a5",
|
||||
"src/messenger/storage_bootstrap.py": "b29a2a1f8864ec3425a7499b1752688f69d8f402f3881957e790ed4522d35589"
|
||||
},
|
||||
"containers": [
|
||||
{
|
||||
"id": "beb1633f31867054f0f1d251df15769de8c8a7a8ee955fb1c5a4df75b0a7fb88",
|
||||
"image": "sha256:362e7406d132beae97a8824381832939f98de42b02ac914367b0a6edf8549ce6",
|
||||
"current_bytes": 83705856,
|
||||
"peak_bytes": 422154240,
|
||||
"events": {
|
||||
"low": 0,
|
||||
"high": 0,
|
||||
"max": 0,
|
||||
"oom": 0,
|
||||
"oom_kill": 0,
|
||||
"oom_group_kill": 0
|
||||
},
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"limit_bytes": 536870912,
|
||||
"runtime_source_matches": true
|
||||
},
|
||||
{
|
||||
"id": "8368fe5482e93bba9a337f21aca3e7e72c6a3844bb2ecd451878c66bbb07aa33",
|
||||
"image": "sha256:362e7406d132beae97a8824381832939f98de42b02ac914367b0a6edf8549ce6",
|
||||
"current_bytes": 83824640,
|
||||
"peak_bytes": 422637568,
|
||||
"events": {
|
||||
"low": 0,
|
||||
"high": 0,
|
||||
"max": 0,
|
||||
"oom": 0,
|
||||
"oom_kill": 0,
|
||||
"oom_group_kill": 0
|
||||
},
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"limit_bytes": 536870912,
|
||||
"runtime_source_matches": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
All checks passed!
|
||||
@@ -0,0 +1 @@
|
||||
All checks passed!
|
||||
@@ -0,0 +1,56 @@
|
||||
[
|
||||
{
|
||||
"service": "api",
|
||||
"container": "fb116950e109b2c4f68378be994e4fa685b1e32d5df70e4f4ba88b9aaac11734",
|
||||
"started_at": "2026-11-06T15:15:49.279244611Z",
|
||||
"running": true
|
||||
},
|
||||
{
|
||||
"service": "api",
|
||||
"container": "255f6fa790fd2b2f5f308846391634c9ff7d308e1d6064085fda31f364b7a6d9",
|
||||
"started_at": "2026-11-06T15:15:49.329476128Z",
|
||||
"running": true
|
||||
},
|
||||
{
|
||||
"service": "cache",
|
||||
"container": "5b1f796409334488ab6738161733ab9bf5a18168f130a97adb3e26115a37ca58",
|
||||
"started_at": "2026-11-06T15:15:48.865336893Z",
|
||||
"running": true
|
||||
},
|
||||
{
|
||||
"service": "lb",
|
||||
"container": "52284c66754124d6476f53fdb606b5c60548d12faa9ead291572e25b054c7998",
|
||||
"started_at": "2026-11-06T15:15:48.806688697Z",
|
||||
"running": true
|
||||
},
|
||||
{
|
||||
"service": "migrate",
|
||||
"container": "2b0e607724660e7759eb19441e55f876fd8f7a5ed70786abff1b598f5a8f6902",
|
||||
"started_at": "2026-11-06T15:15:51.577483807Z",
|
||||
"running": false
|
||||
},
|
||||
{
|
||||
"service": "postgres",
|
||||
"container": "f7114ab3fbe35b16192783e8a6482e6498af0add82239395a3855c672ff04973",
|
||||
"started_at": "2026-11-06T15:15:48.896278712Z",
|
||||
"running": true
|
||||
},
|
||||
{
|
||||
"service": "s3",
|
||||
"container": "2d81a2bfeaf92d8fee8221e7a1747c30d1da158fe987ce977940dae91307d9c0",
|
||||
"started_at": "2026-11-06T15:15:48.917467586Z",
|
||||
"running": true
|
||||
},
|
||||
{
|
||||
"service": "s3-bootstrap",
|
||||
"container": "83ea8d79ab0e55db166db204f0e2c297a0773e1718552b6c4723fea097b3e758",
|
||||
"started_at": "2026-11-06T15:15:51.576960641Z",
|
||||
"running": false
|
||||
},
|
||||
{
|
||||
"service": "storage",
|
||||
"container": "d680a5826a35dcaf058c08801e477ffa23ae9114ff1deabccbadcded7cc76ecb",
|
||||
"started_at": "2026-11-06T15:15:48.934995346Z",
|
||||
"running": true
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,56 @@
|
||||
[
|
||||
{
|
||||
"service": "api",
|
||||
"container": "fb116950e109b2c4f68378be994e4fa685b1e32d5df70e4f4ba88b9aaac11734",
|
||||
"started_at": "2026-11-06T15:13:47.712944078Z",
|
||||
"running": true
|
||||
},
|
||||
{
|
||||
"service": "api",
|
||||
"container": "255f6fa790fd2b2f5f308846391634c9ff7d308e1d6064085fda31f364b7a6d9",
|
||||
"started_at": "2026-11-06T15:13:47.729250356Z",
|
||||
"running": true
|
||||
},
|
||||
{
|
||||
"service": "cache",
|
||||
"container": "5b1f796409334488ab6738161733ab9bf5a18168f130a97adb3e26115a37ca58",
|
||||
"started_at": "2026-11-06T15:13:09.057038043Z",
|
||||
"running": true
|
||||
},
|
||||
{
|
||||
"service": "lb",
|
||||
"container": "52284c66754124d6476f53fdb606b5c60548d12faa9ead291572e25b054c7998",
|
||||
"started_at": "2026-11-06T15:13:29.211107429Z",
|
||||
"running": true
|
||||
},
|
||||
{
|
||||
"service": "migrate",
|
||||
"container": "2b0e607724660e7759eb19441e55f876fd8f7a5ed70786abff1b598f5a8f6902",
|
||||
"started_at": "2026-11-06T15:13:11.679089233Z",
|
||||
"running": false
|
||||
},
|
||||
{
|
||||
"service": "postgres",
|
||||
"container": "f7114ab3fbe35b16192783e8a6482e6498af0add82239395a3855c672ff04973",
|
||||
"started_at": "2026-11-06T15:13:09.057550292Z",
|
||||
"running": true
|
||||
},
|
||||
{
|
||||
"service": "s3",
|
||||
"container": "2d81a2bfeaf92d8fee8221e7a1747c30d1da158fe987ce977940dae91307d9c0",
|
||||
"started_at": "2026-11-06T15:14:23.761816807Z",
|
||||
"running": true
|
||||
},
|
||||
{
|
||||
"service": "s3-bootstrap",
|
||||
"container": "83ea8d79ab0e55db166db204f0e2c297a0773e1718552b6c4723fea097b3e758",
|
||||
"started_at": "2026-11-06T15:13:11.756618786Z",
|
||||
"running": false
|
||||
},
|
||||
{
|
||||
"service": "storage",
|
||||
"container": "d680a5826a35dcaf058c08801e477ffa23ae9114ff1deabccbadcded7cc76ecb",
|
||||
"started_at": "2026-11-06T15:13:09.05733731Z",
|
||||
"running": true
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,3 @@
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://127.0.0.1:8084"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,515 @@
|
||||
{
|
||||
"hypothesis": "Durable intent, row locks, grace and live HEAD make reconciliation repeatable and protect fresh/used data",
|
||||
"started_at": "2026-11-06T15:13:23.135411+00:00",
|
||||
"database": "research_fc070dd14e38",
|
||||
"bucket": "research-fc070dd14e38",
|
||||
"grace_seconds": 2,
|
||||
"checks": [
|
||||
{
|
||||
"name": "real_db_insert_failure_after_s3_put",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "real_s3_connect_failure_is_503",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "commit_ack_loss_injected",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "uncertain_response_keeps_committed_original",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "dry_run_changes_neither_db_nor_s3",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "all_reconcile_passes_have_no_errors",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "orphan_removed",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "missing_marked_failed_metadata_kept",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "used_original_kept",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "fresh_metadata_and_original_kept",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "fresh_orphan_kept",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "old_intent_fresh_object_kept",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "active_writer_object_kept",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "committed_original_survives_reconciliation",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "repeat_has_no_duplicate_mutations",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "s3_delete_failure_observed",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "dry_run_after_failed_apply_still_read_only",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "failed_cleanup_recovers",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "real_db_delete_failure_after_s3_delete",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "dry_run_does_not_resume_partial_delete",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "partial_delete_resumes_only_on_apply",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "scan_has_no_errors_10_0",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "scan_has_no_errors_10_1",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "scan_has_no_errors_10_2",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "scan_has_no_errors_100_0",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "scan_has_no_errors_100_1",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "scan_has_no_errors_100_2",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "scan_has_no_errors_1000_0",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "scan_has_no_errors_1000_1",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "scan_has_no_errors_1000_2",
|
||||
"passed": true
|
||||
}
|
||||
],
|
||||
"scan_cost": [
|
||||
{
|
||||
"seeded_intact": 10,
|
||||
"repeat": 1,
|
||||
"mode": "dry-run",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 100,
|
||||
"intents_scanned": 0,
|
||||
"objects_scanned": 13,
|
||||
"metadata_scanned": 13,
|
||||
"old_intents": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 0,
|
||||
"deleted_objects": 0,
|
||||
"deleted_intents": 0,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 0,
|
||||
"errors": 0,
|
||||
"duration_seconds": 0.023085
|
||||
},
|
||||
{
|
||||
"seeded_intact": 10,
|
||||
"repeat": 2,
|
||||
"mode": "dry-run",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 100,
|
||||
"intents_scanned": 0,
|
||||
"objects_scanned": 13,
|
||||
"metadata_scanned": 13,
|
||||
"old_intents": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 0,
|
||||
"deleted_objects": 0,
|
||||
"deleted_intents": 0,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 0,
|
||||
"errors": 0,
|
||||
"duration_seconds": 0.018874
|
||||
},
|
||||
{
|
||||
"seeded_intact": 10,
|
||||
"repeat": 3,
|
||||
"mode": "dry-run",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 100,
|
||||
"intents_scanned": 0,
|
||||
"objects_scanned": 13,
|
||||
"metadata_scanned": 13,
|
||||
"old_intents": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 0,
|
||||
"deleted_objects": 0,
|
||||
"deleted_intents": 0,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 0,
|
||||
"errors": 0,
|
||||
"duration_seconds": 0.025435
|
||||
},
|
||||
{
|
||||
"seeded_intact": 100,
|
||||
"repeat": 1,
|
||||
"mode": "dry-run",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 100,
|
||||
"intents_scanned": 0,
|
||||
"objects_scanned": 103,
|
||||
"metadata_scanned": 103,
|
||||
"old_intents": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 0,
|
||||
"deleted_objects": 0,
|
||||
"deleted_intents": 0,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 0,
|
||||
"errors": 0,
|
||||
"duration_seconds": 0.189366
|
||||
},
|
||||
{
|
||||
"seeded_intact": 100,
|
||||
"repeat": 2,
|
||||
"mode": "dry-run",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 100,
|
||||
"intents_scanned": 0,
|
||||
"objects_scanned": 103,
|
||||
"metadata_scanned": 103,
|
||||
"old_intents": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 0,
|
||||
"deleted_objects": 0,
|
||||
"deleted_intents": 0,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 0,
|
||||
"errors": 0,
|
||||
"duration_seconds": 0.146632
|
||||
},
|
||||
{
|
||||
"seeded_intact": 100,
|
||||
"repeat": 3,
|
||||
"mode": "dry-run",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 100,
|
||||
"intents_scanned": 0,
|
||||
"objects_scanned": 103,
|
||||
"metadata_scanned": 103,
|
||||
"old_intents": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 0,
|
||||
"deleted_objects": 0,
|
||||
"deleted_intents": 0,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 0,
|
||||
"errors": 0,
|
||||
"duration_seconds": 0.170581
|
||||
},
|
||||
{
|
||||
"seeded_intact": 1000,
|
||||
"repeat": 1,
|
||||
"mode": "dry-run",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 100,
|
||||
"intents_scanned": 0,
|
||||
"objects_scanned": 1003,
|
||||
"metadata_scanned": 1003,
|
||||
"old_intents": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 0,
|
||||
"deleted_objects": 0,
|
||||
"deleted_intents": 0,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 0,
|
||||
"errors": 0,
|
||||
"duration_seconds": 1.559015
|
||||
},
|
||||
{
|
||||
"seeded_intact": 1000,
|
||||
"repeat": 2,
|
||||
"mode": "dry-run",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 100,
|
||||
"intents_scanned": 0,
|
||||
"objects_scanned": 1003,
|
||||
"metadata_scanned": 1003,
|
||||
"old_intents": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 0,
|
||||
"deleted_objects": 0,
|
||||
"deleted_intents": 0,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 0,
|
||||
"errors": 0,
|
||||
"duration_seconds": 1.868045
|
||||
},
|
||||
{
|
||||
"seeded_intact": 1000,
|
||||
"repeat": 3,
|
||||
"mode": "dry-run",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 100,
|
||||
"intents_scanned": 0,
|
||||
"objects_scanned": 1003,
|
||||
"metadata_scanned": 1003,
|
||||
"old_intents": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 0,
|
||||
"deleted_objects": 0,
|
||||
"deleted_intents": 0,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 0,
|
||||
"errors": 0,
|
||||
"duration_seconds": 1.581705
|
||||
}
|
||||
],
|
||||
"source": {
|
||||
"src/messenger/__init__.py": "9a72a49106367ca514cc6147d0e727e62c4d33fefd61572d209a5c9494551a2c",
|
||||
"src/messenger/__main__.py": "ba9a59ad44ee8884cd65cf88d5ea15cbd7051b10f7c729043ddd44ca2f34defe",
|
||||
"src/messenger/app.py": "cb708a0f2ccd99ff421883ec318ccba5cecc0c228ec2155ee00a64aa8ebfac4d",
|
||||
"src/messenger/attachments.py": "0d14697afb4064a530f1ca99f59460879ef81af5b7d49af9e5d31661fa11ba28",
|
||||
"src/messenger/config.py": "e4d4aaf674ede8b5abdc361f77c7793ee94d8d7856030c28834eb7c95291b193",
|
||||
"src/messenger/domain.py": "33086cb229083ecee3bcee09f143b4bc09e48896a0c497bd9902e738e2e6b1af",
|
||||
"src/messenger/migrate.py": "eb5cad7ac6abe38dd40b2db307d298b297abe9543b3928c36bab8ef06283664e",
|
||||
"src/messenger/models.py": "c43769d2d4ba0369129a86bf80364a626ab91442f9b9020e6bc904e363a39665",
|
||||
"src/messenger/postgres.py": "8a9c0cd275bbb04604d94c1a0155176e9f0348d1e05abe2120c74b0b83f36f6c",
|
||||
"src/messenger/reconcile.py": "792e21f50e777458df367069694e5ff751817fff4dbec4276e4d73e9c64a2fd7",
|
||||
"src/messenger/storage.py": "70b0fb157b285b674a7388a2bfe5c5a7feb8149a9266ac7ad035961d769008a5",
|
||||
"src/messenger/storage_bootstrap.py": "b29a2a1f8864ec3425a7499b1752688f69d8f402f3881957e790ed4522d35589"
|
||||
},
|
||||
"dry_run": {
|
||||
"mode": "dry-run",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 1,
|
||||
"intents_scanned": 4,
|
||||
"objects_scanned": 8,
|
||||
"metadata_scanned": 3,
|
||||
"old_intents": 2,
|
||||
"orphan_objects": 1,
|
||||
"missing_objects": 1,
|
||||
"deleted_objects": 0,
|
||||
"deleted_intents": 0,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 5,
|
||||
"errors": 0,
|
||||
"duration_seconds": 0.019806
|
||||
},
|
||||
"apply": {
|
||||
"mode": "apply",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 1,
|
||||
"intents_scanned": 4,
|
||||
"objects_scanned": 7,
|
||||
"metadata_scanned": 3,
|
||||
"old_intents": 2,
|
||||
"orphan_objects": 1,
|
||||
"missing_objects": 1,
|
||||
"deleted_objects": 3,
|
||||
"deleted_intents": 2,
|
||||
"marked_failed": 1,
|
||||
"fresh_objects_skipped": 5,
|
||||
"errors": 0,
|
||||
"duration_seconds": 0.016948
|
||||
},
|
||||
"repeat": {
|
||||
"mode": "apply",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 1,
|
||||
"intents_scanned": 2,
|
||||
"objects_scanned": 6,
|
||||
"metadata_scanned": 2,
|
||||
"old_intents": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 0,
|
||||
"deleted_objects": 0,
|
||||
"deleted_intents": 0,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 5,
|
||||
"errors": 0,
|
||||
"duration_seconds": 0.008812
|
||||
},
|
||||
"failed_cleanup": {
|
||||
"mode": "apply",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 100,
|
||||
"intents_scanned": 2,
|
||||
"objects_scanned": 6,
|
||||
"metadata_scanned": 3,
|
||||
"old_intents": 2,
|
||||
"orphan_objects": 1,
|
||||
"missing_objects": 0,
|
||||
"deleted_objects": 0,
|
||||
"deleted_intents": 0,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 0,
|
||||
"errors": 3,
|
||||
"duration_seconds": 0.013409
|
||||
},
|
||||
"recovery_dry": {
|
||||
"mode": "dry-run",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 100,
|
||||
"intents_scanned": 2,
|
||||
"objects_scanned": 6,
|
||||
"metadata_scanned": 3,
|
||||
"old_intents": 2,
|
||||
"orphan_objects": 1,
|
||||
"missing_objects": 0,
|
||||
"deleted_objects": 0,
|
||||
"deleted_intents": 0,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 0,
|
||||
"errors": 0,
|
||||
"duration_seconds": 0.011906
|
||||
},
|
||||
"recovery_apply": {
|
||||
"mode": "apply",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 100,
|
||||
"intents_scanned": 2,
|
||||
"objects_scanned": 4,
|
||||
"metadata_scanned": 3,
|
||||
"old_intents": 2,
|
||||
"orphan_objects": 1,
|
||||
"missing_objects": 0,
|
||||
"deleted_objects": 3,
|
||||
"deleted_intents": 2,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 0,
|
||||
"errors": 0,
|
||||
"duration_seconds": 0.013727
|
||||
},
|
||||
"partial_delete_dry": {
|
||||
"mode": "dry-run",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 100,
|
||||
"intents_scanned": 1,
|
||||
"objects_scanned": 3,
|
||||
"metadata_scanned": 3,
|
||||
"old_intents": 1,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 0,
|
||||
"deleted_objects": 0,
|
||||
"deleted_intents": 0,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 0,
|
||||
"errors": 0,
|
||||
"duration_seconds": 0.018603
|
||||
},
|
||||
"partial_delete_apply": {
|
||||
"mode": "apply",
|
||||
"grace_seconds": 2,
|
||||
"page_size": 100,
|
||||
"intents_scanned": 1,
|
||||
"objects_scanned": 3,
|
||||
"metadata_scanned": 3,
|
||||
"old_intents": 1,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 0,
|
||||
"deleted_objects": 1,
|
||||
"deleted_intents": 1,
|
||||
"marked_failed": 0,
|
||||
"fresh_objects_skipped": 0,
|
||||
"errors": 0,
|
||||
"duration_seconds": 0.012837
|
||||
},
|
||||
"limitations": [
|
||||
"One local host and warm services; scan measures HEAD/SQL round trips, not production SLA",
|
||||
"Missing originals are marked failed; reconciliation cannot recreate lost bytes without backup",
|
||||
"Valid unattached ready attachments are retained; only abandoned intents and untracked old original objects are removed",
|
||||
"No atomic transaction spans S3 and PostgreSQL; retries plus durable intent recover the selected windows",
|
||||
"Cost dataset is in disposable isolated DB/bucket, includes a few preserved fault fixtures beyond the seeded intact count"
|
||||
],
|
||||
"temporary_resources_deleted": true,
|
||||
"host_manifest": {
|
||||
"system": "Darwin",
|
||||
"machine": "arm64",
|
||||
"release": "24.3.0",
|
||||
"git_revision": "619155f1e01457ee02da561200a571cbd5674055",
|
||||
"docker": {
|
||||
"version": "29.5.2",
|
||||
"cpus": 4,
|
||||
"memory_bytes": 8307167232
|
||||
},
|
||||
"containers": [
|
||||
{
|
||||
"service": "api",
|
||||
"image": "sha256:1beedea111bd3f8f5de5a31b7a67b2013ffc9c0271b51313bb6968bcaea96f6e",
|
||||
"cpu_nano": 500000000,
|
||||
"memory_limit": 536870912
|
||||
},
|
||||
{
|
||||
"service": "api",
|
||||
"image": "sha256:1beedea111bd3f8f5de5a31b7a67b2013ffc9c0271b51313bb6968bcaea96f6e",
|
||||
"cpu_nano": 500000000,
|
||||
"memory_limit": 536870912
|
||||
},
|
||||
{
|
||||
"service": "cache",
|
||||
"image": "sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773",
|
||||
"cpu_nano": 500000000,
|
||||
"memory_limit": 134217728
|
||||
},
|
||||
{
|
||||
"service": "lb",
|
||||
"image": "sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0",
|
||||
"cpu_nano": 500000000,
|
||||
"memory_limit": 134217728
|
||||
},
|
||||
{
|
||||
"service": "postgres",
|
||||
"image": "sha256:742f40ea20b9ff2ff31db5458d127452988a2164df9e17441e191f3b72252193",
|
||||
"cpu_nano": 1000000000,
|
||||
"memory_limit": 805306368
|
||||
},
|
||||
{
|
||||
"service": "s3",
|
||||
"image": "sha256:1593bd2a98964f5d4df83fa7db2b3d4ee7b20190813cc5bf8c3200e0e70d346e",
|
||||
"cpu_nano": 500000000,
|
||||
"memory_limit": 268435456
|
||||
},
|
||||
{
|
||||
"service": "storage",
|
||||
"image": "sha256:1593bd2a98964f5d4df83fa7db2b3d4ee7b20190813cc5bf8c3200e0e70d346e",
|
||||
"cpu_nano": 1000000000,
|
||||
"memory_limit": 536870912
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,60 @@
|
||||
# Исследование согласованности PostgreSQL/S3
|
||||
|
||||
Дата начала (UTC): 2026-11-06T15:13:23.135411+00:00.
|
||||
|
||||
Успешных проверок: 30/30.
|
||||
|
||||
| Добавлено intact | Просмотрено metadata | Медиана обхода, с |
|
||||
|---:|---:|---:|
|
||||
| 10 | 13 | 0.023085 |
|
||||
| 100 | 103 | 0.170581 |
|
||||
| 1000 | 1003 | 1.581705 |
|
||||
|
||||
По три dry-run на размер, page_size100, прогретый локальный стенд.
|
||||
Дополнительные три intact fault fixtures входят в фактический scan.
|
||||
|
||||
Первый apply: удалено intent 2, операций удаления объекта 3, missing помечено failed 1.
|
||||
Счётчик удаления объекта — число успешных идемпотентных DELETE, включая отсутствие bytes у intent.
|
||||
|
||||
Временные ресурсы удалены: True.
|
||||
|
||||
## Проверенные инварианты
|
||||
|
||||
- PASS: real_db_insert_failure_after_s3_put
|
||||
- PASS: real_s3_connect_failure_is_503
|
||||
- PASS: commit_ack_loss_injected
|
||||
- PASS: uncertain_response_keeps_committed_original
|
||||
- PASS: dry_run_changes_neither_db_nor_s3
|
||||
- PASS: all_reconcile_passes_have_no_errors
|
||||
- PASS: orphan_removed
|
||||
- PASS: missing_marked_failed_metadata_kept
|
||||
- PASS: used_original_kept
|
||||
- PASS: fresh_metadata_and_original_kept
|
||||
- PASS: fresh_orphan_kept
|
||||
- PASS: old_intent_fresh_object_kept
|
||||
- PASS: active_writer_object_kept
|
||||
- PASS: committed_original_survives_reconciliation
|
||||
- PASS: repeat_has_no_duplicate_mutations
|
||||
- PASS: s3_delete_failure_observed
|
||||
- PASS: dry_run_after_failed_apply_still_read_only
|
||||
- PASS: failed_cleanup_recovers
|
||||
- PASS: real_db_delete_failure_after_s3_delete
|
||||
- PASS: dry_run_does_not_resume_partial_delete
|
||||
- PASS: partial_delete_resumes_only_on_apply
|
||||
- PASS: scan_has_no_errors_10_0
|
||||
- PASS: scan_has_no_errors_10_1
|
||||
- PASS: scan_has_no_errors_10_2
|
||||
- PASS: scan_has_no_errors_100_0
|
||||
- PASS: scan_has_no_errors_100_1
|
||||
- PASS: scan_has_no_errors_100_2
|
||||
- PASS: scan_has_no_errors_1000_0
|
||||
- PASS: scan_has_no_errors_1000_1
|
||||
- PASS: scan_has_no_errors_1000_2
|
||||
|
||||
## Ограничения
|
||||
|
||||
- One local host and warm services; scan measures HEAD/SQL round trips, not production SLA
|
||||
- Missing originals are marked failed; reconciliation cannot recreate lost bytes without backup
|
||||
- Valid unattached ready attachments are retained; only abandoned intents and untracked old original objects are removed
|
||||
- No atomic transaction spans S3 and PostgreSQL; retries plus durable intent recover the selected windows
|
||||
- Cost dataset is in disposable isolated DB/bucket, includes a few preserved fault fixtures beyond the seeded intact count
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 tests/smoke.py --base-url "http://127.0.0.1:8084"
|
||||
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1 @@
|
||||
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,142 @@
|
||||
{
|
||||
"checks": [
|
||||
{
|
||||
"name": "unrelated_bucket_denied",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "backend_unreachable",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "gateway_filer_unreachable",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "no_admin_secrets",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "anonymous_original_denied",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "bucket_bootstrap_repeatable",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "s3_down_ready_503",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "s3_down_content_503",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "s3_restart_original_unchanged",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "paused_pg_ready_503_with_client_deadline",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "paused_pg_auth_503_with_client_deadline",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "old_session_recovers_after_unpause",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "missing_required_table_ready_503",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "schema_restore_ready_200",
|
||||
"passed": true
|
||||
},
|
||||
{
|
||||
"name": "lb_readmits_recovered_api",
|
||||
"passed": true
|
||||
}
|
||||
],
|
||||
"faults": [
|
||||
{
|
||||
"service": "s3",
|
||||
"ready": {
|
||||
"status": 503,
|
||||
"elapsed": 0.010417848010547459,
|
||||
"json": {
|
||||
"error": {
|
||||
"code": "unavailable",
|
||||
"message": "Хранилище недоступно",
|
||||
"request_id": "eacb2683-a734-450a-ab88-873976aaf1a2"
|
||||
}
|
||||
},
|
||||
"sha256": "6c93ed3dd714ac1d6e6ea952a436cb1ed67fe5be9e1401ded99c66ef9b50120e"
|
||||
},
|
||||
"download": {
|
||||
"status": 503,
|
||||
"elapsed": 0.012548128957860172,
|
||||
"json": {
|
||||
"error": {
|
||||
"code": "unavailable",
|
||||
"message": "Хранилище файлов временно недоступно",
|
||||
"request_id": "19f68dc9-a1c5-41ba-b8c1-7764f3c715f1"
|
||||
}
|
||||
},
|
||||
"sha256": "be4a4560dfe7e74fb4c243b760e103c31cd16be4195c9a5c852e2ff1ed2b1ef5"
|
||||
}
|
||||
},
|
||||
{
|
||||
"service": "paused_postgres",
|
||||
"ready": {
|
||||
"status": 503,
|
||||
"elapsed": 3.0085260499618016,
|
||||
"json": {
|
||||
"error": {
|
||||
"code": "unavailable",
|
||||
"message": "Хранилище недоступно",
|
||||
"request_id": "400bdaa7-e2e5-43e3-873e-fdfd8a5da545"
|
||||
}
|
||||
},
|
||||
"sha256": "82ff75670fbb92a7d5852887154f6baf684f2782a6aa145aa406fae8fc16e5a0"
|
||||
},
|
||||
"me": {
|
||||
"status": 503,
|
||||
"elapsed": 2.0085200910107233,
|
||||
"json": {
|
||||
"error": {
|
||||
"code": "unavailable",
|
||||
"message": "Хранилище временно недоступно",
|
||||
"request_id": "bfd8f577-3cd7-4d8e-981a-04537fb47c7d"
|
||||
}
|
||||
},
|
||||
"sha256": "38aa5fc7df41d74f4c3cde71a84e96805568e9a469d2be9ff6340fb578af0268"
|
||||
}
|
||||
},
|
||||
{
|
||||
"service": "missing_message_requests",
|
||||
"ready": {
|
||||
"status": 503,
|
||||
"elapsed": 0.08961376297520474,
|
||||
"json": {
|
||||
"error": {
|
||||
"code": "unavailable",
|
||||
"message": "Хранилище недоступно",
|
||||
"request_id": "3e778ff4-c1fd-485d-973a-7fa367556469"
|
||||
}
|
||||
},
|
||||
"sha256": "6f1f6ba3ac28b6ac691d4dc7da3e4102cc5169bc01040701210a4200b25dcd43"
|
||||
}
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"anonymous_status": 403,
|
||||
"unrelated_bucket_denied": true,
|
||||
"backend_unreachable": true,
|
||||
"gateway_filer_unreachable": true,
|
||||
"no_admin_secrets": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"passed": 15}
|
||||
@@ -0,0 +1,3 @@
|
||||
........................................................................ [ 64%]
|
||||
........................................ [100%]
|
||||
112 passed in 34.16s
|
||||
@@ -0,0 +1,4 @@
|
||||
........................................................................ [ 46%]
|
||||
........................................................................ [ 92%]
|
||||
........... [100%]
|
||||
155 passed in 50.44s
|
||||
@@ -0,0 +1,285 @@
|
||||
{
|
||||
"concurrency": 10,
|
||||
"api_replicas": 2,
|
||||
"sampled_api_and_lb_containers": [
|
||||
"fb116950e109b2c4f68378be994e4fa685b1e32d5df70e4f4ba88b9aaac11734",
|
||||
"255f6fa790fd2b2f5f308846391634c9ff7d308e1d6064085fda31f364b7a6d9",
|
||||
"52284c66754124d6476f53fdb606b5c60548d12faa9ead291572e25b054c7998"
|
||||
],
|
||||
"api_restarted_before_trial": true,
|
||||
"runs": [
|
||||
{
|
||||
"image_dimensions": [
|
||||
512,
|
||||
512
|
||||
],
|
||||
"size_bytes": 788100,
|
||||
"before": {
|
||||
"fb116950e109b2c4f68378be994e4fa685b1e32d5df70e4f4ba88b9aaac11734": {
|
||||
"current": 79519744,
|
||||
"peak": 122773504,
|
||||
"events": {
|
||||
"low": 0,
|
||||
"high": 0,
|
||||
"max": 0,
|
||||
"oom": 0,
|
||||
"oom_kill": 0,
|
||||
"oom_group_kill": 0
|
||||
},
|
||||
"process_hwm": "VmHWM:\t 139516 kB"
|
||||
},
|
||||
"255f6fa790fd2b2f5f308846391634c9ff7d308e1d6064085fda31f364b7a6d9": {
|
||||
"current": 79613952,
|
||||
"peak": 122679296,
|
||||
"events": {
|
||||
"low": 0,
|
||||
"high": 0,
|
||||
"max": 0,
|
||||
"oom": 0,
|
||||
"oom_kill": 0,
|
||||
"oom_group_kill": 0
|
||||
},
|
||||
"process_hwm": "VmHWM:\t 139728 kB"
|
||||
},
|
||||
"52284c66754124d6476f53fdb606b5c60548d12faa9ead291572e25b054c7998": {
|
||||
"current": 11587584,
|
||||
"peak": 13217792,
|
||||
"events": {
|
||||
"low": 0,
|
||||
"high": 0,
|
||||
"max": 0,
|
||||
"oom": 0,
|
||||
"oom_kill": 0,
|
||||
"oom_group_kill": 0
|
||||
},
|
||||
"process_hwm": "VmHWM:\t 13704 kB"
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"fb116950e109b2c4f68378be994e4fa685b1e32d5df70e4f4ba88b9aaac11734": {
|
||||
"current": 83845120,
|
||||
"peak": 122773504,
|
||||
"events": {
|
||||
"low": 0,
|
||||
"high": 0,
|
||||
"max": 0,
|
||||
"oom": 0,
|
||||
"oom_kill": 0,
|
||||
"oom_group_kill": 0
|
||||
},
|
||||
"process_hwm": "VmHWM:\t 139516 kB"
|
||||
},
|
||||
"255f6fa790fd2b2f5f308846391634c9ff7d308e1d6064085fda31f364b7a6d9": {
|
||||
"current": 84389888,
|
||||
"peak": 122679296,
|
||||
"events": {
|
||||
"low": 0,
|
||||
"high": 0,
|
||||
"max": 0,
|
||||
"oom": 0,
|
||||
"oom_kill": 0,
|
||||
"oom_group_kill": 0
|
||||
},
|
||||
"process_hwm": "VmHWM:\t 139728 kB"
|
||||
},
|
||||
"52284c66754124d6476f53fdb606b5c60548d12faa9ead291572e25b054c7998": {
|
||||
"current": 11927552,
|
||||
"peak": 14299136,
|
||||
"events": {
|
||||
"low": 0,
|
||||
"high": 0,
|
||||
"max": 0,
|
||||
"oom": 0,
|
||||
"oom_kill": 0,
|
||||
"oom_group_kill": 0
|
||||
},
|
||||
"process_hwm": "VmHWM:\t 13704 kB"
|
||||
}
|
||||
},
|
||||
"responses": [
|
||||
{
|
||||
"status": 201,
|
||||
"elapsed": 0.10770674998639151,
|
||||
"attachment_id": "4e85ee5d-1b9b-49de-b78a-df0a2b025927"
|
||||
},
|
||||
{
|
||||
"status": 201,
|
||||
"elapsed": 0.09620504203485325,
|
||||
"attachment_id": "848f0e91-208e-4272-a80c-6cdc3badfba2"
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.049307000008411705
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.0555269590113312
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.056070291029755026
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.04627674998482689
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.059664790984243155
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.05963275005342439
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.05560016701929271
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.0469216660130769
|
||||
}
|
||||
],
|
||||
"ready_after": true
|
||||
},
|
||||
{
|
||||
"image_dimensions": [
|
||||
1700,
|
||||
1700
|
||||
],
|
||||
"size_bytes": 8683594,
|
||||
"before": {
|
||||
"fb116950e109b2c4f68378be994e4fa685b1e32d5df70e4f4ba88b9aaac11734": {
|
||||
"current": 83865600,
|
||||
"peak": 122773504,
|
||||
"events": {
|
||||
"low": 0,
|
||||
"high": 0,
|
||||
"max": 0,
|
||||
"oom": 0,
|
||||
"oom_kill": 0,
|
||||
"oom_group_kill": 0
|
||||
},
|
||||
"process_hwm": "VmHWM:\t 139516 kB"
|
||||
},
|
||||
"255f6fa790fd2b2f5f308846391634c9ff7d308e1d6064085fda31f364b7a6d9": {
|
||||
"current": 84439040,
|
||||
"peak": 122679296,
|
||||
"events": {
|
||||
"low": 0,
|
||||
"high": 0,
|
||||
"max": 0,
|
||||
"oom": 0,
|
||||
"oom_kill": 0,
|
||||
"oom_group_kill": 0
|
||||
},
|
||||
"process_hwm": "VmHWM:\t 139728 kB"
|
||||
},
|
||||
"52284c66754124d6476f53fdb606b5c60548d12faa9ead291572e25b054c7998": {
|
||||
"current": 11866112,
|
||||
"peak": 14299136,
|
||||
"events": {
|
||||
"low": 0,
|
||||
"high": 0,
|
||||
"max": 0,
|
||||
"oom": 0,
|
||||
"oom_kill": 0,
|
||||
"oom_group_kill": 0
|
||||
},
|
||||
"process_hwm": "VmHWM:\t 13704 kB"
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"fb116950e109b2c4f68378be994e4fa685b1e32d5df70e4f4ba88b9aaac11734": {
|
||||
"current": 86425600,
|
||||
"peak": 122773504,
|
||||
"events": {
|
||||
"low": 0,
|
||||
"high": 0,
|
||||
"max": 0,
|
||||
"oom": 0,
|
||||
"oom_kill": 0,
|
||||
"oom_group_kill": 0
|
||||
},
|
||||
"process_hwm": "VmHWM:\t 139516 kB"
|
||||
},
|
||||
"255f6fa790fd2b2f5f308846391634c9ff7d308e1d6064085fda31f364b7a6d9": {
|
||||
"current": 86462464,
|
||||
"peak": 122679296,
|
||||
"events": {
|
||||
"low": 0,
|
||||
"high": 0,
|
||||
"max": 0,
|
||||
"oom": 0,
|
||||
"oom_kill": 0,
|
||||
"oom_group_kill": 0
|
||||
},
|
||||
"process_hwm": "VmHWM:\t 139728 kB"
|
||||
},
|
||||
"52284c66754124d6476f53fdb606b5c60548d12faa9ead291572e25b054c7998": {
|
||||
"current": 11878400,
|
||||
"peak": 19656704,
|
||||
"events": {
|
||||
"low": 0,
|
||||
"high": 0,
|
||||
"max": 0,
|
||||
"oom": 0,
|
||||
"oom_kill": 0,
|
||||
"oom_group_kill": 0
|
||||
},
|
||||
"process_hwm": "VmHWM:\t 13704 kB"
|
||||
}
|
||||
},
|
||||
"responses": [
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.31627862504683435
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.32798779202857986
|
||||
},
|
||||
{
|
||||
"status": 201,
|
||||
"elapsed": 0.8054331250023097,
|
||||
"attachment_id": "f0a451ee-d667-4f29-9409-4304ec59a156"
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.32699191698338836
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.32789891597349197
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.3272826250176877
|
||||
},
|
||||
{
|
||||
"status": 201,
|
||||
"elapsed": 0.8380368750076741,
|
||||
"attachment_id": "e35b8424-19b3-4ef5-8e37-23bdc23f1ccf"
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.32766412501223385
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.3256588340154849
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"elapsed": 0.19960300001548603
|
||||
}
|
||||
],
|
||||
"ready_after": true
|
||||
}
|
||||
],
|
||||
"limitations": [
|
||||
"Kernel cgroup peak and process VmHWM are lifetime peaks; before/after reported, not attributed solely to upload buffers",
|
||||
"Fast rejection 429 is intentional backpressure, not a successful upload",
|
||||
"Local two-replica stand; not a throughput benchmark"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
Container mtusi-vasilev-lab4-api-2 Restarting
|
||||
Container mtusi-vasilev-lab4-api-1 Restarting
|
||||
Container mtusi-vasilev-lab4-api-1 Started
|
||||
Container mtusi-vasilev-lab4-api-2 Started
|
||||
{"runs": [{"size_bytes": 788100, "statuses": [201, 201, 429, 429, 429, 429, 429, 429, 429, 429]}, {"size_bytes": 8683594, "statuses": [429, 429, 201, 429, 429, 429, 201, 429, 429, 429]}]}
|
||||
@@ -0,0 +1,2 @@
|
||||
..... [100%]
|
||||
5 passed in 0.14s
|
||||
@@ -25,6 +25,8 @@ resolvers docker
|
||||
|
||||
frontend public
|
||||
bind :8080
|
||||
http-request set-var(txn.lb_request_id) uuid()
|
||||
http-request return status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"No ready API","request_id":"%[var(txn.lb_request_id)]"}}' hdr X-Request-Id '%[var(txn.lb_request_id)]' if { nbsrv(apis) eq 0 }
|
||||
default_backend apis
|
||||
|
||||
backend apis
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# Трек 2: согласованность PostgreSQL и S3
|
||||
|
||||
## Гипотеза
|
||||
|
||||
Durable intent до S3 PUT, row lock на время PUT/финализации и консервативный reconciler с grace + актуальным HEAD позволяют обнаружить и безопасно убрать остатки незавершённых upload, сохранив подтверждённые и свежие данные. Один COMMIT не делает распределённую транзакцию с S3, поэтому результат проверяется fault-injection.
|
||||
|
||||
## Протокол upload
|
||||
|
||||
1. Поток HTTP складывается в ограниченный spool: 256 KiB в RAM, затем временный файл на ограниченном tmpfs; максимум 10 MiB.
|
||||
2. После полного приёма короткоживущий ограниченный child проверяет PNG/JPEG. Пиксельный предел применяется до decode: для APNG это сумма canvas всех кадров≤40M. JPEG полностью декодирует строгий djpeg384MiB построчно, PNG/APNG декодирует Pillow; decoded buffers не остаются в API. Последние edge исправлены после исходного измерения сверки, его raw snapshot не переписывался.
|
||||
3. Создаётся и фиксируется upload_intent с уникальным server key.
|
||||
4. Новая транзакция блокирует intent, выполняет S3 PUT и создаёт ready attachment, удаляет intent, COMMIT.
|
||||
5. Только после успешной фиксации возвращается 201. При неопределённом исходе COMMIT объект немедленно не удаляется.
|
||||
|
||||
## Reconciler
|
||||
|
||||
По умолчанию dry-run. `--apply` явно разрешает изменения; default grace 3600 секунд. Обход SQL keyset, S3 paginator, page-size 1..1000. Метрики выводятся без credentials и пользовательских текстов.
|
||||
|
||||
- Старые intent: `FOR UPDATE SKIP LOCKED` пропускает живой upload. Недавний LastModified объекта защищает его даже при старом intent. При отсутствии ready metadata apply удаляет остаточный объект, затем intent.
|
||||
- Старые S3 objects в server prefix original/: повторно проверяются PostgreSQL и HEAD. Свежие, учтённые и live intent объекты не удаляются. Чужие prefix вне политики удаления.
|
||||
- Ready metadata без оригинала: актуальный HEAD под row lock; после grace apply меняет status на failed/storage_missing. Метаданные и связи сообщений сохраняются. Reconciler не может восстановить потерянные bytes без backup.
|
||||
- Полноценные ready вложения, даже пока не прикреплённые к сообщению, не удаляются.
|
||||
- Audit пишется только в apply. После частично завершённого удаления повторный dry-run не продолжает очистку.
|
||||
|
||||
## Воспроизведение
|
||||
|
||||
Из корня репозитория после `make up`:
|
||||
|
||||
```sh
|
||||
# Исследование получает admin keys только в отдельном profile tools.
|
||||
# Создаёт отдельные БД и bucket, очищает только их в finally.
|
||||
uv run --locked python research/run_local.py --output evidence/reconcile-repeat.json
|
||||
```
|
||||
|
||||
Контроллер сохраняет raw output, JSON со счётчиками, проверками, хешами кода, результатами времени и кратким host manifest; рядом создаётся summary.md. В исходном выводе контейнера JSON начинается со строки `RESULT `. Основная messenger БД и bucket не очищаются.
|
||||
|
||||
Ошибки: настоящий trigger PostgreSQL после PUT; реальная ошибка подключения S3; успешный COMMIT с искусственно потерянным подтверждением; ошибка DELETE PostgreSQL после удаления bytes; ошибка S3 delete. Проверяются повтор, dry-run после сбоя, старый intent со свежим объектом, live row lock, missing used metadata и сохранность подтверждённого оригинала.
|
||||
|
||||
Стоимость обхода: 10/100/1000 специально добавленных intact attachment, по три dry-run на точку, page_size=100. Перед каждым размером объекты выдерживаются за границу grace, чтобы fresh-skip не менял профиль работы. Дополнительно остаются несколько fault fixtures; точное число просмотренных metadata/objects записывается в каждой строке. Сервисы прогреты, однопоточный обход; временные БД/bucket используются на том же PostgreSQL/S3 без внешней нагрузки. Это цена выбранной сверки, не HTTP throughput и не производственный SLA.
|
||||
|
||||
## Память десяти конкурентных upload
|
||||
|
||||
```sh
|
||||
uv run --locked python research/upload_memory.py --restart-api --output evidence/upload-memory-repeat.json
|
||||
```
|
||||
|
||||
Генератор использует настоящие PNG 512×512 и 1700×1700. На каждой точке десять клиентов стартуют через barrier и идут через LB. По одному upload slot на API-реплику, занятые места возвращают контролируемый 429 с Retry-After. Сохраняются status/latency и cgroup current/peak/memory.events, VmHWM API и LB. Проверяются readiness и отсутствие OOM.
|
||||
|
||||
Kernel peaks накопительные с момента старта; before/after показаны честно, без приписывания всей памяти image buffer. Регистрация и импорт Argon2 тоже влияют на high-water. Это проверка ограниченной памяти/backpressure, а не доказательство роста максимальной пропускной способности.
|
||||
|
||||
## Ограничения
|
||||
|
||||
Нет атомарной транзакции через обе системы. Консервативная очистка допускает временные остатки до grace и явного apply. Сбой самого S3/БД не интерпретируется как отсутствие объекта. Ручной администратор с правом перезаписи может изменить объект после HEAD; инструмент рассчитан на уникальные immutable server keys штатного API. Один host/LB/PostgreSQL/Seaweed backend остаются SPOF. Нет репликации и внешнего backup в этом эксперименте.
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Summarize the saved raw reconciliation measurements without re-running them."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import statistics
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("input", nargs="?", default="evidence/reconcile-study.json")
|
||||
parser.add_argument("--output", default="evidence/reconcile-summary.md")
|
||||
args = parser.parse_args()
|
||||
result = json.loads(Path(args.input).read_text())
|
||||
checks = result["checks"]
|
||||
lines = [
|
||||
"# Исследование согласованности PostgreSQL/S3",
|
||||
"",
|
||||
f"Дата начала (UTC): {result['started_at']}.",
|
||||
"",
|
||||
f"Успешных проверок: {sum(c['passed'] for c in checks)}/{len(checks)}.",
|
||||
"",
|
||||
"| Добавлено intact | Просмотрено metadata | Медиана обхода, с |",
|
||||
"|---:|---:|---:|",
|
||||
]
|
||||
for size in sorted({r["seeded_intact"] for r in result["scan_cost"]}):
|
||||
runs = [r for r in result["scan_cost"] if r["seeded_intact"] == size]
|
||||
lines.append(
|
||||
f"| {size} | {runs[0]['metadata_scanned']} | {statistics.median(r['duration_seconds'] for r in runs):.6f} |"
|
||||
)
|
||||
lines += [
|
||||
"",
|
||||
"По три dry-run на размер, page_size100, прогретый локальный стенд.",
|
||||
"Дополнительные три intact fault fixtures входят в фактический scan.",
|
||||
"",
|
||||
f"Первый apply: удалено intent {result['apply']['deleted_intents']}, "
|
||||
f"операций удаления объекта {result['apply']['deleted_objects']}, "
|
||||
f"missing помечено failed {result['apply']['marked_failed']}.",
|
||||
"Счётчик удаления объекта — число успешных идемпотентных DELETE, включая отсутствие bytes у intent.",
|
||||
"",
|
||||
f"Временные ресурсы удалены: {result['temporary_resources_deleted']}.",
|
||||
"",
|
||||
"## Проверенные инварианты",
|
||||
"",
|
||||
]
|
||||
lines += [f"- {'PASS' if c['passed'] else 'FAIL'}: {c['name']}" for c in checks]
|
||||
lines += ["", "## Ограничения", ""] + ["- " + s for s in result["limitations"]]
|
||||
Path(args.output).write_text("\n".join(lines) + "\n")
|
||||
print(args.output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -247,6 +247,44 @@ def main():
|
||||
)
|
||||
record("failed_cleanup_recovers", recovery_apply["errors"] == 0)
|
||||
|
||||
# Failure after deleting bytes but before deleting the durable intent.
|
||||
delete_id, delete_key = str(uuid4()), "original/delete-ack-fault-" + suffix
|
||||
with store.connection() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO upload_intents VALUES (%s,%s,now()-interval '1 day')",
|
||||
(delete_id, delete_key),
|
||||
)
|
||||
storage.put(delete_key, BytesIO(data), len(data), "image/png")
|
||||
time.sleep(2.2)
|
||||
with store.connection() as conn:
|
||||
conn.execute(
|
||||
"CREATE FUNCTION reject_intent_delete() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected intent DELETE failure'; END $$"
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE TRIGGER research_reject_delete BEFORE DELETE ON upload_intents FOR EACH ROW EXECUTE FUNCTION reject_intent_delete()"
|
||||
)
|
||||
try:
|
||||
reconcile(store, storage, apply=True, grace_seconds=2)
|
||||
raise AssertionError("DELETE fault did not fire")
|
||||
except psycopg.errors.RaiseException:
|
||||
record("real_db_delete_failure_after_s3_delete", not storage.exists(delete_key))
|
||||
finally:
|
||||
with store.connection() as conn:
|
||||
conn.execute("DROP TRIGGER research_reject_delete ON upload_intents")
|
||||
conn.execute("DROP FUNCTION reject_intent_delete()")
|
||||
with store.connection() as conn:
|
||||
before_count = conn.execute("SELECT count(*) AS n FROM upload_intents").fetchone()["n"]
|
||||
dry_after_delete = reconcile(store, storage, grace_seconds=2)
|
||||
with store.connection() as conn:
|
||||
after_count = conn.execute("SELECT count(*) AS n FROM upload_intents").fetchone()["n"]
|
||||
record(
|
||||
"dry_run_does_not_resume_partial_delete",
|
||||
before_count == after_count and dry_after_delete["deleted_intents"] == 0,
|
||||
)
|
||||
resumed = reconcile(store, storage, apply=True, grace_seconds=2)
|
||||
record("partial_delete_resumes_only_on_apply", resumed["deleted_intents"] == 1)
|
||||
result["partial_delete_dry"], result["partial_delete_apply"] = dry_after_delete, resumed
|
||||
|
||||
# Measure an increasing population of intact, aged metadata/objects. Rows
|
||||
# share no client names or object paths, and all are in this disposable DB.
|
||||
current = 0
|
||||
@@ -254,6 +292,8 @@ def main():
|
||||
for _ in range(target - current):
|
||||
upload("scan.png")
|
||||
current = target
|
||||
# Equalize age policy: no point may skip freshly seeded object checks.
|
||||
time.sleep(2.2)
|
||||
with store.connection() as conn:
|
||||
conn.execute("UPDATE attachments SET created_at=now()-interval '1 day'")
|
||||
for repeat in range(3):
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Run and save the isolated experiment, plus a small sanitized host manifest."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import platform
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--output", default="evidence/reconcile-study.json")
|
||||
args = parser.parse_args()
|
||||
output = ROOT / args.output
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
run = subprocess.run(
|
||||
["docker", "compose", "run", "--rm", "--no-deps", "research"],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
output.with_suffix(".raw.txt").write_text(run.stdout + run.stderr)
|
||||
if run.returncode:
|
||||
raise SystemExit(f"Experiment failed; inspect {output.with_suffix('.raw.txt')}")
|
||||
marker = next(
|
||||
(line[7:] for line in run.stdout.splitlines() if line.startswith("RESULT ")), None
|
||||
)
|
||||
if marker is None:
|
||||
raise SystemExit("Experiment did not emit RESULT")
|
||||
result = json.loads(marker)
|
||||
result["host_manifest"] = {
|
||||
"system": platform.system(),
|
||||
"machine": platform.machine(),
|
||||
"release": platform.release(),
|
||||
"git_revision": subprocess.check_output(
|
||||
["git", "rev-parse", "HEAD"], cwd=ROOT, text=True
|
||||
).strip(),
|
||||
}
|
||||
result["host_manifest"]["docker"] = json.loads(
|
||||
subprocess.check_output(
|
||||
[
|
||||
"docker",
|
||||
"info",
|
||||
"--format",
|
||||
'{"version":"{{.ServerVersion}}","cpus":{{.NCPU}},"memory_bytes":{{.MemTotal}}}',
|
||||
],
|
||||
text=True,
|
||||
)
|
||||
)
|
||||
containers = subprocess.check_output(
|
||||
["docker", "compose", "ps", "-q"], cwd=ROOT, text=True
|
||||
).split()
|
||||
result["host_manifest"]["containers"] = []
|
||||
for container in containers:
|
||||
record = json.loads(subprocess.check_output(["docker", "inspect", container], text=True))[0]
|
||||
result["host_manifest"]["containers"].append(
|
||||
{
|
||||
"service": record["Config"]["Labels"].get("com.docker.compose.service"),
|
||||
"image": record["Image"],
|
||||
"cpu_nano": record["HostConfig"]["NanoCpus"],
|
||||
"memory_limit": record["HostConfig"]["Memory"],
|
||||
}
|
||||
)
|
||||
output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
||||
subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"research/analyze.py",
|
||||
str(output),
|
||||
"--output",
|
||||
str(output.with_suffix(".summary.md")),
|
||||
],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
)
|
||||
print(
|
||||
f"Saved {len(result['checks'])} checks and {len(result['scan_cost'])} scan runs to {output}"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Ten simultaneous HTTP uploads through LB, with kernel memory high-water readings."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--output", default="evidence/upload-memory.json")
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:8084")
|
||||
parser.add_argument("--restart-api", action="store_true")
|
||||
args = parser.parse_args()
|
||||
c = Client(args.base_url)
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
if args.restart_api:
|
||||
subprocess.run(
|
||||
["docker", "compose", "restart", "api"], check=True, stdout=subprocess.DEVNULL
|
||||
)
|
||||
for _ in range(40):
|
||||
try:
|
||||
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
break
|
||||
except AssertionError:
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
raise AssertionError("API did not recover with old token")
|
||||
ids = subprocess.check_output(["docker", "compose", "ps", "-q", "api"], text=True).split()
|
||||
|
||||
api_count = len(ids)
|
||||
ids += subprocess.check_output(["docker", "compose", "ps", "-q", "lb"], text=True).split()
|
||||
|
||||
def memory():
|
||||
result = {}
|
||||
for container in ids:
|
||||
lines = subprocess.check_output(
|
||||
[
|
||||
"docker",
|
||||
"exec",
|
||||
container,
|
||||
"cat",
|
||||
"/sys/fs/cgroup/memory.current",
|
||||
"/sys/fs/cgroup/memory.peak",
|
||||
"/sys/fs/cgroup/memory.events",
|
||||
"/proc/1/status",
|
||||
],
|
||||
text=True,
|
||||
).splitlines()
|
||||
result[container] = {
|
||||
"current": int(lines[0]),
|
||||
"peak": int(lines[1]),
|
||||
"events": {
|
||||
line.split()[0]: int(line.split()[1])
|
||||
for line in lines[2:]
|
||||
if line.split()
|
||||
and line.split()[0]
|
||||
in {"low", "high", "max", "oom", "oom_kill", "oom_group_kill"}
|
||||
},
|
||||
"process_hwm": next(line for line in lines if line.startswith("VmHWM:")),
|
||||
}
|
||||
return result
|
||||
|
||||
result = {
|
||||
"concurrency": 10,
|
||||
"api_replicas": api_count,
|
||||
"sampled_api_and_lb_containers": ids,
|
||||
"api_restarted_before_trial": args.restart_api,
|
||||
"runs": [],
|
||||
"limitations": [
|
||||
"Kernel cgroup peak and process VmHWM are lifetime peaks; before/after reported, not attributed solely to upload buffers",
|
||||
"Fast rejection 429 is intentional backpressure, not a successful upload",
|
||||
"Local two-replica stand; not a throughput benchmark",
|
||||
],
|
||||
}
|
||||
for side in (512, 1700):
|
||||
output = BytesIO()
|
||||
Image.frombytes("RGB", (side, side), random.Random(42).randbytes(side * side * 3)).save(
|
||||
output, "PNG"
|
||||
)
|
||||
data = output.getvalue()
|
||||
barrier = threading.Barrier(10)
|
||||
before = memory()
|
||||
|
||||
def send(_, barrier=barrier, data=data):
|
||||
barrier.wait()
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
with httpx.Client(timeout=20, trust_env=False) as client:
|
||||
response = client.post(
|
||||
args.base_url
|
||||
+ f"/api/v1/chats/{chat['id']}/attachments?filename=memory.png",
|
||||
content=data,
|
||||
headers={
|
||||
"Authorization": "Bearer " + alice["token"],
|
||||
"Content-Type": "image/png",
|
||||
},
|
||||
)
|
||||
record = {
|
||||
"status": response.status_code,
|
||||
"elapsed": time.perf_counter() - started,
|
||||
}
|
||||
if response.status_code == 201:
|
||||
record["attachment_id"] = response.json()["id"]
|
||||
return record
|
||||
except httpx.HTTPError as exc:
|
||||
return {"error": type(exc).__name__, "elapsed": time.perf_counter() - started}
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
responses = list(pool.map(send, range(10)))
|
||||
after = memory()
|
||||
c.call("GET", "/health/ready", schema="Health")
|
||||
for record in responses:
|
||||
if record.get("status") not in {201, 429}:
|
||||
raise AssertionError(record)
|
||||
for container in ids:
|
||||
state = json.loads(
|
||||
subprocess.check_output(["docker", "inspect", container], text=True)
|
||||
)[0]["State"]
|
||||
if state["OOMKilled"] or not state["Running"]:
|
||||
raise AssertionError("API OOM or not running")
|
||||
result["runs"].append(
|
||||
{
|
||||
"image_dimensions": [side, side],
|
||||
"size_bytes": len(data),
|
||||
"before": before,
|
||||
"after": after,
|
||||
"responses": responses,
|
||||
"ready_after": True,
|
||||
}
|
||||
)
|
||||
Path(args.output).write_text(json.dumps(result, indent=2) + "\n")
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"runs": [
|
||||
{
|
||||
"size_bytes": r["size_bytes"],
|
||||
"statuses": [x.get("status", x.get("error")) for x in r["responses"]],
|
||||
}
|
||||
for r in result["runs"]
|
||||
]
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+26
-5
@@ -1,19 +1,40 @@
|
||||
"""Map a process alias to its real container, then leave exactly it stopped."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
wanted = os.environ["TARGET_INSTANCE_ID"]
|
||||
ids = subprocess.check_output(["docker", "compose", "ps", "-q", "api"], text=True).split()
|
||||
for cid in ids:
|
||||
result = subprocess.run(
|
||||
["docker", "exec", cid, "python", "-c",
|
||||
"import urllib.request; r=urllib.request.urlopen('http://127.0.0.1:8080/health/live'); print(r.headers['X-Instance-Id'])"],
|
||||
text=True, capture_output=True, check=False,
|
||||
[
|
||||
"docker",
|
||||
"exec",
|
||||
cid,
|
||||
"python",
|
||||
"-c",
|
||||
"import urllib.request; r=urllib.request.urlopen('http://127.0.0.1:8080/health/live'); print(r.headers['X-Instance-Id'])",
|
||||
],
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
)
|
||||
if result.returncode == 0 and result.stdout.strip() == wanted:
|
||||
subprocess.run(["docker", "stop", "--time", "8", cid], check=True, stdout=subprocess.DEVNULL)
|
||||
print(json.dumps({"stopped_container": cid, "instance_id": wanted}))
|
||||
subprocess.run(
|
||||
["docker", "stop", "--time", "8", cid], check=True, stdout=subprocess.DEVNULL
|
||||
)
|
||||
record = {
|
||||
"stopped_container": cid,
|
||||
"instance_id": wanted,
|
||||
"stopped_at": datetime.now(UTC).isoformat(),
|
||||
}
|
||||
Path("evidence").mkdir(exist_ok=True)
|
||||
with Path("evidence/failover-hooks.jsonl").open("a") as output:
|
||||
output.write(json.dumps(record) + "\n")
|
||||
print(json.dumps(record))
|
||||
break
|
||||
else:
|
||||
raise SystemExit("Target instance not found among this project's API containers")
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stop the actual uploader, read via another process, and test LB's no-backend JSON."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client # noqa: E402 - load the unchanged public helper after adding tests path.
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(os.getenv("BASE_URL", "http://127.0.0.1:8084"))
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
data = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
uploaded = c.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=failover.png",
|
||||
201,
|
||||
actor=alice,
|
||||
raw=data,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)
|
||||
target = uploaded["headers"]["X-Instance-Id"]
|
||||
started = time.monotonic()
|
||||
try:
|
||||
subprocess.run(
|
||||
[str(ROOT / "scripts/stop-one.sh")],
|
||||
cwd=ROOT,
|
||||
env={**os.environ, "TARGET_INSTANCE_ID": target},
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
for _ in range(40):
|
||||
try:
|
||||
downloaded = c.call(
|
||||
"GET", f"/api/v1/attachments/{uploaded['json']['id']}/content", actor=bob
|
||||
)
|
||||
if downloaded["headers"]["X-Instance-Id"] != target:
|
||||
break
|
||||
except AssertionError:
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
raise AssertionError("Uploader failover timed out")
|
||||
assert downloaded["bytes"] == data
|
||||
result = {
|
||||
"uploader_instance": target,
|
||||
"download_instance": downloaded["headers"]["X-Instance-Id"],
|
||||
"same_original_bytes": True,
|
||||
"sha256": uploaded["json"]["sha256"],
|
||||
"elapsed_seconds": time.monotonic() - started,
|
||||
}
|
||||
finally:
|
||||
subprocess.run(
|
||||
["docker", "compose", "up", "-d", "--wait", "--no-recreate"],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
subprocess.run(["docker", "compose", "stop", "api"], cwd=ROOT, check=True, capture_output=True)
|
||||
try:
|
||||
time.sleep(3)
|
||||
try:
|
||||
response = urllib.request.urlopen(c.base + "/api/v1/users/me", timeout=3)
|
||||
except urllib.error.HTTPError as exc:
|
||||
response = exc
|
||||
with response:
|
||||
body = json.loads(response.read())
|
||||
assert response.code == 503 and body["error"]["code"] == "unavailable"
|
||||
assert response.headers["X-Request-Id"] == body["error"]["request_id"]
|
||||
assert not response.headers.get("X-Instance-Id")
|
||||
result["lb_no_backend"] = {
|
||||
"status": response.code,
|
||||
"request_id": response.headers["X-Request-Id"],
|
||||
"no_fake_instance": True,
|
||||
}
|
||||
finally:
|
||||
subprocess.run(
|
||||
["docker", "compose", "up", "-d", "--wait", "--no-recreate"],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
result["existing_session_recovers"] = True
|
||||
(ROOT / "evidence/attachment-failover.json").write_text(
|
||||
json.dumps(result, ensure_ascii=False, indent=2) + "\n"
|
||||
)
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real storage ACL and dependency failure checks; tokens never leave memory/stdin."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(
|
||||
["docker", "compose", *args], cwd=ROOT, check=True, capture_output=True, text=True
|
||||
)
|
||||
|
||||
|
||||
def inside(code, payload=None):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "--index", "1", "api", "python", "-c", code],
|
||||
cwd=ROOT,
|
||||
input=json.dumps(payload or {}),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def request(path, token=None):
|
||||
return inside(
|
||||
"""import json,sys,time,urllib.request,urllib.error
|
||||
p=json.load(sys.stdin);h={"Authorization":"Bearer "+p["token"]} if p.get("token") else {}
|
||||
start=time.monotonic()
|
||||
try:r=urllib.request.urlopen(urllib.request.Request("http://127.0.0.1:8080"+p["path"],headers=h),timeout=8)
|
||||
except urllib.error.HTTPError as e:r=e
|
||||
data=r.read()
|
||||
print(json.dumps({"status":r.code,"elapsed":time.monotonic()-start,"json":json.loads(data) if r.headers.get_content_type()=="application/json" else None,"sha256":__import__("hashlib").sha256(data).hexdigest()}))
|
||||
""",
|
||||
{"path": path, "token": token},
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(os.getenv("BASE_URL", "http://127.0.0.1:8084"))
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
attachment, content = c.attachment(alice, chat)
|
||||
report = {"checks": [], "faults": []}
|
||||
|
||||
def check(name, condition):
|
||||
if not condition:
|
||||
raise AssertionError(name)
|
||||
report["checks"].append({"name": name, "passed": True})
|
||||
|
||||
security = inside(
|
||||
"""import json,sys,os,socket,urllib.request,urllib.error,uuid
|
||||
from pathlib import Path
|
||||
from messenger.storage import ObjectStorage
|
||||
from messenger.postgres import PostgresStore
|
||||
from botocore.exceptions import ClientError
|
||||
p=json.load(sys.stdin);s=ObjectStorage();db=PostgresStore()
|
||||
with db.connection() as conn:key=conn.execute("SELECT object_key FROM attachments WHERE id=%s",(p["id"],)).fetchone()["object_key"]
|
||||
try:r=urllib.request.urlopen(os.getenv("S3_ENDPOINT")+"/"+s.bucket+"/"+key,timeout=3);anon=r.code;r.close()
|
||||
except urllib.error.HTTPError as e:anon=e.code
|
||||
try:s.client.create_bucket(Bucket="forbidden-"+uuid.uuid4().hex);denied=False
|
||||
except ClientError as e:denied=e.response["ResponseMetadata"]["HTTPStatusCode"]==403
|
||||
try:socket.create_connection(("storage",8888),timeout=.5).close();backend=False
|
||||
except OSError:backend=True
|
||||
try:socket.create_connection(("s3",8888),timeout=.5).close();gateway=False
|
||||
except OSError:gateway=True
|
||||
print(json.dumps({"anonymous_status":anon,"unrelated_bucket_denied":denied,"backend_unreachable":backend,"gateway_filer_unreachable":gateway,"no_admin_secrets":not Path("/run/secrets/s3_admin_access_key").exists() and not any(k.startswith("S3_ADMIN") for k in os.environ)}));db.close();s.close()
|
||||
""",
|
||||
{"id": attachment["id"]},
|
||||
)
|
||||
report["security"] = security
|
||||
for key in [
|
||||
"unrelated_bucket_denied",
|
||||
"backend_unreachable",
|
||||
"gateway_filer_unreachable",
|
||||
"no_admin_secrets",
|
||||
]:
|
||||
check(key, security[key])
|
||||
check("anonymous_original_denied", security["anonymous_status"] in {401, 403})
|
||||
compose("run", "--rm", "--no-deps", "s3-bootstrap")
|
||||
check("bucket_bootstrap_repeatable", True)
|
||||
try:
|
||||
compose("stop", "s3")
|
||||
ready = request("/health/ready")
|
||||
download = request(f"/api/v1/attachments/{attachment['id']}/content", alice["token"])
|
||||
check("s3_down_ready_503", ready["status"] == 503 and ready["elapsed"] < 8)
|
||||
check("s3_down_content_503", download["status"] == 503 and download["elapsed"] < 8)
|
||||
report["faults"].append({"service": "s3", "ready": ready, "download": download})
|
||||
finally:
|
||||
compose("start", "s3")
|
||||
for _ in range(30):
|
||||
try:
|
||||
downloaded = request(f"/api/v1/attachments/{attachment['id']}/content", alice["token"])
|
||||
if downloaded["status"] == 200:
|
||||
break
|
||||
except (AssertionError, subprocess.CalledProcessError):
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
raise AssertionError("S3 recovery timed out")
|
||||
check(
|
||||
"s3_restart_original_unchanged", downloaded["sha256"] == hashlib.sha256(content).hexdigest()
|
||||
)
|
||||
try:
|
||||
compose("pause", "postgres")
|
||||
ready = request("/health/ready")
|
||||
me = request("/api/v1/users/me", alice["token"])
|
||||
check(
|
||||
"paused_pg_ready_503_with_client_deadline",
|
||||
ready["status"] == 503 and ready["elapsed"] < 8,
|
||||
)
|
||||
check("paused_pg_auth_503_with_client_deadline", me["status"] == 503 and me["elapsed"] < 8)
|
||||
report["faults"].append({"service": "paused_postgres", "ready": ready, "me": me})
|
||||
finally:
|
||||
compose("unpause", "postgres")
|
||||
for _ in range(30):
|
||||
try:
|
||||
me = request("/api/v1/users/me", alice["token"])
|
||||
if me["status"] == 200:
|
||||
break
|
||||
except subprocess.CalledProcessError:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
raise AssertionError("PostgreSQL recovery timed out")
|
||||
check("old_session_recovers_after_unpause", me["json"]["id"] == alice["id"])
|
||||
inside(
|
||||
"from messenger.postgres import PostgresStore; s=PostgresStore(); "
|
||||
"c=s.pool.getconn(); c.execute('ALTER TABLE message_requests RENAME TO message_requests_readiness_test'); "
|
||||
"s.pool.putconn(c); s.close(); print('{}')"
|
||||
)
|
||||
try:
|
||||
absent_table = request("/health/ready")
|
||||
check("missing_required_table_ready_503", absent_table["status"] == 503)
|
||||
report["faults"].append({"service": "missing_message_requests", "ready": absent_table})
|
||||
finally:
|
||||
inside(
|
||||
"from messenger.postgres import PostgresStore; s=PostgresStore(); "
|
||||
"c=s.pool.getconn(); c.execute('ALTER TABLE message_requests_readiness_test RENAME TO message_requests'); "
|
||||
"s.pool.putconn(c); s.close(); print('{}')"
|
||||
)
|
||||
check("schema_restore_ready_200", request("/health/ready")["status"] == 200)
|
||||
for _ in range(30):
|
||||
try:
|
||||
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
break
|
||||
except AssertionError:
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
raise AssertionError("LB did not readmit recovered API")
|
||||
check("lb_readmits_recovered_api", True)
|
||||
Path(ROOT / "evidence/storage-checks.json").write_text(
|
||||
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
||||
)
|
||||
print(json.dumps({"passed": len(report["checks"])}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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:
|
||||
|
||||
@@ -1,20 +1,19 @@
|
||||
"""Synchronous attachment intake: bounded spool, full image validation, durable intent."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import unicodedata
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from .domain import Failure, timestamp
|
||||
from .image_validation import MAX_BYTES
|
||||
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",
|
||||
@@ -41,43 +40,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)
|
||||
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:
|
||||
decoded = subprocess.run(
|
||||
["djpeg", "-strict", "-maxmemory", "192m", "-outfile", "/dev/null"],
|
||||
stdin=fileobj,
|
||||
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
|
||||
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):
|
||||
|
||||
+11
-2
@@ -30,10 +30,19 @@ def boundary(scope: str, cursor: str | None) -> tuple[str, str] | None:
|
||||
if not cursor or len(cursor) > 1024 or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor):
|
||||
raise ValueError
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)))
|
||||
if not isinstance(data, list) or len(data) != 4 or data[:2] != [1, scope]:
|
||||
if (
|
||||
not isinstance(data, list)
|
||||
or len(data) != 4
|
||||
or type(data[0]) is not int
|
||||
or data[0] != 1
|
||||
or data[1] != scope
|
||||
):
|
||||
raise ValueError
|
||||
date, uid = data[2:]
|
||||
if not isinstance(date, str) or not date.endswith("Z"):
|
||||
if not isinstance(date, str) or not re.fullmatch(
|
||||
r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?Z",
|
||||
date,
|
||||
):
|
||||
raise ValueError
|
||||
datetime.fromisoformat(date.replace("Z", "+00:00"))
|
||||
if not isinstance(uid, str) or str(UUID(uid)) != uid:
|
||||
|
||||
@@ -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()
|
||||
@@ -101,9 +101,13 @@ class PostgresStore:
|
||||
def ready(self):
|
||||
try:
|
||||
with self.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
conn.execute(
|
||||
"SELECT u.id,c.id,m.chat_id,msg.id,s.token_digest,r.key,a.id,i.id,ma.message_id "
|
||||
"FROM users u,chats c,members m,messages msg,sessions s,message_requests r,"
|
||||
"attachments a,upload_intents i,message_attachments ma WHERE false"
|
||||
)
|
||||
return True
|
||||
except Failure:
|
||||
except (Failure, psycopg.Error):
|
||||
return False
|
||||
|
||||
def _cached_user(self, uid):
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"""Black-box regressions derived from the contract and teacher review comments."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import uuid
|
||||
@@ -199,3 +201,81 @@ def test_truncated_jpeg_with_forged_eoi(scenario):
|
||||
mime="image/jpeg",
|
||||
status=415,
|
||||
)
|
||||
|
||||
|
||||
def test_internal_jpeg_bytesio_fallback():
|
||||
import shutil
|
||||
|
||||
from messenger.attachments import validate_image
|
||||
|
||||
if shutil.which("djpeg") is None:
|
||||
pytest.skip(
|
||||
"Internal BytesIO helper requires host djpeg; HTTP JPEG validation runs in Docker regardless"
|
||||
)
|
||||
stream = BytesIO(image_bytes("JPEG"))
|
||||
assert validate_image(stream, "image/jpeg") == ("image/jpeg", 32, 20)
|
||||
assert stream.tell() == 0
|
||||
|
||||
|
||||
def test_parallel_same_key_across_replicas(scenario):
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
c, alice, _, _, chat = scenario
|
||||
key = uuid.uuid4().hex
|
||||
barrier = threading.Barrier(10)
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
body = {"text": "concurrent idempotent message"}
|
||||
|
||||
def send(_):
|
||||
barrier.wait()
|
||||
return Client(c.base).call(
|
||||
"POST",
|
||||
path,
|
||||
201,
|
||||
actor=alice,
|
||||
body=body,
|
||||
headers={"Idempotency-Key": key},
|
||||
schema="Message",
|
||||
)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
responses = list(pool.map(send, range(10)))
|
||||
assert len({r["json"]["id"] for r in responses}) == 1
|
||||
assert len({r["headers"]["X-Instance-Id"] for r in responses}) >= 2
|
||||
history = c.call("GET", path, actor=alice, schema="MessagePage")["json"]["items"]
|
||||
assert sum(m["id"] == responses[0]["json"]["id"] for m in history) == 1
|
||||
|
||||
|
||||
def test_exact_pixel_boundary_is_accepted(scenario):
|
||||
uploaded = upload(scenario, data=image_bytes(size=(8000, 5000)))["json"]
|
||||
assert uploaded["status"] == "ready"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"version,date",
|
||||
[
|
||||
(True, "2026-01-01T00:00:00Z"),
|
||||
(1.0, "2026-01-01T00:00:00Z"),
|
||||
(1, "2026-W01-1T00:00:00Z"),
|
||||
(1, "20260101T000000Z"),
|
||||
(1, "2026-01-01 00:00:00Z"),
|
||||
(1, "2026-01-01X00:00:00Z"),
|
||||
(1, "2026-02-30T00:00:00Z"),
|
||||
(1, "2026-01-01T00:00:00.1234567Z"),
|
||||
(1, "0000-01-01T00:00:00Z"),
|
||||
(1, "2026-01-01T24:00:00Z"),
|
||||
],
|
||||
)
|
||||
def test_noncanonical_cursor_over_http(scenario, version, date):
|
||||
c, alice, _, _, chat = scenario
|
||||
for path, scope in [
|
||||
("/api/v1/chats", "chats:" + alice["id"]),
|
||||
(f"/api/v1/chats/{chat['id']}/messages", "messages:" + chat["id"]),
|
||||
]:
|
||||
cursor = (
|
||||
base64.urlsafe_b64encode(json.dumps([version, scope, date, str(uuid.uuid4())]).encode())
|
||||
.decode()
|
||||
.rstrip("=")
|
||||
)
|
||||
c.call("GET", path + "?cursor=" + cursor, 400, actor=alice)
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import base64
|
||||
import json
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from messenger.domain import Failure, boundary
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"version,date",
|
||||
[
|
||||
(True, "2026-01-01T00:00:00Z"),
|
||||
(1.0, "2026-01-01T00:00:00Z"),
|
||||
(1, "2026-W01-1T00:00:00Z"),
|
||||
(1, "20260101T000000Z"),
|
||||
(1, "2026-01-01 00:00:00Z"),
|
||||
(1, "2026-01-01X00:00:00Z"),
|
||||
(1, "2026-02-30T00:00:00Z"),
|
||||
(1, "2026-01-01T00:00:00.1234567Z"),
|
||||
],
|
||||
)
|
||||
def test_boundary_rejects_python_iso_extensions(version, date):
|
||||
payload = [version, "scope", date, str(uuid4())]
|
||||
cursor = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
|
||||
with pytest.raises(Failure) as error:
|
||||
boundary("scope", cursor)
|
||||
assert error.value.status == 400
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"date", ["2026-01-01T00:00:00Z", "2026-01-01T00:00:00.1Z", "2026-01-01T00:00:00.123456Z"]
|
||||
)
|
||||
def test_boundary_preserves_generated_format(date):
|
||||
uid = str(uuid4())
|
||||
cursor = (
|
||||
base64.urlsafe_b64encode(json.dumps([1, "scope", date, uid]).encode()).decode().rstrip("=")
|
||||
)
|
||||
assert boundary("scope", cursor) == (date, uid)
|
||||
@@ -0,0 +1,199 @@
|
||||
"""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:8084"))
|
||||
return c, *c.bootstrap()
|
||||
|
||||
|
||||
def upload(scenario, data, mime, expected):
|
||||
c, alice, _, _, chat = scenario
|
||||
return c.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=edge.png",
|
||||
expected,
|
||||
actor=alice,
|
||||
raw=data,
|
||||
headers={"Content-Type": mime},
|
||||
schema="Attachment" if expected == 201 else None,
|
||||
)
|
||||
|
||||
|
||||
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_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)
|
||||
@@ -0,0 +1,140 @@
|
||||
import base64
|
||||
import codecs
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
|
||||
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
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Process boundary failures must stay bounded and map to contract errors."""
|
||||
|
||||
import signal
|
||||
import subprocess
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
|
||||
from messenger.attachments import validate_image
|
||||
from messenger.domain import Failure
|
||||
|
||||
|
||||
class FakeProcess:
|
||||
pid = 999999999
|
||||
returncode = 0
|
||||
|
||||
def __init__(self, output=b'{"ok":["image/png",1,1]}', crash=False, timeout=False):
|
||||
self.output, self.timeout, self.calls = output, timeout, 0
|
||||
self.returncode = -11 if crash else 0
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
pass
|
||||
|
||||
def communicate(self, input=None, timeout=None):
|
||||
self.calls += 1
|
||||
if self.timeout and self.calls == 1:
|
||||
raise subprocess.TimeoutExpired("validator", 5)
|
||||
return self.output, b""
|
||||
|
||||
|
||||
def test_timeout_kills_group_and_returns_415(monkeypatch):
|
||||
process = FakeProcess(timeout=True)
|
||||
killed = []
|
||||
monkeypatch.setattr("messenger.attachments.subprocess.Popen", lambda *a, **k: process)
|
||||
monkeypatch.setattr(
|
||||
"messenger.attachments.os.killpg", lambda pid, sig: killed.append((pid, sig))
|
||||
)
|
||||
with pytest.raises(Failure) as failure:
|
||||
validate_image(BytesIO(b"synthetic"), "image/png")
|
||||
assert failure.value.status == 415
|
||||
assert killed == [(process.pid, signal.SIGKILL)]
|
||||
assert process.calls == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"output,crash", [(b"", True), (b"not-json", False), (b"null", False), (b"[]", False)]
|
||||
)
|
||||
def test_crash_or_malformed_child_result_returns_415(monkeypatch, output, crash):
|
||||
monkeypatch.setattr(
|
||||
"messenger.attachments.subprocess.Popen", lambda *a, **k: FakeProcess(output, crash=crash)
|
||||
)
|
||||
with pytest.raises(Failure) as failure:
|
||||
validate_image(BytesIO(b"synthetic"), "image/png")
|
||||
assert failure.value.status == 415
|
||||
Reference in New Issue
Block a user