feat: establish PostgreSQL lab2 baseline with benchmark tooling
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
# Что доказывает: решение собирается и проходит проверки из копии только
|
||||
# тех файлов, что попадут в git (как чистый clone): без .env, .venv,
|
||||
# кэшей и пробных меток стенда.
|
||||
# Дата (UTC): 2026-10-01T23:50:44Z — 2026-10-01T23:50:57Z
|
||||
# Окружение: macOS 26.6.2, Apple M3 Pro; Docker 29.8.1, Compose 5.5.1;
|
||||
# uv 0.12.17; python3 хоста 3.11.9
|
||||
# Как сделана копия: проект — не git-репозиторий, поэтому список файлов
|
||||
# взят у git с временным GIT_DIR вне проекта по правилам .gitignore:
|
||||
# git --git-dir=<tmp>/g init -q
|
||||
# git --git-dir=<tmp>/g --work-tree=. ls-files -co --exclude-standard -z \
|
||||
# | tar --null -T - -cf - | tar -xf - -C <tmp>/fresh
|
||||
# Код src_sha256 8a7e256c540af433. Временные пути заменены на <tmp>.
|
||||
|
||||
$ cd <tmp>/fresh; find . -type f | wc -l; test -e .env || echo "no .env"; test -e .venv || echo "no .venv"; ls evidence/bench 2>/dev/null || echo "no quick labels"
|
||||
119
|
||||
no .env
|
||||
no .venv
|
||||
no quick labels
|
||||
|
||||
$ make check
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
|
||||
$ uv sync --frozen
|
||||
...
|
||||
+ urllib3==2.8.0
|
||||
+ uvicorn==0.54.0
|
||||
|
||||
$ make lint
|
||||
...
|
||||
74 files already formatted
|
||||
uv run ruff check .
|
||||
All checks passed!
|
||||
|
||||
$ make requirements-check
|
||||
requirements.txt matches uv.lock
|
||||
|
||||
$ make validate PYTHON=.venv/bin/python
|
||||
.venv/bin/python scripts/validate_openapi.py
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
|
||||
$ make test-isolated
|
||||
[isolated] project=vladimirceva-lab2-isolated
|
||||
[isolated] build image
|
||||
[isolated] start postgres and valkey
|
||||
[isolated] migrations
|
||||
[isolated] ready: api=http://127.0.0.1:56737
|
||||
[isolated] make test
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
[isolated] pytest
|
||||
====================== 54 passed, 12 deselected in 4.60s =======================
|
||||
[isolated] cleanup
|
||||
[isolated] results: {'test': 0, 'student-test': 0}
|
||||
|
||||
# Из копии без локальных файлов: контракт и OpenAPI валидны, линтер чист,
|
||||
# requirements.txt совпадает с uv.lock, образ собирается, на пустой базе
|
||||
# smoke PASS и 54 passed. Отдельному стенду .env не нужен: пароли он
|
||||
# генерирует сам. Настоящий git clone — после публикации (REPORT.md).
|
||||
@@ -0,0 +1,186 @@
|
||||
# Что доказывает: стенд поднимается с нуля одной командой — миграции на
|
||||
# пустом volume до старта API, все сервисы healthy, публичный smoke PASS;
|
||||
# повторный запуск миграций ничего не меняет; схема с ключами,
|
||||
# ограничениями и индексами совпадает с описанием в коде.
|
||||
# Дата (UTC): 2026-10-01T23:14:47Z — 2026-10-01T23:15:05Z
|
||||
# Окружение: macOS 26.6.2, Apple M3 Pro; Docker 29.8.1, Compose 5.5.1,
|
||||
# VM Docker 12 CPU / 7,7 ГБ; PostgreSQL 18.6, Valkey 9.1.2
|
||||
# Стенд: compose-проект vladimirceva-lab2 (make up); код src_sha256
|
||||
# 8a7e256c540af433 (src/ и migrations/), git нет
|
||||
# Как повторить: команды ниже. `make wipe` удаляет учебные данные стенда.
|
||||
|
||||
$ echo yes | make wipe
|
||||
Container vladimirceva-lab2-api-1 Removed
|
||||
Container vladimirceva-lab2-migrate-1 Removed
|
||||
Container vladimirceva-lab2-valkey-1 Removed
|
||||
Container vladimirceva-lab2-postgres-1 Removed
|
||||
Volume vladimirceva-lab2_pgdata Removed
|
||||
Network vladimirceva-lab2_default Removed
|
||||
|
||||
$ make up
|
||||
...
|
||||
Container vladimirceva-lab2-valkey-1 Waiting
|
||||
Container vladimirceva-lab2-migrate-1 Waiting
|
||||
Container vladimirceva-lab2-migrate-1 Exited
|
||||
Container vladimirceva-lab2-valkey-1 Healthy
|
||||
Container vladimirceva-lab2-postgres-1 Healthy
|
||||
Container vladimirceva-lab2-api-1 Healthy
|
||||
|
||||
$ docker compose ps -a --format "table {{.Service}}\t{{.Status}}\t{{.Ports}}"
|
||||
SERVICE STATUS PORTS
|
||||
api Up 1 second (healthy) 127.0.0.1:8080->8080/tcp
|
||||
migrate Exited (0) 1 second ago
|
||||
postgres Up 4 seconds (healthy) 127.0.0.1:5433->5432/tcp
|
||||
valkey Up 4 seconds (healthy) 127.0.0.1:6380->6379/tcp
|
||||
|
||||
$ docker compose logs migrate
|
||||
2026-10-01T23:14:51.810Z INFO src.migrations [rid=-] migrations started db=postgres:5432/messenger
|
||||
2026-10-01T23:14:51.828Z INFO alembic.runtime.migration [rid=-] Context impl PostgresqlImpl.
|
||||
2026-10-01T23:14:51.828Z INFO alembic.runtime.migration [rid=-] Will assume transactional DDL.
|
||||
2026-10-01T23:14:51.833Z INFO alembic.runtime.migration [rid=-] Running upgrade -> 0001, messenger schema: users, sessions, chats, chat members, messages
|
||||
2026-10-01T23:14:51.855Z INFO src.migrations [rid=-] migrations finished db=messenger
|
||||
|
||||
$ curl -s -i http://127.0.0.1:8080/health/ready
|
||||
HTTP/1.1 200 OK
|
||||
date: Thu, 01 Oct 2026 23:14:54 GMT
|
||||
content-length: 15
|
||||
content-type: application/json
|
||||
x-request-id: 80240d27de40499ea77cecdd1f1a76ed
|
||||
|
||||
{"status":"ok"}
|
||||
|
||||
$ make test
|
||||
python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
|
||||
# Миграции на пустом volume выполнил одноразовый сервис migrate (Exited 0)
|
||||
# до старта api; api стартовал после healthy postgres и valkey. Порты —
|
||||
# только 127.0.0.1. Smoke лабы 2 прошёл.
|
||||
|
||||
$ psql: SELECT (SELECT count(*) FROM users) users, (SELECT count(*) FROM sessions) sessions, (SELECT count(*) FROM chats) chats, (SELECT count(*) FROM chat_members) members, (SELECT count(*) FROM messages) messages;
|
||||
users | sessions | chats | members | messages
|
||||
-------+----------+-------+---------+----------
|
||||
3 | 2 | 1 | 2 | 2
|
||||
(1 row)
|
||||
|
||||
$ docker compose run --rm migrate
|
||||
2026-10-01T23:15:03.527Z INFO src.migrations [rid=-] migrations started db=postgres:5432/messenger
|
||||
2026-10-01T23:15:03.545Z INFO alembic.runtime.migration [rid=-] Context impl PostgresqlImpl.
|
||||
2026-10-01T23:15:03.545Z INFO alembic.runtime.migration [rid=-] Will assume transactional DDL.
|
||||
2026-10-01T23:15:03.549Z INFO src.migrations [rid=-] migrations finished db=messenger
|
||||
|
||||
$ psql: (тот же запрос числа строк)
|
||||
users | sessions | chats | members | messages
|
||||
-------+----------+-------+---------+----------
|
||||
3 | 2 | 1 | 2 | 2
|
||||
(1 row)
|
||||
|
||||
$ psql: SELECT version_num FROM alembic_version;
|
||||
0001
|
||||
|
||||
# Повторный запуск миграций — no-op: ни одной строки «Running upgrade»,
|
||||
# число строк не изменилось (данные smoke на месте, дублей нет).
|
||||
|
||||
$ psql: \d users
|
||||
Table "public.users"
|
||||
Column | Type | Collation | Nullable | Default
|
||||
---------------+--------------------------+-----------+----------+---------
|
||||
id | uuid | | not null |
|
||||
username | text | | not null |
|
||||
display_name | text | | not null |
|
||||
password_hash | text | | not null |
|
||||
created_at | timestamp with time zone | | not null |
|
||||
Indexes:
|
||||
"pk_users" PRIMARY KEY, btree (id)
|
||||
"uq_users_username" UNIQUE CONSTRAINT, btree (username)
|
||||
Check constraints:
|
||||
"ck_users_display_name_length" CHECK (char_length(display_name) >= 1 AND char_length(display_name) <= 100)
|
||||
"ck_users_password_hash_argon2id" CHECK (password_hash ~~ '$argon2id$%'::text)
|
||||
"ck_users_username_format" CHECK (username ~ '^[a-z0-9_]{3,32}$'::text)
|
||||
Referenced by:
|
||||
TABLE "chat_members" CONSTRAINT "fk_chat_members_user_id_users" FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
TABLE "sessions" CONSTRAINT "fk_sessions_user_id_users" FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
|
||||
$ psql: \d sessions
|
||||
Table "public.sessions"
|
||||
Column | Type | Collation | Nullable | Default
|
||||
------------+--------------------------+-----------+----------+---------
|
||||
id | uuid | | not null |
|
||||
user_id | uuid | | not null |
|
||||
token_hash | bytea | | not null |
|
||||
created_at | timestamp with time zone | | not null |
|
||||
expires_at | timestamp with time zone | | not null |
|
||||
Indexes:
|
||||
"pk_sessions" PRIMARY KEY, btree (id)
|
||||
"uq_sessions_token_hash" UNIQUE CONSTRAINT, btree (token_hash)
|
||||
Check constraints:
|
||||
"ck_sessions_expires_after_created" CHECK (expires_at > created_at)
|
||||
"ck_sessions_token_hash_length" CHECK (octet_length(token_hash) = 32)
|
||||
Foreign-key constraints:
|
||||
"fk_sessions_user_id_users" FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
|
||||
$ psql: \d chats
|
||||
Table "public.chats"
|
||||
Column | Type | Collation | Nullable | Default
|
||||
------------+--------------------------+-----------+----------+---------
|
||||
id | uuid | | not null |
|
||||
title | text | | not null |
|
||||
created_at | timestamp with time zone | | not null |
|
||||
Indexes:
|
||||
"pk_chats" PRIMARY KEY, btree (id)
|
||||
Check constraints:
|
||||
"ck_chats_title_length" CHECK (char_length(title) >= 1 AND char_length(title) <= 100)
|
||||
Referenced by:
|
||||
TABLE "chat_members" CONSTRAINT "fk_chat_members_chat_id_chats" FOREIGN KEY (chat_id) REFERENCES chats(id)
|
||||
|
||||
$ psql: \d chat_members
|
||||
Table "public.chat_members"
|
||||
Column | Type | Collation | Nullable | Default
|
||||
------------+--------------------------+-----------+----------+---------
|
||||
chat_id | uuid | | not null |
|
||||
user_id | uuid | | not null |
|
||||
position | smallint | | not null |
|
||||
created_at | timestamp with time zone | | not null |
|
||||
Indexes:
|
||||
"pk_chat_members" PRIMARY KEY, btree (chat_id, user_id)
|
||||
"ix_chat_members_user_id_created_at_chat_id" btree (user_id, created_at, chat_id)
|
||||
"uq_chat_members_chat_id_position" UNIQUE CONSTRAINT, btree (chat_id, "position")
|
||||
Check constraints:
|
||||
"ck_chat_members_position_non_negative" CHECK ("position" >= 0)
|
||||
Foreign-key constraints:
|
||||
"fk_chat_members_chat_id_chats" FOREIGN KEY (chat_id) REFERENCES chats(id)
|
||||
"fk_chat_members_user_id_users" FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
Referenced by:
|
||||
TABLE "messages" CONSTRAINT "fk_messages_chat_id_sender_id_chat_members" FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
|
||||
|
||||
$ psql: \d messages
|
||||
Table "public.messages"
|
||||
Column | Type | Collation | Nullable | Default
|
||||
------------+--------------------------+-----------+----------+---------
|
||||
id | uuid | | not null |
|
||||
chat_id | uuid | | not null |
|
||||
sender_id | uuid | | not null |
|
||||
text | text | | not null |
|
||||
created_at | timestamp with time zone | | not null |
|
||||
Indexes:
|
||||
"pk_messages" PRIMARY KEY, btree (id)
|
||||
"ix_messages_chat_id_created_at_id" btree (chat_id, created_at, id)
|
||||
Check constraints:
|
||||
"ck_messages_text_length" CHECK (char_length(text) >= 1 AND char_length(text) <= 4000)
|
||||
Foreign-key constraints:
|
||||
"fk_messages_chat_id_sender_id_chat_members" FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
|
||||
|
||||
# Первичные и внешние ключи, уникальность username, CHECK по контракту.
|
||||
# Отправитель сообщения обязан быть участником чата: составной внешний
|
||||
# ключ messages → chat_members. Индексы под keyset истории и списка чатов.
|
||||
|
||||
# Сверка схемы с описанием в коде (src/storage/tables.py), 2026-10-01T23:42:05Z,
|
||||
# с хоста против PostgreSQL того же стенда (make db-up; переменные из .env,
|
||||
# в выводе их нет):
|
||||
$ DB_HOST=127.0.0.1 DB_PORT=$POSTGRES_HOST_PORT ... uv run alembic check
|
||||
...
|
||||
2026-10-01T23:42:06.574Z INFO alembic.runtime.plugins [rid=-] setting up autogenerate plugin alembic.autogenerate.comments
|
||||
2026-10-01T23:42:06.630Z INFO src.migrations [rid=-] migrations finished db=messenger
|
||||
No new upgrade operations detected.
|
||||
|
||||
# Миграция и таблицы в коде не расходятся.
|
||||
@@ -0,0 +1,55 @@
|
||||
# Что доказывает: если миграции завершились ошибкой, API не стартует —
|
||||
# compose ждёт от migrate кода 0 (service_completed_successfully).
|
||||
# Дата (UTC): 2026-10-01T23:15:20Z
|
||||
# Окружение: macOS 26.6.2, Apple M3 Pro; Docker 29.8.1, Compose 5.5.1
|
||||
# Стенд: compose-проект vladimirceva-lab2; код src_sha256 8a7e256c540af433
|
||||
# Как повторить: override с несуществующей базой только для migrate
|
||||
# (файл вне репозитория):
|
||||
# services:
|
||||
# migrate:
|
||||
# environment:
|
||||
# DB_NAME: no_such_database
|
||||
|
||||
$ docker compose rm -sf api migrate
|
||||
Container vladimirceva-lab2-api-1 Removed
|
||||
Container vladimirceva-lab2-migrate-1 Removed
|
||||
|
||||
$ docker compose -f compose.yaml -f broken-migrate.yml up -d api; echo "exit=$?"
|
||||
...
|
||||
Container vladimirceva-lab2-postgres-1 Healthy
|
||||
Container vladimirceva-lab2-valkey-1 Healthy
|
||||
Container vladimirceva-lab2-migrate-1 Error service "migrate" didn't complete successfully: exit 1
|
||||
service "migrate" didn't complete successfully: exit 1
|
||||
exit=1
|
||||
|
||||
$ docker compose ps -a --format "table {{.Service}}\t{{.Status}}"
|
||||
SERVICE STATUS
|
||||
api Created
|
||||
migrate Exited (1) Less than a second ago
|
||||
postgres Up 29 seconds (healthy)
|
||||
valkey Up 30 seconds (healthy)
|
||||
|
||||
$ docker compose logs --no-log-prefix migrate | tail -3
|
||||
raise translated_error from error
|
||||
sqlalchemy.exc.DBAPIError: (sqlalchemy.dialects.postgresql.asyncpg.Error) database "no_such_database" does not exist
|
||||
(Background on this error at: https://sqlalche.me/e/21/dbapi)
|
||||
|
||||
$ curl -s -o /dev/null -w "%{http_code}\n" --max-time 2 http://127.0.0.1:8080/health/live
|
||||
000
|
||||
|
||||
# migrate завершился с кодом 1, api остался в состоянии Created и порт не
|
||||
# слушает: сервис не начинает работу на базе без схемы. Причина — в журнале
|
||||
# migrate, без пароля.
|
||||
|
||||
$ make up
|
||||
...
|
||||
Container vladimirceva-lab2-valkey-1 Healthy
|
||||
Container vladimirceva-lab2-api-1 Healthy
|
||||
|
||||
$ docker compose ps --format "table {{.Service}}\t{{.Status}}"
|
||||
SERVICE STATUS
|
||||
api Up 1 second (healthy)
|
||||
postgres Up 33 seconds (healthy)
|
||||
valkey Up 34 seconds (healthy)
|
||||
|
||||
# С верной базой стенд поднимается обычной командой, без ручной уборки.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Что доказывает: пользователи, чаты, сообщения и действующие сессии
|
||||
# переживают рестарт API и всех хранилищ (PostgreSQL и Valkey) без
|
||||
# удаления volume; прежний токен читает те же данные. Hook действительно
|
||||
# перезапускает все три контейнера (StartedAt до и после).
|
||||
# Дата (UTC): 2026-10-01T23:15:31Z — 2026-10-01T23:15:36Z
|
||||
# Окружение: macOS 26.6.2, Apple M3 Pro; Docker 29.8.1, Compose 5.5.1
|
||||
# Стенд: compose-проект vladimirceva-lab2 (make up), SESSION_TTL_SECONDS
|
||||
# 3600; код src_sha256 8a7e256c540af433
|
||||
# Как повторить: команды ниже. StartedAt — `docker inspect -f
|
||||
# '{{.State.StartedAt}}' $(docker compose ps -q <сервис>)`.
|
||||
|
||||
$ StartedAt before
|
||||
api 2026-10-01T23:15:21.944519753Z
|
||||
postgres 2026-10-01T23:14:49.610658211Z
|
||||
valkey 2026-10-01T23:14:49.515236336Z
|
||||
|
||||
$ docker compose exec valkey valkey-cli DBSIZE
|
||||
1
|
||||
|
||||
$ time make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
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.
|
||||
real 5.03
|
||||
user 0.29
|
||||
sys 0.13
|
||||
|
||||
$ StartedAt after
|
||||
api 2026-10-01T23:15:34.375132676Z
|
||||
postgres 2026-10-01T23:15:31.435863175Z
|
||||
valkey 2026-10-01T23:15:31.485186883Z
|
||||
|
||||
$ docker compose exec valkey valkey-cli DBSIZE
|
||||
1
|
||||
|
||||
$ docker compose ps --format "table {{.Service}}\t{{.Status}}"
|
||||
SERVICE STATUS
|
||||
api Up 1 second (healthy)
|
||||
postgres Up 4 seconds (healthy)
|
||||
valkey Up 4 seconds (healthy)
|
||||
|
||||
# PASS: тест создал данные и сессию, вызвал hook и тем же токеном прочитал
|
||||
# те же данные. У api, postgres и valkey новый StartedAt — перезапущены все
|
||||
# три. Volume pgdata не удалялся (hook: stop api → restart postgres valkey →
|
||||
# up --wait → start api). Ключ в Valkey после теста — карточка, которую
|
||||
# тест снова прочитал после рестарта: persistence у Valkey выключен, кэш
|
||||
# заполняется при чтении (пустой кэш сразу после рестарта Valkey показан в
|
||||
# cache/valkey.txt).
|
||||
Reference in New Issue
Block a user