ЛР 2: PostgreSQL, сессии и Valkey — на 4
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
Date: 2026-10-23, Europe/Moscow
|
||||
Commands: git branch/status/diff --check/check-ignore/ls-files (read-only); exact local secret scan; HTTP readiness.
|
||||
PASS: existing branch solution/bvt2301-gamayunov; no Git mutations performed.
|
||||
PASS: teacher README/COURSE/CONTRIBUTING/contracts/tests/Makefile/examples/templates/original CI unchanged.
|
||||
PASS: lab1-reference working tree is clean; used for reading only.
|
||||
PASS: ignored local files: .env, secrets/postgres_password, secrets/database_url, secrets/cache_url
|
||||
PASS: exact generated PostgreSQL secret and private key markers absent from all tracked/untracked-to-submit files; secrets were not printed.
|
||||
PASS: git diff --check and own source trailing-whitespace check.
|
||||
PASS: host http://127.0.0.1:8080/health/ready = 200 application/json; X-Request-Id present.
|
||||
All grade 3 and 4 criteria: PASS locally (see REPORT.md per-criterion mapping). Remote CI, commit/push/PR: not executed.
|
||||
PASS: final Compose/application CI YAML, all application/student Python, all shell scripts parse; make check validate repeated after documentation changes.
|
||||
Main api/postgres/valkey left running; auxiliary api-expiry stopped after tests.
|
||||
Exact changed-file list: evidence/changed-files.txt. Only REPORT.md modified among tracked skeleton files; new source files are untracked and unstaged.
|
||||
|
||||
Release audit supersedes this earlier summary: evidence/release-audit.md; latest source/build/tests: evidence/release/.
|
||||
@@ -0,0 +1,12 @@
|
||||
Fresh named volumes mtusi-lab2-bootstrap_postgres_data and mtusi-lab2-bootstrap_valkey_data were created by Compose on 2026-10-23.
|
||||
Command: API_PORT=18080 docker compose -p mtusi-lab2-bootstrap --env-file .env up -d --wait api
|
||||
001_initial.sql
|
||||
0
|
||||
0
|
||||
0
|
||||
python3 tests/smoke.py --base-url "http://api:8080"
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
|
||||
Linux init-env.sh was also executed twice in /tmp/bootstrap inside an isolated tools container.
|
||||
Observed secret directory mode=700, secret file mode=444; no credentials were printed.
|
||||
Bootstrap containers were stopped and removed with compose down; both named volumes were preserved.
|
||||
@@ -0,0 +1,9 @@
|
||||
Historical build before release-audit; current code/build proof: evidence/release/build.txt.
|
||||
Command: docker compose build api; docker compose --profile test up -d --wait api api-expiry
|
||||
Final running image:
|
||||
CONTAINER REPOSITORY TAG PLATFORM IMAGE ID SIZE CREATED
|
||||
mtusi-lab2-api-1 mtusi-lab2-api local linux/amd64 d17dea09ac6a 56.7MB About a minute ago
|
||||
mtusi-lab2-api-expiry-1 mtusi-lab2-api local linux/amd64 d17dea09ac6a 56.7MB About a minute ago
|
||||
PASS: running API image equals the current locally built image: sha256:d17dea09ac6adf3ab6e4e9ca0e12286826aba878edd7110e07b1234546a4f713
|
||||
PASS: SHA-256 of every src/*.py and migrations/*.sql matches the actual running container.
|
||||
{"migrations/001_initial.sql": "5154c63cca9b5068821e5270b3d8dbc14c542b88ae5ce65422d72874118a14e5", "src/__init__.py": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b", "src/cache.py": "0f92c67b59f57a1ac5ee44d99bb5d992efa208e1d3c6fa44e5b537b913be926c", "src/config.py": "7d18c6b03d1130ca633055599f13a002d05a722a86427f2c47700b65908223b5", "src/db.py": "d21da56f3551eef2fb7e930a184264a0731eef8d6eb531929e611f8fa3df4d47", "src/errors.py": "8906150236b7b90081878cd7730964e4dee981897798a37c2a3441c3705cadc0", "src/main.py": "5c36a8dc3fa3dc84c69ebbfee94d1536619ee090da8d5d49931a99bfbd25f436", "src/models.py": "7fa8f35f7fd64e3b7ae6e1c2e4a621cbddb8ed6e4ddf595a71abcb0fe3958863", "src/pagination.py": "bba67fcab7b6ead93c4848319feccecd5e608287f0e983981b04ce0e1ca4b8f3", "src/security.py": "43a8b463e41053fe8ab125570eb7e93bbbbc13e4f5b6599457cbec22c00dc4d6", "src/store.py": "dc8c9512979dba9d54617e27b19beb40ca45972dd8f294263144bb2de716c548"}
|
||||
@@ -0,0 +1,62 @@
|
||||
Modified tracked files:
|
||||
REPORT.md
|
||||
New files (untracked, not staged):
|
||||
.gitattributes
|
||||
.github/workflows/application.yml
|
||||
Dockerfile
|
||||
PR_DRAFT.md
|
||||
compose.yaml
|
||||
evidence/audit.txt
|
||||
evidence/bootstrap.txt
|
||||
evidence/build.txt
|
||||
evidence/changed-files.txt
|
||||
evidence/checks.txt
|
||||
evidence/environment.txt
|
||||
evidence/expiry.txt
|
||||
evidence/explain.txt
|
||||
evidence/failures.txt
|
||||
evidence/load-resources.txt
|
||||
evidence/load.json
|
||||
evidence/migrations.txt
|
||||
evidence/persistence.txt
|
||||
evidence/release-audit.md
|
||||
evidence/release/bootstrap.txt
|
||||
evidence/release/build.txt
|
||||
evidence/release/checks.txt
|
||||
evidence/release/expiry.txt
|
||||
evidence/release/explain.txt
|
||||
evidence/release/failures.txt
|
||||
evidence/release/host-smoke.txt
|
||||
evidence/release/migrations.txt
|
||||
evidence/release/persistence.txt
|
||||
evidence/release/repository.txt
|
||||
evidence/release/session-persistence.txt
|
||||
evidence/release/smoke.txt
|
||||
evidence/release/student.txt
|
||||
evidence/requirements.md
|
||||
evidence/schema.txt
|
||||
evidence/session-persistence.txt
|
||||
evidence/smoke.txt
|
||||
evidence/student.txt
|
||||
infra/Dockerfile.tools
|
||||
infra/requirements-tools.lock
|
||||
migrations/001_initial.sql
|
||||
requirements.lock
|
||||
requirements.txt
|
||||
scripts/init-env.ps1
|
||||
scripts/init-env.sh
|
||||
scripts/restart.sh
|
||||
scripts/run-checks.sh
|
||||
src/__init__.py
|
||||
src/cache.py
|
||||
src/config.py
|
||||
src/db.py
|
||||
src/errors.py
|
||||
src/main.py
|
||||
src/models.py
|
||||
src/pagination.py
|
||||
src/security.py
|
||||
src/store.py
|
||||
student-tests/README.md
|
||||
student-tests/grade4.py
|
||||
student-tests/load_measure.py
|
||||
@@ -0,0 +1,4 @@
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
python3 scripts/validate_openapi.py
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
@@ -0,0 +1,13 @@
|
||||
Date: 2026-10-23, Europe/Moscow; local unstaged solution/bvt2301-gamayunov
|
||||
CPU: Intel(R) Core(TM) i5-6300U CPU @ 2.40GHz; cores=2; logical=4
|
||||
Host RAM bytes: 17004175360
|
||||
Docker client=29.5.2 server=29.5.2
|
||||
Docker Compose version v5.1.3
|
||||
Docker VM: CPUs=4 RAM bytes=8242409472 OS=Docker Desktop (containerized)
|
||||
Limits: api 1 CPU / 512MiB; PostgreSQL 1 CPU / 512MiB; Valkey 0.5 CPU / 128MiB; tools 1 CPU / 512MiB. api-expiry: same as api.
|
||||
Python 3.12.10
|
||||
uid=10001(appuser) gid=10001(appuser) groups=10001(appuser)
|
||||
Valkey server v=8.0.2 sha=00000000:0 malloc=jemalloc-5.3.0 bits=64 build=6559adb0eb9ba245
|
||||
Python 3.12.15
|
||||
GNU Make 4.4.1
|
||||
Docker Compose version v2.33.0
|
||||
@@ -0,0 +1 @@
|
||||
PASS: SESSION_TTL_SECONDS=2: immediate authentication succeeds; after 2.21s cached profile cannot bypass expiry/logout
|
||||
@@ -0,0 +1,33 @@
|
||||
Rows in test chat: 10000
|
||||
|
||||
Position: 0
|
||||
Limit (cost=0.41..10.95 rows=51 width=70) (actual time=0.061..0.085 rows=51 loops=1)
|
||||
Buffers: shared hit=4
|
||||
-> Index Scan using messages_history on messages (cost=0.41..2063.98 rows=9985 width=70) (actual time=0.059..0.076 rows=51 loops=1)
|
||||
Index Cond: (chat_id = '969e1211-e475-4545-bd15-7e56dc71896d'::uuid)
|
||||
Buffers: shared hit=4
|
||||
Planning:
|
||||
Buffers: shared hit=19
|
||||
Planning Time: 0.220 ms
|
||||
Execution Time: 0.148 ms
|
||||
|
||||
Position: 5000
|
||||
Limit (cost=0.41..17.20 rows=51 width=70) (actual time=0.013..0.058 rows=51 loops=1)
|
||||
Buffers: shared hit=5
|
||||
-> Index Scan using messages_history on messages (cost=0.41..1741.06 rows=5288 width=70) (actual time=0.012..0.050 rows=51 loops=1)
|
||||
Index Cond: ((chat_id = '969e1211-e475-4545-bd15-7e56dc71896d'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.005001+00'::timestamp with time zone, 'fa66b073-e248-4fb4-9603-7515b64b598e'::uuid)))
|
||||
Buffers: shared hit=5
|
||||
Planning Time: 0.107 ms
|
||||
Execution Time: 0.104 ms
|
||||
|
||||
Position: 9900
|
||||
Limit (cost=0.41..94.31 rows=51 width=70) (actual time=0.017..0.029 rows=51 loops=1)
|
||||
Buffers: shared hit=4
|
||||
-> Index Scan using messages_history on messages (cost=0.41..1324.25 rows=719 width=70) (actual time=0.016..0.025 rows=51 loops=1)
|
||||
Index Cond: ((chat_id = '969e1211-e475-4545-bd15-7e56dc71896d'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.009901+00'::timestamp with time zone, 'b484fd5f-6223-4f33-9f32-7d154df937da'::uuid)))
|
||||
Buffers: shared hit=4
|
||||
Planning Time: 0.087 ms
|
||||
Execution Time: 0.046 ms
|
||||
PostgreSQL: 16.8 (Debian 16.8-1.pgdg120+1)
|
||||
Durability: on on
|
||||
PASS: actual EXPLAIN ANALYZE BUFFERS at first/middle/tail; API traversal 10000 rows, 100 pages, 1.851s
|
||||
@@ -0,0 +1,4 @@
|
||||
PASS: Valkey stopped: ready=200, authenticated read/write via PG, unknown/missing/revoked=401, outsider=404; scenario 0.374s
|
||||
PASS: PostgreSQL stopped: ready/auth/write=503, live=200, no credentials=401, no cached authentication; scenario 0.063s
|
||||
PASS: PostgreSQL recovery 2.811s, same valid token/data survive, revoked token remains revoked, rejected write absent
|
||||
PASS: all 22 HTTP requests bounded below 4.5s; maximum 0.274s
|
||||
@@ -0,0 +1,10 @@
|
||||
Command: python3 tests/load.py --base-url http://api:8080 --duration 15 --concurrency 4 --output evidence/load.json
|
||||
Start UTC: 2026-10-23T14:05:18.741681+00:00
|
||||
Sample UTC: 2026-10-23T14:05:23.743063+00:00
|
||||
End UTC: 2026-10-23T14:05:35.228415+00:00
|
||||
Warm-up: completed functional checks; no separate timed warm-up. One run.
|
||||
Dataset: dedicated new load chat starts empty; total PG message rows before=32149 after=33232
|
||||
One live docker stats sample during load; neither average nor peak.
|
||||
mtusi-lab2-api-1 CPU=99.56% Memory=62.46MiB / 512MiB
|
||||
mtusi-lab2-postgres-1 CPU=11.76% Memory=39.64MiB / 512MiB
|
||||
mtusi-lab2-valkey-1 CPU=7.36% Memory=3.77MiB / 128MiB
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 2,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 15.0,
|
||||
"elapsed_seconds": 15.3,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 1083,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 70.786,
|
||||
"successful_latency_ms": {
|
||||
"p50": 50.826,
|
||||
"p95": 98.821,
|
||||
"p99": 109.824
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
PASS: versioned migrations applied (already applied versions skipped)
|
||||
PASS: versioned migrations applied (already applied versions skipped)
|
||||
PASS: two repeated migrations; all table counts and absolute session expiries unchanged: {'users': 50, 'chats': 18, 'chat_members': 30, 'messages': 22146, 'sessions': 39, 'schema_migrations': 1}
|
||||
@@ -0,0 +1,9 @@
|
||||
/mtusi-lab2-api-1 2026-10-23T14:02:23.376971704Z sha256:d17dea09ac6adf3ab6e4e9ca0e12286826aba878edd7110e07b1234546a4f713
|
||||
/mtusi-lab2-postgres-1 2026-10-23T14:03:17.170328016Z sha256:301bcb60b8a3ee4ab7e147932723e3abd1cef53516ce5210b39fd9fe5e3602ae
|
||||
/mtusi-lab2-valkey-1 2026-10-23T14:03:15.90085233Z sha256:752ba000a58bc8925d11ee863a39b5225617cd2cb3dbc9ec8ac65268b65ebb6d
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://api: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.
|
||||
/mtusi-lab2-api-1 2026-10-23T14:03:22.87874847Z sha256:d17dea09ac6adf3ab6e4e9ca0e12286826aba878edd7110e07b1234546a4f713
|
||||
/mtusi-lab2-postgres-1 2026-10-23T14:03:22.522723549Z sha256:301bcb60b8a3ee4ab7e147932723e3abd1cef53516ce5210b39fd9fe5e3602ae
|
||||
/mtusi-lab2-valkey-1 2026-10-23T14:03:22.343578822Z sha256:752ba000a58bc8925d11ee863a39b5225617cd2cb3dbc9ec8ac65268b65ebb6d
|
||||
@@ -0,0 +1,56 @@
|
||||
# Финальный release-audit — 23.10.2026 Europe/Moscow
|
||||
|
||||
Вердикт: **READY FOR PR**. Изменения остаются unstaged/uncommitted; ветка `solution/bvt2301-gamayunov`, HEAD skeleton `65003b6`. Оценка 4: весь уровень 3 + все четыре пункта уровня 4. Удалённый CI и PR не выполнялись.
|
||||
|
||||
Проверка заново опиралась на README/CONTRIBUTING/contracts/OpenAPI, исходники и реально запущенный чистый стенд; прежние PASS не принимались как единственное доказательство.
|
||||
|
||||
| Оригинальный критерий | Проверенный код / решение | Реальная проверка / доказательство | Итог |
|
||||
| --- | --- | --- | --- |
|
||||
| 3.1: минимум ЛР1 + сохранность данных/действующей сессии | main/store/models/pagination, PG volume, restart всех stores | release/smoke.txt, persistence.txt, session-persistence.txt; StartedAt до/после, прежний token, unchanged expires_at | PASS |
|
||||
| 3.2: PG users/chats/members/messages, PK/FK/UNIQUE, миграции с нуля, атомарный чат | 001_initial.sql, migrate advisory lock, один connection transaction | release/bootstrap.txt: сначала 0 users/chats/messages; core: реальный FK rollback после INSERT родителя; migrations.txt | PASS |
|
||||
| 3.3: Basic только login; Bearer/expiry/logout; X-User-Id не авторизует; KDF | security.py, require_user проверяет PG каждый запрос; Argon2id; opaque 256-bit token, только hash в PG | release/student.txt, smoke.txt, expiry.txt, session-persistence.txt; Unicode password 128 code points с ':' | PASS |
|
||||
| 3.4: make test/test-persistence, повторяемые миграции, secrets/volumes вне Git | исходные Makefile/tests сохранены, restart без удаления данных | release/checks.txt, smoke.txt, persistence.txt, migrations.txt; Git ignore + private value scan | PASS |
|
||||
| 4.1: реальный Redis/Valkey, TTL, истина/инвалидация/persistence | immutable public user profile cache, TTL60 без sliding; PG sessions остаются источником истины; AOF необязателен для корректности | core: INFO hits, key/TTL/expiry/refill/logout; failures: потеря Valkey безопасна | PASS |
|
||||
| 4.2: параметры SQL, bounded pool/timeouts, username race/rollback | все значения psycopg parameters; max8/wait2/connect2/statement2; FK transaction | core: 12 регистраций = 1×201 + 11×409, rollback/counts; failures bounded requests | PASS |
|
||||
| 4.3: индекс истории + EXPLAIN ANALYZE BUFFERS >=10000, без полного scan на страницу | messages_history(chat_id,created_at,id), tuple >, ORDER BY, LIMIT n+1 | release/explain.txt: 10000 строк, Index Scan в 3 позициях; 100 HTTP страниц без потерь/повторов | PASS |
|
||||
| 4.4: auto expiry/logout/wrong password/Redis+DB outage, безопасная bounded ошибка | PG auth всегда перед профилем; cache fallback + budget 250ms | release/expiry.txt, student.txt, failures.txt; реальные stop/start, max HTTP 0.261 s (<4.5), без анонимного доверия | PASS |
|
||||
|
||||
## Найдено и исправлено
|
||||
|
||||
- `U+0000` в display_name/title/text раньше проходил валидатор, затем отказ PostgreSQL превращался в 503. Три проверки входных строк теперь дают 400 invalid_request; regression assertions добавлены в core. В чистом новом процессе/БД подтверждено: все три поля 400, ready остаётся 200. Архитектура/SQL-схема не менялись.
|
||||
- Новый Git mode нельзя получить через `.gitattributes` или Windows chmod: `core.filemode=false`, три новых .sh ещё не находятся в индексе. Исправлен вводящий в заблуждение комментарий restart.sh; ниже даны точные команды для mode 100755. Агент их **не выполнял**.
|
||||
- `src/errors.py` приведён из CRLF к LF согласно .gitattributes, чтобы Git-кандидат и Linux-образ совпадали побайтно. Это только окончания строк.
|
||||
- REPORT/PR_DRAFT теперь ссылаются на свежий release-набор; старый load остаётся историческим замером образа d17dea09ac6a до валидации NUL. Нагрузка повторно не запускалась. Старый build.txt явно помечен историческим.
|
||||
|
||||
## Чистый запуск
|
||||
|
||||
Поскольку новые файлы ещё не committed и Git-записи запрещены, настоящий новый checkout этого решения невозможен. Экспортированы ровно tracked + untracked/non-ignored файлы-кандидаты (`git ls-files --cached --others --exclude-standard`), без .git/.env/secrets. Нормализованы окончания *.sh/*.py/*.sql согласно .gitattributes; для трёх новых .sh применены ожидаемые после staging права 0755. Исходный преподавательский restart.example.sh уже имеет Git mode 100755 и сохранён.
|
||||
|
||||
Экспорт помещён на новый Linux Docker volume mtusi-lab2-release-checkout, собран через исходный compose.yaml; создан отдельный проект mtusi-lab2-release с пустыми PostgreSQL/Valkey volumes и API_PORT=18082. Никакие teacher/source/service файлы не подменялись. Проверены:
|
||||
|
||||
1. init-env.sh дважды, локальные секреты с 700/444; non-root API UID10001 успешно читает mounted secrets.
|
||||
2. compose config --quiet; profile test build; up -d --wait; 001_initial.sql и нули users/chats/messages до тестов.
|
||||
3. scripts/run-checks.sh: make check/validate/test, core, expiry=2, повторные миграции, короткий EXPLAIN-тест на 10000, реальные stop/start Valkey/PG, публичный make test-persistence с ACTION_SCRIPT=scripts/restart.sh, неизменность expires_at.
|
||||
4. Раздельные результаты скопированы в evidence/release/. Полный нагрузочный benchmark не повторялся.
|
||||
5. Аудит-стенд остановлен через compose down без --volumes. Основной API обновлён тем же исправленным образом; повторный public smoke на исходной PG прошёл (release/host-smoke.txt). Все src/*.py и migrations/*.sql совпали с работающим контейнером по SHA-256 (release/build.txt).
|
||||
|
||||
COMPOSE_PROJECT_NAME=mtusi-lab2-release передавался и в tools, чтобы fault/restart hooks обращались только к изолированному проекту. Обычная инструкция REPORT использует имя mtusi-lab2 и не требует этого override.
|
||||
|
||||
## Репозиторий и staging
|
||||
|
||||
Teacher README/COURSE/CONTRIBUTING/contracts/tests/Makefile/.env.example/original CI/PR template не менялись относительно HEAD. `.env`, `secrets/`, volumes/, data/, *.pyc и __pycache__ исключены; Docker named volumes находятся вне checkout. Новые файлы перечислены в changed-files.txt; временный экспорт не находится внутри Git-репозитория. Проверены реальные значения приватных secret-файлов в кандидатах, значения/токены в evidence не публиковались. Индекс пуст; запрещённых Git-операций не выполнялось.
|
||||
|
||||
Команды ниже выполняет автор после проверки. Первая команда намеренно перечисляет только файлы решения; вторая явно задаёт mode новым shell-скриптам. После неё ожидаются ровно три строки с mode 100755. До staging такого mode в Git для untracked файлов ещё нет.
|
||||
|
||||
```sh
|
||||
git add -- .gitattributes .github/workflows/application.yml Dockerfile compose.yaml requirements.txt requirements.lock src migrations student-tests infra/Dockerfile.tools infra/requirements-tools.lock scripts/init-env.ps1 REPORT.md PR_DRAFT.md evidence
|
||||
git add --chmod=+x -- scripts/init-env.sh scripts/restart.sh scripts/run-checks.sh
|
||||
git diff --cached --check
|
||||
git ls-files --stage -- scripts/init-env.sh scripts/restart.sh scripts/run-checks.sh
|
||||
git diff --cached --stat
|
||||
git status --short
|
||||
git commit -m "ЛР 2: PostgreSQL, сессии и Valkey — на 4"
|
||||
git push -u origin solution/bvt2301-gamayunov
|
||||
```
|
||||
|
||||
Заголовок PR строго по CONTRIBUTING: **ЛР 2 — БВТ2301 — Гамаюнов — на 4**. Тело — PR_DRAFT.md. Базовый репозиторий/ветку выбрать по выдаче преподавателя; автоматически они не выбирались. После ручной публикации дополнить поле Commit/PR в REPORT.md (при необходимости отдельным последующим изменением). Удалённый CI не проверялся; это не подменяет выполненные локальные проверки.
|
||||
@@ -0,0 +1,12 @@
|
||||
Fresh Linux export; no inherited secrets/data. Commands: init-env.sh twice; compose profile test build/up --wait; run-checks.sh.
|
||||
700 secrets
|
||||
444 secrets/postgres_password
|
||||
444 secrets/database_url
|
||||
444 secrets/cache_url
|
||||
755 scripts/init-env.sh
|
||||
755 scripts/restart.sh
|
||||
755 scripts/run-checks.sh
|
||||
001_initial.sql
|
||||
0
|
||||
0
|
||||
0
|
||||
@@ -0,0 +1,5 @@
|
||||
Release audit 2026-10-23 Europe/Moscow. Commands: clean Linux export; compose --profile test build/up; scripts/run-checks.sh; host compose up --wait api; public smoke.
|
||||
Running image=sha256:cbe9af6839830fd268490f97f97c9eae922339b03a6f9983914a330355a27568 configured=mtusi-lab2-api:local
|
||||
Built image=sha256:cbe9af6839830fd268490f97f97c9eae922339b03a6f9983914a330355a27568
|
||||
PASS: all src/*.py and migrations/*.sql hashes in actual updated host API equal working tree (LF, as required by .gitattributes).
|
||||
{"migrations/001_initial.sql": "5154c63cca9b5068821e5270b3d8dbc14c542b88ae5ce65422d72874118a14e5", "src/__init__.py": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b", "src/cache.py": "0f92c67b59f57a1ac5ee44d99bb5d992efa208e1d3c6fa44e5b537b913be926c", "src/config.py": "7d18c6b03d1130ca633055599f13a002d05a722a86427f2c47700b65908223b5", "src/db.py": "d21da56f3551eef2fb7e930a184264a0731eef8d6eb531929e611f8fa3df4d47", "src/errors.py": "1561923a04ed06088ab23accf1c60429187b7fc8a468082ab0cdb2ccd0aafa53", "src/main.py": "5c36a8dc3fa3dc84c69ebbfee94d1536619ee090da8d5d49931a99bfbd25f436", "src/models.py": "886786c4fa8c962c3e619e11fb0ec05870887f8ebef1c3fc7790816947f8859c", "src/pagination.py": "bba67fcab7b6ead93c4848319feccecd5e608287f0e983981b04ce0e1ca4b8f3", "src/security.py": "43a8b463e41053fe8ab125570eb7e93bbbbc13e4f5b6599457cbec22c00dc4d6", "src/store.py": "dc8c9512979dba9d54617e27b19beb40ca45972dd8f294263144bb2de716c548"}
|
||||
@@ -0,0 +1,4 @@
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
python3 scripts/validate_openapi.py
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
@@ -0,0 +1 @@
|
||||
PASS: SESSION_TTL_SECONDS=2: immediate authentication succeeds; after 2.21s cached profile cannot bypass expiry/logout
|
||||
@@ -0,0 +1,33 @@
|
||||
Rows in test chat: 10000
|
||||
|
||||
Position: 0
|
||||
Limit (cost=0.29..4.17 rows=51 width=70) (actual time=0.013..0.029 rows=51 loops=1)
|
||||
Buffers: shared hit=3
|
||||
-> Index Scan using messages_history on messages (cost=0.29..762.03 rows=10000 width=70) (actual time=0.012..0.022 rows=51 loops=1)
|
||||
Index Cond: (chat_id = 'afb33e87-5203-44cd-8aaa-6352dd299bff'::uuid)
|
||||
Buffers: shared hit=3
|
||||
Planning:
|
||||
Buffers: shared hit=20
|
||||
Planning Time: 0.229 ms
|
||||
Execution Time: 0.049 ms
|
||||
|
||||
Position: 5000
|
||||
Limit (cost=0.29..5.43 rows=51 width=70) (actual time=0.011..0.023 rows=51 loops=1)
|
||||
Buffers: shared hit=4
|
||||
-> Index Scan using messages_history on messages (cost=0.29..503.22 rows=4981 width=70) (actual time=0.010..0.018 rows=51 loops=1)
|
||||
Index Cond: ((chat_id = 'afb33e87-5203-44cd-8aaa-6352dd299bff'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.005001+00'::timestamp with time zone, '0c66c126-2dbf-49ff-a50d-6ffe6d9b9d0c'::uuid)))
|
||||
Buffers: shared hit=4
|
||||
Planning Time: 0.146 ms
|
||||
Execution Time: 0.053 ms
|
||||
|
||||
Position: 9900
|
||||
Limit (cost=0.29..68.37 rows=51 width=70) (actual time=0.086..0.104 rows=51 loops=1)
|
||||
Buffers: shared hit=3
|
||||
-> Index Scan using messages_history on messages (cost=0.29..135.12 rows=101 width=70) (actual time=0.085..0.097 rows=51 loops=1)
|
||||
Index Cond: ((chat_id = 'afb33e87-5203-44cd-8aaa-6352dd299bff'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.009901+00'::timestamp with time zone, '1f3e9d78-d453-4240-8e54-585c7ee9e9a6'::uuid)))
|
||||
Buffers: shared hit=3
|
||||
Planning Time: 0.150 ms
|
||||
Execution Time: 0.131 ms
|
||||
PostgreSQL: 16.8 (Debian 16.8-1.pgdg120+1)
|
||||
Durability: on on
|
||||
PASS: actual EXPLAIN ANALYZE BUFFERS at first/middle/tail; API traversal 10000 rows, 100 pages, 1.907s
|
||||
@@ -0,0 +1,4 @@
|
||||
PASS: Valkey stopped: ready=200, authenticated read/write via PG, unknown/missing/revoked=401, outsider=404; scenario 0.363s
|
||||
PASS: PostgreSQL stopped: ready/auth/write=503, live=200, no credentials=401, no cached authentication; scenario 0.056s
|
||||
PASS: PostgreSQL recovery 2.737s, same valid token/data survive, revoked token remains revoked, rejected write absent
|
||||
PASS: all 22 HTTP requests bounded below 4.5s; maximum 0.261s
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 tests/smoke.py --base-url "http://api:8080"
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,3 @@
|
||||
PASS: versioned migrations applied (already applied versions skipped)
|
||||
PASS: versioned migrations applied (already applied versions skipped)
|
||||
PASS: two repeated migrations; all table counts and absolute session expiries unchanged: {'users': 9, 'chats': 3, 'chat_members': 5, 'messages': 43, 'sessions': 6, 'schema_migrations': 1}
|
||||
@@ -0,0 +1,9 @@
|
||||
/mtusi-lab2-release-api-1 2026-10-23T14:41:25.192595559Z sha256:cbe9af6839830fd268490f97f97c9eae922339b03a6f9983914a330355a27568
|
||||
/mtusi-lab2-release-postgres-1 2026-10-23T14:43:17.90804068Z sha256:301bcb60b8a3ee4ab7e147932723e3abd1cef53516ce5210b39fd9fe5e3602ae
|
||||
/mtusi-lab2-release-valkey-1 2026-10-23T14:43:16.720128385Z sha256:752ba000a58bc8925d11ee863a39b5225617cd2cb3dbc9ec8ac65268b65ebb6d
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://api: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.
|
||||
/mtusi-lab2-release-api-1 2026-10-23T14:43:23.222109188Z sha256:cbe9af6839830fd268490f97f97c9eae922339b03a6f9983914a330355a27568
|
||||
/mtusi-lab2-release-postgres-1 2026-10-23T14:43:22.82384855Z sha256:301bcb60b8a3ee4ab7e147932723e3abd1cef53516ce5210b39fd9fe5e3602ae
|
||||
/mtusi-lab2-release-valkey-1 2026-10-23T14:43:22.700262536Z sha256:752ba000a58bc8925d11ee863a39b5225617cd2cb3dbc9ec8ac65268b65ebb6d
|
||||
@@ -0,0 +1,6 @@
|
||||
Release audit repository checks, 2026-10-23 Europe/Moscow.
|
||||
PASS: correct existing branch; no changes to teacher files; index empty; git diff --check.
|
||||
PASS: exactly three new shell scripts, shebang and LF verified. They remain untracked; explicit git add --chmod=+x required to set Git mode 100755.
|
||||
PASS: REPORT evidence references resolve; changed-files manifest refreshed.
|
||||
PASS: no local/release private secret values, private keys, ignored state, or files >=1MiB in submission candidates
|
||||
PASS: Python/Compose/CI parse; existing load summary arithmetic/order correct; historical build provenance explicit
|
||||
@@ -0,0 +1 @@
|
||||
PASS: same opaque token authenticates after all services restart; absolute PG expires_at unchanged; only 32-byte token hash stored
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 tests/smoke.py --base-url "http://api:8080"
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,7 @@
|
||||
PASS: concurrent same username: 12 requests, 1 x 201, 11 x 409
|
||||
PASS: unknown member FK after parent INSERT rolls back chat and memberships; duplicate/missing owner -> 400
|
||||
PASS: NUL in display_name/title/text -> 400; PostgreSQL readiness remains 200
|
||||
PASS: strict types/extra fields, malformed JSON, UUID, limits/cursors, blank/oversized text, outsider isolation
|
||||
PASS: 40 concurrent writes; tied timestamp UUID ordering; complete keyset traversal, scoped cursors, changing limit, read-after-write
|
||||
PASS: malformed Basic, wrong/unknown credentials uniform 401, X-User-Id ignored, 128-code-point UTF8 colon password, stored Argon2id
|
||||
PASS: real Valkey GET hits, TTL <=60 without sliding; expiry/refill; logout rejects cached profile and repeated logout
|
||||
@@ -0,0 +1,16 @@
|
||||
# Матрица требований (до реализации, 2026-10-23)
|
||||
|
||||
| Критерий преподавателя | Решение / файлы | Проверка | Evidence |
|
||||
| --- | --- | --- | --- |
|
||||
| 3: API ЛР1, Bearer, права, cursor | src/models.py, pagination.py из собственной ЛР1; main.py, store.py | make test + student-tests | smoke.txt, student.txt |
|
||||
| 3: PostgreSQL, PK/FK/UNIQUE, атомарный чат | migrations/001_initial.sql, src/db.py, store.py | с нуля; повтор миграций; ошибка FK после INSERT чата | migrations.txt, student.txt |
|
||||
| 3: password KDF, Basic только login, expiry/logout | Argon2id, SHA-256 случайного 256-bit token, PG sessions | негативные, expiry=2, logout | student.txt, expiry.txt |
|
||||
| 3: данные и сессии переживают все рестарты | PG named volume, restart.sh: api/postgres/valkey | make test-persistence, timestamps до/после | persistence.txt |
|
||||
| 3: check/test, секреты вне Git | Docker tools, .gitignore/.dockerignore | make check/validate/test, git diff | checks.txt, audit.txt |
|
||||
| 4: реальный Valkey с TTL | cache.py: immutable user profiles, PG truth, TTL 60; fail-open только кэш | cached key + TTL + hit; outage fallback | student.txt, failures.txt |
|
||||
| 4: параметры, bounded pool/timeouts, гонка/rollback | psycopg, pool max8/wait2, SQL timeout2s | concurrent username + FK rollback | student.txt |
|
||||
| 4: индекс истории, EXPLAIN >=10000 | (chat_id,created_at,id), keyset LIMIT n+1 | 10000 синтетических записей, ANALYZE, реальный EXPLAIN | explain.txt |
|
||||
| 4: expiry/logout/wrong password/Redis/DB outage | student-tests, scripts | короткий TTL; stop/start только сервисов проекта | expiry.txt, failures.txt |
|
||||
|
||||
Не изменять README.md, COURSE.md, CONTRIBUTING.md, contracts/, tests/.
|
||||
ЛР1: переносятся только собственные models/pagination/errors; in-memory store заменяется PostgreSQL; X-User-Id заменяется сессиями.
|
||||
@@ -0,0 +1,30 @@
|
||||
Command: docker compose exec -T postgres psql -U messenger -d messenger -At -c <pg_constraint / pg_indexes diagnostics>
|
||||
chat_members|f|FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
chat_members|f|FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE
|
||||
chat_members|p|PRIMARY KEY (chat_id, user_id)
|
||||
chats|c|CHECK ((((char_length(title) >= 1) AND (char_length(title) <= 100)) AND (btrim(title) <> ''::text)))
|
||||
chats|p|PRIMARY KEY (id)
|
||||
messages|c|CHECK ((((char_length(text) >= 1) AND (char_length(text) <= 4000)) AND (btrim(text) <> ''::text)))
|
||||
messages|f|FOREIGN KEY (chat_id) REFERENCES chats(id)
|
||||
messages|f|FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
|
||||
messages|p|PRIMARY KEY (id)
|
||||
schema_migrations|p|PRIMARY KEY (version)
|
||||
sessions|c|CHECK ((octet_length(token_hash) = 32))
|
||||
sessions|c|CHECK ((expires_at > created_at))
|
||||
sessions|f|FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
sessions|p|PRIMARY KEY (token_hash)
|
||||
users|c|CHECK ((username ~ '^[a-z0-9_]{3,32}$'::text))
|
||||
users|c|CHECK ((((char_length(display_name) >= 1) AND (char_length(display_name) <= 100)) AND (btrim(display_name) <> ''::text)))
|
||||
users|p|PRIMARY KEY (id)
|
||||
users|u|UNIQUE (username)
|
||||
chat_members|chat_members_pkey|CREATE UNIQUE INDEX chat_members_pkey ON public.chat_members USING btree (chat_id, user_id)
|
||||
chat_members|chat_members_user|CREATE INDEX chat_members_user ON public.chat_members USING btree (user_id, chat_id)
|
||||
chats|chats_order|CREATE INDEX chats_order ON public.chats USING btree (created_at, id)
|
||||
chats|chats_pkey|CREATE UNIQUE INDEX chats_pkey ON public.chats USING btree (id)
|
||||
messages|messages_history|CREATE INDEX messages_history ON public.messages USING btree (chat_id, created_at, id)
|
||||
messages|messages_pkey|CREATE UNIQUE INDEX messages_pkey ON public.messages USING btree (id)
|
||||
schema_migrations|schema_migrations_pkey|CREATE UNIQUE INDEX schema_migrations_pkey ON public.schema_migrations USING btree (version)
|
||||
sessions|sessions_expiry|CREATE INDEX sessions_expiry ON public.sessions USING btree (expires_at)
|
||||
sessions|sessions_pkey|CREATE UNIQUE INDEX sessions_pkey ON public.sessions USING btree (token_hash)
|
||||
users|users_pkey|CREATE UNIQUE INDEX users_pkey ON public.users USING btree (id)
|
||||
users|users_username_key|CREATE UNIQUE INDEX users_username_key ON public.users USING btree (username)
|
||||
@@ -0,0 +1 @@
|
||||
PASS: same opaque token authenticates after all services restart; absolute PG expires_at unchanged; only 32-byte token hash stored
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 tests/smoke.py --base-url "http://api:8080"
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,6 @@
|
||||
PASS: concurrent same username: 12 requests, 1 x 201, 11 x 409
|
||||
PASS: unknown member FK after parent INSERT rolls back chat and memberships; duplicate/missing owner -> 400
|
||||
PASS: strict types/extra fields, malformed JSON, UUID, limits/cursors, blank/oversized text, outsider isolation
|
||||
PASS: 40 concurrent writes; tied timestamp UUID ordering; complete keyset traversal, scoped cursors, changing limit, read-after-write
|
||||
PASS: malformed Basic, wrong/unknown credentials uniform 401, X-User-Id ignored, 128-code-point UTF8 colon password, stored Argon2id
|
||||
PASS: real Valkey GET hits, TTL <=60 without sliding; expiry/refill; logout rejects cached profile and repeated logout
|
||||
Reference in New Issue
Block a user