From 508340638dc2be3a142b485a50bedd8af25df763 Mon Sep 17 00:00:00 2001 From: Alina Dykhanova Date: Thu, 22 Oct 2026 17:00:08 +0300 Subject: [PATCH 1/2] =?UTF-8?q?=D0=B2=D1=8B=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=BD=D0=B0=D1=8F=20=D0=BB=D0=B0=D0=B12?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 7 +- .github/pull_request_template.md | 30 +- Dockerfile | 10 + Makefile | 12 + REPORT.md | 182 +++- app/main.py | 192 ++++ app/migrate.py | 18 + compose.yaml | 62 ++ docs/schema.md | 38 + evidence/build.txt | 74 ++ evidence/check.txt | 2 + evidence/contract-extra.txt | 1 + evidence/environment.json | 10 + evidence/experiments.json | 77 ++ evidence/integration.txt | 1 + evidence/load-1.json | 17 + evidence/load-2.json | 17 + evidence/load-3.json | 17 + evidence/load-resources.json | 906 ++++++++++++++++++ evidence/load-summary.txt | 1 + evidence/migrations.txt | 2 + evidence/persistence.txt | 3 + evidence/research.json | 1538 ++++++++++++++++++++++++++++++ evidence/restart-after.json | 30 + evidence/restart-before.json | 30 + evidence/restore-storage.json | 24 + evidence/smoke.txt | 2 + evidence/source-manifest.json | 18 + evidence/validation.txt | 2 + migrations/001_initial.sql | 12 + requirements.lock | 18 + requirements.txt | 5 + scripts/bootstrap.py | 12 + scripts/container_state.py | 4 + scripts/contract_extra.py | 20 + scripts/experiments.py | 122 +++ scripts/load_experiments.py | 12 + scripts/research.py | 45 + scripts/restart.sh | 7 + 39 files changed, 3547 insertions(+), 33 deletions(-) create mode 100644 Dockerfile create mode 100644 app/main.py create mode 100644 app/migrate.py create mode 100644 compose.yaml create mode 100644 docs/schema.md create mode 100644 evidence/build.txt create mode 100644 evidence/check.txt create mode 100644 evidence/contract-extra.txt create mode 100644 evidence/environment.json create mode 100644 evidence/experiments.json create mode 100644 evidence/integration.txt create mode 100644 evidence/load-1.json create mode 100644 evidence/load-2.json create mode 100644 evidence/load-3.json create mode 100644 evidence/load-resources.json create mode 100644 evidence/load-summary.txt create mode 100644 evidence/migrations.txt create mode 100644 evidence/persistence.txt create mode 100644 evidence/research.json create mode 100644 evidence/restart-after.json create mode 100644 evidence/restart-before.json create mode 100644 evidence/restore-storage.json create mode 100644 evidence/smoke.txt create mode 100644 evidence/source-manifest.json create mode 100644 evidence/validation.txt create mode 100644 migrations/001_initial.sql create mode 100644 requirements.lock create mode 100644 requirements.txt create mode 100644 scripts/bootstrap.py create mode 100644 scripts/container_state.py create mode 100644 scripts/contract_extra.py create mode 100644 scripts/experiments.py create mode 100644 scripts/load_experiments.py create mode 100644 scripts/research.py create mode 100755 scripts/restart.sh diff --git a/.env.example b/.env.example index 714c8076..fcd6b337 100644 --- a/.env.example +++ b/.env.example @@ -1,11 +1,10 @@ -# Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. +# python3 scripts/bootstrap.py creates .env and local secret files. +# Compose exposes the API only on 127.0.0.1:8080; Gunicorn binds 0.0.0.0:8080 inside. 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: +# PostgreSQL is the session source of truth; Redis caches immutable public users. SESSION_STORE=postgres CACHE_URL_FILE=/run/secrets/cache_url diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 8ceefa10..342be21c 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,18 +1,20 @@ ## Лабораторная 2 -Автор / группа: TODO -Целевая оценка (3/4/5): TODO -Трек 5, если заявлен: TODO +Автор: Алина Дыханова. Группа: вписать перед сдачей (в исходных данных не указана). +Целевая оценка: 5. Трек 2 — план запроса и восстановление. -Что реализовано и что перенесено: TODO -Команды запуска из чистого clone: TODO -Результаты проверок и ссылка на REPORT.md: TODO -Ограничения / известные ошибки: TODO -Источники и использование ИИ: TODO +Реализован REST-мессенджер на Flask/PostgreSQL, безопасная аутентификация Basic → opaque Bearer, Argon2id, постоянные сессии, keyset-пагинация и кэш публичного профиля в Redis. Миграции и Compose обеспечивают запуск с нуля. Реализован функциональный минимум lab1 с переходами lab2; исходного личного приложения lab1 в skeleton нет. -- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. -- [ ] Контракт и публичные тесты не ослаблены. -- [ ] make check и make test выполнены; приложен реальный вывод. -- [ ] Сценарии отказов/безопасности своего уровня воспроизведены. -- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. -- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. +Запуск: `python3 scripts/bootstrap.py`, затем `docker compose up -d --build --wait`. +Проверки: `make check`, `make test`, `make test-persistence ACTION_SCRIPT=scripts/restart.sh`, `python3 scripts/experiments.py`, `python3 scripts/load_experiments.py`. Полная схема: `make validate PYTHON=.venv/bin/python` после установки requirements-dev.txt. + +Результаты, сырые данные и ограничения: [REPORT.md](../REPORT.md), каталог evidence. Исследованы 120000 сообщений с перекосом чатов, два индекса и два запроса, стоимость INSERT; backup восстановлен в новую БД и сверен по count/checksum/выбранным записям. Сравнение выполнено на одном хосте, тёплых буферах; нет HA, PITR и внешнего backup. + +Источники перечислены в отчёте. Codex использован для реализации, экспериментов и оформления. + +- [x] Обязательный минимум сохранён с объявленными переходами. +- [x] Контракт и публичные тесты не ослаблены. +- [x] make check и make test выполнены; реальный вывод приложен. +- [x] Сохранность и собственные сценарии уровня 4/5 воспроизведены. +- [x] Секреты вне Git; отчёт и summaries не содержат bearer tokens. +- [x] README задания сохранён, REPORT.md описывает это решение. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..ce5c0bed --- /dev/null +++ b/Dockerfile @@ -0,0 +1,10 @@ +FROM python:3.12.12-slim +WORKDIR /srv +COPY requirements.lock . +RUN pip install --no-cache-dir --timeout 120 --retries 5 -r requirements.lock +COPY app app +COPY migrations migrations +RUN useradd --uid 10001 --create-home api +USER api +EXPOSE 8080 +CMD ["sh", "-c", "python -m app.migrate && exec gunicorn --bind 0.0.0.0:8080 --workers 2 --threads 4 --timeout 15 app.main:app"] diff --git a/Makefile b/Makefile index 9ecb223e..b6ac756c 100644 --- a/Makefile +++ b/Makefile @@ -24,3 +24,15 @@ load: test-persistence: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +.PHONY: bootstrap up down test-integration research-load +bootstrap: + $(PYTHON) scripts/bootstrap.py +up: bootstrap + docker compose up -d --build --wait +down: + docker compose --profile research down +test-integration: + $(PYTHON) scripts/experiments.py +research-load: + $(PYTHON) scripts/load_experiments.py diff --git a/REPORT.md b/REPORT.md index e42f2b05..42652050 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,189 @@ # Отчёт — лабораторная 2 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор: Алина Дыханова БВТ2301 +- Целевая оценка: **5**. Трек 2: **план запроса и восстановление**. Выполнены также критерии уровней 3 и 4. +- Основа: skeleton commit `65003b6`. Реализация находится в рабочем дереве; commit/PR с решением пока не опубликован. +- Библиотеки: Python 3.12.12, Flask 3.1.2, Gunicorn 23.0.0, psycopg 3.2.10, psycopg-pool 3.3.3, Redis client 6.4.0, argon2-cffi 25.1.0. Полный lock — [requirements.lock](requirements.lock). ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Docker Desktop/Engine с Compose v2+ и Python 3.9+ на хосте. Порт 127.0.0.1:8080 должен быть свободен. Образы: `python:3.12.12-slim`, `postgres:16.10-alpine`, `redis:7.4.6-alpine`; Python-зависимости закреплены в lock. Первый build требует доступа к registry/PyPI. + +```sh +python3 scripts/bootstrap.py +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build --wait +make check +make test +make test-persistence ACTION_SCRIPT=scripts/restart.sh +python3 scripts/experiments.py +python3 scripts/load_experiments.py +python3 scripts/contract_extra.py +``` + +Bootstrap идемпотентно создаёт локальные `secrets/` с правами 0700, файлы 0600 и `.env`. Пароль генерируется криптографически, не выводится в терминал и не включается в Git. Уже существующие secrets не перезаписываются. Миграции автоматически выполняются перед Gunicorn; повторно: + +```sh +docker compose exec -T api python -m app.migrate +``` + +`--wait` ожидает healthcheck. Проверить вручную: `curl -f http://localhost:8080/health/ready`. Изолированное имя проекта — `mtusi_lab2_solution`; создаются volumes `mtusi_lab2_solution_pgdata` и `mtusi_lab2_solution_redisdata`. Нельзя менять пароль файла после инициализации volume без согласованного изменения роли PostgreSQL. + +Полная проверка схемы: + +```sh +python3 -m venv .venv +.venv/bin/pip install -r requirements-dev.txt +make validate PYTHON=.venv/bin/python +``` + +Безопасная остановка: `docker compose --profile research down` — данные в именованных volumes остаются. **Намеренное удаление учебных данных:** `docker compose --profile research down --volumes`. Эта команда не входит в тесты перезапуска. Дамп исследования хранится внутри контейнера PostgreSQL в `/tmp/research.dump`; сценарий также сохраняет локальную копию `backups/research.dump` вне Git. Отдельная ручная команда копирования, например `docker compose cp postgres:/tmp/research.dump /tmp/lab2-research.dump`. + +Оператор запускает сценарии последовательно: интеграционные проверки временно останавливают зависимости и пересоздают API с TTL=2, затем восстанавливают TTL=3600. Исследование пересоздаёт только выделенную базу `research` в основном PostgreSQL и схему `research_restored` в отдельном сервисе `postgres_restore`; оно не удаляет таблицы рабочей базы `messenger`. Не направлять сценарии на чужой/боевой PostgreSQL. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +```text +Клиент → 127.0.0.1:8080 → Gunicorn (2 workers × 4 threads) → PostgreSQL + ↘ Redis (кэш User) +``` + +PostgreSQL — источник истины для пользователей, чатов, участников, сообщений и сессий. Redis хранит только публичные неизменяемые профили по `user:` на 60 секунд. Попадание в кэш экономит SELECT профиля, но не проверку сессии. На каждый защищённый запрос действительность сессии проверяется в PostgreSQL. Redis не критичен для readiness: ошибка кэша приводит к чтению профиля из БД; PostgreSQL критичен. + +Подробный проект таблиц, ограничений, индексов и транзакционных границ — [docs/schema.md](docs/schema.md), реализация — [migrations/001_initial.sql](migrations/001_initial.sql). Есть PK/FK, UNIQUE username, CHECK обязательных строк и длин. Создание чата и всех участников — одна транзакция. Advisory lock сериализует миграции, журнал версий предотвращает повторное применение. SQL использует параметры, pool ограничен 8 соединениями на worker (16 на API); ожидание pool/connect — 3 s, statement — 3 s, lock — 2 s. + +Минимум lab1 реализован заново в этом skeleton: регистрация, текущий пользователь, создание/чтение/список чатов, отправка и история сообщений, проверка членства и health. Исходников личной lab1 в репозитории не было. Объявленный переход lab2: password при регистрации, Basic только на создание сессии, Bearer для бизнес-запросов. X-User-Id не даёт доступ и не заменяет владельца токена. Вложения и Idempotency-Key относятся к следующим лабораторным и для lab2 не добавлялись. + +Пароль: библиотечный Argon2id, m=19456 KiB, t=2, p=1, случайная соль библиотеки; UTF-8 не усекается. Неизвестный username также проходит проверку dummy hash. Opaque токен создаётся из 32 случайных байт (256 бит). В БД сохраняется только SHA-256 токена, пользователь и абсолютный expires_at. SHA-256 здесь применяется к случайному токену, а не к паролю. TTL не продлевается чтениями или перезапуском. Logout удаляет строку сессии. Истёкшие строки недействительны даже без физического удаления. + +История не кэшируется. После COMMIT следующий SELECT из primary видит сообщение; поэтому Redis не может нарушить read-after-write. Неизменяемые профили не требуют инвалидации; при появлении редактирования нужно удаление/версионирование ключей. После FLUSHDB кэш наполняется из PostgreSQL. Redis имеет AOF everysec и volume, но потеря до секунды его содержимого не теряет сессии или сообщения. + +Курсор — непрозрачная base64url-строка с ресурсом и парой `(created_at,id)`. Чужой ресурс отвергается. Запрос использует `WHERE chat_id = ... AND (created_at,id) > (...) ORDER BY created_at,id LIMIT ...`, без OFFSET. Следующая страница определяется выборкой limit+1. Для неизменной истории нет повторов/пропусков. Между запросами общего snapshot нет: задержанный COMMIT или коррекция часов могут поместить конкурентную запись до уже пройденного курсора. + +| Переменная .env.example | Реальная конфигурация | +| --- | --- | +| SESSION_TTL_SECONDS | Compose передаёт API; по умолчанию 3600, тест expiry — 2 | +| DATABASE_URL_FILE | API читает DSN из `/run/secrets/database_url` | +| CACHE_URL_FILE | API читает URL Redis из `/run/secrets/cache_url` | +| SESSION_STORE=postgres | Декларация выбранной архитектуры; переключение на иное хранилище не поддерживается | +| APP_HOST, APP_PORT | Документируют фиксированную привязку Gunicorn 0.0.0.0:8080 внутри контейнера; не являются переключателями | +| APP_ENV=lab | Документирует учебный профиль; логика приложения от него не зависит | ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Публичный smoke, минимум lab1 и переход lab2 | `make test` | PASS; Unicode, доступ, Bearer, logout, страницы | [smoke.txt](evidence/smoke.txt) | +| Неослабленный контракт/структура | `make check`; `make validate PYTHON=.venv/bin/python` | Обе проверки PASS | [check.txt](evidence/check.txt), [validation.txt](evidence/validation.txt) | +| PostgreSQL, PK/FK, UNIQUE, миграции с нуля | `docker compose up -d --build --wait` | Чистые отдельные volumes; API готов после миграций | [build.txt](evidence/build.txt), [001_initial.sql](migrations/001_initial.sql) | +| Повтор миграций | Два `docker compose exec -T api python -m app.migrate` | Ошибок нет; версия 001_initial.sql ровно одна | [migrations.txt](evidence/migrations.txt) | +| Атомарность создания чата | `python3 scripts/experiments.py`, rollback | Тестовый trigger отклоняет INSERT участника после INSERT чата; чат отсутствует после отката | [experiments.json](evidence/experiments.json) | +| Регистрация в гонке | Тот же сценарий, 8 потоков | 1×201, 7×409 | [experiments.json](evidence/experiments.json) | +| KDF, entropy, срок и отзыв сессии | Smoke + expiry, код регистрации/логина | Неверный пароль, Basic на бизнес-API, X-User-Id и отозванный токен дают 401 | [smoke.txt](evidence/smoke.txt), [main.py](app/main.py) | +| UTF-8 пароль 128 code points, двоеточие; malformed JSON и большой limit | `python3 scripts/contract_extra.py` | Логин 201, неверные запросы 400 | [contract-extra.txt](evidence/contract-extra.txt) | +| Короткий TTL | Временный API с SESSION_TTL_SECONDS=2 | После ожидания 2.2 s — 401; обычный TTL восстановлен | [experiments.json](evidence/experiments.json) | +| Сохранность данных и прежнего токена | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS после restart API, PostgreSQL и Redis | [persistence.txt](evidence/persistence.txt) | +| Реальный полный restart, volumes сохранены | Hook снимает docker inspect до/после | StartedAt изменился у всех трёх; ID контейнеров и имена volumes сохранены | [restart-before.json](evidence/restart-before.json), [restart-after.json](evidence/restart-after.json) | +| Redis реально используется, TTL/инвалидация | Прогрев /users/me, INFO stats, stop/start/FLUSHDB | Cache hits +1; при отказе запрос успешен; после очистки профиль восстановлен | [experiments.json](evidence/experiments.json) | +| Безопасный SQL, pool и таймауты | Проверка конфигурации и отказа БД | Параметризованные запросы; ограниченные pool/connect/statement/lock | [main.py](app/main.py), [schema.md](docs/schema.md) | +| Индекс истории, EXPLAIN ≥10000 сообщений | Тот же интеграционный сценарий | 120000 сообщений; составной индекс, keyset, нет полного обхода истории на страницу | [research.json](evidence/research.json) | +| Отказы Redis и БД, anonymous fail closed | stop/start соответствующего сервиса | Redis: 200 с fallback; БД: ready/защищённый путь 503; анонимный 401 | [experiments.json](evidence/experiments.json) | +| Строгий JSON, чужой курсор, read-after-write | Собственные интеграционные проверки | Лишнее поле/тип/пустая строка и чужой курсор — 400; запись видна участнику | [experiments.json](evidence/experiments.json) | +| Трек 2: ≥100000, перекос, ≥2 индекса/запроса, стоимость записи | `python3 scripts/experiments.py` → research.py | 3 размера чатов, 2 индекса × 2 способа чтения; 5 повторов, INSERT 5000 | [research.json](evidence/research.json) | +| Трек 2: backup → новое хранилище → сверка | pg_dump -Fc; pg_restore в research_restored | 120000 строк, общая контрольная сумма и 5 выбранных сообщений совпали | [experiments.json](evidence/experiments.json) | +| Secrets и volumes вне Git | .gitignore и .dockerignore; локальный bootstrap | В Git подготовлены только исходники и очищенные summaries | [.gitignore](.gitignore), [.dockerignore](.dockerignore) | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +### Среда и методика + +Хост: Apple M4, macOS-27.0.1-arm64-arm-64bit-Mach-O; Docker Engine 29.8.0, aarch64. Docker VM: 10 CPU, 7.75 GiB RAM, Docker Desktop. Compose 5.5.1. Дополнительные per-container CPU/RAM лимиты не установлены; сервисы делят ресурсы VM и хоста. На хосте могли работать другие приложения/старые учебные контейнеры. Поэтому это воспроизводимая локальная демонстрация, а не предел производительности сервера. Точные сведения — [environment.json](evidence/environment.json). + +### Трек 2: гипотеза и план запроса + +**Гипотеза:** индекс только по chat_id оставляет фильтрацию/сортировку глубокой страницы; составной B-tree `(chat_id,created_at,id)` с keyset позволяет сразу перейти к границе. OFFSET даже с составным индексом обходит предшествующие записи. Составной индекс занимает больше места и может удорожать запись. + +Скрипт `scripts/research.py` создаёт в отдельной БД **ту же миграционную схему**, что и API (UUID, FK, CHECK). Генерируются 120000 синтетических сообщений по 100 ASCII-символов: 100000 / 15000 / 5000 в трёх чатах. ID детерминированы для сравнения, времена разнесены на 1 ms; это синтетическая упорядоченная история. Каждая выборка возвращает до 50 полных Message. Позиции: 90000, 10000 и 4000 внутри соответствующих чатов. + +Сравниваются индекс `chat_only` и `composite`; для каждого — keyset и OFFSET. После ANALYZE выполняются два прогревочных чтения и пять `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)`. Concurrency=1; запросы подаются последовательно, arrival rate определяется временем выполнения. Ниже медиана Execution Time, ms; JSON содержит все пять времён и полный последний план каждой комбинации. Это время PostgreSQL с инструментированием, без HTTP/сети. + +| Чат / число сообщений | chat_only + keyset | composite + keyset | chat_only + OFFSET | composite + OFFSET | +| --- | --- | --- | --- | --- | +| 1 / 100,000 | 4.400 | 0.016 | 27.952 | 6.906 | +| 2 / 15,000 | 0.964 | 0.019 | 3.986 | 4.173 | +| 3 / 5,000 | 0.292 | 0.015 | 0.883 | 0.952 | + +Для большого чата keyset ускорился примерно в 275.0 раза. На последнем прогоне число Shared Hit Blocks уменьшилось с 2806 до 5. План составного keyset: Limit → Index Scan с диапазоном по составному ключу. Планы baseline и OFFSET показывают дополнительную обработку строк. Проверяемая причина улучшения — количество просмотренных строк/буферов, а не только малое абсолютное время. + +### Стоимость записи + +Для каждого индекса выполнено пять INSERT по 5000 строк с сохранёнными FK/PK. Измеряется время выполнения INSERT клиентом внутри транзакции, **без времени COMMIT**. Затем тестовые строки удаляются в той же транзакции. Пакеты выполняются последовательно, concurrency=1, отдельного прогрева записи нет. Показаны медианы: + +| Индекс | Размер индекса до INSERT, bytes | INSERT 5000, ms | +| --- | --- | --- | +| chat_only | 860160 | 68.960 | +| composite | 7094272 | 73.526 | + +Оба варианта сохраняют PK и проверки FK. Это не WAL-байты, не latency отдельного COMMIT и не изолированная стоимость обслуживания индекса. Порядок вариантов фиксирован, повторные INSERT/DELETE оставляют dead tuples; cold-cache, рандомизация порядка и доверительные интервалы не исследовались. Поэтому большой выигрыш чтения подтверждён планом, а небольшая разница записи не доказывает устойчивую регрессию. Размер составного индекса показывает реальный расход памяти/диска. + +### Backup и восстановление + +После исследования остаются ровно 120000 сообщений. Состояния двух контейнеров и разные имена volumes зафиксированы в [restore-storage.json](evidence/restore-storage.json). `pg_dump -Fc research` создаёт custom-format backup; `pg_restore --exit-on-error` восстанавливает его в **БД research_restored другого контейнера postgres_restore с отдельным volume restoredata**, не поверх источника. Сервис запускается через профиль research. Это новый экземпляр PostgreSQL и отдельный volume; перенос на другой физический host/диск не проверялся. + +Backup занял 0.271 s, restore — 0.395 s (включая запуск команды через Compose, без запуска нового контейнера и последующей сверки). Перенос dump через хост занял 0.156 s. Восстановились схема, индексы и строки; число строк сверено также для users/chats/members/sessions. Количество и контрольная сумма отсортированного содержимого: + +```text +source: 120000|8875a7ede51a3769bf6725a3d57afda0 +restored: 120000|8875a7ede51a3769bf6725a3d57afda0 +``` + +Дополнительно побайтно сравнены поля пяти выбранных сообщений с исходными номерами 1, 50000, 100000, 110000, 120000. MD5 здесь — удобная проверка случайного расхождения учебных данных; это не криптографическая защита backup. Выбранные записи сохранены в research.json. + +Дамп соответствует согласованному snapshot; все изменения после его начала могут отсутствовать при восстановлении. В эксперименте конкурентных записей во время backup не было, потеря строк — 0. Без WAL-архива и PITR RPO определяется возрастом последнего backup, а не обещанием нулевой потери. Измеренные 0.395 s — время маленького локального restore, не production RTO: оно не включает поиск/передачу копии, создание сервера, secrets, DNS и переключение клиентов. + +### HTTP-нагрузка + +`python3 scripts/load_experiments.py`: три независимых прогона `tests/load.py`, каждый по 10 s, 4 клиента, closed-loop POST сообщений, без retries, без искусственной паузы между запросами. Каждый прогон создаёт отдельный чат; размер истории растёт. Инициализация пользователей вне измеряемого цикла; отдельного HTTP-прогрева нет. Arrival rate не фиксирован. RPS — число успешных HTTP-подтверждений / elapsed, квантили только успешных ответов. + +| Повтор | Успешные запросы | RPS | Ошибки | p50, ms | p95, ms | p99, ms | +| --- | --- | --- | --- | --- | --- | --- | +| 1 | 13898 | 1381.482 | 0 | 2.509 | 4.806 | 8.953 | +| 2 | 15141 | 1504.304 | 0 | 2.377 | 4.288 | 6.102 | +| 3 | 15682 | 1558.333 | 0 | 2.296 | 4.081 | 6.06 | + +Сырые summaries без токенов: [load-1.json](evidence/load-1.json), [load-2.json](evidence/load-2.json), [load-3.json](evidence/load-3.json). CPU/RAM снимались `docker compose stats --no-stream` во время нагрузки; ниже максимум наблюдаемого CPU и RAM в том же снимке, а не гарантированный непрерывный пик: + +| Сервис | Максимум CPU из samples | RAM в этом sample / лимит VM | +| --- | --- | --- | +| api | 119.79% | 116.4MiB / 7.748GiB | +| postgres | 48.81% | 41.66MiB / 7.748GiB | +| redis | 1.97% | 10.14MiB / 7.748GiB | + +Все samples — [load-resources.json](evidence/load-resources.json). Генератор ограничен клиентом и имеет coordinated omission; результаты не устанавливают максимальную ёмкость, не моделируют open-loop arrival и не заменяют длительный soak-test. CPU может превышать 100% при использовании нескольких ядер. Измерения SQL и HTTP сделаны раздельно, нагрузка HTTP не сравнивает варианты индекса. + +### Матрица отказов | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| restart API + PostgreSQL + Redis, volumes сохранены | Старый токен и данные работают | Публичный persistence PASS; StartedAt всех трёх изменился | После readiness данные доступны; подтверждённые тестовые данные не потеряны; точное RTO hook отдельно не измерялось | +| Недоступен Redis | Fallback в БД, анонимный не доверяется | /users/me 200; POST сообщения 201; anonymous 401 | Fallback-запрос 16.47 ms; после start + FLUSHDB повторное наполнение; потеря обязательных данных 0 | +| Недоступен PostgreSQL | live 200, ready/бизнес-путь 503 | Ожидаемые статусы, anonymous 401 | Проверки заняли 0.009 s на уже оборванных соединениях; готовность после start за 0.561 s; прежняя сессия работает | +| TTL=2, ожидание 2.2 s | Истёкший токен отвергается | 401 | Ожидаемое истечение; API возвращён к TTL=3600 | +| Logout | Отзыв немедленно действует | Повторный /me и logout — 401 | Сессия удалена транзакционно | +| Ошибка INSERT участника | Откат всего нового чата | Ответ 503, в БД 0 чатов с тестовым title | После удаления тестового trigger работа продолжается | +| 8 одновременных регистраций | Ровно один username | 1×201, 7×409 | Дубликатов нет | +| Backup → отдельная БД | Схема и данные совпадают | 120000 строк, checksum и 5 сообщений совпали | Restore 0.395 s; в статическом наборе потерь 0 | ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Подтверждены полный управляемый restart с volumes, безопасный отказ кэша, fail-closed БД, expiry/logout, гонка уникальности, rollback и восстановление из логической копии. Управляемый restart не моделирует потерю питания, повреждение диска, partition или failover primary. PostgreSQL использует штатные fsync/synchronous_commit/full_page_writes; COMMIT подтверждает запись WAL в рамках гарантий локального диска/VM, а не репликацию на другой узел. + +Стенд имеет одну БД, один Redis и один API-контейнер с двумя worker, без HA. Учебная роль БД создана штатным POSTGRES_USER и обладает избыточными полномочиями; следующий шаг — отдельные роли мигратора и runtime. HTTP/Basic допустимы только на изолированном localhost с синтетическими данными; внешняя демонстрация требует TLS. Rate limiting, очистка истёкших сессий и повторное хеширование при изменении параметров KDF не реализованы. + +Redis в этом решении ускоряет неизменяемый профиль, а не историю; его полезность подтверждена попаданием в кэш, но отдельный throughput-выигрыш /me не исследовался. Трек согласованности кэша не заявляется. Значительный выигрыш keyset подтверждён для данной перекошенной синтетической истории и тёплых буферов; другие распределения, холодный диск и масштаб больше RAM требуют отдельных опытов. Backup на том же физическом хосте не защищает от потери хоста; нужны внешнее хранение, расписание backup, WAL-архив и регулярные restore drill. + +При первой финальной пересборке PyPI дал сетевой read timeout; повторная сборка использует увеличенный timeout и retries. + +Перед сдачей необходимо вписать номер группы и после публикации добавить ссылку на собственный commit/PR. Оценку выставляет преподаватель по запуску и защите; прохождение smoke само по себе её не гарантирует. + +Источники: [контракт курса](contracts/README.md), [PostgreSQL 16: составные индексы](https://www.postgresql.org/docs/16/indexes-multicolumn.html), [PostgreSQL 16: backup/restore](https://www.postgresql.org/docs/16/backup-dump.html), [PostgreSQL EXPLAIN](https://www.postgresql.org/docs/16/using-explain.html), [argon2-cffi: password hashing](https://argon2-cffi.readthedocs.io/en/stable/howto.html), [Redis persistence](https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/), [RFC 7617](https://www.rfc-editor.org/info/rfc7617/). diff --git a/app/main.py b/app/main.py new file mode 100644 index 00000000..4e7fa4a9 --- /dev/null +++ b/app/main.py @@ -0,0 +1,192 @@ +import base64 +import datetime as dt +import hashlib +import json +import os +import re +import secrets +import uuid +from flask import Flask, request, g +from werkzeug.exceptions import HTTPException +from argon2 import PasswordHasher +from argon2.exceptions import VerificationError +from psycopg.rows import dict_row +from psycopg.errors import UniqueViolation +from psycopg_pool import ConnectionPool +import psycopg +import redis +from app.migrate import setting + +app = Flask(__name__) +app.config['MAX_CONTENT_LENGTH'] = 65536 +pool = ConnectionPool(setting('DATABASE_URL'), min_size=1, max_size=8, timeout=3, + kwargs={'row_factory':dict_row,'connect_timeout':3,'options':'-c statement_timeout=3000 -c lock_timeout=2000'}) +cache = redis.Redis.from_url(setting('CACHE_URL'),socket_connect_timeout=.2,socket_timeout=.2) +kdf = PasswordHasher(time_cost=2,memory_cost=19456,parallelism=1) +dummy = kdf.hash(secrets.token_urlsafe(32)) +ttl = int(os.getenv('SESSION_TTL_SECONDS','3600')) + +class Problem(Exception): + def __init__(self,status,code): self.status,self.code=status,code + +def fail(status,code): raise Problem(status,code) +def invalid(): fail(400,'invalid_request') +def uid(value): + try: return str(uuid.UUID(value)) + except (ValueError,TypeError,AttributeError): invalid() +def clean(row): + return {k:(v.isoformat().replace('+00:00','Z') if isinstance(v,dt.datetime) else str(v) if isinstance(v,uuid.UUID) else v) for k,v in row.items()} +def user(row): return clean({k:row[k] for k in ('id','username','display_name','created_at')}) +def body(fields): + if request.mimetype != 'application/json': fail(415,'unsupported_media_type') + try: data = request.get_json() + except HTTPException: invalid() + if not isinstance(data,dict) or set(data)!=set(fields): invalid() + return data +def string(s,maximum,minimum=1): + if not isinstance(s,str) or not s.strip() or not minimum<=len(s)<=maximum: invalid() + try: s.encode('utf-8') + except UnicodeError: invalid() + return s + +def actor(c): + auth = request.headers.get('Authorization','') + if not auth.startswith('Bearer ') or not 1<=len(auth[7:])<=256: fail(401,'unauthorized') + digest = hashlib.sha256(auth[7:].encode()).hexdigest() + row=c.execute('SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at>clock_timestamp()',(digest,)).fetchone() + if not row: fail(401,'unauthorized') + g.digest=digest + return row['user_id'] + +def public_user(c,ident): + key='user:'+str(ident) + try: + value=cache.get(key) + if value: return json.loads(value) + except (redis.RedisError,ValueError): pass + result=user(c.execute('SELECT * FROM users WHERE id=%s',(ident,)).fetchone()) + try: cache.setex(key,60,json.dumps(result)) + except redis.RedisError: pass + return result + +def chat(c,ident,who): + row=c.execute('SELECT c.* FROM chats c JOIN members m ON c.id=m.chat_id WHERE c.id=%s AND m.user_id=%s',(ident,who)).fetchone() + if not row: fail(404,'not_found') + row=clean(row) + row['member_ids']=[str(x['user_id']) for x in c.execute('SELECT user_id FROM members WHERE chat_id=%s ORDER BY user_id',(ident,))] + return row + +def page_args(resource): + if set(request.args)-{'limit','cursor'} or any(len(request.args.getlist(k))!=1 for k in request.args): invalid() + raw=request.args.get('limit','50') + if len(raw)>3 or not re.fullmatch(r'[0-9]+',raw) or not 1<=int(raw)<=100: invalid() + cursor=request.args.get('cursor') + pair=None + if cursor is not None: + try: + data=json.loads(base64.b64decode(cursor,altchars=b'-_',validate=True)) + if not isinstance(data,list) or len(data)!=3 or data[0]!=resource: invalid() + stamp=dt.datetime.fromisoformat(data[1].replace('Z','+00:00')) + if stamp.tzinfo is None: invalid() + pair=(stamp,uid(data[2])) + except (ValueError,TypeError,KeyError,AttributeError,OverflowError): invalid() + return int(raw),pair + +def page(rows,limit,resource): + more=len(rows)>limit + rows=rows[:limit] + cursor=base64.urlsafe_b64encode(json.dumps([resource,rows[-1]['created_at'],rows[-1]['id']]).encode()).decode() if more else None + return {'items':rows,'next_cursor':cursor} + +@app.before_request +def before(): g.request_id=str(uuid.uuid4()) +@app.after_request +def after(response): + response.headers['X-Request-Id']=g.request_id + return response +@app.errorhandler(Exception) +def error(exc): + if isinstance(exc,Problem): status,code=exc.status,exc.code + elif isinstance(exc,UniqueViolation): status,code=409,'conflict' + elif isinstance(exc,(psycopg.Error, __import__('psycopg_pool').PoolTimeout)): status,code=503,'unavailable' + elif isinstance(exc,HTTPException): + status=exc.code + code={404:'not_found',413:'payload_too_large',415:'unsupported_media_type'}.get(status,'invalid_request') + else: + app.logger.error('Unhandled exception type: %s',type(exc).__name__) + status,code=500,'internal_error' + response=app.json.response({'error':{'code':code,'message':code,'request_id':g.request_id}}) + response.status_code=status + if status==401: + response.headers['WWW-Authenticate']='Basic realm="messenger", charset="UTF-8"' if request.path=='/api/v1/auth/sessions' else 'Bearer realm="messenger"' + return response +@app.get('/health/live') +def live(): return {'status':'ok'} +@app.get('/health/ready') +def ready(): + with pool.connection() as c: c.execute('SELECT 1') + return {'status':'ok'} + +@app.route('/api/v1/',methods=['GET','POST','DELETE']) +def api(path): + public = (path in ('users','auth/sessions') and request.method=='POST') + if not public and not request.headers.get('Authorization','').startswith('Bearer '): fail(401,'unauthorized') + with pool.connection() as c: + if path=='users' and request.method=='POST': + d=body(['username','display_name','password']) + if not isinstance(d['username'],str) or not re.fullmatch('[a-z0-9_]{3,32}',d['username']): invalid() + string(d['display_name'],100); string(d['password'],128,12) + row=c.execute('INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING *',(uuid.uuid4(),d['username'],d['display_name'],kdf.hash(d['password']))).fetchone() + return user(row),201 + if path=='auth/sessions' and request.method=='POST': + a=request.headers.get('Authorization','') + try: + if not a.startswith('Basic ') or request.get_data(): raise ValueError() + name,password=base64.b64decode(a[6:],validate=True).decode('utf-8').split(':',1) + except (ValueError,UnicodeError): fail(401,'unauthorized') + row=c.execute('SELECT * FROM users WHERE username=%s',(name,)).fetchone() + try: valid=kdf.verify(row['password_hash'] if row else dummy,password) + except VerificationError: valid=False + if not valid or not row: fail(401,'unauthorized') + token=secrets.token_urlsafe(32) + expires=c.execute("INSERT INTO sessions VALUES (%s,%s,clock_timestamp() + %s * interval '1 second') RETURNING expires_at",(hashlib.sha256(token.encode()).hexdigest(),row['id'],ttl)).fetchone()['expires_at'] + return {'token':token,'token_type':'Bearer','expires_at':expires.isoformat().replace('+00:00','Z'),'user':user(row)},201 + who=actor(c) + if path=='auth/sessions/current' and request.method=='DELETE': + c.execute('DELETE FROM sessions WHERE token_hash=%s',(g.digest,)) + return '',204 + if path=='users/me' and request.method=='GET': return public_user(c,who) + if path=='chats': + if request.method=='POST': + d=body(['title','member_ids']); string(d['title'],100) + ids=d['member_ids'] + if not isinstance(ids,list) or not 1<=len(ids)<=100: invalid() + ids=[uid(x) for x in ids] + if len(ids)!=len(set(ids)) or str(who) not in ids: invalid() + if c.execute('SELECT count(*) AS n FROM users WHERE id=ANY(%s::uuid[])',(ids,)).fetchone()['n']!=len(ids): invalid() + ident=uuid.uuid4() + c.execute('INSERT INTO chats(id,title) VALUES (%s,%s)',(ident,d['title'])) + for member in ids: c.execute('INSERT INTO members VALUES (%s,%s)',(ident,member)) + return chat(c,ident,who),201 + if request.method=='GET': + resource='chats:'+str(who); limit,pair=page_args(resource) + query='SELECT c.id FROM chats c JOIN members m ON c.id=m.chat_id WHERE m.user_id=%s' + params=[who] + if pair: query+=' AND (c.created_at,c.id)>(%s,%s)'; params+=list(pair) + query+=' ORDER BY c.created_at,c.id LIMIT %s'; params+=[limit+1] + return page([chat(c,x['id'],who) for x in c.execute(query,params).fetchall()],limit,resource) + parts=path.split('/') + if len(parts) in (2,3) and parts[0]=='chats': + ident=uid(parts[1]); result=chat(c,ident,who) + if len(parts)==2 and request.method=='GET': return result + if len(parts)==3 and parts[2]=='messages': + if request.method=='POST': + d=body(['text']); string(d['text'],4000) + return clean(c.execute('INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *',(uuid.uuid4(),ident,who,d['text'])).fetchone()),201 + if request.method=='GET': + limit,pair=page_args(ident) + query='SELECT * FROM messages WHERE chat_id=%s'; params=[ident] + if pair: query+=' AND (created_at,id)>(%s,%s)'; params+=list(pair) + query+=' ORDER BY created_at,id LIMIT %s'; params+=[limit+1] + return page([clean(x) for x in c.execute(query,params)],limit,ident) + fail(404,'not_found') diff --git a/app/migrate.py b/app/migrate.py new file mode 100644 index 00000000..ec8eeae4 --- /dev/null +++ b/app/migrate.py @@ -0,0 +1,18 @@ +import os +from pathlib import Path +import psycopg + +def setting(name): + file = os.getenv(name + '_FILE') + return Path(file).read_text().strip() if file else os.environ[name] + +def migrate(): + with psycopg.connect(setting('DATABASE_URL'), connect_timeout=3) as c: + c.execute('SELECT pg_advisory_xact_lock(202602)') + c.execute('CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())') + for p in sorted(Path('migrations').glob('*.sql')): + if not c.execute('SELECT 1 FROM schema_migrations WHERE version=%s',(p.name,)).fetchone(): + c.execute(p.read_text()) + c.execute('INSERT INTO schema_migrations(version) VALUES (%s)',(p.name,)) +if __name__ == '__main__': + migrate() diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..caac2c1d --- /dev/null +++ b/compose.yaml @@ -0,0 +1,62 @@ +name: mtusi_lab2_solution +services: + postgres: + image: postgres:16.10-alpine + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/db_password + secrets: [db_password] + volumes: [pgdata:/var/lib/postgresql/data] + healthcheck: + test: [CMD-SHELL, 'pg_isready -U messenger -d messenger'] + interval: 2s + timeout: 2s + retries: 30 + redis: + image: redis:7.4.6-alpine + command: [redis-server, --appendonly, 'yes', --appendfsync, everysec] + volumes: [redisdata:/data] + healthcheck: + test: [CMD, redis-cli, ping] + interval: 2s + timeout: 2s + retries: 30 + postgres_restore: + image: postgres:16.10-alpine + profiles: [research] + environment: + POSTGRES_USER: messenger + POSTGRES_DB: research_restored + POSTGRES_PASSWORD_FILE: /run/secrets/db_password + secrets: [db_password] + volumes: [restoredata:/var/lib/postgresql/data] + healthcheck: + test: [CMD-SHELL, 'pg_isready -U messenger -d research_restored'] + interval: 2s + timeout: 2s + retries: 30 + api: + build: . + environment: + DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL_FILE: /run/secrets/cache_url + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + secrets: [database_url, cache_url] + ports: ['127.0.0.1:8080:8080'] + depends_on: + postgres: {condition: service_healthy} + redis: {condition: service_healthy} + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready', timeout=4)"] + interval: 3s + timeout: 5s + retries: 30 +volumes: + pgdata: + redisdata: + restoredata: +secrets: + db_password: {file: ./secrets/db_password} + database_url: {file: ./secrets/database_url} + cache_url: {file: ./secrets/cache_url} diff --git a/docs/schema.md b/docs/schema.md new file mode 100644 index 00000000..a18c9737 --- /dev/null +++ b/docs/schema.md @@ -0,0 +1,38 @@ +# Модель хранения и границы транзакций + +| Таблица | Ключи и ограничения | Назначение | +| --- | --- | --- | +| users | UUID PK; UNIQUE username; CHECK username/display_name | Неизменяемый публичный профиль и Argon2id hash | +| chats | UUID PK; CHECK title | Чат | +| members | PK(chat_id,user_id); FK chats, users | Доступ пользователя к чату | +| messages | UUID PK; NOT NULL FK chat_id, sender_id; CHECK text | Подтверждённые сообщения | +| sessions | SHA-256(token) PK; FK user_id; NOT NULL expires_at | Источник истины для сессий | +| schema_migrations | version PK | Применённые версии миграций | + +UUID создаются приложением, время — PostgreSQL clock_timestamp(). Индекс +messages(chat_id,created_at,id) соответствует равенству chat_id, диапазону пары +(created_at,id), ORDER BY и LIMIT. members(user_id,chat_id) помогает списку чатов. +Индекс sessions(expires_at) предусмотрен для будущей пакетной очистки; expiry +уже проверяется на каждом запросе и не зависит от фоновой очистки. + +Одна HTTP-операция использует одну транзакцию READ COMMITTED. COMMIT происходит +при успешном выходе из pool.connection() до передачи HTTP-ответа Flask. +Исключение откатывает все действия, включая уже вставленный чат. Чат и все +members вставляются вместе. UNIQUE PostgreSQL, а не проверка в Python, +разрешает гонку username. SQL параметризован. Каждый worker ограничен восемью +соединениями; два worker дают максимум 16. Pool wait/connect timeout — 3 s, +statement timeout — 3 s, lock timeout — 2 s. + +Redis содержит только JSON публичного пользователя user:, TTL 60 s. +Профиль в обязательном API неизменяемый, поэтому инвалидация при обновлении +не нужна. Будущее редактирование профиля потребует удаления/версионирования +этого ключа. Сессия всегда проверяется в PostgreSQL до обращения к кэшу. +История сообщений не кэшируется: SELECT из primary после подтверждённого +COMMIT обеспечивает read-after-write. Потеря Redis безопасна; потеря БД — 503. + +Курсор кодирует ресурс и последнюю пару (created_at,id) в base64url JSON. +Список чатов также привязан к пользователю. Курсор не является credential. +При конкурентных вставках это последовательный обход, а не общий snapshot: +сообщение с ключом <= последнего курсора может не попасть в следующие страницы. +Это возможно при задержанном COMMIT/коррекции часов; для неизменной истории +потерь и повторений нет. Приложение не обещает глобальный порядок COMMIT по часам. diff --git a/evidence/build.txt b/evidence/build.txt new file mode 100644 index 00000000..aef80f2e --- /dev/null +++ b/evidence/build.txt @@ -0,0 +1,74 @@ + Image mtusi_lab2_solution-api Building +#1 [internal] load local bake definitions +#1 reading from stdin 584B done +#1 DONE 0.0s + +#2 [internal] load build definition from Dockerfile +#2 transferring dockerfile: 412B done +#2 DONE 0.0s + +#3 [auth] library/python:pull token for registry-1.docker.io +#3 DONE 0.0s + +#4 [internal] load metadata for docker.io/library/python:3.12.12-slim +#4 DONE 1.8s + +#5 [internal] load .dockerignore +#5 transferring context: 196B done +#5 DONE 0.0s + +#6 [1/7] FROM docker.io/library/python:3.12.12-slim@sha256:f3fa41d74a768c2fce8016b98c191ae8c1bacd8f1152870a3f9f87d350920b7c +#6 resolve docker.io/library/python:3.12.12-slim@sha256:f3fa41d74a768c2fce8016b98c191ae8c1bacd8f1152870a3f9f87d350920b7c done +#6 DONE 0.0s + +#7 [internal] load build context +#7 transferring context: 31.53kB done +#7 DONE 0.0s + +#8 [2/7] WORKDIR /srv +#8 CACHED + +#9 [3/7] COPY requirements.lock . +#9 CACHED + +#10 [4/7] RUN pip install --no-cache-dir --timeout 120 --retries 5 -r requirements.lock +#10 CACHED + +#11 [5/7] COPY app app +#11 DONE 0.0s + +#12 [6/7] COPY migrations migrations +#12 DONE 0.0s + +#13 [7/7] RUN useradd --uid 10001 --create-home api +#13 DONE 0.1s + +#14 exporting to image +#14 exporting layers 0.0s done +#14 exporting manifest sha256:195eb74ee052bab3c0d529698f465e0da609ab8383fb854c334f3757d02a1e03 done +#14 exporting config sha256:3c150847214a6a3acc72c5462bd153e786b088e0ec2ea276c5e4771ec660f3cf done +#14 exporting attestation manifest sha256:7a47078f37a4b9464b441ecb33703736f94e91cce5c5b1beec1451fad546e0d8 done +#14 exporting manifest list sha256:e7e7fbebc3183fb70b6cf5474a9de4e04ce83263b1217ef99e8ce2466813c545 done +#14 naming to docker.io/library/mtusi_lab2_solution-api:latest done +#14 unpacking to docker.io/library/mtusi_lab2_solution-api:latest 0.0s done +#14 DONE 0.1s + +#15 resolving provenance for metadata file +#15 DONE 0.0s + Image mtusi_lab2_solution-api Built + Container mtusi_lab2_solution-redis-1 Running + Container mtusi_lab2_solution-postgres-1 Running + Container mtusi_lab2_solution-api-1 Recreate + Container mtusi_lab2_solution-api-1 Recreated + Container mtusi_lab2_solution-redis-1 Waiting + Container mtusi_lab2_solution-postgres-1 Waiting + Container mtusi_lab2_solution-redis-1 Healthy + Container mtusi_lab2_solution-postgres-1 Healthy + Container mtusi_lab2_solution-api-1 Starting + Container mtusi_lab2_solution-api-1 Started + Container mtusi_lab2_solution-postgres-1 Waiting + Container mtusi_lab2_solution-redis-1 Waiting + Container mtusi_lab2_solution-api-1 Waiting + Container mtusi_lab2_solution-redis-1 Healthy + Container mtusi_lab2_solution-postgres-1 Healthy + Container mtusi_lab2_solution-api-1 Healthy diff --git a/evidence/check.txt b/evidence/check.txt new file mode 100644 index 00000000..9a553306 --- /dev/null +++ b/evidence/check.txt @@ -0,0 +1,2 @@ +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. diff --git a/evidence/contract-extra.txt b/evidence/contract-extra.txt new file mode 100644 index 00000000..3b6da94c --- /dev/null +++ b/evidence/contract-extra.txt @@ -0,0 +1 @@ +PASS: 128-codepoint UTF-8 password with colon; malformed JSON and oversized limit rejected diff --git a/evidence/environment.json b/evidence/environment.json new file mode 100644 index 00000000..f7566dae --- /dev/null +++ b/evidence/environment.json @@ -0,0 +1,10 @@ +{ + "ServerVersion": "29.8.0", + "Architecture": "aarch64", + "NCPU": 10, + "MemTotal": 8319504384, + "OperatingSystem": "Docker Desktop", + "KernelVersion": "7.0.12-linuxkit", + "host": "macOS-27.0.1-arm64-arm-64bit-Mach-O", + "processor": "Apple M4" +} \ No newline at end of file diff --git a/evidence/experiments.json b/evidence/experiments.json new file mode 100644 index 00000000..898f71ef --- /dev/null +++ b/evidence/experiments.json @@ -0,0 +1,77 @@ +{ + "registration_race": { + "concurrency": 8, + "statuses": [ + 201, + 409, + 409, + 409, + 409, + 409, + 409, + 409 + ] + }, + "rollback": { + "failure": "trigger rejects membership after chat INSERT", + "remaining_chats": 0 + }, + "contract_extra": { + "malformed_cursor_rejected": true, + "read_after_write": true, + "foreign_cursor_rejected": true, + "strict_json": true + }, + "redis_outage": { + "cache_hits_delta": 1, + "fallback_request_ms": 6.44, + "anonymous_status": 401, + "recovered": true + }, + "postgres_outage": { + "ready_status": 503, + "authenticated_status": 503, + "anonymous_status": 401, + "checks_seconds": 0.008, + "recovery_seconds": 1.079 + }, + "expiry": { + "ttl_seconds": 2, + "wait_seconds": 2.2, + "status": 401 + }, + "backup_restore": { + "backup_seconds": 0.272, + "copy_seconds": 0.15, + "restore_seconds": 0.382, + "source": "120000|8875a7ede51a3769bf6725a3d57afda0", + "restored": "120000|8875a7ede51a3769bf6725a3d57afda0", + "samples_equal": true, + "target": "postgres_restore / research_restored / restoredata", + "rows": 120000 + }, + "restored_table_counts": { + "users": { + "source": 1, + "restored": 1 + }, + "chats": { + "source": 3, + "restored": 3 + }, + "members": { + "source": 3, + "restored": 3 + }, + "messages": { + "source": 120000, + "restored": 120000 + }, + "sessions": { + "source": 0, + "restored": 0 + } + }, + "resources": "{\"BlockIO\":\"0B / 0B\",\"CPUPerc\":\"5.69%\",\"Container\":\"0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee\",\"ID\":\"0f631adbffd4\",\"MemPerc\":\"0.94%\",\"MemUsage\":\"74.46MiB / 7.748GiB\",\"Name\":\"mtusi_lab2_solution-api-1\",\"NetIO\":\"567kB / 44.8kB\",\"PIDs\":\"13\"}\n{\"BlockIO\":\"0B / 11.1MB\",\"CPUPerc\":\"2.10%\",\"Container\":\"f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf\",\"ID\":\"f5f36655f35c\",\"MemPerc\":\"0.59%\",\"MemUsage\":\"46.6MiB / 7.748GiB\",\"Name\":\"mtusi_lab2_solution-postgres_restore-1\",\"NetIO\":\"872B / 126B\",\"PIDs\":\"6\"}\n{\"BlockIO\":\"0B / 15.4MB\",\"CPUPerc\":\"1.70%\",\"Container\":\"ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529\",\"ID\":\"ef48c5bc40d5\",\"MemPerc\":\"0.87%\",\"MemUsage\":\"69.17MiB / 7.748GiB\",\"Name\":\"mtusi_lab2_solution-postgres-1\",\"NetIO\":\"56.7kB / 576kB\",\"PIDs\":\"8\"}\n{\"BlockIO\":\"8.19kB / 0B\",\"CPUPerc\":\"2.61%\",\"Container\":\"5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0\",\"ID\":\"5e0d35373794\",\"MemPerc\":\"0.13%\",\"MemUsage\":\"10.55MiB / 7.748GiB\",\"Name\":\"mtusi_lab2_solution-redis-1\",\"NetIO\":\"4.44kB / 1.38kB\",\"PIDs\":\"7\"}\n", + "versions": "Docker Compose version v5.5.1\n" +} \ No newline at end of file diff --git a/evidence/integration.txt b/evidence/integration.txt new file mode 100644 index 00000000..296192ac --- /dev/null +++ b/evidence/integration.txt @@ -0,0 +1 @@ +PASS: registration race, rollback, strict contract, Redis/DB failure, expiry, 120000-row plans, backup/restore; evidence saved without tokens. diff --git a/evidence/load-1.json b/evidence/load-1.json new file mode 100644 index 00000000..c6baeaab --- /dev/null +++ b/evidence/load-1.json @@ -0,0 +1,17 @@ +{ + "lab": 2, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 10.0, + "elapsed_seconds": 10.067, + "concurrency": 4, + "successful_requests": 17175, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1706.064, + "successful_latency_ms": { + "p50": 2.16, + "p95": 3.422, + "p99": 5.233 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/load-2.json b/evidence/load-2.json new file mode 100644 index 00000000..b09e04d6 --- /dev/null +++ b/evidence/load-2.json @@ -0,0 +1,17 @@ +{ + "lab": 2, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 10.0, + "elapsed_seconds": 10.064, + "concurrency": 4, + "successful_requests": 15871, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1577.068, + "successful_latency_ms": { + "p50": 2.267, + "p95": 3.971, + "p99": 5.958 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/load-3.json b/evidence/load-3.json new file mode 100644 index 00000000..87b82849 --- /dev/null +++ b/evidence/load-3.json @@ -0,0 +1,17 @@ +{ + "lab": 2, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 10.0, + "elapsed_seconds": 10.061, + "concurrency": 4, + "successful_requests": 16757, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1665.588, + "successful_latency_ms": { + "p50": 2.184, + "p95": 3.473, + "p99": 5.305 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/load-resources.json b/evidence/load-resources.json new file mode 100644 index 00000000..7b0bf42d --- /dev/null +++ b/evidence/load-resources.json @@ -0,0 +1,906 @@ +{ + "host": "macOS-27.0.1-arm64-arm-64bit-Mach-O", + "machine": "arm64", + "samples": [ + { + "run": 1, + "elapsed_epoch": 1792675732.052019, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "124.73%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "1.49%", + "MemUsage": "117.9MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "6.86MB / 5.43MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "1.57%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.63%", + "MemUsage": "50.02MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "44.12%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.06%", + "MemUsage": "84.48MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "2.87MB / 4.51MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "0.97%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.13%", + "MemUsage": "10.68MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 1, + "elapsed_epoch": 1792675734.054676, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "112.32%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "1.49%", + "MemUsage": "118.4MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "14.2MB / 11.6MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.62%", + "MemUsage": "49.43MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "39.57%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.07%", + "MemUsage": "84.67MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "6.03MB / 9.02MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "0.96%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.13%", + "MemUsage": "10.52MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 1, + "elapsed_epoch": 1792675736.0638368, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "111.13%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "1.49%", + "MemUsage": "118.1MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "21.5MB / 17.8MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.62%", + "MemUsage": "49.55MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "39.79%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.07%", + "MemUsage": "84.7MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "9.18MB / 13.5MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "0.93%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.13%", + "MemUsage": "10.3MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 1, + "elapsed_epoch": 1792675738.071408, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "109.29%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "1.49%", + "MemUsage": "118.3MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "28.5MB / 23.8MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.63%", + "MemUsage": "50.06MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "37.83%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.07%", + "MemUsage": "84.52MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "12.2MB / 17.8MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "0.97%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.14%", + "MemUsage": "10.73MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 1, + "elapsed_epoch": 1792675740.0812669, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "106.04%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "1.49%", + "MemUsage": "118.2MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "34.9MB / 29.2MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.63%", + "MemUsage": "49.81MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "37.98%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.07%", + "MemUsage": "84.99MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "15MB / 21.8MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "0.89%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.14%", + "MemUsage": "11.09MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 1, + "elapsed_epoch": 1792675742.1150851, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "0.08%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "1.49%", + "MemUsage": "118MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "35.3MB / 29.5MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.63%", + "MemUsage": "50.02MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "0.04%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.06%", + "MemUsage": "84.23MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "15.1MB / 22MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "2.13%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.13%", + "MemUsage": "10.4MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 2, + "elapsed_epoch": 1792675744.114024, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "101.97%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "2.21%", + "MemUsage": "175.2MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "41MB / 34.4MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.63%", + "MemUsage": "49.85MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "35.23%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.07%", + "MemUsage": "84.72MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "17.6MB / 25.5MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "0.96%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.13%", + "MemUsage": "10.7MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 2, + "elapsed_epoch": 1792675746.122337, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "106.89%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "2.21%", + "MemUsage": "175MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "48.1MB / 40.4MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.62%", + "MemUsage": "49.55MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "37.64%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.07%", + "MemUsage": "85.1MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "20.7MB / 29.9MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "0.95%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.14%", + "MemUsage": "10.74MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 2, + "elapsed_epoch": 1792675748.134932, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "108.80%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "2.21%", + "MemUsage": "175.4MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "54.4MB / 45.7MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.62%", + "MemUsage": "49.44MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "40.72%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.07%", + "MemUsage": "85.18MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "23.4MB / 33.8MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "1.00%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.14%", + "MemUsage": "10.91MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 2, + "elapsed_epoch": 1792675750.14941, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "116.16%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "2.22%", + "MemUsage": "175.8MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "61.2MB / 51.5MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.63%", + "MemUsage": "50.34MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "41.38%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.08%", + "MemUsage": "85.54MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "26.3MB / 38MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "0.91%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.13%", + "MemUsage": "10.67MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 2, + "elapsed_epoch": 1792675752.159658, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "123.22%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "2.21%", + "MemUsage": "175.2MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "66.7MB / 56.1MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.63%", + "MemUsage": "49.85MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "47.36%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.07%", + "MemUsage": "84.94MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "28.7MB / 41.4MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "1.12%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.13%", + "MemUsage": "10.55MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 2, + "elapsed_epoch": 1792675754.190971, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "0.06%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "2.21%", + "MemUsage": "175.1MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "67.3MB / 56.6MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.63%", + "MemUsage": "50.04MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "0.02%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.07%", + "MemUsage": "84.77MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "28.9MB / 41.8MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "2.21%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.13%", + "MemUsage": "10.49MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 3, + "elapsed_epoch": 1792675756.192448, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "130.29%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "2.93%", + "MemUsage": "232.5MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "72.8MB / 61.3MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.63%", + "MemUsage": "50MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "47.24%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.08%", + "MemUsage": "85.61MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "31.3MB / 45.2MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "1.00%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.14%", + "MemUsage": "10.87MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 3, + "elapsed_epoch": 1792675758.204885, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "126.21%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "2.93%", + "MemUsage": "232.3MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "79.7MB / 67.2MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.62%", + "MemUsage": "49.33MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "46.18%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.09%", + "MemUsage": "86.26MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "34.3MB / 49.5MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "1.06%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.13%", + "MemUsage": "10.48MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 3, + "elapsed_epoch": 1792675760.216644, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "114.00%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "2.93%", + "MemUsage": "232.2MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "86.1MB / 72.6MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.63%", + "MemUsage": "50.11MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "40.83%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.08%", + "MemUsage": "85.98MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "37.1MB / 53.5MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "0.92%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.13%", + "MemUsage": "10.33MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 3, + "elapsed_epoch": 1792675762.223538, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "111.84%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "2.93%", + "MemUsage": "232.5MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "93.2MB / 78.6MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.63%", + "MemUsage": "49.69MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "38.19%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.10%", + "MemUsage": "87.19MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "40.2MB / 57.8MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "0.96%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.13%", + "MemUsage": "10.48MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 3, + "elapsed_epoch": 1792675764.2305222, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "109.30%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "2.93%", + "MemUsage": "232.7MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "100MB / 84.6MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.62%", + "MemUsage": "49.54MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "37.83%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.10%", + "MemUsage": "87.66MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "43.2MB / 62.2MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "0.94%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.13%", + "MemUsage": "10.3MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + }, + { + "run": 3, + "elapsed_epoch": 1792675766.254682, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "0.08%", + "Container": "0f631adbffd4b3d66754fb6cfd0c560f9ea9f360582ae6ea5a6d624d4383afee", + "ID": "0f631adbffd4", + "MemPerc": "2.93%", + "MemUsage": "232.3MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-api-1", + "NetIO": "101MB / 85.2MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 41.2MB", + "CPUPerc": "0.00%", + "Container": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "ID": "f5f36655f35c", + "MemPerc": "0.63%", + "MemUsage": "49.67MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres_restore-1", + "NetIO": "872B / 126B", + "PIDs": "6" + }, + { + "BlockIO": "0B / 72.4MB", + "CPUPerc": "0.00%", + "Container": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "ID": "ef48c5bc40d5", + "MemPerc": "1.11%", + "MemUsage": "87.77MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-postgres-1", + "NetIO": "43.5MB / 62.6MB", + "PIDs": "14" + }, + { + "BlockIO": "12.3kB / 4.1kB", + "CPUPerc": "2.19%", + "Container": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "ID": "5e0d35373794", + "MemPerc": "0.14%", + "MemUsage": "10.83MiB / 7.748GiB", + "Name": "mtusi_lab2_solution-redis-1", + "NetIO": "4.44kB / 1.38kB", + "PIDs": "7" + } + ] + } + ] +} \ No newline at end of file diff --git a/evidence/load-summary.txt b/evidence/load-summary.txt new file mode 100644 index 00000000..45a87275 --- /dev/null +++ b/evidence/load-summary.txt @@ -0,0 +1 @@ +PASS: three 10-second runs, concurrency 4; HTTP metrics and container resource samples saved. diff --git a/evidence/migrations.txt b/evidence/migrations.txt new file mode 100644 index 00000000..f291ac76 --- /dev/null +++ b/evidence/migrations.txt @@ -0,0 +1,2 @@ +001_initial.sql +1 diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 00000000..793b001d --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/research.json b/evidence/research.json new file mode 100644 index 00000000..a27e552a --- /dev/null +++ b/evidence/research.json @@ -0,0 +1,1538 @@ +{ + "dataset": { + "messages": 120000, + "chat_sizes": [ + 100000, + 15000, + 5000 + ] + }, + "plans": { + "chat_only": { + "1_keyset": { + "execution_ms": [ + 4.214, + 4.13, + 4.14, + 4.122, + 4.124 + ], + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 5690.04, + "Total Cost": 5695.79, + "Plan Rows": 50, + "Plan Width": 157, + "Actual Startup Time": 3.361, + "Actual Total Time": 4.114, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 2806, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Gather Merge", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 5690.04, + "Total Cost": 7376.86, + "Plan Rows": 14668, + "Plan Width": 157, + "Actual Startup Time": 3.361, + "Actual Total Time": 4.112, + "Actual Rows": 50, + "Actual Loops": 1, + "Workers Planned": 1, + "Workers Launched": 1, + "Shared Hit Blocks": 2806, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4690.03, + "Total Cost": 4726.7, + "Plan Rows": 14668, + "Plan Width": 157, + "Actual Startup Time": 2.673, + "Actual Total Time": 2.674, + "Actual Rows": 46, + "Actual Loops": 2, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 37, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 2806, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Workers": [ + { + "Worker Number": 0, + "Sort Method": "top-N heapsort", + "Sort Space Used": 37, + "Sort Space Type": "Memory" + } + ], + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": true, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.0, + "Total Cost": 4202.76, + "Plan Rows": 14668, + "Plan Width": 157, + "Actual Startup Time": 1.794, + "Actual Total Time": 2.444, + "Actual Rows": 5000, + "Actual Loops": 2, + "Filter": "((chat_id = '64fbbeee-3c1b-b5be-9d4f-5bd05fe83171'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:01:30'::interval), 'e98ff526-ad76-393f-7dfb-9717aa548154'::uuid)))", + "Rows Removed by Filter": 55000, + "Shared Hit Blocks": 2791, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Workers": [] + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.024, + "Triggers": [], + "Execution Time": 4.124 + } + }, + "1_offset": { + "execution_ms": [ + 27.208, + 27.171, + 27.137, + 27.233, + 27.65 + ], + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 20717.37, + "Total Cost": 20717.5, + "Plan Rows": 50, + "Plan Width": 157, + "Actual Startup Time": 26.575, + "Actual Total Time": 26.579, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 2791, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 1913, + "Temp Written Blocks": 2092, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 20492.37, + "Total Cost": 20742.87, + "Plan Rows": 100200, + "Plan Width": 157, + "Actual Startup Time": 19.711, + "Actual Total Time": 24.953, + "Actual Rows": 90050, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "external merge", + "Sort Space Used": 16680, + "Sort Space Type": "Disk", + "Shared Hit Blocks": 2791, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 1913, + "Temp Written Blocks": 2092, + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.0, + "Total Cost": 4291.0, + "Plan Rows": 100200, + "Plan Width": 157, + "Actual Startup Time": 0.002, + "Actual Total Time": 5.484, + "Actual Rows": 100000, + "Actual Loops": 1, + "Filter": "(chat_id = '64fbbeee-3c1b-b5be-9d4f-5bd05fe83171'::uuid)", + "Rows Removed by Filter": 20000, + "Shared Hit Blocks": 2791, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.032, + "Triggers": [], + "Execution Time": 27.65 + } + }, + "2_keyset": { + "execution_ms": [ + 0.93, + 0.923, + 0.932, + 0.937, + 0.909 + ], + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3287.69, + "Total Cost": 3287.82, + "Plan Rows": 50, + "Plan Width": 157, + "Actual Startup Time": 0.882, + "Actual Total Time": 0.886, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 365, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3287.69, + "Total Cost": 3290.73, + "Plan Rows": 1216, + "Plan Width": 157, + "Actual Startup Time": 0.882, + "Actual Total Time": 0.883, + "Actual Rows": 50, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 37, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 365, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Heap Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 162.7, + "Total Cost": 3247.3, + "Plan Rows": 1216, + "Plan Width": 157, + "Actual Startup Time": 0.462, + "Actual Total Time": 0.695, + "Actual Rows": 5000, + "Actual Loops": 1, + "Recheck Cond": "(chat_id = '88255127-540c-95c6-cac6-18d9e4630a5b'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:01:50'::interval), '2e07b8c9-c228-97db-d06c-b0888eb7e540'::uuid))", + "Rows Removed by Filter": 10000, + "Exact Heap Blocks": 350, + "Lossy Heap Blocks": 0, + "Shared Hit Blocks": 365, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Index Name": "candidate", + "Startup Cost": 0.0, + "Total Cost": 162.39, + "Plan Rows": 14680, + "Plan Width": 0, + "Actual Startup Time": 0.117, + "Actual Total Time": 0.117, + "Actual Rows": 15000, + "Actual Loops": 1, + "Index Cond": "(chat_id = '88255127-540c-95c6-cac6-18d9e4630a5b'::uuid)", + "Shared Hit Blocks": 15, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.032, + "Triggers": [], + "Execution Time": 0.909 + } + }, + "2_offset": { + "execution_ms": [ + 3.878, + 3.869, + 3.868, + 3.938, + 3.911 + ], + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4181.53, + "Total Cost": 4181.66, + "Plan Rows": 50, + "Plan Width": 157, + "Actual Startup Time": 3.648, + "Actual Total Time": 3.653, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 365, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 257, + "Temp Written Blocks": 314, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4156.53, + "Total Cost": 4193.23, + "Plan Rows": 14680, + "Plan Width": 157, + "Actual Startup Time": 3.074, + "Actual Total Time": 3.478, + "Actual Rows": 10050, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "external merge", + "Sort Space Used": 2504, + "Sort Space Type": "Disk", + "Shared Hit Blocks": 365, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 257, + "Temp Written Blocks": 314, + "Plans": [ + { + "Node Type": "Bitmap Heap Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 166.06, + "Total Cost": 3140.56, + "Plan Rows": 14680, + "Plan Width": 157, + "Actual Startup Time": 0.103, + "Actual Total Time": 0.66, + "Actual Rows": 15000, + "Actual Loops": 1, + "Recheck Cond": "(chat_id = '88255127-540c-95c6-cac6-18d9e4630a5b'::uuid)", + "Rows Removed by Index Recheck": 0, + "Exact Heap Blocks": 350, + "Lossy Heap Blocks": 0, + "Shared Hit Blocks": 365, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Index Name": "candidate", + "Startup Cost": 0.0, + "Total Cost": 162.39, + "Plan Rows": 14680, + "Plan Width": 0, + "Actual Startup Time": 0.094, + "Actual Total Time": 0.094, + "Actual Rows": 15000, + "Actual Loops": 1, + "Index Cond": "(chat_id = '88255127-540c-95c6-cac6-18d9e4630a5b'::uuid)", + "Shared Hit Blocks": 15, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.011, + "Triggers": [], + "Execution Time": 3.911 + } + }, + "3_keyset": { + "execution_ms": [ + 0.299, + 0.261, + 0.259, + 0.265, + 0.27 + ], + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3007.35, + "Total Cost": 3007.46, + "Plan Rows": 41, + "Plan Width": 157, + "Actual Startup Time": 0.255, + "Actual Total Time": 0.258, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 123, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3007.35, + "Total Cost": 3007.46, + "Plan Rows": 41, + "Plan Width": 157, + "Actual Startup Time": 0.255, + "Actual Total Time": 0.256, + "Actual Rows": 50, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 37, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 123, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Heap Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 58.7, + "Total Cost": 3006.26, + "Plan Rows": 41, + "Plan Width": 157, + "Actual Startup Time": 0.156, + "Actual Total Time": 0.207, + "Actual Rows": 1000, + "Actual Loops": 1, + "Recheck Cond": "(chat_id = '4b1f4c22-a3ac-7b71-5a63-76fc23f4b574'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:01:59'::interval), 'eb87440f-7144-c629-715c-4a41d200bf84'::uuid))", + "Rows Removed by Filter": 4000, + "Exact Heap Blocks": 117, + "Lossy Heap Blocks": 0, + "Shared Hit Blocks": 123, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Index Name": "candidate", + "Startup Cost": 0.0, + "Total Cost": 58.69, + "Plan Rows": 5120, + "Plan Width": 0, + "Actual Startup Time": 0.029, + "Actual Total Time": 0.029, + "Actual Rows": 5000, + "Actual Loops": 1, + "Index Cond": "(chat_id = '4b1f4c22-a3ac-7b71-5a63-76fc23f4b574'::uuid)", + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.017, + "Triggers": [], + "Execution Time": 0.27 + } + }, + "3_offset": { + "execution_ms": [ + 0.849, + 0.833, + 0.827, + 0.842, + 0.861 + ], + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3294.57, + "Total Cost": 3294.69, + "Plan Rows": 50, + "Plan Width": 157, + "Actual Startup Time": 0.789, + "Actual Total Time": 0.792, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 123, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3284.57, + "Total Cost": 3297.37, + "Plan Rows": 5120, + "Plan Width": 157, + "Actual Startup Time": 0.642, + "Actual Total Time": 0.724, + "Actual Rows": 4050, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 1482, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 123, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Heap Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 59.97, + "Total Cost": 2969.13, + "Plan Rows": 5120, + "Plan Width": 157, + "Actual Startup Time": 0.034, + "Actual Total Time": 0.221, + "Actual Rows": 5000, + "Actual Loops": 1, + "Recheck Cond": "(chat_id = '4b1f4c22-a3ac-7b71-5a63-76fc23f4b574'::uuid)", + "Rows Removed by Index Recheck": 0, + "Exact Heap Blocks": 117, + "Lossy Heap Blocks": 0, + "Shared Hit Blocks": 123, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Index Name": "candidate", + "Startup Cost": 0.0, + "Total Cost": 58.69, + "Plan Rows": 5120, + "Plan Width": 0, + "Actual Startup Time": 0.03, + "Actual Total Time": 0.03, + "Actual Rows": 5000, + "Actual Loops": 1, + "Index Cond": "(chat_id = '4b1f4c22-a3ac-7b71-5a63-76fc23f4b574'::uuid)", + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.011, + "Triggers": [], + "Execution Time": 0.861 + } + } + }, + "composite": { + "1_keyset": { + "execution_ms": [ + 0.016, + 0.02, + 0.015, + 0.016, + 0.02 + ], + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 21.53, + "Plan Rows": 50, + "Plan Width": 157, + "Actual Startup Time": 0.005, + "Actual Total Time": 0.008, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 10643.64, + "Plan Rows": 25214, + "Plan Width": 157, + "Actual Startup Time": 0.004, + "Actual Total Time": 0.006, + "Actual Rows": 50, + "Actual Loops": 1, + "Index Cond": "((chat_id = '64fbbeee-3c1b-b5be-9d4f-5bd05fe83171'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:01:30'::interval), 'e98ff526-ad76-393f-7dfb-9717aa548154'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.015, + "Triggers": [], + "Execution Time": 0.02 + } + }, + "1_offset": { + "execution_ms": [ + 6.416, + 6.822, + 7.246, + 7.195, + 7.1 + ], + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 13270.24, + "Total Cost": 13277.61, + "Plan Rows": 50, + "Plan Width": 157, + "Actual Startup Time": 7.081, + "Actual Total Time": 7.086, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 2741, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 14705.73, + "Plan Rows": 99736, + "Plan Width": 157, + "Actual Startup Time": 0.009, + "Actual Total Time": 5.419, + "Actual Rows": 90050, + "Actual Loops": 1, + "Index Cond": "(chat_id = '64fbbeee-3c1b-b5be-9d4f-5bd05fe83171'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 2741, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.041, + "Triggers": [], + "Execution Time": 7.1 + } + }, + "2_keyset": { + "execution_ms": [ + 0.026, + 0.02, + 0.019, + 0.023, + 0.016 + ], + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 118.01, + "Plan Rows": 50, + "Plan Width": 157, + "Actual Startup Time": 0.005, + "Actual Total Time": 0.009, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 2994.32, + "Plan Rows": 1273, + "Plan Width": 157, + "Actual Startup Time": 0.005, + "Actual Total Time": 0.007, + "Actual Rows": 50, + "Actual Loops": 1, + "Index Cond": "((chat_id = '88255127-540c-95c6-cac6-18d9e4630a5b'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:01:50'::interval), '2e07b8c9-c228-97db-d06c-b0888eb7e540'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.018, + "Triggers": [], + "Execution Time": 0.016 + } + }, + "2_offset": { + "execution_ms": [ + 4.411, + 4.009, + 4.139, + 4.236, + 4.167 + ], + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 5193.47, + "Total Cost": 5193.59, + "Plan Rows": 50, + "Plan Width": 157, + "Actual Startup Time": 3.898, + "Actual Total Time": 3.902, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 460, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 257, + "Temp Written Blocks": 314, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 5168.47, + "Total Cost": 5206.25, + "Plan Rows": 15112, + "Plan Width": 157, + "Actual Startup Time": 3.302, + "Actual Total Time": 3.723, + "Actual Rows": 10050, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "external merge", + "Sort Space Used": 2504, + "Sort Space Type": "Disk", + "Shared Hit Blocks": 460, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 257, + "Temp Written Blocks": 314, + "Plans": [ + { + "Node Type": "Bitmap Heap Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 557.54, + "Total Cost": 4119.44, + "Plan Rows": 15112, + "Plan Width": 157, + "Actual Startup Time": 0.206, + "Actual Total Time": 0.797, + "Actual Rows": 15000, + "Actual Loops": 1, + "Recheck Cond": "(chat_id = '88255127-540c-95c6-cac6-18d9e4630a5b'::uuid)", + "Rows Removed by Index Recheck": 0, + "Exact Heap Blocks": 350, + "Lossy Heap Blocks": 0, + "Shared Hit Blocks": 460, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Index Name": "candidate", + "Startup Cost": 0.0, + "Total Cost": 553.76, + "Plan Rows": 15112, + "Plan Width": 0, + "Actual Startup Time": 0.196, + "Actual Total Time": 0.196, + "Actual Rows": 15000, + "Actual Loops": 1, + "Index Cond": "(chat_id = '88255127-540c-95c6-cac6-18d9e4630a5b'::uuid)", + "Shared Hit Blocks": 110, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.015, + "Triggers": [], + "Execution Time": 4.167 + } + }, + "3_keyset": { + "execution_ms": [ + 0.016, + 0.018, + 0.015, + 0.019, + 0.015 + ], + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 132.18, + "Plan Rows": 46, + "Plan Width": 157, + "Actual Startup Time": 0.005, + "Actual Total Time": 0.008, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 132.18, + "Plan Rows": 46, + "Plan Width": 157, + "Actual Startup Time": 0.005, + "Actual Total Time": 0.007, + "Actual Rows": 50, + "Actual Loops": 1, + "Index Cond": "((chat_id = '4b1f4c22-a3ac-7b71-5a63-76fc23f4b574'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:01:59'::interval), 'eb87440f-7144-c629-715c-4a41d200bf84'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.016, + "Triggers": [], + "Execution Time": 0.015 + } + }, + "3_offset": { + "execution_ms": [ + 0.955, + 0.939, + 0.968, + 0.952, + 0.964 + ], + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4113.46, + "Total Cost": 4113.58, + "Plan Rows": 50, + "Plan Width": 157, + "Actual Startup Time": 0.891, + "Actual Total Time": 0.894, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 155, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4103.46, + "Total Cost": 4116.34, + "Plan Rows": 5152, + "Plan Width": 157, + "Actual Startup Time": 0.716, + "Actual Total Time": 0.809, + "Actual Rows": 4050, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 1482, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 155, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Heap Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 192.35, + "Total Cost": 3785.81, + "Plan Rows": 5152, + "Plan Width": 157, + "Actual Startup Time": 0.062, + "Actual Total Time": 0.261, + "Actual Rows": 5000, + "Actual Loops": 1, + "Recheck Cond": "(chat_id = '4b1f4c22-a3ac-7b71-5a63-76fc23f4b574'::uuid)", + "Rows Removed by Index Recheck": 0, + "Exact Heap Blocks": 117, + "Lossy Heap Blocks": 0, + "Shared Hit Blocks": 155, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Index Name": "candidate", + "Startup Cost": 0.0, + "Total Cost": 191.06, + "Plan Rows": 5152, + "Plan Width": 0, + "Actual Startup Time": 0.058, + "Actual Total Time": 0.058, + "Actual Rows": 5000, + "Actual Loops": 1, + "Index Cond": "(chat_id = '4b1f4c22-a3ac-7b71-5a63-76fc23f4b574'::uuid)", + "Shared Hit Blocks": 38, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.012, + "Triggers": [], + "Execution Time": 0.964 + } + } + } + }, + "write": { + "chat_only": { + "index_bytes": 860160, + "runs": [ + { + "insert_5000_ms": 70.39191700005176 + }, + { + "insert_5000_ms": 72.31700000011188 + }, + { + "insert_5000_ms": 70.44754199978343 + }, + { + "insert_5000_ms": 67.24729200004731 + }, + { + "insert_5000_ms": 71.58987499997238 + } + ] + }, + "composite": { + "index_bytes": 7094272, + "runs": [ + { + "insert_5000_ms": 74.53383299980487 + }, + { + "insert_5000_ms": 71.4828749996741 + }, + { + "insert_5000_ms": 72.96954200000982 + }, + { + "insert_5000_ms": 74.03824999983044 + }, + { + "insert_5000_ms": 73.96383400009654 + } + ] + } + }, + "count": 120000, + "samples": [ + [ + "1017bfd4-6739-55ff-ee46-41ad3d481b1c", + "64fbbeee-3c1b-b5be-9d4f-5bd05fe83171", + "ee11cbb1-9052-e40b-07aa-c0ca060c23ee", + "2026-01-01 00:00:50+00", + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + ], + [ + "14ee22ea-ba29-7944-c96a-fdbe5b16c65b", + "64fbbeee-3c1b-b5be-9d4f-5bd05fe83171", + "ee11cbb1-9052-e40b-07aa-c0ca060c23ee", + "2026-01-01 00:01:40+00", + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + ], + [ + "2e07b8c9-c228-97db-d06c-b0888eb7e540", + "88255127-540c-95c6-cac6-18d9e4630a5b", + "ee11cbb1-9052-e40b-07aa-c0ca060c23ee", + "2026-01-01 00:01:50+00", + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + ], + [ + "5344237a-d062-53d4-7cee-9a4c091aa663", + "4b1f4c22-a3ac-7b71-5a63-76fc23f4b574", + "ee11cbb1-9052-e40b-07aa-c0ca060c23ee", + "2026-01-01 00:02:00+00", + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + ], + [ + "c4ca4238-a0b9-2382-0dcc-509a6f75849b", + "64fbbeee-3c1b-b5be-9d4f-5bd05fe83171", + "ee11cbb1-9052-e40b-07aa-c0ca060c23ee", + "2026-01-01 00:00:00.001+00", + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + ] + ], + "postgres_version": "PostgreSQL 16.10 on aarch64-unknown-linux-musl, compiled by gcc (Alpine 14.2.0) 14.2.0, 64-bit" +} \ No newline at end of file diff --git a/evidence/restart-after.json b/evidence/restart-after.json new file mode 100644 index 00000000..05ce1b3e --- /dev/null +++ b/evidence/restart-after.json @@ -0,0 +1,30 @@ +[ + { + "name": "/mtusi_lab2_solution-api-1", + "id": "4dc6a54d3f262a6c58bb4cb448568c31c6116555fac4e487fe0eab29b2c4c2fe", + "started_at": "2026-10-22T11:20:08.835805761Z", + "volumes": [] + }, + { + "name": "/mtusi_lab2_solution-postgres-1", + "id": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "started_at": "2026-10-22T11:20:07.999397344Z", + "volumes": [ + { + "name": "mtusi_lab2_solution_pgdata", + "destination": "/var/lib/postgresql/data" + } + ] + }, + { + "name": "/mtusi_lab2_solution-redis-1", + "id": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "started_at": "2026-10-22T11:20:08.081507553Z", + "volumes": [ + { + "name": "mtusi_lab2_solution_redisdata", + "destination": "/data" + } + ] + } +] diff --git a/evidence/restart-before.json b/evidence/restart-before.json new file mode 100644 index 00000000..d2ccac8f --- /dev/null +++ b/evidence/restart-before.json @@ -0,0 +1,30 @@ +[ + { + "name": "/mtusi_lab2_solution-api-1", + "id": "4dc6a54d3f262a6c58bb4cb448568c31c6116555fac4e487fe0eab29b2c4c2fe", + "started_at": "2026-10-22T11:05:56.380127547Z", + "volumes": [] + }, + { + "name": "/mtusi_lab2_solution-postgres-1", + "id": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "started_at": "2026-10-22T11:05:55.45244238Z", + "volumes": [ + { + "name": "mtusi_lab2_solution_pgdata", + "destination": "/var/lib/postgresql/data" + } + ] + }, + { + "name": "/mtusi_lab2_solution-redis-1", + "id": "5e0d353737947339004634ec5e15f4dbca871263749a82efcc1d534212af18d0", + "started_at": "2026-10-22T11:05:55.526434964Z", + "volumes": [ + { + "name": "mtusi_lab2_solution_redisdata", + "destination": "/data" + } + ] + } +] diff --git a/evidence/restore-storage.json b/evidence/restore-storage.json new file mode 100644 index 00000000..db680747 --- /dev/null +++ b/evidence/restore-storage.json @@ -0,0 +1,24 @@ +[ + { + "name": "/mtusi_lab2_solution-postgres-1", + "id": "ef48c5bc40d55e509e4caaedcb99594931fe0c23ec1456c6b51e713598abc529", + "started_at": "2026-10-22T11:20:28.430795215Z", + "volumes": [ + { + "name": "mtusi_lab2_solution_pgdata", + "destination": "/var/lib/postgresql/data" + } + ] + }, + { + "name": "/mtusi_lab2_solution-postgres_restore-1", + "id": "f5f36655f35cebd4bd89c82dff2c0df1b97897ba23c2b68ebe75ef4362aceebf", + "started_at": "2026-10-22T11:20:38.50506947Z", + "volumes": [ + { + "name": "mtusi_lab2_solution_restoredata", + "destination": "/var/lib/postgresql/data" + } + ] + } +] diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 00000000..404a2c60 --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8080" +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/source-manifest.json b/evidence/source-manifest.json new file mode 100644 index 00000000..c57b19b7 --- /dev/null +++ b/evidence/source-manifest.json @@ -0,0 +1,18 @@ +{ + "Dockerfile": "585287e24d0e142b9cb4aef850121e8b4ec46d7ab067884689d782be29a93782", + "compose.yaml": "e2ceb599e45f042b5816d1aceea90a65e1310d4d3563cc01d958def57e9f9646", + "requirements.lock": "38c6fdee1220a6a22c9f6ffd9dec973aed420139e30d33325cd85be4ce9f573a", + "requirements.txt": "194dde19a47db50adf2ead77311a11ef9ce30d4e1201eec1171825b8786424d8", + "app/main.py": "b96737e1153eb23f101a2ebc8b9dea132022b523048a43e49e2279cf5eeb22b6", + "app/migrate.py": "e8fe9d98bf74fbeb0b402b1dde41e7371f602683e6898990f88abedf1e698243", + "migrations/001_initial.sql": "0fb9c58900c7ecd12d6fafe656a30c86be1e796f655eb5b0334ed290b108e25b", + "scripts/bootstrap.py": "99788b6e60a75347c752b776a57df91de48ccaf86c860cd62922082da053d6ed", + "scripts/check_contract.py": "7c4402c2a6ab80d3b4676e1866d6ecc87b6daea14c080bcb9be9a7e8b959d671", + "scripts/container_state.py": "e637480695e7d6bff435078a14ca9847d258b1bb535869d03732c20569c2a290", + "scripts/contract_extra.py": "82887d76eb27ba0244a188241dc94732c5516c1a1de9dff19e17e87c4125449e", + "scripts/experiments.py": "db198a4c818933f4abc1db468f754c4f68151c278457357be9468358ab9be0c9", + "scripts/load_experiments.py": "76ecd2c03262691556c4b7e84334035b81efabe5e4b7891901aea7dcd40e27ad", + "scripts/research.py": "ea5abf4c06982abec587f7985f81d5762902b8273360917a93569b61d9f6b13b", + "scripts/validate_openapi.py": "4e981acbfc10dac58817bf922d5896e996798551fedc1b2385130e1cddb13d54", + "scripts/restart.sh": "1adaf6842ecca38fe475d7528cc623bc775393ad05a8b541473a293a3b08ef77" +} \ No newline at end of file diff --git a/evidence/validation.txt b/evidence/validation.txt new file mode 100644 index 00000000..37e81884 --- /dev/null +++ b/evidence/validation.txt @@ -0,0 +1,2 @@ +.venv/bin/python scripts/validate_openapi.py +PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql new file mode 100644 index 00000000..279835b2 --- /dev/null +++ b/migrations/001_initial.sql @@ -0,0 +1,12 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, username text NOT NULL UNIQUE CHECK(username ~ '^[a-z0-9_]{3,32}$'), + display_name text NOT NULL CHECK(length(btrim(display_name))>0 AND length(display_name)<=100), + password_hash text NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE TABLE chats (id uuid PRIMARY KEY, title text NOT NULL CHECK(length(btrim(title))>0 AND length(title)<=100), created_at timestamptz NOT NULL DEFAULT clock_timestamp()); +CREATE TABLE members (chat_id uuid REFERENCES chats ON DELETE CASCADE, user_id uuid REFERENCES users, PRIMARY KEY(chat_id,user_id)); +CREATE INDEX members_user ON members(user_id,chat_id); +CREATE TABLE messages (id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats, sender_id uuid NOT NULL REFERENCES users, text text NOT NULL CHECK(length(btrim(text))>0 AND length(text)<=4000), created_at timestamptz NOT NULL DEFAULT clock_timestamp()); +CREATE INDEX messages_history ON messages(chat_id,created_at,id); +CREATE TABLE sessions (token_hash text PRIMARY KEY, user_id uuid NOT NULL REFERENCES users, expires_at timestamptz NOT NULL); +CREATE INDEX sessions_expiry ON sessions(expires_at); diff --git a/requirements.lock b/requirements.lock new file mode 100644 index 00000000..4a04a611 --- /dev/null +++ b/requirements.lock @@ -0,0 +1,18 @@ +argon2-cffi==25.1.0 +argon2-cffi-bindings==26.1.0 +blinker==1.9.0 +cffi==2.1.1 +click==8.5.0 +Flask==3.1.2 +gunicorn==23.0.0 +itsdangerous==2.2.0 +Jinja2==3.1.6 +MarkupSafe==3.0.4 +packaging==26.3 +psycopg==3.2.10 +psycopg-binary==3.2.10 +psycopg-pool==3.3.3 +pycparser==3.11 +redis==6.4.0 +typing_extensions==4.16.0 +Werkzeug==3.1.9 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..08a24586 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +Flask==3.1.2 +gunicorn==23.0.0 +psycopg[binary,pool]==3.2.10 +redis==6.4.0 +argon2-cffi==25.1.0 diff --git a/scripts/bootstrap.py b/scripts/bootstrap.py new file mode 100644 index 00000000..6b16665a --- /dev/null +++ b/scripts/bootstrap.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +from pathlib import Path +import secrets +p=Path('secrets'); p.mkdir(mode=0o700,exist_ok=True) +password=p/'db_password' +if not password.exists(): password.write_text(secrets.token_hex(24)) +for name,value in {'database_url':'postgresql://messenger:'+password.read_text().strip()+'@postgres:5432/messenger','cache_url':'redis://redis:6379/0'}.items(): + target=p/name + if not target.exists(): target.write_text(value) +for target in p.iterdir(): target.chmod(0o600) +if not Path('.env').exists(): Path('.env').write_text('SESSION_TTL_SECONDS=3600\n') +print('Local configuration created; secrets were not printed.') diff --git a/scripts/container_state.py b/scripts/container_state.py new file mode 100644 index 00000000..dcb1df3d --- /dev/null +++ b/scripts/container_state.py @@ -0,0 +1,4 @@ +import json, subprocess, sys +ids=subprocess.check_output(['docker','compose','ps','-q',*(sys.argv[1:] or ['api','postgres','redis'])],text=True).split() +rows=json.loads(subprocess.check_output(['docker','inspect',*ids],text=True)) +print(json.dumps([{'name':r['Name'],'id':r['Id'],'started_at':r['State']['StartedAt'],'volumes':[{'name':m.get('Name'),'destination':m['Destination']} for m in r['Mounts'] if m['Type']=='volume']} for r in rows],indent=2)) diff --git a/scripts/contract_extra.py b/scripts/contract_extra.py new file mode 100644 index 00000000..d3c2456b --- /dev/null +++ b/scripts/contract_extra.py @@ -0,0 +1,20 @@ +import sys,base64,uuid +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests')) +from client import Client,check +c=Client() +a,b,e,chat=c.bootstrap() +path='/api/v1/chats/'+chat['id'] +results={'contract_extra':{}} +# Full UTF-8 password range, including a colon; malformed JSON and invalid limits. +unicode_name='utf_'+uuid.uuid4().hex[:16] +unicode_password='🔑'*120+':пароль!' +check(len(unicode_password)==128,'password fixture length') +c.call('POST','/api/v1/users',201,body={'username':unicode_name,'display_name':'UTF-8','password':unicode_password},schema='User') +credential=base64.b64encode((unicode_name+':'+unicode_password).encode()).decode() +c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session') +c.call('POST','/api/v1/users',400,raw=b'{',headers={'Content-Type':'application/json'}) +c.call('GET',path+'/messages?limit='+('9'*100),400,actor=a) +results['contract_extra']['utf8_128_password_with_colon']=True + +print('PASS: 128-codepoint UTF-8 password with colon; malformed JSON and oversized limit rejected') diff --git a/scripts/experiments.py b/scripts/experiments.py new file mode 100644 index 00000000..6d658ebd --- /dev/null +++ b/scripts/experiments.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""Integration experiments. No credentials or bearer tokens are written to evidence.""" +import concurrent.futures as cf +import json, os, pathlib, subprocess, sys, time, uuid, base64 +sys.path.insert(0,str(pathlib.Path(__file__).resolve().parents[1]/'tests')) +from client import Client, check +root=pathlib.Path(__file__).resolve().parents[1] +os.chdir(root) +evidence=root/'evidence'; evidence.mkdir(exist_ok=True) +results={} +def dc(*args,input=None): + return subprocess.run(['docker','compose',*args],input=input,text=True,capture_output=True,check=True).stdout +def sql(query,db='messenger'): + return dc('exec','-T','postgres','psql','-U','messenger','-d',db,'-At','-v','ON_ERROR_STOP=1','-c',query).strip() +def ready(): + start=time.monotonic() + while time.monotonic()-start<90: + try: + Client(timeout=5).call('GET','/health/ready',schema='Health') + return round(time.monotonic()-start,3) + except Exception: time.sleep(.5) + raise RuntimeError('Readiness timeout') +def save(): (evidence/'experiments.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)) +c=Client(); a,b,e,chat=c.bootstrap(); path='/api/v1/chats/'+chat['id'] +# Race: one insert wins, unique index rejects the others. +d={'username':'race_'+uuid.uuid4().hex[:16],'display_name':'Гонка','password':'race-password-12345'} +def register(_): return Client().call('POST','/api/v1/users',[201,409],body=d)['status'] +with cf.ThreadPoolExecutor(max_workers=8) as executor: statuses=list(executor.map(register,range(8))) +check(statuses.count(201)==1 and statuses.count(409)==7,'registration race') +results['registration_race']={'concurrency':8,'statuses':statuses} +# Trigger a failure AFTER the chat insert; a database trigger is test-only and always removed. +name='rollback_'+uuid.uuid4().hex[:8] +sql("CREATE FUNCTION lab_reject_member() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected'; END $$; CREATE TRIGGER lab_reject_member BEFORE INSERT ON members FOR EACH ROW EXECUTE FUNCTION lab_reject_member()") +try: + c.call('POST','/api/v1/chats',503,actor=a,body={'title':name,'member_ids':[a['id'],b['id']]}) + check(sql("SELECT count(*) FROM chats WHERE title='"+name+"'")=='0','partial chat survived') +finally: sql('DROP TRIGGER lab_reject_member ON members; DROP FUNCTION lab_reject_member()') +results['rollback']={'failure':'trigger rejects membership after chat INSERT','remaining_chats':0} +# Negative API and access cases, resource-bound cursor and immediate visibility. +for payload in [{'text':'ok','sender_id':e['id']},{'text':34},{'text':' '}]: + c.call('POST',path+'/messages',400,actor=a,body=payload) +first=c.message(a,chat,'read-after-write 👋')['json'] +c.message(b,chat,'second') +page=c.call('GET',path+'/messages?limit=1',actor=b,schema='MessagePage')['json'] +check(page['items'][0]==first,'read after write') +other=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'other','member_ids':[a['id']]},schema='Chat')['json'] +from urllib.parse import quote +c.call('GET','/api/v1/chats/'+other['id']+'/messages?cursor='+quote(page['next_cursor']),400,actor=a) +c.call('GET',path+'/messages?cursor='+quote(base64.urlsafe_b64encode(json.dumps([chat['id'],123,a['id']]).encode()).decode()),400,actor=a) +results['contract_extra']={'malformed_cursor_rejected':True,'read_after_write':True,'foreign_cursor_rejected':True,'strict_json':True} +# Redis: warm cache, real hits, outage fallback, restart, cold-cache recovery. +c.call('GET','/api/v1/users/me',actor=a,schema='User') +before=dc('exec','-T','redis','redis-cli','INFO','stats') +c.call('GET','/api/v1/users/me',actor=a,schema='User') +after=dc('exec','-T','redis','redis-cli','INFO','stats') +def hits(info): return int(next(x.split(':')[1] for x in info.splitlines() if x.startswith('keyspace_hits:'))) +check(hits(after)>hits(before),'Redis unused') +start=time.monotonic(); dc('stop','redis') +c.call('GET','/api/v1/users/me',actor=a,schema='User') +c.call('GET','/api/v1/users/me',401) +c.message(a,chat,'redis unavailable') +results['redis_outage']={'cache_hits_delta':hits(after)-hits(before),'fallback_request_ms':None,'anonymous_status':401} +t=time.monotonic(); c.call('GET','/api/v1/users/me',actor=a,schema='User'); results['redis_outage']['fallback_request_ms']=round((time.monotonic()-t)*1000,2) +dc('start','redis'); dc('exec','-T','redis','redis-cli','FLUSHDB') +c.call('GET','/api/v1/users/me',actor=a,schema='User') +results['redis_outage']['recovered']=True +# DB outage is bounded and fails closed; process stays alive. +dc('stop','postgres'); start=time.monotonic() +c.call('GET','/health/live',schema='Health') +c.call('GET','/health/ready',503) +c.call('GET','/api/v1/users/me',503,actor=a) +c.call('GET','/api/v1/users/me',401) +results['postgres_outage']={'ready_status':503,'authenticated_status':503,'anonymous_status':401,'checks_seconds':round(time.monotonic()-start,3)} +dc('start','postgres'); results['postgres_outage']['recovery_seconds']=ready() +c.call('GET','/api/v1/users/me',actor=a,schema='User') +save() +# Short-lived sessions on a recreated API, then restore ordinary TTL unconditionally. +try: + env=dict(os.environ,SESSION_TTL_SECONDS='2') + subprocess.run(['docker','compose','up','-d','--no-deps','--force-recreate','api'],env=env,check=True,capture_output=True) + ready(); short=Client().user('expiry'); time.sleep(2.2) + Client().call('GET','/api/v1/users/me',401,actor=short) + results['expiry']={'ttl_seconds':2,'wait_seconds':2.2,'status':401} +finally: + env=dict(os.environ,SESSION_TTL_SECONDS='3600') + subprocess.run(['docker','compose','up','-d','--no-deps','--force-recreate','api'],env=env,check=True,capture_output=True) + ready() +# Dedicated database to avoid destructive benchmark operations on the app tables. +if sql("SELECT count(*) FROM pg_database WHERE datname='research'")=='0': sql('CREATE DATABASE research') +source=(root/'scripts/research.py').read_text() +research=json.loads(dc('exec','-T','api','python','-',input=source)) +(evidence/'research.json').write_text(json.dumps(research,ensure_ascii=False,indent=2)) +# Restore on another PostgreSQL instance with an independent persistent volume. +dc('--profile','research','up','-d','--wait','postgres_restore') +def restored_sql(query): + return dc('exec','-T','postgres_restore','psql','-U','messenger','-d','research_restored','-At','-v','ON_ERROR_STOP=1','-c',query).strip() +restored_sql('DROP SCHEMA public CASCADE; CREATE SCHEMA public') +start=time.monotonic() +dc('exec','-T','postgres','pg_dump','-U','messenger','-d','research','-Fc','-f','/tmp/research.dump') +backup_seconds=time.monotonic()-start +backup_dir=root/'backups'; backup_dir.mkdir(exist_ok=True) +start=time.monotonic() +dc('cp','postgres:/tmp/research.dump',str(backup_dir/'research.dump')) +dc('cp',str(backup_dir/'research.dump'),'postgres_restore:/tmp/research.dump') +copy_seconds=time.monotonic()-start +start=time.monotonic(); dc('exec','-T','postgres_restore','pg_restore','-U','messenger','-d','research_restored','--exit-on-error','/tmp/research.dump') +restore_seconds=time.monotonic()-start +query="SELECT count(*),md5(string_agg(id::text||':'||chat_id::text||':'||sender_id::text||':'||created_at::text||':'||text,'|' ORDER BY id)) FROM messages" +original=sql(query,'research'); restored=restored_sql(query); check(original==restored,'restored data differs') +samples="SELECT id,chat_id,sender_id,created_at,text FROM messages WHERE id IN (SELECT md5(n::text)::uuid FROM unnest(ARRAY[1,50000,100000,110000,120000]) n) ORDER BY id" +check(sql(samples,'research')==restored_sql(samples),'sample mismatch') +results['backup_restore']={'backup_seconds':round(backup_seconds,3),'copy_seconds':round(copy_seconds,3),'restore_seconds':round(restore_seconds,3),'source':original,'restored':restored,'samples_equal':True,'target':'postgres_restore / research_restored / restoredata','rows':120000} +results['restored_table_counts']={} +for table in ['users','chats','members','messages','sessions']: + original_count=sql('SELECT count(*) FROM '+table,'research') + restored_count=restored_sql('SELECT count(*) FROM '+table) + check(original_count==restored_count,'table count mismatch: '+table) + results['restored_table_counts'][table]={'source':int(original_count),'restored':int(restored_count)} +(evidence/'restore-storage.json').write_text(subprocess.check_output(['python3','scripts/container_state.py','postgres','postgres_restore'],text=True)) +results['resources']=dc('stats','--no-stream','--format','json') +results['versions']=dc('version') +save(); print('PASS: registration race, rollback, strict contract, Redis/DB failure, expiry, 120000-row plans, backup/restore; evidence saved without tokens.') diff --git a/scripts/load_experiments.py b/scripts/load_experiments.py new file mode 100644 index 00000000..bf2d3e36 --- /dev/null +++ b/scripts/load_experiments.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +import json, pathlib, platform, subprocess, time +root=pathlib.Path(__file__).resolve().parents[1] +samples=[] +for n in range(1,4): + process=subprocess.Popen(['python3','tests/load.py','--duration','10','--concurrency','4','--output',f'evidence/load-{n}.json'],cwd=root,stdout=subprocess.DEVNULL) + while process.poll() is None: + result=subprocess.run(['docker','compose','stats','--no-stream','--format','json'],capture_output=True,text=True,check=True) + samples.append({'run':n,'elapsed_epoch':time.time(),'containers':[json.loads(line) for line in result.stdout.splitlines() if line.strip()]}) + if process.returncode: raise SystemExit(process.returncode) +(root/'evidence/load-resources.json').write_text(json.dumps({'host':platform.platform(),'machine':platform.machine(),'samples':samples},indent=2)) +print('PASS: three 10-second runs, concurrency 4; HTTP metrics and container resource samples saved.') diff --git a/scripts/research.py b/scripts/research.py new file mode 100644 index 00000000..eeaf2b65 --- /dev/null +++ b/scripts/research.py @@ -0,0 +1,45 @@ +"""Run only in an isolated research database, created by experiments.py.""" +import json, time, uuid, statistics, os +from pathlib import Path +import psycopg +from app.migrate import setting + +url=setting('DATABASE_URL').rsplit('/',1)[0]+'/research' +summary={'dataset':{'messages':120000,'chat_sizes':[100000,15000,5000]},'plans':{},'write':{}} +with psycopg.connect(url,autocommit=True) as c: + c.execute('DROP SCHEMA public CASCADE; CREATE SCHEMA public') + c.execute(Path('migrations/001_initial.sql').read_text()) + c.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES (md5('user')::uuid,'bench_user','Benchmark','synthetic-not-a-login')") + c.execute("INSERT INTO chats(id,title) SELECT md5('chat'||n)::uuid,'Benchmark '||n FROM generate_series(1,3) n") + c.execute("INSERT INTO members SELECT id,md5('user')::uuid FROM chats") + c.execute("INSERT INTO messages(id,chat_id,sender_id,created_at,text) SELECT md5(n::text)::uuid,md5('chat'||CASE WHEN n<=100000 THEN 1 WHEN n<=115000 THEN 2 ELSE 3 END)::uuid,md5('user')::uuid, '2026-01-01'::timestamptz+n*interval '1 millisecond',repeat('x',100) FROM generate_series(1,120000) n") + c.execute('DROP INDEX messages_history') + c.execute('ANALYZE messages') + for variant,ddl in [('chat_only','CREATE INDEX candidate ON messages(chat_id)'),('composite','CREATE INDEX candidate ON messages(chat_id,created_at,id)')]: + c.execute(ddl); c.execute('ANALYZE messages') + plans={} + for chat,offset in [(1,90000),(2,110000),(3,119000)]: + for kind in ['keyset','offset']: + q="SELECT * FROM messages WHERE chat_id=md5('chat'||%s::text)::uuid" + params=[chat] + if kind=='keyset': q+=" AND (created_at,id)>('2026-01-01'::timestamptz+%s*interval '1 millisecond',md5(%s::text)::uuid)"; params += [offset,offset] + q+=' ORDER BY created_at,id LIMIT 50' + if kind=='offset': q+=' OFFSET %s'; params += [offset-({1:0,2:100000,3:115000}[chat])] + for _ in range(2): c.execute(q,params).fetchall() + runs=[c.execute('EXPLAIN (ANALYZE,BUFFERS,FORMAT JSON) '+q,params).fetchone()[0][0] for _ in range(5)] + plans[str(chat)+'_'+kind]={'execution_ms':[r['Execution Time'] for r in runs],'plan':runs[-1]} + summary['plans'][variant]=plans + summary['write'][variant]={'index_bytes':c.execute("SELECT pg_relation_size('candidate')").fetchone()[0],'runs':[]} + for rep in range(5): + with c.transaction(): + start=time.perf_counter() + c.execute("INSERT INTO messages(id,chat_id,sender_id,created_at,text) SELECT md5(n::text)::uuid,md5('chat1')::uuid,md5('user')::uuid,'2027-01-01'::timestamptz,repeat('w',100) FROM generate_series(200001,205000) n") + elapsed=(time.perf_counter()-start)*1000 + summary['write'][variant]['runs'].append({'insert_5000_ms':elapsed}) + c.execute("DELETE FROM messages WHERE created_at>='2027-01-01'") + c.execute('DROP INDEX candidate') + c.execute('CREATE INDEX candidate ON messages(chat_id,created_at,id)') + summary['count']=c.execute('SELECT count(*) FROM messages').fetchone()[0] + summary['samples']=c.execute("SELECT id::text,chat_id::text,sender_id::text,created_at::text,text FROM messages WHERE id IN (SELECT md5(n::text)::uuid FROM unnest(ARRAY[1,50000,100000,110000,120000]) n) ORDER BY id").fetchall() + summary['postgres_version']=c.execute('SELECT version()').fetchone()[0] +print(json.dumps(summary,ensure_ascii=False,indent=2)) diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..c8958921 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,7 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +mkdir -p evidence +python3 scripts/container_state.py > evidence/restart-before.json +docker compose restart api postgres redis >/dev/null +python3 scripts/container_state.py > evidence/restart-after.json -- 2.54.0 From 90f58162a6c7f9cb726f7bf47e078419dcfbbd8f Mon Sep 17 00:00:00 2001 From: Alina Dykhanova Date: Thu, 22 Oct 2026 17:20:36 +0300 Subject: [PATCH 2/2] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=20=D0=BE=D1=82=D1=87=D0=B5=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- REPORT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/REPORT.md b/REPORT.md index 42652050..522e4658 100644 --- a/REPORT.md +++ b/REPORT.md @@ -2,7 +2,7 @@ - Автор: Алина Дыханова БВТ2301 - Целевая оценка: **5**. Трек 2: **план запроса и восстановление**. Выполнены также критерии уровней 3 и 4. -- Основа: skeleton commit `65003b6`. Реализация находится в рабочем дереве; commit/PR с решением пока не опубликован. +- Commit/PR: - Библиотеки: Python 3.12.12, Flask 3.1.2, Gunicorn 23.0.0, psycopg 3.2.10, psycopg-pool 3.3.3, Redis client 6.4.0, argon2-cffi 25.1.0. Полный lock — [requirements.lock](requirements.lock). ## Запуск из чистого clone -- 2.54.0