ЛР 2: PostgreSQL, сессии в Valkey, трек 2

This commit is contained in:
alenchha
2026-10-19 19:11:28 +03:00
parent 65003b6119
commit 6bec450e20
50 changed files with 3210 additions and 14 deletions
+29
View File
@@ -0,0 +1,29 @@
=== 1. Останавливаю кэш сессий (valkey) ===
Container mtusi-lab2-valkey-1 Stopping
Container mtusi-lab2-valkey-1 Stopped
api Up 31 seconds (healthy)
postgres Up 37 seconds (unhealthy)
PASS login_and_read_work_without_cache
PASS unknown_token_is_still_rejected
PASS readiness_ignores_the_cache
3/3 checks passed
Container mtusi-lab2-valkey-1 Starting
Container mtusi-lab2-valkey-1 Started
=== 2. Останавливаю PostgreSQL ===
Container mtusi-lab2-postgres-1 Stopping
Container mtusi-lab2-postgres-1 Stopped
api Up 31 seconds (healthy)
valkey Up Less than a second (health: starting)
PASS readiness_reports_the_outage
PASS writes_fail_with_503
PASS unknown_token_never_becomes_trusted
PASS login_fails_closed
4/4 checks passed
Container mtusi-lab2-postgres-1 Starting
Container mtusi-lab2-postgres-1 Started
=== 3. Состояние восстановлено ===
api Up 38 seconds (healthy)
postgres Up Less than a second (health: starting)
valkey Up 7 seconds (healthy)
+5
View File
@@ -0,0 +1,5 @@
Поднимаю отдельный API с SESSION_TTL_SECONDS=2 на порту 8081 (сеть mtusi-lab2_default)
PASS session_expires_after_ttl
PASS expired_session_cannot_write_or_logout
PASS expires_at_matches_configured_ttl
3/3 checks passed
+88
View File
@@ -0,0 +1,88 @@
sh student-tests/explain.sh
=== Стенд ===
api mtusi-messenger:lab2 Up About a minute (healthy)
postgres postgres:17.7-alpine@sha256:bb377b7239d2774ac8cc76f481596ce96c5a6b5e9d141f6d0a0ee371a6e7c0f2 Up About a minute (healthy)
valkey valkey/valkey:8.1-alpine@sha256:081c2f5cb575efc901aa80ff9cdbd1ec6a301682fd35e1ebb4b0990a4a4a8507 Up Less than a second (health: starting)
=== Засев 10000 сообщений с неравномерными чатами ===
seed_duration | seeded_rows | target_total | messages_total
-----------------+-------------+--------------+----------------
00:00:00.001309 | 0 | 10000 | 53764
(1 row)
=== План запроса истории ===
postgres_version
-----------------------------------------------------------------------------------------------
PostgreSQL 17.7 on aarch64-unknown-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit
(1 row)
messages_total | chats_with_messages | table_size | indexes_size
----------------+---------------------+------------+--------------
53764 | 14 | 5368 kB | 6320 kB
(1 row)
--- распределение истории по чатам: 5 самых больших и 5 самых маленьких ---
chat_id | rows
--------------------------------------+-------
e8b55eec-ce6b-4cc4-9003-e6f1f33ddd32 | 32944
c995246c-35ed-422d-b097-c71f8829a0e0 | 20775
d73dc509-7b93-4fc3-b6de-b7079bcc294f | 25
7485e75e-455e-4a7b-b164-3dbc84099fc0 | 5
63d536a7-78d4-4502-92fa-9bbac4e7c5c4 | 3
(5 rows)
chat_id | rows
--------------------------------------+------
143b0ced-4c1a-4742-a4ad-02c4b606ba0f | 1
b4faa937-91fc-4f41-b25e-f3f692878c1f | 1
84d473db-544b-4a24-995b-43a4852c68ab | 1
574fc146-1610-484a-85a9-cb084afa7d28 | 1
836ed5bf-8ccb-419e-96d5-2c4fe7342292 | 1
(5 rows)
--- A. keyset, первая страница самого большого чата ---
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.41..6.89 rows=50 width=67) (actual time=0.006..0.016 rows=50 loops=1)
Buffers: shared hit=24
-> Index Scan using messages_history_idx on messages (cost=0.41..4269.16 rows=32968 width=67) (actual time=0.006..0.014 rows=50 loops=1)
Index Cond: (chat_id = 'e8b55eec-ce6b-4cc4-9003-e6f1f33ddd32'::uuid)
Buffers: shared hit=24
Planning:
Buffers: shared hit=6
Planning Time: 0.046 ms
Execution Time: 0.026 ms
(9 rows)
--- B. keyset, страница на глубине 90% истории (так работает cursor API) ---
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.41..11.51 rows=50 width=67) (actual time=0.017..0.025 rows=50 loops=1)
Buffers: shared hit=53
-> Index Scan using messages_history_idx on messages (cost=0.41..3272.65 rows=14746 width=67) (actual time=0.017..0.023 rows=50 loops=1)
Index Cond: ((chat_id = 'e8b55eec-ce6b-4cc4-9003-e6f1f33ddd32'::uuid) AND (ROW(created_at, id) > ROW('2026-10-19 15:51:38.025965+00'::timestamp with time zone, '0375fd16-e024-4391-93a5-0d5a1a21786d'::uuid)))
Buffers: shared hit=53
Planning Time: 0.027 ms
Execution Time: 0.063 ms
(7 rows)
--- C. OFFSET на той же глубине (так API не делает: цена растёт со страницей) ---
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=3839.41..3845.89 rows=50 width=67) (actual time=4.152..4.159 rows=50 loops=1)
Buffers: shared hit=29813
-> Index Scan using messages_history_idx on messages (cost=0.41..4269.16 rows=32968 width=67) (actual time=0.008..3.474 rows=29699 loops=1)
Index Cond: (chat_id = 'e8b55eec-ce6b-4cc4-9003-e6f1f33ddd32'::uuid)
Buffers: shared hit=29813
Planning Time: 0.018 ms
Execution Time: 4.172 ms
(7 rows)
--- индексы таблицы messages ---
index | size | scans
----------------------+---------+-------
messages_history_idx | 4072 kB | 12
messages_pkey | 2248 kB | 0
(2 rows)
+32
View File
@@ -0,0 +1,32 @@
M .env.example
M Makefile
M REPORT.md
?? .github/workflows/app.yml
?? Dockerfile
?? app/
?? compose.yaml
?? evidence/dependency.txt
?? evidence/expiry.txt
?? evidence/explain-10k.txt
?? evidence/git-hygiene.txt
?? evidence/level4-tests.txt
?? evidence/load-cache.json
?? evidence/load-nocache.json
?? evidence/load.txt
?? evidence/migrations.txt
?? evidence/outages.txt
?? evidence/persistence.txt
?? evidence/smoke.txt
?? evidence/stand.txt
?? evidence/track2/
?? migrations/
?? requirements.txt
?? scripts/bootstrap.sh
?? scripts/migrate.py
?? scripts/restart.sh
?? student-tests/
--- правила игнорирования ---
.gitignore:2:.env .env
.gitignore:5:secrets/ secrets/database_url
.gitignore:5:secrets/ secrets/postgres_password
.gitignore:15:backups/ backups
+24
View File
@@ -0,0 +1,24 @@
PASS wrong_password_gives_same_401
PASS basic_is_rejected_on_business_endpoints
PASS x_user_id_does_not_authenticate
PASS logout_revokes_only_its_own_token
PASS token_is_opaque_and_unique
PASS short_password_is_rejected
PASS password_is_never_returned
PASS login_rejects_a_request_body
PASS broken_utf8_credentials_are_rejected
9/9 checks passed
PASS duplicate_username_race_creates_one_user
PASS unknown_member_rolls_chat_back
PASS keyset_pagination_is_complete
PASS cursor_is_bound_to_its_chat
PASS limit_bounds_are_enforced
PASS sql_injection_is_not_executed
PASS malformed_requests_are_rejected
PASS nul_and_unicode_text_round_trips
PASS text_length_limit_counts_code_points
PASS unicode_blanks_are_rejected
PASS broken_json_does_not_break_the_api
PASS content_type_is_required
12/12 checks passed
+17
View File
@@ -0,0 +1,17 @@
{
"lab": 2,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.012,
"concurrency": 4,
"successful_requests": 32944,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 1097.706,
"successful_latency_ms": {
"p50": 3.248,
"p95": 6.063,
"p99": 10.603
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+17
View File
@@ -0,0 +1,17 @@
{
"lab": 2,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.033,
"concurrency": 4,
"successful_requests": 20775,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 691.741,
"successful_latency_ms": {
"p50": 5.447,
"p95": 8.152,
"p99": 11.778
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+34
View File
@@ -0,0 +1,34 @@
{
"lab": 2,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.012,
"concurrency": 4,
"successful_requests": 32944,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 1097.706,
"successful_latency_ms": {
"p50": 3.248,
"p95": 6.063,
"p99": 10.603
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
{
"lab": 2,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.033,
"concurrency": 4,
"successful_requests": 20775,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 691.741,
"successful_latency_ms": {
"p50": 5.447,
"p95": 8.152,
"p99": 11.778
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+35
View File
@@ -0,0 +1,35 @@
--- первый запуск (из логов сервиса migrate) ---
migrate-1 | apply 0001_init
migrate-1 | migrations complete: 1 file(s)
--- повторный запуск ---
Container mtusi-lab2-postgres-1 Running
Container mtusi-lab2-postgres-1 Waiting
Container mtusi-lab2-postgres-1 Healthy
Container mtusi-lab2-migrate-run-d04acc691283 Creating
Container mtusi-lab2-migrate-run-d04acc691283 Created
skip 0001_init
migrations complete: 1 file(s)
--- схема ---
Table "public.messages"
Column | Type | Collation | Nullable | Default | Storage | Compression | Stats target | Description
------------+--------------------------+-----------+----------+---------+----------+-------------+--------------+-------------
id | uuid | | not null | | plain | | |
chat_id | uuid | | not null | | plain | | |
sender_id | uuid | | not null | | plain | | |
text | bytea | | not null | | extended | | |
created_at | timestamp with time zone | | not null | | plain | | |
Indexes:
"messages_pkey" PRIMARY KEY, btree (id)
"messages_history_idx" btree (chat_id, created_at, id)
Check constraints:
"messages_text_size" CHECK (octet_length(text) >= 1 AND octet_length(text) <= 16000)
Foreign-key constraints:
"messages_chat_id_fkey" FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE
"messages_sender_id_fkey" FOREIGN KEY (sender_id) REFERENCES users(id) ON DELETE RESTRICT
Access method: heap
version | checksum | applied_at
-----------+------------------------------------------------------------------+-------------------------------
0001_init | 4fd0a8c68a5cffd3ae67a21646eb1928477d18b8716e68c1220469d858ccb9c1 | 2026-10-19 15:50:30.673311+00
(1 row)
+5
View File
@@ -0,0 +1,5 @@
PASS revoked_session_stays_revoked_after_cache_restart
PASS logout_is_not_confirmed_while_cache_is_down
PASS cached_sessions_do_not_cross_users
PASS hung_database_fails_fast
4/4 checks passed
+18
View File
@@ -0,0 +1,18 @@
--- состояние контейнеров до рестарта ---
api Up 38 seconds (healthy)
postgres Up Less than a second (health: starting)
valkey Up 7 seconds (healthy)
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.
--- состояние контейнеров после рестарта ---
api Up Less than a second (health: starting)
postgres Up Less than a second (health: starting)
valkey Up Less than a second (health: starting)
--- логи postgres о перезапуске ---
postgres-1 | 2026-10-19 15:51:09.945 UTC [1] LOG: starting PostgreSQL 17.7 on aarch64-unknown-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit
postgres-1 | 2026-10-19 15:51:09.945 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
postgres-1 | 2026-10-19 15:51:09.945 UTC [1] LOG: listening on IPv6 address "::", port 5432
postgres-1 | 2026-10-19 15:51:09.946 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres-1 | 2026-10-19 15:51:09.949 UTC [29] LOG: database system was shut down at 2026-10-19 15:51:09 UTC
postgres-1 | 2026-10-19 15:51:09.951 UTC [1] LOG: database system is ready to accept connections
+2
View File
@@ -0,0 +1,2 @@
python3 tests/smoke.py --base-url "http://localhost:8080"
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
+8
View File
@@ -0,0 +1,8 @@
Darwin arm64
Docker version 29.7.2, build a7dcaa6
Docker Compose version v5.5.1
api mtusi-messenger:lab2 Up 1 second (health: starting)
postgres postgres:17.7-alpine@sha256:bb377b7239d2774ac8cc76f481596ce96c5a6b5e9d141f6d0a0ee371a6e7c0f2 Up 7 seconds (healthy)
valkey valkey/valkey:8.1-alpine@sha256:081c2f5cb575efc901aa80ff9cdbd1ec6a301682fd35e1ebb4b0990a4a4a8507 Up 7 seconds (healthy)
PostgreSQL 17.7 on aarch64-unknown-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit
Valkey server v=8.1.10 sha=00000000:1 malloc=jemalloc-5.3.0 bits=64 build=2cb63ac0e4567989
+227
View File
@@ -0,0 +1,227 @@
=== Стенд и версии ===
api mtusi-messenger:lab2 Up About a minute (healthy)
postgres postgres:17.7-alpine@sha256:bb377b7239d2774ac8cc76f481596ce96c5a6b5e9d141f6d0a0ee371a6e7c0f2 Up About a minute (healthy)
valkey valkey/valkey:8.1-alpine@sha256:081c2f5cb575efc901aa80ff9cdbd1ec6a301682fd35e1ebb4b0990a4a4a8507 Up Less than a second (health: starting)
Darwin arm64
Docker version 29.7.2, build a7dcaa6
=== 1. Засев истории: цель 120000 сообщений, чаты неравномерные ===
seed_duration | seeded_rows | target_total | messages_total
----------------+-------------+--------------+----------------
00:00:00.63315 | 66236 | 120000 | 120000
(1 row)
=== 2. Сравнение индексов и цены записи (каждый вариант в откатываемой транзакции) ===
messages_total
----------------
120000
(1 row)
############ Вариант A: messages_history_idx (chat_id, created_at, id) ############
index_size
------------
10 MB
(1 row)
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.42..37.36 rows=50 width=89) (actual time=0.015..0.025 rows=50 loops=1)
Buffers: shared hit=53
-> Index Scan using messages_history_idx on messages (cost=0.42..5594.06 rows=7570 width=89) (actual time=0.014..0.022 rows=50 loops=1)
Index Cond: ((chat_id = 'e8b55eec-ce6b-4cc4-9003-e6f1f33ddd32'::uuid) AND (ROW(created_at, id) > ROW('2026-10-19 15:51:38.025965+00'::timestamp with time zone, '0375fd16-e024-4391-93a5-0d5a1a21786d'::uuid)))
Buffers: shared hit=53
Planning:
Buffers: shared hit=17
Planning Time: 0.098 ms
Execution Time: 0.048 ms
(9 rows)
pages_measured
----------------
5000
(1 row)
hundred_pages_duration
------------------------
00:00:00.001121
(1 row)
insert_10k_duration
---------------------
00:00:00.083689
(1 row)
############ Вариант B: только (chat_id) ############
index_size
------------
848 kB
(1 row)
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=3134.85..3134.97 rows=50 width=89) (actual time=1.691..1.695 rows=50 loops=1)
Buffers: shared hit=411 read=30
I/O Timings: shared read=0.076
-> Sort (cost=3134.85..3153.65 rows=7522 width=89) (actual time=1.691..1.692 rows=50 loops=1)
Sort Key: created_at, id
Sort Method: top-N heapsort Memory: 33kB
Buffers: shared hit=411 read=30
I/O Timings: shared read=0.076
-> Bitmap Heap Scan on messages (cost=368.71..2884.97 rows=7522 width=89) (actual time=1.378..1.560 rows=3294 loops=1)
Recheck Cond: (chat_id = 'e8b55eec-ce6b-4cc4-9003-e6f1f33ddd32'::uuid)
Filter: (ROW(created_at, id) > ROW('2026-10-19 15:51:38.025965+00'::timestamp with time zone, '0375fd16-e024-4391-93a5-0d5a1a21786d'::uuid))
Rows Removed by Filter: 29650
Heap Blocks: exact=411
Buffers: shared hit=411 read=30
I/O Timings: shared read=0.076
-> Bitmap Index Scan on messages_chat_only_idx (cost=0.00..366.83 rows=32872 width=0) (actual time=0.333..0.333 rows=32944 loops=1)
Index Cond: (chat_id = 'e8b55eec-ce6b-4cc4-9003-e6f1f33ddd32'::uuid)
Buffers: shared read=30
I/O Timings: shared read=0.076
Planning:
Buffers: shared hit=26 read=1
I/O Timings: shared read=0.009
Planning Time: 0.130 ms
Execution Time: 1.728 ms
(24 rows)
pages_measured
----------------
5000
(1 row)
hundred_pages_duration
------------------------
00:00:02.186353
(1 row)
insert_10k_duration
---------------------
00:00:00.078473
(1 row)
############ Вариант C: (chat_id, created_at, id) INCLUDE (sender_id, text) ############
index_size
------------
14 MB
(1 row)
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.42..34.19 rows=50 width=89) (actual time=0.017..0.021 rows=50 loops=1)
Buffers: shared hit=1 read=3
I/O Timings: shared read=0.006
-> Index Only Scan using messages_history_covering_idx on messages (cost=0.42..5110.68 rows=7565 width=89) (actual time=0.016..0.019 rows=50 loops=1)
Index Cond: ((chat_id = 'e8b55eec-ce6b-4cc4-9003-e6f1f33ddd32'::uuid) AND (ROW(created_at, id) > ROW('2026-10-19 15:51:38.025965+00'::timestamp with time zone, '0375fd16-e024-4391-93a5-0d5a1a21786d'::uuid)))
Heap Fetches: 0
Buffers: shared hit=1 read=3
I/O Timings: shared read=0.006
Planning:
Buffers: shared hit=28 read=1
I/O Timings: shared read=0.005
Planning Time: 0.184 ms
Execution Time: 0.031 ms
(13 rows)
pages_measured
----------------
5000
(1 row)
hundred_pages_duration
------------------------
00:00:00.000744
(1 row)
insert_10k_duration
---------------------
00:00:00.084611
(1 row)
############ Схема после эксперимента (ROLLBACK вернул индексы) ############
indexname
----------------------
messages_history_idx
messages_pkey
(2 rows)
Самый большой чат: e8b55eec-ce6b-4cc4-9003-e6f1f33ddd32
=== 3. Состояние источника до бэкапа ===
relation | rows
--------------+--------
chat_members | 1036
chats | 68
messages | 120000
sessions | 43
users | 74
(5 rows)
big_chat_rows | big_chat_md5
---------------+----------------------------------
32944 | 6c6725a76404fbb0b8b5b509707e30b5
(1 row)
id | created_at | text
--------------------------------------+-------------------------------+----------
8ecedfe9-56ef-410d-98b3-e3fc414128d9 | 2026-10-19 15:51:11.010631+00 | load-1-0
424bfa46-6e49-4b60-8ca3-ac3c3f9be02a | 2026-10-19 15:51:11.011234+00 | load-3-0
05b0e1a2-5862-461a-b8aa-1f91f647e18d | 2026-10-19 15:51:11.01201+00 | load-2-0
(3 rows)
marker_rows
-------------
0
(1 row)
=== 4. Бэкап pg_dump -Fc ===
backup_seconds=0.761
dump_size=5.6M
=== 5. Запись после бэкапа: граница потери данных ===
в источнике маркеров: 1
=== 6. Новое хранилище: отдельный контейнер и отдельный том ===
/var/run/postgresql:5432 - accepting connections
=== 7. Восстановление в новое хранилище ===
restore_seconds=0.370
=== 8. Сверка восстановленной копии ===
relation | rows
--------------+--------
chat_members | 1036
chats | 68
messages | 120000
sessions | 43
users | 74
(5 rows)
big_chat_rows | big_chat_md5
---------------+----------------------------------
32944 | 6c6725a76404fbb0b8b5b509707e30b5
(1 row)
id | created_at | text
--------------------------------------+-------------------------------+----------
8ecedfe9-56ef-410d-98b3-e3fc414128d9 | 2026-10-19 15:51:11.010631+00 | load-1-0
424bfa46-6e49-4b60-8ca3-ac3c3f9be02a | 2026-10-19 15:51:11.011234+00 | load-3-0
05b0e1a2-5862-461a-b8aa-1f91f647e18d | 2026-10-19 15:51:11.01201+00 | load-2-0
(3 rows)
marker_rows
-------------
0
(1 row)
=== 9. Итог ===
backup_seconds=0.761 restore_seconds=0.370
messages_source_without_marker=120000 messages_restored=120000
big_chat_md5_source=6c6725a76404fbb0b8b5b509707e30b5
big_chat_md5_restored=6c6725a76404fbb0b8b5b509707e30b5
RESULT: восстановленная копия совпадает с источником на момент бэкапа
маркеров после бэкапа в восстановленной копии: 0 (ожидается 0: всё, что подтверждено после снимка, в дампе отсутствует)