refactoring

This commit is contained in:
Матвей
2026-10-22 16:38:54 +03:00
parent 483d7eecb3
commit c84d112f0d
34 changed files with 791 additions and 84 deletions
+21 -8
View File
@@ -1,14 +1,27 @@
## Лабораторная 4
Автор / группа: TODO
Целевая оценка (3/4/5): TODO
Трек 5, если заявлен: TODO
Автор / группа: Матвей Козырев / БВТ2301
Целевая оценка (3/4/5): 5
Трек 5, если заявлен: 2 — согласованность PostgreSQL и S3
Что реализовано и что перенесено: TODO
Команды запуска из чистого clone: TODO
Результаты проверок и ссылка на REPORT.md: TODO
Ограничения / известные ошибки: TODO
Источники и использование ИИ: TODO
Что реализовано и что перенесено: основа lab3 (две API-реплики, общие сессии,
идемпотентные сообщения); приватные S3-вложения PNG/JPEG, ACL и лимиты;
reconciler с dry-run, grace period и блокировкой параллельного upload/COMMIT.
Команды запуска из чистого clone:
`python3 scripts/init-secrets.py`, `docker compose up -d --build --wait`, `make test`.
Полные зависимости и порядок аудита — в [REPORT.md](../REPORT.md).
Результаты проверок: [последовательный аудит](../evidence/audit/results.json),
логи каждого шага в `evidence/audit/`; гипотеза и ограничения трека в REPORT.md.
Ограничения: один Docker-host; отсутствующий оригинал восстанавливается из
известной копии оператором; полный inventory требует O(N) памяти и на время
сверки задерживает PUT/COMMIT. Измерения RAM дискретные, benchmark локальный.
Источники и использование ИИ: собственный проект lab3; контракт курса;
SeaweedFS, Pillow, boto3; Codex использован для реализации, тестов и ревью.
Ссылки и закреплённые версии — в REPORT.md.
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
- [ ] Контракт и публичные тесты не ослаблены.
+7
View File
@@ -54,6 +54,13 @@ test-reconcile:
test-reconcile-benchmark:
$(PYTHON) student-tests/reconcile_benchmark.py --base-url "$(BASE_URL)"
.PHONY: test-reconcile-audit audit
test-reconcile-audit:
$(PYTHON) student-tests/reconcile_audit.py --base-url "$(BASE_URL)"
audit:
$(PYTHON) scripts/audit.py
test-upload-memory:
uv run python student-tests/upload_memory.py --base-url "$(BASE_URL)"
+33 -22
View File
@@ -69,9 +69,9 @@ SeaweedFS закреплён digest `sha256:186de7ef977a20343ee9a5544073f081976a
### Согласованность PostgreSQL и S3
Атомарной транзакции между PostgreSQL и S3 нет. Если PUT прошёл, но процесс или БД отказали до подтверждённого INSERT, API возвращает 503 и намеренно не удаляет объект синхронно: исход COMMIT мог быть неизвестен. Вместо небезопасного удаления применяется [src.reconcile](src/reconcile.py).
Атомарной транзакции между PostgreSQL и S3 нет. При обработанной ошибке после PUT и до подтверждённого COMMIT API возвращает 503; при аварийном завершении процесса клиент может не получить ответ. Приложение намеренно не удаляет объект синхронно: исход COMMIT мог быть неизвестен. Вместо небезопасного удаления применяется [src.reconcile](src/reconcile.py).
`make reconcile` запускает inventory в **dry-run**. Он сравнивает только `originals/` S3 с `attachments.object_key`, сообщает orphan, свежие unreferenced и missing objects. `make reconcile-apply` удаляет только orphan старше 3600 секунд; отсутствующие объекты и все referenced записи не удаляются. Grace period защищает объект при задержанном COMMIT/наблюдении. Для ручной аварийной проверки возможно `docker compose --profile maintenance run --rm --no-deps reconcile --apply --grace-seconds N`; значение 0 применяется только в изолированных тестах. Reconciler использует отдельные admin credentials, API не получает эти секреты.
`make reconcile` запускает inventory в **dry-run**. Он сравнивает только `originals/` S3 с `attachments.object_key`, сообщает orphan, свежие unreferenced и missing objects. `make reconcile-apply` удаляет только orphan старше 3600 секунд; отсутствующие объекты и все referenced записи не удаляются. Возраст объекта отсчитывается от начала обхода. Grace period дополняет общую advisory-блокировку PostgreSQL: upload удерживает shared transaction lock от PUT до COMMIT, а reconciler — exclusive lock на время inventory и удаления. Это исключает гонку с API, завершающим запись. Ожидание блокировки ограничено 5 с; при ошибке БД сверка прекращается. Для ручной аварийной проверки возможно `docker compose --profile maintenance run --rm --no-deps reconcile --apply --grace-seconds N`; значение 0 применяется только в тестах с `--object-key originals/<точный-ключ>`; этот повторяемый флаг ограничивает apply выбранными ключами, сохраняя полный inventory. Reconciler использует отдельные admin credentials, API не получает эти секреты.
Missing object считается наблюдаемой ошибкой, а не поводом удалить метаданные: download вернёт 503, а maintenance output содержит attachment ID и object key. Восстановление байтов требует оператора или резервной копии; автоматическое восстановление не заявляется. Это безопаснее удаления используемого сообщения/метаданных без источника оригинала.
@@ -79,16 +79,18 @@ Missing object считается наблюдаемой ошибкой, а не
**Гипотеза.** Полный inventory ключей `originals/` в S3 и `attachments.object_key` в PostgreSQL позволяет повторяемо обнаружить оба направления рассогласования. При удалении только aged orphan и при запрете автоматического удаления метаданных свежий или используемый файл не будет удалён maintenance-командой.
**Методика.** [student-tests/reconcile.py](student-tests/reconcile.py) создаёт используемое вложение, новый orphan и запускает dry-run, apply с grace 3600 с и apply с grace 0. Затем повторяет apply и проверяет, что уже исправленный orphan не появился снова. Ошибка на стороне PostgreSQL моделируется контролируемым отказом API после успешного S3 PUT и до INSERT; следующая сверка обнаруживает orphan и удаляет его. Ошибка на стороне S3 моделируется удалением оригинала после созданной metadata; сверка сообщает пару `attachment_id`/`object_key`, не удаляет metadata, после восстановления байтов следующий обход не сообщает missing. Во всех проверках скачивается защищённое используемое вложение.
**Методика.** [student-tests/reconcile.py](student-tests/reconcile.py) создаёт используемое вложение, новый orphan и запускает dry-run, apply с grace 3600 с и apply с grace 0. Затем повторяет apply и проверяет, что уже исправленный orphan не появился снова. Граница между хранилищами моделируется контролируемым отказом API после успешного S3 PUT и до INSERT; следующая сверка обнаруживает orphan и удаляет его. Ошибка на стороне S3 моделируется удалением оригинала после созданной metadata; сверка сообщает пару `attachment_id`/`object_key`, не удаляет metadata, после восстановления байтов следующий обход не сообщает missing. Защищённое вложение прикреплено к сообщению; после исправления проверяются история и оригинал. Дополнительно [reconcile_audit.py](student-tests/reconcile_audit.py) временно устанавливает PostgreSQL trigger только для собственного тестового чата: реальный INSERT отвергается после PUT, API возвращает 503, dry-run находит orphan, apply удаляет только выбранный ключ, повторный apply ничего не удаляет. Тот же тест проверяет незавершённый PUT/COMMIT параллельно с apply, обрыв клиентского upload и реальную S3-пагинацию с `MaxKeys=7`.
**Стоимость обхода.** [student-tests/reconcile_benchmark.py](student-tests/reconcile_benchmark.py) добавляет 32, затем 128 свежих неиспользуемых объектов с уникальным префиксом. Для каждого размера выполняются три dry-run обхода; после измерения fixtures удаляются. Reconciler возвращает число объектов, metadata-строк, S3 list pages и длительности стадий, поэтому результат не зависит от ручного таймера.
**Стоимость обхода.** [student-tests/reconcile_benchmark.py](student-tests/reconcile_benchmark.py) добавляет 32, затем 128 свежих неиспользуемых объектов с уникальным префиксом. Для каждого размера выполняются три dry-run обхода; после измерения fixtures удаляются. Reconciler возвращает число объектов, metadata-строк, S3 list pages и длительности стадий. `total_seconds` измеряется после подключения и получения блокировки; запуск контейнера, подключение и ожидание lock в него не входят. Inventory хранит все ключи в памяти: время и RAM имеют порядок O(S3 keys + metadata rows), число LIST зависит от страниц провайдера. Это не измерение предельной пропускной способности.
В зафиксированном прогоне для 32 добавленных объектов проверены 119 S3 keys и 87 metadata-строк, одна S3 page; длительности 0,299804, 0,204790 и 0,321822 с, медиана 0,299804 с. Для 128 добавленных объектов: 215 keys, те же 87 metadata-строк, одна page; 0,311197, 0,301204 и 0,220673 с, медиана 0,301204 с. Полный машинный вывод — [evidence/reconcile-benchmark.txt](evidence/reconcile-benchmark.txt). Шесть локальных замеров недостаточны для вывода о производительности при большом числе объектов или нескольких S3 pages; это измерение стоимости именно данного стенда.
В актуальном прогоне для 32 добавленных объектов проверены 155 S3 keys и 122 metadata-строки, одна S3 page; длительности 0,405214, 0,404481 и 0,406961 с, медиана 0,405214 с. Для 128 добавленных объектов: 251 keys, те же 122 metadata-строки, одна page; 0,406231, 0,304459 и 0,403061 с, медиана 0,403061 с. Медиана — среднее по порядку значение отсортированной тройки. Полный машинный вывод — [evidence/audit/reconcile-benchmark.txt](evidence/audit/reconcile-benchmark.txt). Эти замеры не показывают монотонного роста задержки на малом наборе и не доказывают масштабируемость. Отдельная функциональная проверка пагинации прочитала 113 keys через 17 страниц с `MaxKeys=7` — [лог](evidence/audit/reconcile-audit.txt).
Недоступность S3: upload/download и readiness возвращают 503 в формате Error; liveness остаётся 200. HAProxy исключает unready backend, поэтому при недоступности обеих реплик сам LB может вернуть собственный 503. Проверка формата ошибки API при таком отказе выполняется напрямую внутри Docker-сети.
Недоступность S3: upload/download и readiness возвращают 503 в формате Error; liveness остаётся 200. HAProxy исключает unready backend, поэтому при недоступности обеих реплик сам LB может вернуть собственный 503. Проверка формата ошибки API при таком отказе выполняется напрямую внутри Docker-сети. После запуска S3 повторяется `s3-init`: реальный PUT/DELETE подтверждает восстановление записи, затем проверяются прежний download и новый upload. Один успешный HeadBucket не гарантирует готовность записи.
## Проверки и доказательства
Полный последовательный повтор: `make audit`. [scripts/audit.py](scripts/audit.py) сохраняет фактический stdout/stderr каждого шага и его exit code в [evidence/audit/results.json](evidence/audit/results.json), останавливаясь при первой ошибке. Актуальные результаты находятся в `evidence/audit/`; прежние логи вне этого каталога относятся к предыдущим версиям. При проверке исходников `git diff ec540a1 -- tests contracts README.md` пуст: обязательные публичные файлы не менялись.
Для собственных image-тестов и полной OpenAPI-валидации нужны локальные зависимости:
```sh
@@ -107,34 +109,43 @@ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
docker compose start api-a api-b
make reconcile
make test-reconcile
make test-reconcile-audit
make test-reconcile-benchmark
make test-upload-memory
make test-s3-permissions
```
Сценарии отказов выполняются последовательно на учебном стенде: они временно останавливают контейнеры. Собственные проверки возвращают остановленные сервисы в работу; публичный `test-failover` оставляет реплику остановленной, поэтому последняя команда нужна для восстановления. Все данные синтетические, токены не сохраняются. Тесты добавляют данные; автоматического удаления нет.
Сценарии отказов выполняются последовательно на учебном стенде: они временно останавливают контейнеры. Собственные проверки возвращают остановленные сервисы в работу; публичный `test-failover` оставляет реплику остановленной, поэтому после него нужна команда восстановления реплик. Все данные синтетические, токены не сохраняются. API-тесты добавляют синтетические данные. Reconcile-тесты удаляют только собственные выбранные orphan, а benchmark удаляет свои временные объекты.
| Критерий | Команда / наблюдение | Результат |
| --- | --- | --- |
| Структура и OpenAPI | `make check validate PYTHON=.venv/bin/python` | [PASS](evidence/contracts.txt) |
| Обязательный API lab4, checksum, ACL | `make test` | [PASS](evidence/smoke.txt) |
| PNG/JPEG, сообщение с вложением, чужой чат, неверный MIME/filename, лимиты, chunked | `make test-attachments PYTHON=.venv/bin/python` | [PASS](evidence/attachments.txt) |
| Приватность bucket вне API | `make test-private`: anonymous GET существующего объекта → 403 | [PASS](evidence/private-bucket.txt) |
| Отказ именно загрузившей API | `make test-upload-failover`: загрузка через api-b, остановка api-b, те же байты через другую реплику | [PASS](evidence/attachment-failover.txt) |
| Недоступность S3 | `make test-s3-outage`: 503, восстановление, прежний оригинал | [PASS](evidence/s3-outage.txt) |
| Перезапуск всех компонентов, сохранение действующей сессии, метаданных и файла | `python3 scripts/verify-persistence.py`; StartedAt каждого сервиса изменился | [PASS](evidence/persistence-level4.txt) |
| Публичный failover, сообщения без дублей и сохранение файла | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | [PASS](evidence/failover-level4.txt) |
| Конкурентная идемпотентность и регрессии lab3 | Собственные проверки lab3 | [Результат](evidence/lab3-regressions.txt) |
| Повторный bootstrap bucket | `docker compose run --rm --no-deps s3-init` | [Результат](evidence/bootstrap.txt) |
| Reconcile: dry-run, grace period, protected object, missing object, post-PUT/pre-DB отказ | `make test-reconcile` | [PASS](evidence/reconcile.txt) |
| Трек 2: три обхода для 32 и 128 добавленных S3-объектов; метрики inventory | `make test-reconcile-benchmark` | [PASS](evidence/reconcile-benchmark.txt) |
| Ограниченные S3 credentials | `make test-s3-permissions`: API не создаёт bucket; отдельный maintenance principal выполняет admin list | [PASS](evidence/s3-permissions.txt) |
| 10 одновременных потоковых upload по 5 MiB | `make test-upload-memory`, cgroup `memory.current` каждые 0,1 с | [PASS](evidence/upload-memory.txt), [raw JSON](evidence/upload-memory.json) |
| Структура и OpenAPI | `make check validate PYTHON=.venv/bin/python` | [PASS](evidence/audit/contracts.txt) |
| Обязательный API lab4, checksum, ACL | `make test` | [PASS](evidence/audit/smoke.txt) |
| PNG/JPEG, сообщение с вложением, чужой чат, неверный MIME/filename, лимиты, chunked | `make test-attachments PYTHON=.venv/bin/python` | [PASS](evidence/audit/attachments.txt) |
| Приватность bucket вне API | `make test-private`: anonymous GET существующего объекта → 403 | [PASS](evidence/audit/private-bucket.txt) |
| Отказ именно загрузившей API | `make test-upload-failover`: загрузка, остановка обслужившей реплики, те же байты через другую реплику | [PASS](evidence/audit/upload-failover.txt) |
| Недоступность S3 | `make test-s3-outage`: 503, восстановление, прежний оригинал | [PASS](evidence/audit/s3-outage.txt) |
| Перезапуск всех компонентов, сохранение действующей сессии, метаданных и файла | `python3 scripts/verify-persistence.py`; StartedAt каждого сервиса изменился | [PASS](evidence/audit/persistence.txt) |
| Публичный failover, сообщения без дублей и сохранение файла | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | [PASS](evidence/audit/public-failover.txt) |
| Конкурентная идемпотентность и регрессии lab3 | Собственные проверки lab3 | [Результат](evidence/audit/idempotency.txt) |
| Повторный bootstrap bucket | `docker compose run --rm --no-deps s3-init` | [Результат](evidence/audit/bootstrap.txt) |
| Reconcile: dry-run, grace period, protected object, missing object, post-PUT/pre-DB отказ | `make test-reconcile` | [PASS](evidence/audit/reconcile.txt) |
| Реальный отказ INSERT, ошибка inventory, гонка PUT/COMMIT, обрыв upload, S3 pagination | `make test-reconcile-audit` | [Лог](evidence/audit/reconcile-audit.txt) |
| Трек 2: три обхода для 32 и 128 добавленных S3-объектов; метрики inventory | `make test-reconcile-benchmark` | [PASS](evidence/audit/reconcile-benchmark.txt) |
| Ограниченные S3 credentials | `make test-s3-permissions`: API не создаёт bucket; отдельный maintenance principal выполняет admin list | [PASS](evidence/audit/s3-permissions.txt) |
| 10 одновременных потоковых upload по 5 MiB | `make test-upload-memory`, cgroup `memory.current`, фактические интервалы опроса в JSON | [PASS](evidence/audit/upload-memory.txt), [raw JSON](evidence/upload-memory.json) |
Точные границы проверены отдельно: PNG с trailing bytes доведён до 10 485 760 байт и скачан без изменений; PNG 8000 × 5000 = 40 000 000 пикселей принят; заголовок 8001 × 5000 = 40 005 000 пикселей отклонён до декодирования. В `upload-memory.json` серия из 10 клиентов по 5 242 880 bytes дала длительность 5,529 с; 22 cgroup-пробы показали peak 105 254 912 и 101 470 208 bytes на двух API. Это на 431 616 000 и 435 400 704 bytes ниже лимита 536 870 912 bytes, соответственно: `536870912 − 105254912` и `536870912 − 101470208`. Измерение дискретное, поэтому это наблюдаемый минимум пика, а не строгая верхняя оценка.
Точные границы проверены отдельно: PNG с trailing bytes доведён до 10 485 760 байт и скачан без изменений; PNG 8000 × 5000 = 40 000 000 пикселей принят; заголовок 8001 × 5000 = 40 005 000 пикселей отклонён до декодирования. Актуальные значения RAM — в [upload-memory.json](evidence/upload-memory.json), вывод запуска — [audit/upload-memory.txt](evidence/audit/upload-memory.txt). Десять клиентов стартуют через barrier; измерение проверяет наличие обеих API, успешность sampler и минимум две пробы. Между завершением опросов есть пауза 0,1 с; реальный интервал включает Docker latency и записывается в `sample_intervals_seconds`. Измерение дискретное: максимальная проба — нижняя оценка истинного пика, а не строгая верхняя граница.
### Итог аудита уровней 3–5
В [results.json](evidence/audit/results.json) завершены 20 шагов, каждый с `exit_code=0`, `complete=true`. Это число включает конфигурацию, восстановление реплик и снимок окружения, а не только тесты. Для повторения нужен запущенный стенд и зависимости из инструкции выше.
Исправления аудита: синхронизация upload/reconcile; ограничение тестового apply точными ключами; проверка вложения, действительно прикреплённого к сообщению; реальный отказ PostgreSQL INSERT и отказ inventory; корректная обработка ClientDisconnect; write-probe при восстановлении S3; фактические интервалы измерения RAM. Заполнен шаблон PR. Аудит запускался на существующем учебном volume после пересборки образов; отдельный запуск из чистого clone с пустыми volumes в этот прогон не входил.
## Ограничения
- Advisory lock действует для писателей, использующих протокол приложения. Ручные SQL/S3-изменения администратора должны выполняться в maintenance-окне. Длительный полный обход задерживает новые PUT/COMMIT; после 5 с ожидания запрос получает 503. Отдельная общая транзакция между S3 и PostgreSQL отсутствует.
- Между S3 PUT и COMMIT PostgreSQL нет общей транзакции; orphan закрывает reconciler с grace period, но missing-object запись восстанавливается только оператором/backup. Автоматический repair исходного файла не реализован. Inventory выполняет полный обход keyspace `originals/` и таблицы metadata, поэтому его стоимость растёт с их размером.
- API буферизует скачивание не более 10 MiB, чтобы проверить checksum до ответа. Эксперимент 10 upload измеряет cgroup memory.current, но не является capacity benchmark и не покрывает произвольные медленные клиенты, filesystem quota и одновременные скачивания.
- Readiness проверяет доступность БД и bucket, но не наличие каждого отдельного объекта. Потеря одного объекта при доступном S3 обнаруживается при скачивании как 503.
+5
View File
@@ -0,0 +1,5 @@
uv run python student-tests/attachments.py --base-url "http://localhost:8080"
PASS: PNG/JPEG originals, metadata, attachment-only messages and ACL
PASS: filename, MIME, malformed image, byte/pixel and chunked limits
PASS: attachment scope, duplicates and idempotency normalization
PASS: inclusive 10 MiB and 40 million pixel boundaries
+3
View File
@@ -0,0 +1,3 @@
Container mtusi2026lab4-s3-init-run-2b50a47ece12 Creating
Container mtusi2026lab4-s3-init-run-2b50a47ece12 Created
PASS: private S3 bucket ready
View File
+4
View File
@@ -0,0 +1,4 @@
.venv/bin/python scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
.venv/bin/python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
+1
View File
@@ -0,0 +1 @@
PASS: sanitized environment and source hashes saved
+2
View File
@@ -0,0 +1,2 @@
python3 tests/smoke.py --base-url "http://localhost:8080"
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
+1
View File
@@ -0,0 +1 @@
PASS: concurrent idempotency through load balancer
+5
View File
@@ -0,0 +1,5 @@
Before: {"api-a": {"container": "20ad79ee2eed", "started_at": "2026-10-22T09:02:05.82757442Z"}, "api-b": {"container": "1af56e498842", "started_at": "2026-10-22T09:03:29.014379Z"}, "load_balancer": {"container": "8cc83af691c9", "started_at": "2026-10-22T08:39:31.728278626Z"}, "postgres": {"container": "b756a119c924", "started_at": "2026-10-22T08:29:42.97697609Z"}, "s3": {"container": "fe8f16b7a24d", "started_at": "2026-10-22T09:05:52.697448136Z"}}
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
After: {"api-a": {"container": "20ad79ee2eed", "started_at": "2026-10-22T09:06:32.459401543Z"}, "api-b": {"container": "1af56e498842", "started_at": "2026-10-22T09:06:32.503877126Z"}, "load_balancer": {"container": "8cc83af691c9", "started_at": "2026-10-22T09:06:32.274093543Z"}, "postgres": {"container": "b756a119c924", "started_at": "2026-10-22T09:06:12.261186631Z"}, "s3": {"container": "fe8f16b7a24d", "started_at": "2026-10-22T09:06:15.296714216Z"}}
PASS: PostgreSQL, S3, both API replicas and LB actually restarted; volumes preserved
+2
View File
@@ -0,0 +1,2 @@
python3 student-tests/attachment_resilience.py --mode private --base-url "http://localhost:8080"
PASS: anonymous S3 GET returns 403 for an existing object
+4
View File
@@ -0,0 +1,4 @@
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 110, "failed_attempts": 1, "first_recovery_seconds": 2.438}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
+8
View File
@@ -0,0 +1,8 @@
python3 student-tests/reconcile_audit.py --base-url "http://localhost:8080"
Container mtusi2026lab4-reconcile-run-15577660c231 Creating
Container mtusi2026lab4-reconcile-run-15577660c231 Created
PASS: failed PostgreSQL inventory aborts apply without deleting the orphan
PASS: actual PostgreSQL INSERT rejection -> 503, dry-run detection, scoped repair, repeat no-op
PASS: apply with zero grace waits for in-flight PUT/COMMIT; committed original survives
PASS: interrupted upload leaves no metadata/object and next upload succeeds
PASS: S3 pagination: 113 keys across 17 pages, no missing/duplicate keys
+23
View File
@@ -0,0 +1,23 @@
python3 student-tests/reconcile_benchmark.py --base-url "http://localhost:8080"
Container mtusi2026lab4-s3-init-run-6a8baf52639c Creating
Container mtusi2026lab4-s3-init-run-6a8baf52639c Created
Container mtusi2026lab4-reconcile-run-59b1c6ee9b52 Creating
Container mtusi2026lab4-reconcile-run-59b1c6ee9b52 Created
Container mtusi2026lab4-reconcile-run-ee05d61bcec3 Creating
Container mtusi2026lab4-reconcile-run-ee05d61bcec3 Created
Container mtusi2026lab4-reconcile-run-153fed7867b0 Creating
Container mtusi2026lab4-reconcile-run-153fed7867b0 Created
Container mtusi2026lab4-s3-init-run-5d803fce14c6 Creating
Container mtusi2026lab4-s3-init-run-5d803fce14c6 Created
Container mtusi2026lab4-s3-init-run-3c280622f4f2 Creating
Container mtusi2026lab4-s3-init-run-3c280622f4f2 Created
Container mtusi2026lab4-reconcile-run-feb4441d6df4 Creating
Container mtusi2026lab4-reconcile-run-feb4441d6df4 Created
Container mtusi2026lab4-reconcile-run-48539f3d2d44 Creating
Container mtusi2026lab4-reconcile-run-48539f3d2d44 Created
Container mtusi2026lab4-reconcile-run-52134038d85e Creating
Container mtusi2026lab4-reconcile-run-52134038d85e Created
Container mtusi2026lab4-s3-init-run-8524bd7d89a0 Creating
Container mtusi2026lab4-s3-init-run-8524bd7d89a0 Created
{"method": "three dry-run inventories per controlled size", "results": [{"added_unreferenced_objects": 32, "median_seconds": 0.405214, "metadata_rows_scanned": 122, "runs": 3, "s3_list_pages": 1, "s3_objects_scanned": 155, "seconds": [0.405214, 0.404481, 0.406961]}, {"added_unreferenced_objects": 128, "median_seconds": 0.403061, "metadata_rows_scanned": 122, "runs": 3, "s3_list_pages": 1, "s3_objects_scanned": 251, "seconds": [0.406231, 0.304459, 0.403061]}]}
PASS: reconciler cost measured for 32 and 128 added S3 objects; fixtures removed
+40
View File
@@ -0,0 +1,40 @@
python3 student-tests/reconcile.py --base-url "http://localhost:8080"
Container mtusi2026lab4-s3-init-run-873e8d2796d3 Creating
Container mtusi2026lab4-s3-init-run-873e8d2796d3 Created
Container mtusi2026lab4-reconcile-run-c2ac112ce56e Creating
Container mtusi2026lab4-reconcile-run-c2ac112ce56e Created
Container mtusi2026lab4-reconcile-run-41147f965ded Creating
Container mtusi2026lab4-reconcile-run-41147f965ded Created
Container mtusi2026lab4-reconcile-run-c9842622f73e Creating
Container mtusi2026lab4-reconcile-run-c9842622f73e Created
Container mtusi2026lab4-reconcile-run-557b0a13c872 Creating
Container mtusi2026lab4-reconcile-run-557b0a13c872 Created
Container mtusi2026lab4-s3-init-run-73474bd49386 Creating
Container mtusi2026lab4-s3-init-run-73474bd49386 Created
Container mtusi2026lab4-reconcile-run-c34b435de6ef Creating
Container mtusi2026lab4-reconcile-run-c34b435de6ef Created
Container mtusi2026lab4-s3-init-run-ee3a098fecf9 Creating
Container mtusi2026lab4-s3-init-run-ee3a098fecf9 Created
Container mtusi2026lab4-reconcile-run-5e20e2eda1ee Creating
Container mtusi2026lab4-reconcile-run-5e20e2eda1ee Created
PASS: S3-side missing object, dry-run, grace period and idempotent orphan repair
Container mtusi2026lab4-reconcile-run-cb994093df21 Creating
Container mtusi2026lab4-reconcile-run-cb994093df21 Created
Container mtusi2026lab4-api-a-1 Recreate
Container mtusi2026lab4-api-a-1 Recreated
Container mtusi2026lab4-api-a-1 Starting
Container mtusi2026lab4-api-a-1 Started
Container mtusi2026lab4-api-a-1 Running
Container mtusi2026lab4-api-a-1 Waiting
Container mtusi2026lab4-api-a-1 Healthy
Container mtusi2026lab4-reconcile-run-9f42ecfc5dfe Creating
Container mtusi2026lab4-reconcile-run-9f42ecfc5dfe Created
Container mtusi2026lab4-reconcile-run-9bb0b9b36ed0 Creating
Container mtusi2026lab4-reconcile-run-9bb0b9b36ed0 Created
PASS: injected pre-INSERT failure repaired; message and used original survive
Container mtusi2026lab4-api-a-1 Recreate
Container mtusi2026lab4-api-a-1 Recreated
Container mtusi2026lab4-api-a-1 Starting
Container mtusi2026lab4-api-a-1 Started
Container mtusi2026lab4-api-a-1 Waiting
Container mtusi2026lab4-api-a-1 Healthy
+1
View File
@@ -0,0 +1 @@
PASS: non-ASCII Bearer returns 401/challenge; malformed JSON returns contract Error/400
+40
View File
@@ -0,0 +1,40 @@
Container mtusi2026lab4-postgres-1 Running
Container mtusi2026lab4-api-a-1 Running
Container mtusi2026lab4-s3-1 Running
Container mtusi2026lab4-load_balancer-1 Running
Container mtusi2026lab4-s3-1 Waiting
Container mtusi2026lab4-postgres-1 Waiting
Container mtusi2026lab4-s3-1 Healthy
Container mtusi2026lab4-postgres-1 Healthy
Container mtusi2026lab4-s3-init-1 Starting
Container mtusi2026lab4-migrate-1 Starting
Container mtusi2026lab4-s3-init-1 Started
Container mtusi2026lab4-migrate-1 Started
Container mtusi2026lab4-s3-init-1 Waiting
Container mtusi2026lab4-migrate-1 Waiting
Container mtusi2026lab4-migrate-1 Waiting
Container mtusi2026lab4-s3-init-1 Waiting
Container mtusi2026lab4-s3-init-1 Exited
Container mtusi2026lab4-s3-init-1 Exited
Container mtusi2026lab4-migrate-1 Exited
Container mtusi2026lab4-migrate-1 Exited
Container mtusi2026lab4-api-b-1 Starting
Container mtusi2026lab4-api-b-1 Started
Container mtusi2026lab4-api-a-1 Waiting
Container mtusi2026lab4-api-b-1 Waiting
Container mtusi2026lab4-api-a-1 Healthy
Container mtusi2026lab4-api-b-1 Healthy
Container mtusi2026lab4-load_balancer-1 Waiting
Container mtusi2026lab4-migrate-1 Waiting
Container mtusi2026lab4-api-b-1 Waiting
Container mtusi2026lab4-s3-init-1 Waiting
Container mtusi2026lab4-postgres-1 Waiting
Container mtusi2026lab4-api-a-1 Waiting
Container mtusi2026lab4-s3-1 Waiting
Container mtusi2026lab4-s3-1 Healthy
Container mtusi2026lab4-load_balancer-1 Healthy
Container mtusi2026lab4-migrate-1 Exited
Container mtusi2026lab4-s3-init-1 Exited
Container mtusi2026lab4-postgres-1 Healthy
Container mtusi2026lab4-api-a-1 Healthy
Container mtusi2026lab4-api-b-1 Healthy
+201
View File
@@ -0,0 +1,201 @@
{
"recorded_at_utc": "2026-10-22T09:10:01.024409+00:00",
"checks": [
{
"name": "contracts",
"command": [
"make",
"check",
"validate",
"PYTHON=.venv/bin/python"
],
"exit_code": 0,
"seconds": 0.529
},
{
"name": "compose",
"command": [
"docker",
"compose",
"config",
"--quiet"
],
"exit_code": 0,
"seconds": 0.206
},
{
"name": "smoke",
"command": [
"make",
"test"
],
"exit_code": 0,
"seconds": 2.432
},
{
"name": "attachments",
"command": [
"make",
"test-attachments"
],
"exit_code": 0,
"seconds": 4.112
},
{
"name": "idempotency",
"command": [
"/Library/Frameworks/Python.framework/Versions/3.14/bin/python3",
"student-tests/idempotency_concurrency.py"
],
"exit_code": 0,
"seconds": 2.78
},
{
"name": "regressions",
"command": [
"/Library/Frameworks/Python.framework/Versions/3.14/bin/python3",
"student-tests/review_regressions.py"
],
"exit_code": 0,
"seconds": 0.071
},
{
"name": "private-bucket",
"command": [
"make",
"test-private"
],
"exit_code": 0,
"seconds": 2.478
},
{
"name": "s3-permissions",
"command": [
"make",
"test-s3-permissions"
],
"exit_code": 0,
"seconds": 3.223
},
{
"name": "bootstrap",
"command": [
"docker",
"compose",
"run",
"--rm",
"--no-deps",
"s3-init"
],
"exit_code": 0,
"seconds": 0.749
},
{
"name": "upload-failover",
"command": [
"make",
"test-upload-failover"
],
"exit_code": 0,
"seconds": 5.878
},
{
"name": "public-failover",
"command": [
"make",
"test-failover",
"ACTION_SCRIPT=scripts/stop-one.sh"
],
"exit_code": 0,
"seconds": 18.54
},
{
"name": "restore-replicas",
"command": [
"docker",
"compose",
"up",
"-d",
"--wait",
"api-a",
"api-b",
"load_balancer"
],
"exit_code": 0,
"seconds": 7.856
},
{
"name": "s3-outage",
"command": [
"make",
"test-s3-outage"
],
"exit_code": 0,
"seconds": 23.474
},
{
"name": "persistence",
"command": [
"/Library/Frameworks/Python.framework/Versions/3.14/bin/python3",
"scripts/verify-persistence.py"
],
"exit_code": 0,
"seconds": 28.621
},
{
"name": "reconcile",
"command": [
"make",
"test-reconcile"
],
"exit_code": 0,
"seconds": 61.524
},
{
"name": "reconcile-audit",
"command": [
"make",
"test-reconcile-audit"
],
"exit_code": 0,
"seconds": 9.908
},
{
"name": "upload-memory",
"command": [
"make",
"test-upload-memory"
],
"exit_code": 0,
"seconds": 10.33
},
{
"name": "reconcile-benchmark",
"command": [
"make",
"test-reconcile-benchmark"
],
"exit_code": 0,
"seconds": 30.609
},
{
"name": "final-smoke",
"command": [
"make",
"test"
],
"exit_code": 0,
"seconds": 2.676
},
{
"name": "environment",
"command": [
"/Library/Frameworks/Python.framework/Versions/3.14/bin/python3",
"scripts/record-environment.py"
],
"exit_code": 0,
"seconds": 1.082
}
],
"complete": true
}
+3
View File
@@ -0,0 +1,3 @@
python3 student-tests/attachment_resilience.py --mode s3-outage --base-url "http://localhost:8080"
PASS: S3 outage gives 503 for readiness, download and upload; liveness stays 200
PASS: original available and new upload accepted after S3 restart/bootstrap
+2
View File
@@ -0,0 +1,2 @@
python3 student-tests/s3_permissions.py --base-url "http://localhost:8080"
PASS: API identity cannot create buckets; maintenance identity has separate admin access
+2
View File
@@ -0,0 +1,2 @@
python3 tests/smoke.py --base-url "http://localhost:8080"
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
+2
View File
@@ -0,0 +1,2 @@
python3 student-tests/attachment_resilience.py --mode failover --base-url "http://localhost:8080"
PASS: uploaded via api-b; stopped that container; original downloaded through another replica
+2
View File
@@ -0,0 +1,2 @@
uv run python student-tests/upload_memory.py --base-url "http://localhost:8080"
{"uploads": 10, "file_bytes": 5242880, "concurrency": 10, "api_upload_concurrency_limit": 1, "elapsed_seconds": 7.319, "baseline_memory_bytes": {"55cc3bd6323e": 82366464, "1af56e498842": 77262848}, "peak_memory_bytes": {"55cc3bd6323e": 95637504, "1af56e498842": 95907840}, "peak_growth_bytes": {"55cc3bd6323e": 13271040, "1af56e498842": 18644992}, "samples": 29, "sample_intervals_seconds": [0.251, 0.231, 0.246, 0.249, 0.256, 0.252, 0.262, 0.251, 0.232, 0.248, 0.26, 0.248, 0.261, 0.254, 0.262, 0.254, 0.267, 0.248, 0.271, 0.241, 0.236, 0.269, 0.227, 0.256, 0.26, 0.265, 0.271, 0.252], "method": "cgroup memory.current via Docker; 0.1s pause AFTER each poll, actual intervals include Docker latency; ten clients start at a barrier and send chunked 512 KiB blocks every 0.5s. Peak is sampled, not continuous."}
+13 -11
View File
@@ -1,6 +1,6 @@
{
"recorded_at_utc": "2026-10-22T08:46:03.568305+00:00",
"base_commit": "901786170792195f6dd95d0939db98236eb932ff",
"recorded_at_utc": "2026-10-22T09:09:59.977765+00:00",
"base_commit": "483d7eecb38eb4addc99143ad718417dd00582f8",
"branch": "solution/BVT2301-Kozyrev",
"note": "Results apply to this working tree, not only the base commit. Functional tests; no load benchmark.",
"host": "macOS-26.1-arm64-arm-64bit-Mach-O",
@@ -12,7 +12,7 @@
"compose_version": "5.5.1",
"sources_sha256": {
"Dockerfile": "efede941e2ccf21cd1e70ebbf8af7647209bd030b2962f9446bee497a2ed6a8c",
"Makefile": "3255468d0a33aae6c111e99a51bc22008171a493d69b4a01aecabc49a0a99eb3",
"Makefile": "2d8be77ed5368450e46a2ef2d67161e245bfaf3a941fd729dbc36012f241bc71",
"compose.yaml": "b239915436be84c7b1000346669ae9a10c89e83c55555a5e9eac0e20828f6fb6",
"infra/README.md": "0e804fa51debba4c38d3cc84abf4704897665e0335b272060363f03aadd6354f",
"infra/filer.toml": "ae3c01bf7708f5d4a319fdb454f753be0f137fe7c31269f1c413cbccc860f5c7",
@@ -22,6 +22,7 @@
"migrations/003_idempotency.sql": "d650ea7c1379928a013e035977a77026d2b8b09ad5b2ea97eecb545e7450353a",
"migrations/004_attachments.sql": "d760453ba130c94c403f5b04222649fc131ab4d091edd0267ede901fdf82a79e",
"pyproject.toml": "d3962edc7a683a62c915c8edec91e85c647c8ae6fe6432603e30b595bd6c3804",
"scripts/audit.py": "5c695c70058b24e975ceca310b2bdc879858081e5ce82b444ea9eab6b9c0d2ed",
"scripts/check_contract.py": "7c4402c2a6ab80d3b4676e1866d6ecc87b6daea14c080bcb9be9a7e8b959d671",
"scripts/init-secrets.py": "01232befe48b69933b5c6b7e4f29cb19a777030ffab00accc7999afb6c082cef",
"scripts/record-environment.py": "716fa7b8edd05d7ab6781fc346338b2254f82186953c6dbf525785c723eee4a1",
@@ -32,7 +33,7 @@
"scripts/validate_openapi.py": "4e981acbfc10dac58817bf922d5896e996798551fedc1b2385130e1cddb13d54",
"scripts/verify-persistence.py": "6c366bf4d85802bcffe65ae3d45d00736b184033313dabb60b80e1270d8874f1",
"src/__init__.py": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b",
"src/attachments.py": "553936936318b8096b5a662ddd85dae4043dffb9b4fb6461e60bfc1962914325",
"src/attachments.py": "11cc27c6687b7e54321f1224f74fa0f9f4bab47eb5e2c68db28d2bc9e9659549",
"src/bootstrap_s3.py": "2c43f5540e63f004a88e08961a72293546fbc5210f46bc719b90b9f5c0f3f9bd",
"src/config.py": "62e214ceef5fcc24be11d23500de0fdaf6cf5efed1d913cdda0921fd34b088c3",
"src/cursor.py": "a9192f2445042b8d4ddac57031718ef558990a52eb2922827074479b7f686775",
@@ -40,22 +41,23 @@
"src/main.py": "6980cdbb09c3b356ff870ee7fc972d85e835c58228d3c0ea27de8a668dc41ece",
"src/migrate.py": "1d164c8921df2b5369e30b1f8936c2b71858c5279070f0fd593f62f66e1f0b7d",
"src/models.py": "b94e6b26559afc5fd90f58d34d906c77bf4b4a78c716ac552358795496ad1d1b",
"src/reconcile.py": "db7cc30de97f62a172024e1ffa94d75f8e6e91b4e80db8b491ce5c213e37aae7",
"src/reconcile.py": "83ecb6c83df77a9b5edc9f3e34d9cf54d39400076fec6bc00ee2648f6f393659",
"src/routes.py": "3c21149a30ea7c2f695547c42133dcebcfbacbd6544bcb73c353be46fa35a2e6",
"src/storage/__init__.py": "05ef66318c4c436eaafc493072640817219ab37bce464a265a2306233389064a",
"src/storage/postgres.py": "c69fea94937fdf00b077a8f1d301e83f35e120c3a7c5153fe205725be0aa0428",
"src/storage/postgres.py": "a1009fc646c570ff181c05a00771c95a40896e0afa034eb5d8cf4d66952ca1a0",
"src/storage/s3.py": "0779e6131c699055a1cff74e62addf207476819252e9a7aaf46c77af6d9044e6",
"student-tests/attachment_resilience.py": "c72c431b355dda919c1b6b854d260f8c7420672ca9f86bf0848692da35dcb0ac",
"student-tests/attachment_resilience.py": "8a4ad367263a5d5a597fcd4a2a657c80946d19a3bbedeebdfffbf75f45531e5d",
"student-tests/attachments.py": "a948fabfe83b73eb8e494c80fb9d1f2a949e2a95b7a21809a05975d65d68fc15",
"student-tests/idempotency_concurrency.py": "db5d139009e4660ac1801af45d10e24665aa81cba737731e527c0f5b4152231e",
"student-tests/readiness_failover.py": "0ef8355d85be66597d7d44eb7308dcb58c6c9a174d18f360b2d6d22fdcfbed14",
"student-tests/readiness_unavailable.py": "46e3f680a3ff9cb79e95568004d97f1752dbdcd88fd4b5f160a9cc38af65a237",
"student-tests/reconcile.py": "25547bd5d41ff7e6650a7f30f8404cbb9dd8e61e5ab97897e065d82296b6c73a",
"student-tests/reconcile.py": "9c82be28eb5a41b38c9ddd63dbf65d3edc238ca09ffa4612fc4b679d64487173",
"student-tests/reconcile_audit.py": "1bcca4da1030901e45c1369672c8363f9a5b08513c0270dc8a6f73b1f0b74221",
"student-tests/reconcile_benchmark.py": "9ae60097cb70e63baf5653559e727e02da246827a256e02580f03b5d47e1ca15",
"student-tests/review_regressions.py": "de58f63b2c794c2775247ddd3fccc523870ccbe673ffa404fdd566274d1d41de",
"student-tests/s3_permissions.py": "f265a64f900952db79d545e6c058a7605870c2843ed2298f5c68ad4a177663ff",
"student-tests/session_expiry.py": "ba8ead4356e4d12c4047ac2b5704d3d3342f71c37b3c13f65a0a9d7c37186ad6",
"student-tests/upload_memory.py": "a1493aaa8ce8e898291a14059826c1405d31a3577027ae926f8c80febf25d3dc",
"student-tests/upload_memory.py": "ed6c013b9e29a826191e1ca904e0546449f0e6ed9ecddbf5aa256d0768f64604",
"uv.lock": "fdbeb5ba0c5eedced1a6e5b62c6a57b2d22f293cf77b9487a806c6e1a8b992a0"
},
"services": {
@@ -83,7 +85,7 @@
},
"api-a": {
"image": "mtusi2026lab4-api-a",
"image_id": "sha256:c6f7a7d42d87e0edbd0b8880e6c4b5b5594dea953154af4ff50158c78db66233",
"image_id": "sha256:c658fea891d5262b78c3b417f6417737bd7dd2d204cd3b354bfbb652e0918707",
"state": "running",
"health": "healthy",
"memory_limit_bytes": 536870912,
@@ -92,7 +94,7 @@
},
"api-b": {
"image": "mtusi2026lab4-api-b",
"image_id": "sha256:466940ca873740202feb1ee727a2e0d0b2487ae8340df776639dd6f6381189fe",
"image_id": "sha256:5f72ab070787d35e2f911f49b33a43da0a0f8148cb3737e0a9285846e308523e",
"state": "running",
"health": "healthy",
"memory_limit_bytes": 536870912,
+39 -9
View File
@@ -3,19 +3,49 @@
"file_bytes": 5242880,
"concurrency": 10,
"api_upload_concurrency_limit": 1,
"elapsed_seconds": 5.529,
"elapsed_seconds": 7.319,
"baseline_memory_bytes": {
"7b09ecf19049": 84668416,
"1bcbfe033cad": 86630400
"55cc3bd6323e": 82366464,
"1af56e498842": 77262848
},
"peak_memory_bytes": {
"7b09ecf19049": 105254912,
"1bcbfe033cad": 101470208
"55cc3bd6323e": 95637504,
"1af56e498842": 95907840
},
"peak_growth_bytes": {
"7b09ecf19049": 20586496,
"1bcbfe033cad": 14839808
"55cc3bd6323e": 13271040,
"1af56e498842": 18644992
},
"samples": 22,
"method": "cgroup memory.current sampled through Docker every 0.1 seconds while clients send chunked 512 KiB blocks every 0.5 seconds; peak is not a continuous profiler."
"samples": 29,
"sample_intervals_seconds": [
0.251,
0.231,
0.246,
0.249,
0.256,
0.252,
0.262,
0.251,
0.232,
0.248,
0.26,
0.248,
0.261,
0.254,
0.262,
0.254,
0.267,
0.248,
0.271,
0.241,
0.236,
0.269,
0.227,
0.256,
0.26,
0.265,
0.271,
0.252
],
"method": "cgroup memory.current via Docker; 0.1s pause AFTER each poll, actual intervals include Docker latency; ten clients start at a barrier and send chunked 512 KiB blocks every 0.5s. Peak is sampled, not continuous."
}
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
"""Sequential lab3-5 verification; capture actual output and exit status, fail fast."""
from datetime import datetime, timezone
import argparse
import json
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
DESTINATION = ROOT / "evidence/audit"
CHECKS = [
("contracts", ["make", "check", "validate", "PYTHON=.venv/bin/python"]),
("compose", ["docker", "compose", "config", "--quiet"]),
("smoke", ["make", "test"]),
("attachments", ["make", "test-attachments"]),
("idempotency", [sys.executable, "student-tests/idempotency_concurrency.py"]),
("regressions", [sys.executable, "student-tests/review_regressions.py"]),
("private-bucket", ["make", "test-private"]),
("s3-permissions", ["make", "test-s3-permissions"]),
("bootstrap", ["docker", "compose", "run", "--rm", "--no-deps", "s3-init"]),
("upload-failover", ["make", "test-upload-failover"]),
("public-failover", ["make", "test-failover", "ACTION_SCRIPT=scripts/stop-one.sh"]),
("restore-replicas", ["docker", "compose", "up", "-d", "--wait", "api-a", "api-b", "load_balancer"]),
("s3-outage", ["make", "test-s3-outage"]),
("persistence", [sys.executable, "scripts/verify-persistence.py"]),
("reconcile", ["make", "test-reconcile"]),
("reconcile-audit", ["make", "test-reconcile-audit"]),
("upload-memory", ["make", "test-upload-memory"]),
("reconcile-benchmark", ["make", "test-reconcile-benchmark"]),
("final-smoke", ["make", "test"]),
("environment", [sys.executable, "scripts/record-environment.py"]),
]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--resume-from', choices=[name for name, _ in CHECKS])
args = parser.parse_args()
DESTINATION.mkdir(parents=True, exist_ok=True)
results = []
checks = CHECKS
if args.resume_from:
offset = [name for name, _ in CHECKS].index(args.resume_from)
previous = json.loads((DESTINATION / 'results.json').read_text())['checks']
results = previous[:offset]
if [item['name'] for item in results] != [name for name, _ in CHECKS[:offset]] or any(item['exit_code'] for item in results):
parser.error('resume requires successful evidence for every earlier step')
checks = CHECKS[offset:]
for name, command in checks:
print(f"RUN {name}", flush=True)
started = time.monotonic()
with (DESTINATION / f"{name}.txt").open("w") as stream:
result = subprocess.run(command, cwd=ROOT, stdout=stream, stderr=subprocess.STDOUT)
results.append({"name": name, "command": command, "exit_code": result.returncode,
"seconds": round(time.monotonic() - started, 3)})
(DESTINATION / "results.json").write_text(json.dumps({
"recorded_at_utc": datetime.now(timezone.utc).isoformat(),
"checks": results, "complete": len(results) == len(CHECKS),
}, indent=2) + "\n")
print(f"{'PASS' if result.returncode == 0 else 'FAIL'} {name}: exit={result.returncode}", flush=True)
if result.returncode:
print((DESTINATION / f"{name}.txt").read_text()[-8000:], flush=True)
return result.returncode
return 0
if __name__ == "__main__":
raise SystemExit(main())
+13 -9
View File
@@ -9,6 +9,7 @@ import warnings
from fastapi import APIRouter, Depends, Query, Request, Response
from PIL import Image, UnidentifiedImageError
from starlette.concurrency import run_in_threadpool
from starlette.requests import ClientDisconnect
from .errors import ApiError
from .models import Attachment
@@ -81,15 +82,18 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
await run_in_threadpool(inspect_image, file, content_type, s3.settings.max_pixels)
attachment_id = uuid4()
key = f"originals/{attachment_id}"
await s3.put(key, file, size, content_type)
# Disabled by default. Used only by the failure-injection test to
# model a process crash after S3 accepts the object and before DB.
if os.environ.get("UPLOAD_FAULT_AFTER_S3_PUT") == "1":
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
return await store.create_attachment(
attachment_id, chat_id, user["id"], filename, content_type,
size, digest.hexdigest(), key,
)
async with store.attachment_transaction() as connection:
await s3.put(key, file, size, content_type)
# Disabled by default; models a crash after PUT, before INSERT.
if os.environ.get("UPLOAD_FAULT_AFTER_S3_PUT") == "1":
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
attachment = await store.create_attachment(
attachment_id, chat_id, user["id"], filename, content_type,
size, digest.hexdigest(), key, connection=connection,
)
return attachment # Transaction has committed before 201.
except ClientDisconnect:
raise ApiError(400, "invalid_request", "Загрузка прервана") from None
except TimeoutError:
raise ApiError(503, "unavailable", "Время загрузки истекло") from None
+19 -5
View File
@@ -20,14 +20,23 @@ async def run(args) -> dict:
settings = load_settings()
db = PostgresStore(settings.database_url)
s3 = S3Store(S3Settings.load())
await db.connect()
try:
await db.connect()
async with db.attachment_transaction(maintenance=True):
return await scan(args, db, s3)
finally:
s3.client.close()
await db.close()
async def scan(args, db, s3) -> dict:
# Age is measured at scan start, not after a potentially slow inventory.
cutoff = datetime.now(timezone.utc) - timedelta(seconds=args.grace_seconds)
started = perf_counter()
objects, s3_pages = await s3.list_with_pages("originals/")
listed_at = perf_counter()
metadata = await db.attachment_keys()
metadata_at = perf_counter()
cutoff = datetime.now(timezone.utc) - timedelta(seconds=args.grace_seconds)
orphan = sorted(key for key, modified in objects.items()
if key not in metadata and modified <= cutoff)
fresh = sorted(key for key, modified in objects.items()
@@ -35,8 +44,11 @@ async def run(args) -> dict:
missing = sorted({str(attachment_id): key for key, attachment_id in metadata.items()
if key not in objects}.items())
deleted = []
selected = set(args.object_key) if args.object_key else None
if args.apply:
for key in orphan:
if selected is not None and key not in selected:
continue
await s3.delete(key)
deleted.append(key)
finished = perf_counter()
@@ -49,6 +61,7 @@ async def run(args) -> dict:
"fresh_unreferenced": fresh,
"missing_objects": [{"attachment_id": item[0], "object_key": item[1]} for item in missing],
"deleted": deleted,
"selected_keys": sorted(selected) if selected is not None else None,
"scan_metrics": {
"s3_list_pages": s3_pages,
"s3_list_seconds": round(listed_at - started, 6),
@@ -56,18 +69,19 @@ async def run(args) -> dict:
"total_seconds": round(finished - started, 6),
},
}
finally:
s3.client.close()
await db.close()
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--apply", action="store_true", help="delete only aged orphan objects")
parser.add_argument("--grace-seconds", type=int, default=3600)
parser.add_argument("--object-key", action="append", default=[],
help="restrict apply to these exact keys; repeatable, inventory stays complete")
args = parser.parse_args()
if not 0 <= args.grace_seconds <= 7 * 24 * 3600:
parser.error("--grace-seconds must be 0..604800")
if any(not key.startswith("originals/") for key in args.object_key):
parser.error("--object-key must start with originals/")
print(json.dumps(asyncio.run(run(args)), ensure_ascii=False, sort_keys=True))
+22 -4
View File
@@ -1,4 +1,5 @@
from datetime import datetime
from contextlib import asynccontextmanager
from hashlib import sha256
import json
from pathlib import Path
@@ -15,7 +16,7 @@ from ..errors import ApiError
ROOT = Path(__file__).resolve().parents[2]
MIGRATIONS = ROOT / "migrations"
PASSWORD_HASHER = PasswordHasher()
DB_ERRORS = (asyncpg.PostgresError, asyncpg.InterfaceError, OSError)
DB_ERRORS = (asyncpg.PostgresError, asyncpg.InterfaceError, OSError, TimeoutError)
class PostgresStore:
@@ -301,10 +302,27 @@ class PostgresStore:
return [self._message(row) for row in rows]
async def create_attachment(self, attachment_id, chat_id, owner_id, filename,
content_type, size_bytes, digest, object_key) -> dict:
@asynccontextmanager
async def attachment_transaction(self, *, maintenance=False):
"""Shared writer / exclusive reconciler lock across all API replicas.
Writers hold the transaction from before PUT through metadata COMMIT.
Maintenance holds the exclusive lock through inventory and deletion.
All attachment writers must participate in this protocol.
"""
try:
row = await self.pool.fetchrow(
async with self.pool.acquire() as connection, connection.transaction():
await connection.execute("SET LOCAL lock_timeout = '5s'")
lock = "pg_advisory_xact_lock" if maintenance else "pg_advisory_xact_lock_shared"
await connection.execute(f"SELECT {lock}(41004, 1)")
yield connection
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
async def create_attachment(self, attachment_id, chat_id, owner_id, filename,
content_type, size_bytes, digest, object_key, *, connection=None) -> dict:
try:
row = await (connection or self.pool).fetchrow(
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key) "
"VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *",
attachment_id, chat_id, owner_id, filename, content_type, size_bytes, digest, object_key,
+6 -1
View File
@@ -106,9 +106,14 @@ print("PASS: S3 outage gives 503 for readiness, download and upload; liveness st
input=json.dumps(payload)).strip())
finally:
compose('start', 's3')
# HeadBucket/read recovery alone does not prove the write path is ready.
# Use the same write-probing bootstrap as the documented restart hook.
compose('run', '--rm', '--no-deps', 's3-init')
wait_ready(c)
check(c.call('GET', content_path, actor=bob)['bytes'] == data, 'original lost after S3 outage')
print('PASS: original available again after S3 restart')
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=after-recovery.png',
201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
print('PASS: original available and new upload accepted after S3 restart/bootstrap')
if __name__ == '__main__':
+22 -13
View File
@@ -72,17 +72,18 @@ def main():
# A reference object must survive an apply sweep, even with zero grace.
protected = upload("protected.png")["json"]
message = client.message(alice, chat, "protected", attachments=[protected["id"]])["json"]
orphan = "originals/test-orphan-" + uuid.uuid4().hex
s3_code("put", orphan)
report = reconcile("--grace-seconds", "3600")
check(orphan in report["fresh_unreferenced"], "fresh orphan missing from dry-run")
check(not report["deleted"], "dry-run deleted an object")
report = reconcile("--apply", "--grace-seconds", "3600")
report = reconcile("--apply", "--grace-seconds", "3600", "--object-key", orphan)
check(orphan in report["fresh_unreferenced"] and not report["deleted"], "grace period ignored")
report = reconcile("--apply", "--grace-seconds", "0")
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", orphan)
check(report["deleted"] == [orphan], "aged orphan was not deleted safely")
report = reconcile("--apply", "--grace-seconds", "0")
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", orphan)
check(orphan not in report["deleted"] and orphan not in report["orphan_candidates"],
"second repair run was not idempotent")
check(client.call("GET", "/api/v1/attachments/" + protected["id"] + "/content", actor=bob)["bytes"] == image,
@@ -92,11 +93,14 @@ def main():
missing = upload("missing.png")["json"]
missing_key = "originals/" + missing["id"]
s3_code("delete", missing_key)
report = reconcile("--grace-seconds", "0")
expected = {"attachment_id": missing["id"], "object_key": missing_key}
check(expected in report["missing_objects"], "missing metadata/object pair not reported")
client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", 503, actor=bob)
s3_code("put", missing_key, image)
try:
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", missing_key)
expected = {"attachment_id": missing["id"], "object_key": missing_key}
check(expected in report["missing_objects"], "missing metadata/object pair not reported")
client.call("GET", "/api/v1/attachments/" + missing["id"], actor=bob, schema="Attachment")
client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", 503, actor=bob)
finally:
s3_code("put", missing_key, image)
check(client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", actor=bob)["bytes"] == image,
"test object was not restored")
report = reconcile("--grace-seconds", "0")
@@ -107,6 +111,7 @@ def main():
# replica. The public load balancer may correctly select the healthy peer,
# which would not exercise this boundary.
environment = dict(__import__("os").environ, UPLOAD_FAULT_AFTER_S3_PUT="1")
before_fault = set(reconcile("--grace-seconds", "0")["orphan_candidates"])
try:
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "--no-deps", "api-a"],
cwd=ROOT, env=environment, check=True, stdout=subprocess.DEVNULL)
@@ -128,14 +133,18 @@ else:
input=json.dumps({"chat_id": chat["id"], "token": alice["token"],
"image": base64.b64encode(image).decode()}))
report = reconcile("--grace-seconds", "0")
injected = [key for key in report["orphan_candidates"] if key.startswith("originals/")]
check(injected, "injected post-PUT failure did not create a detectable orphan")
report = reconcile("--apply", "--grace-seconds", "0")
injected = sorted(set(report["orphan_candidates"]) - before_fault)
check(len(injected) == 1, "fault must create exactly one new orphan; run without other writers")
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", injected[0])
check(set(injected).issubset(report["deleted"]), "reconciler did not clean injected orphan")
print("PASS: PostgreSQL-side post-PUT/pre-DB failure is repaired without deleting references", flush=True)
history = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob, schema="MessagePage")["json"]
check(message in history["items"], "message reference was lost")
check(client.call("GET", "/api/v1/attachments/" + protected["id"] + "/content", actor=bob)["bytes"] == image,
"used original was lost")
print("PASS: injected pre-INSERT failure repaired; message and used original survive", flush=True)
finally:
environment["UPLOAD_FAULT_AFTER_S3_PUT"] = "0"
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "--no-deps", "api-a"],
subprocess.run(["docker", "compose", "up", "-d", "--wait", "--force-recreate", "--no-deps", "api-a"],
cwd=ROOT, env=environment, check=True, stdout=subprocess.DEVNULL)
+159
View File
@@ -0,0 +1,159 @@
#!/usr/bin/env python3
"""Real database rejection, concurrent commit, interrupted upload and pagination."""
import base64
import json
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, run
PROBE = r'''
import asyncio, base64, hashlib, http.client, json, sys, urllib.request, urllib.error
from types import SimpleNamespace
from uuid import UUID, uuid4
from src.config import load_settings
from src.storage.postgres import PostgresStore
from src.storage.s3 import S3Store, S3Settings
from src.reconcile import run as reconcile, scan
payload = json.load(sys.stdin)
image = base64.b64decode(payload['image'])
chat_id, user_id = UUID(payload['chat_id']), UUID(payload['user_id'])
def upload(filename):
req = urllib.request.Request('http://api-a:8080/api/v1/chats/' + str(chat_id) +
'/attachments?filename=' + filename, data=image, method='POST',
headers={'Authorization': 'Bearer ' + payload['token'], 'Content-Type': 'image/png'})
try:
with urllib.request.urlopen(req, timeout=30) as response:
return response.status, json.load(response)
except urllib.error.HTTPError as error:
return error.code, json.load(error)
async def main():
db = PostgresStore(load_settings().database_url)
s3 = S3Store(S3Settings.load())
await db.connect()
def args(key):
return SimpleNamespace(apply=True, grace_seconds=0, object_key=[key])
try:
# A failed metadata inventory must not authorize any S3 deletion.
key = 'originals/audit-inventory-' + uuid4().hex
await s3.call('put_object', Bucket=s3.settings.bucket, Key=key, Body=image)
class BrokenInventory:
async def attachment_keys(self):
# Real SQL failure, not an empty inventory on error.
return await db.pool.fetch('SELECT * FROM audit_missing_table_' + uuid4().hex)
try:
async with db.attachment_transaction(maintenance=True):
try:
await scan(args(key), BrokenInventory(), s3)
except Exception:
pass
else:
raise AssertionError('failed inventory did not abort')
assert key in await s3.list('originals/')
finally:
await s3.delete(key)
print('PASS: failed PostgreSQL inventory aborts apply without deleting the orphan', flush=True)
# An actual PostgreSQL trigger rejects only this test chat's INSERT.
suffix = uuid4().hex
name = 'audit_reject_' + suffix
before = await s3.list('originals/')
await db.pool.execute(f"""CREATE FUNCTION {name}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN IF NEW.chat_id = '{chat_id}'::uuid THEN
RAISE EXCEPTION 'synthetic audit rejection' USING ERRCODE = '23514';
END IF; RETURN NEW; END $$""")
try:
await db.pool.execute(f'CREATE TRIGGER {name} BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION {name}()')
status, body = await asyncio.to_thread(upload, 'db-failure.png')
assert status == 503 and body['error']['code'] == 'unavailable', (status, body)
assert await db.pool.fetchval('SELECT count(*) FROM attachments WHERE chat_id=$1', chat_id) == 0
finally:
await db.pool.execute(f'DROP TRIGGER IF EXISTS {name} ON attachments')
await db.pool.execute(f'DROP FUNCTION {name}()')
created = set(await s3.list('originals/')) - set(before)
assert len(created) == 1, created
key = created.pop()
report = await reconcile(SimpleNamespace(apply=False, grace_seconds=0, object_key=[key]))
assert key in report['orphan_candidates'] and not report['deleted']
assert (await reconcile(args(key)))['deleted'] == [key]
assert not (await reconcile(args(key)))['deleted']
print('PASS: actual PostgreSQL INSERT rejection -> 503, dry-run detection, scoped repair, repeat no-op', flush=True)
# Writer holds a shared lock after PUT; cleanup must wait for COMMIT.
identifier = uuid4()
key = 'originals/' + str(identifier)
async with db.attachment_transaction() as connection:
await s3.call('put_object', Bucket=s3.settings.bucket, Key=key, Body=image)
sweep = asyncio.create_task(reconcile(args(key)))
for _ in range(40):
waiting = await db.pool.fetchval("SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND classid=41004 AND objid=1 AND NOT granted")
if waiting:
break
await asyncio.sleep(.05)
assert waiting and not sweep.done(), 'maintenance failed to wait for active writer'
await db.create_attachment(identifier, chat_id, user_id, 'concurrent.png', 'image/png',
len(image), hashlib.sha256(image).hexdigest(), key, connection=connection)
report = await sweep
assert key not in report['deleted'] and key not in report['orphan_candidates']
row = await db.attachment_for_member(identifier, user_id)
assert await s3.download(row) == image
print('PASS: apply with zero grace waits for in-flight PUT/COMMIT; committed original survives', flush=True)
# Abrupt client close before all bytes arrive must not persist a file.
before = await s3.list('originals/')
rows = await db.attachment_keys()
def interrupt():
conn = http.client.HTTPConnection('api-a', 8080, timeout=10)
conn.putrequest('POST', '/api/v1/chats/' + str(chat_id) + '/attachments?filename=interrupted.png')
conn.putheader('Authorization', 'Bearer ' + payload['token'])
conn.putheader('Content-Type', 'image/png')
conn.putheader('Content-Length', str(len(image) + 100000))
conn.endheaders()
conn.send(image[:32])
conn.close()
await asyncio.to_thread(interrupt)
await asyncio.sleep(1)
assert await db.attachment_keys() == rows
assert await s3.list('originals/') == before
status, body = await asyncio.to_thread(upload, 'after-disconnect.png')
assert status == 201, (status, body)
print('PASS: interrupted upload leaves no metadata/object and next upload succeeds', flush=True)
# Exercise pagination on real S3 without adding thousands of fixtures.
original_call = s3.call
async def small_pages(method, **kwargs):
if method == 'list_objects_v2':
kwargs['MaxKeys'] = 7
return await original_call(method, **kwargs)
expected = await s3.list('originals/')
s3.call = small_pages
actual, pages = await s3.list_with_pages('originals/')
assert actual == expected and pages > 1
print(f'PASS: S3 pagination: {len(actual)} keys across {pages} pages, no missing/duplicate keys', flush=True)
finally:
s3.client.close()
await db.close()
asyncio.run(main())
'''
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file, timeout=30)
alice, _, _, chat = client.bootstrap()
payload = {"chat_id": chat["id"], "user_id": alice["id"], "token": alice["token"],
"image": base64.b64encode((ROOT / "tests/fixtures/sample.png").read_bytes()).decode()}
subprocess.run(["docker", "compose", "--profile", "maintenance", "run", "--rm", "--no-deps",
"--entrypoint", "/app/.venv/bin/python", "reconcile", "-c", PROBE],
cwd=ROOT, input=json.dumps(payload), text=True, check=True)
if __name__ == "__main__":
run(main)
+16 -2
View File
@@ -34,16 +34,27 @@ def main():
seed = (ROOT / "tests/fixtures/sample.png").read_bytes()
payload = seed + b"\0" * (args.size_mib * 1024 * 1024 - len(seed))
baseline, peak, samples, stop = api_memory(), {}, [], threading.Event()
check(len(baseline) == 2, "memory experiment requires two running APIs")
sampling_errors = []
timestamps = []
barrier = threading.Barrier(10)
def sampler():
while not stop.is_set():
values = api_memory()
try:
values = api_memory()
check(set(values) == set(baseline), "API containers changed during measurement")
except Exception as error:
sampling_errors.append(type(error).__name__)
return
timestamps.append(time.monotonic())
samples.append(values)
for name, value in values.items():
peak[name] = max(peak.get(name, 0), value)
time.sleep(.1)
def upload(index):
barrier.wait(timeout=15)
parsed = urlsplit(client.base)
connection = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=60)
@@ -73,13 +84,16 @@ def main():
thread.join(timeout=5)
elapsed = time.monotonic() - started
check(len({item["id"] for item in attachments}) == 10, "uploads were not distinct")
check(not sampling_errors and len(samples) >= 2 and not thread.is_alive(),
"memory sampler failed or did not collect enough samples: " + repr(sampling_errors))
report = {
"uploads": 10, "file_bytes": len(payload), "concurrency": 10,
"api_upload_concurrency_limit": 1, "elapsed_seconds": round(elapsed, 3),
"baseline_memory_bytes": baseline, "peak_memory_bytes": peak,
"peak_growth_bytes": {name: peak.get(name, 0) - baseline.get(name, 0) for name in baseline},
"samples": len(samples),
"method": "cgroup memory.current sampled through Docker every 0.1 seconds while clients send chunked 512 KiB blocks every 0.5 seconds; peak is not a continuous profiler.",
"sample_intervals_seconds": [round(b-a, 3) for a, b in zip(timestamps, timestamps[1:])],
"method": "cgroup memory.current via Docker; 0.1s pause AFTER each poll, actual intervals include Docker latency; ten clients start at a barrier and send chunked 512 KiB blocks every 0.5s. Peak is sampled, not continuous.",
}
destination = ROOT / args.output
destination.parent.mkdir(parents=True, exist_ok=True)