This commit is contained in:
2026-10-15 00:24:46 +03:00
parent 0ab3a341aa
commit d9b9e8593c
73 changed files with 5029 additions and 37 deletions
+2
View File
@@ -0,0 +1,2 @@
python scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
+32
View File
@@ -0,0 +1,32 @@
docker compose --profile tools run --rm db-test
Container mtusi-lab3-postgres-1 Running
Container mtusi-lab3-postgres-1 Waiting
Container mtusi-lab3-postgres-1 Healthy
Container mtusi-lab3-db-test-run-20693dcae707 Creating
Container mtusi-lab3-db-test-run-20693dcae707 Created
test_concurrent_registration_has_one_winner (test_store.StoreIntegrationTest.test_concurrent_registration_has_one_winner) ...
20 параллельных create_user: 1 создан, 19 получили Conflict (409)
ok
test_concurrent_same_idempotency_key_creates_one_row (test_store.StoreIntegrationTest.test_concurrent_same_idempotency_key_creates_one_row) ...
20 одновременных add_message с одним ключом: 1 строка, 1 новое + 19 повторов с тем же сообщением
ok
test_create_chat_rolls_back_when_failing_midway (test_store.StoreIntegrationTest.test_create_chat_rolls_back_when_failing_midway) ... ok
test_database_rejects_message_from_non_member (test_store.StoreIntegrationTest.test_database_rejects_message_from_non_member) ...
чат с несуществующим участником: транзакция откатилась, строк chats/chat_members не осталось
INSERT сообщения от не-участника напрямую в БД: ForeignKeyViolation
ok
test_migrations_rerun_is_noop (test_store.StoreIntegrationTest.test_migrations_rerun_is_noop) ...
schema_migrations: ['001_core', '002_sessions', '003_text_as_bytes', '004_message_idempotency']; повторный migrate() ничего не применил
ok
test_old_version_insert_without_key_still_works (test_store.StoreIntegrationTest.test_old_version_insert_without_key_still_works) ...
INSERT как в lab2 (без ключа) после миграции 004 работает: старая версия совместима со схемой
ok
test_same_key_other_body_is_conflict (test_store.StoreIntegrationTest.test_same_key_other_body_is_conflict) ... ok
тот же ключ с другим телом: Conflict (409), в базе по-прежнему одна строка
----------------------------------------------------------------------
Ran 7 tests in 0.259s
OK
+22
View File
@@ -0,0 +1,22 @@
docker compose --profile ttl up -d --wait api-short-ttl
Container mtusi-lab3-postgres-1 Running
Container mtusi-lab3-valkey-1 Running
Container mtusi-lab3-api-short-ttl-1 Creating
Container mtusi-lab3-api-short-ttl-1 Created
Container mtusi-lab3-valkey-1 Waiting
Container mtusi-lab3-postgres-1 Waiting
Container mtusi-lab3-postgres-1 Healthy
Container mtusi-lab3-valkey-1 Healthy
Container mtusi-lab3-api-short-ttl-1 Starting
Container mtusi-lab3-api-short-ttl-1 Started
Container mtusi-lab3-postgres-1 Waiting
Container mtusi-lab3-valkey-1 Waiting
Container mtusi-lab3-api-short-ttl-1 Waiting
Container mtusi-lab3-valkey-1 Healthy
Container mtusi-lab3-postgres-1 Healthy
Container mtusi-lab3-api-short-ttl-1 Healthy
python student-tests/expiry.py; status=$?; docker compose --profile ttl rm -sf api-short-ttl >/dev/null 2>&1; exit $status
session issued by short-TTL API, expires in 1.99s
before expiry: GET /users/me -> 200 (short API twice, main API once)
after expiry: GET /users/me -> 401 on both instances
PASS: session expired after SESSION_TTL_SECONDS; cache did not extend it
+76
View File
@@ -0,0 +1,76 @@
docker compose exec -T postgres psql -X -q -U messenger -d messenger -v ON_ERROR_STOP=1 < infra/sql/explain_history.sql
=== Объём данных
messages_total | messages_in_big_chat
----------------+----------------------
21635 | 12000
=== Индекс истории (migrations/001_core.sql)
indexdef
-------------------------------------------------------------------------------------------------
CREATE INDEX messages_chat_history_idx ON public.messages USING btree (chat_id, created_at, id)
=== 1. Первая страница (limit=50, приложение просит 51 строку, чтобы понять, есть ли следующая)
QUERY PLAN
---------------------------------------------------------------------------------------------------------
Limit (actual time=0.016..0.030 rows=51 loops=1)
Buffers: shared hit=4
-> Index Scan using messages_chat_history_idx on messages (actual time=0.015..0.026 rows=51 loops=1)
Index Cond: (chat_id = 'e4e1b497-87b7-4320-9a40-27873d99fc1a'::uuid)
Buffers: shared hit=4
Planning:
Buffers: shared hit=7
Planning Time: 0.139 ms
Execution Time: 0.050 ms
=== 2. Страница из середины истории по keyset-курсору (после 6000-го сообщения)
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (actual time=0.009..0.029 rows=51 loops=1)
Buffers: shared hit=5
-> Index Scan using messages_chat_history_idx on messages (actual time=0.009..0.025 rows=51 loops=1)
Index Cond: ((chat_id = 'e4e1b497-87b7-4320-9a40-27873d99fc1a'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 01:40:00+00'::timestamp with time zone, '509a5d7d-2d2f-4322-8b64-938949155ce0'::uuid)))
Buffers: shared hit=5
Planning Time: 0.087 ms
Execution Time: 0.059 ms
=== 3. Для сравнения: та же страница через OFFSET (так приложение НЕ делает)
QUERY PLAN
-----------------------------------------------------------------------------------------------------------
Limit (actual time=1.583..1.600 rows=51 loops=1)
Buffers: shared hit=127
-> Index Scan using messages_chat_history_idx on messages (actual time=0.021..1.393 rows=6051 loops=1)
Index Cond: (chat_id = 'e4e1b497-87b7-4320-9a40-27873d99fc1a'::uuid)
Buffers: shared hit=127
Planning Time: 0.089 ms
Execution Time: 1.621 ms
=== 4. Для сравнения: запрос 2 без индекса (индекс удалён только внутри этой транзакции)
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------------------
Limit (actual time=2.654..2.660 rows=51 loops=1)
Buffers: shared hit=172
-> Sort (actual time=2.653..2.655 rows=51 loops=1)
Sort Key: created_at, id
Sort Method: top-N heapsort Memory: 31kB
Buffers: shared hit=172
-> Bitmap Heap Scan on messages (actual time=0.782..1.755 rows=6000 loops=1)
Recheck Cond: (chat_id = 'e4e1b497-87b7-4320-9a40-27873d99fc1a'::uuid)
Filter: (ROW(created_at, id) > ROW('2026-01-01 01:40:00+00'::timestamp with time zone, '509a5d7d-2d2f-4322-8b64-938949155ce0'::uuid))
Rows Removed by Filter: 6000
Heap Blocks: exact=161
Buffers: shared hit=172
-> Bitmap Index Scan on messages_idempotency_unique (actual time=0.201..0.202 rows=12000 loops=1)
Index Cond: (chat_id = 'e4e1b497-87b7-4320-9a40-27873d99fc1a'::uuid)
Buffers: shared hit=11
Planning:
Buffers: shared hit=5
Planning Time: 0.097 ms
Execution Time: 2.681 ms
=== ROLLBACK: синтетические данные удалены, индекс на месте
+169
View File
@@ -0,0 +1,169 @@
{
"profile": {
"writers": 4,
"readers": 1,
"client_timeout_seconds": 2,
"warmup_seconds": 3,
"after_seconds": 10,
"replicas": 2,
"client_python": "3.11.5"
},
"runs": [
{
"replica": "4e5560c6d072",
"mode": "stop",
"command_seconds": 4.11,
"lb_excluded_after_seconds": 0.83,
"errors": 0,
"error_codes": {},
"errors_stopped_after_seconds": 0.0,
"before": {
"seconds": 3.0,
"write_rps": 231.0,
"reads": 42,
"errors": 0,
"error_codes": {},
"write_p50_ms": 16.0,
"write_p95_ms": 32.0,
"write_max_ms": 109.0
},
"after": {
"seconds": 10.0,
"write_rps": 112.4,
"reads": 101,
"errors": 0,
"error_codes": {},
"write_p50_ms": 31.0,
"write_p95_ms": 78.0,
"write_max_ms": 282.0
},
"stopped_replica_answers_after_stop": 0,
"integrity": {
"confirmed_writes": 1817,
"messages_in_history": 1817,
"duplicates": 0,
"lost": 0
},
"rejoin_seconds": 4.01
},
{
"replica": "4e5560c6d072",
"mode": "kill",
"command_seconds": 0.75,
"lb_excluded_after_seconds": 0.2,
"errors": 4,
"error_codes": {
"502": 4
},
"errors_stopped_after_seconds": 0.11,
"before": {
"seconds": 3.0,
"write_rps": 184.7,
"reads": 39,
"errors": 0,
"error_codes": {},
"write_p50_ms": 16.0,
"write_p95_ms": 47.0,
"write_max_ms": 94.0
},
"after": {
"seconds": 10.0,
"write_rps": 98.0,
"reads": 84,
"errors": 4,
"error_codes": {
"502": 4
},
"write_p50_ms": 32.0,
"write_p95_ms": 93.0,
"write_max_ms": 156.0
},
"stopped_replica_answers_after_stop": 0,
"integrity": {
"confirmed_writes": 1536,
"messages_in_history": 1536,
"duplicates": 0,
"lost": 0
},
"rejoin_seconds": 4.01
},
{
"replica": "7740e49a1d8c",
"mode": "stop",
"command_seconds": 4.24,
"lb_excluded_after_seconds": 1.27,
"errors": 0,
"error_codes": {},
"errors_stopped_after_seconds": 0.0,
"before": {
"seconds": 3.0,
"write_rps": 204.0,
"reads": 40,
"errors": 0,
"error_codes": {},
"write_p50_ms": 16.0,
"write_p95_ms": 32.0,
"write_max_ms": 109.0
},
"after": {
"seconds": 10.0,
"write_rps": 110.7,
"reads": 102,
"errors": 0,
"error_codes": {},
"write_p50_ms": 31.0,
"write_p95_ms": 78.0,
"write_max_ms": 125.0
},
"stopped_replica_answers_after_stop": 0,
"integrity": {
"confirmed_writes": 1719,
"messages_in_history": 1719,
"duplicates": 0,
"lost": 0
},
"rejoin_seconds": 4.91
},
{
"replica": "7740e49a1d8c",
"mode": "kill",
"command_seconds": 0.83,
"lb_excluded_after_seconds": 0.17,
"errors": 2,
"error_codes": {
"502": 2
},
"errors_stopped_after_seconds": 0.11,
"before": {
"seconds": 3.0,
"write_rps": 151.7,
"reads": 42,
"errors": 0,
"error_codes": {},
"write_p50_ms": 16.0,
"write_p95_ms": 78.0,
"write_max_ms": 109.0
},
"after": {
"seconds": 10.0,
"write_rps": 103.7,
"reads": 103,
"errors": 2,
"error_codes": {
"502": 2
},
"write_p50_ms": 31.0,
"write_p95_ms": 78.0,
"write_max_ms": 1031.0
},
"stopped_replica_answers_after_stop": 0,
"integrity": {
"confirmed_writes": 1492,
"messages_in_history": 1492,
"duplicates": 0,
"lost": 0
},
"rejoin_seconds": 4.17
}
]
}
+25
View File
@@ -0,0 +1,25 @@
python student-tests/failover_metrics.py
api replicas: ['4e5560c6d072', '7740e49a1d8c']; load: 4 writers without pauses + 1 reader, client timeout 2 s, retry with the same Idempotency-Key; 3 s before and 10 s after the failure
--- stop 4e5560c6d072 ...
docker stop: 4.11 s; HAProxy excluded it after 0.83 s; errors: 0 {}, last error ended 0.0 s after the failure
write RPS before 231.0 -> after 112.4; p95 after 78.0 ms, max 282.0 ms; answers from the stopped replica after stop: 0
confirmed 1817, in history 1817, lost 0, duplicates 0; back in the balancer 4.01 s after docker start
--- kill 4e5560c6d072 ...
docker kill: 0.75 s; HAProxy excluded it after 0.2 s; errors: 4 {'502': 4}, last error ended 0.11 s after the failure
write RPS before 184.7 -> after 98.0; p95 after 93.0 ms, max 156.0 ms; answers from the stopped replica after stop: 0
confirmed 1536, in history 1536, lost 0, duplicates 0; back in the balancer 4.01 s after docker start
--- stop 7740e49a1d8c ...
docker stop: 4.24 s; HAProxy excluded it after 1.27 s; errors: 0 {}, last error ended 0.0 s after the failure
write RPS before 204.0 -> after 110.7; p95 after 78.0 ms, max 125.0 ms; answers from the stopped replica after stop: 0
confirmed 1719, in history 1719, lost 0, duplicates 0; back in the balancer 4.91 s after docker start
--- kill 7740e49a1d8c ...
docker kill: 0.83 s; HAProxy excluded it after 0.17 s; errors: 2 {'502': 2}, last error ended 0.11 s after the failure
write RPS before 151.7 -> after 103.7; p95 after 78.0 ms, max 1031.0 ms; answers from the stopped replica after stop: 0
confirmed 1492, in history 1492, lost 0, duplicates 0; back in the balancer 4.17 s after docker start
replica mode cmd,s lb_out,s errors errors_end,s rps_before rps_after p95_after,ms rejoin,s
4e5560c6d072 stop 4.11 0.83 0 0.0 231.0 112.4 78.0 4.01
4e5560c6d072 kill 0.75 0.2 4 0.11 184.7 98.0 93.0 4.01
7740e49a1d8c stop 4.24 1.27 0 0.0 204.0 110.7 78.0 4.91
7740e49a1d8c kill 0.83 0.17 2 0.11 151.7 103.7 78.0 4.17
PASS: every replica was stopped (stop, kill) and restored; no lost or duplicated messages; saved evidence/failover-metrics.json
+48
View File
@@ -0,0 +1,48 @@
python student-tests/run_failover.py
hook: scripts/stop-one.cmd; api replicas: ['4e5560c6d072', '7740e49a1d8c']
=== run 1: containers before (HAProxy: api1 UP, api2 UP)
SERVICE CONTAINER STATE STARTED AT (UTC)
api 4e5560c6d072 running (healthy) 2026-10-14T20:46:50.376
api 7740e49a1d8c running (healthy) 2026-10-14T20:46:50.691
lb 91c0051bd4c8 running (healthy) 2026-10-14T20:46:51.195
migrate 523965b912bb exited 2026-10-14T20:46:48.669
postgres 5c16b9b684f2 running (healthy) 2026-10-14T21:05:32.785
valkey c74935587700 running (healthy) 2026-10-14T21:05:11.672
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.␍
{"observed_instances_before": 2, "successful_writes": 124, "failed_attempts": 0, "first_recovery_seconds": 4.437}␍
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
containers after (HAProxy: api2 UP)
SERVICE CONTAINER STATE STARTED AT (UTC)
api 4e5560c6d072 running (healthy) 2026-10-14T20:46:50.376
api 7740e49a1d8c exited 2026-10-14T20:46:50.691
lb 91c0051bd4c8 running (healthy) 2026-10-14T20:46:51.195
migrate 523965b912bb exited 2026-10-14T20:46:48.669
postgres 5c16b9b684f2 running (healthy) 2026-10-14T21:05:32.785
valkey c74935587700 running (healthy) 2026-10-14T21:05:11.672
the hook stopped 7740e49a1d8c (X-Instance-Id of that replica = container ID); other api containers, postgres, valkey and lb kept running
restored: docker start 7740e49a1d8c -> healthy and back in HAProxy (api1 UP, api2 UP)
=== run 2: containers before (HAProxy: api1 UP, api2 UP)
SERVICE CONTAINER STATE STARTED AT (UTC)
api 4e5560c6d072 running (healthy) 2026-10-14T20:46:50.376
api 7740e49a1d8c running (healthy) 2026-10-14T21:07:12.761
lb 91c0051bd4c8 running (healthy) 2026-10-14T20:46:51.195
migrate 523965b912bb exited 2026-10-14T20:46:48.669
postgres 5c16b9b684f2 running (healthy) 2026-10-14T21:05:32.785
valkey c74935587700 running (healthy) 2026-10-14T21:05:11.672
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.␍
{"observed_instances_before": 2, "successful_writes": 124, "failed_attempts": 0, "first_recovery_seconds": 4.594}␍
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
containers after (HAProxy: api1 UP)
SERVICE CONTAINER STATE STARTED AT (UTC)
api 4e5560c6d072 exited 2026-10-14T20:46:50.376
api 7740e49a1d8c running (healthy) 2026-10-14T21:07:12.761
lb 91c0051bd4c8 running (healthy) 2026-10-14T20:46:51.195
migrate 523965b912bb exited 2026-10-14T20:46:48.669
postgres 5c16b9b684f2 running (healthy) 2026-10-14T21:05:32.785
valkey c74935587700 running (healthy) 2026-10-14T21:05:11.672
the hook stopped 4e5560c6d072 (X-Instance-Id of that replica = container ID); other api containers, postgres, valkey and lb kept running
restored: docker start 4e5560c6d072 -> healthy and back in HAProxy (api1 UP, api2 UP)
PASS: public failover test passed 2 times; every api replica was stopped once and restored
+12
View File
@@ -0,0 +1,12 @@
python student-tests/dependency_failure.py postgres
stopping postgres (docker compose stop postgres)
/health/live -> 200: процесс жив
/health/ready -> 503 (1000 ms): без PostgreSQL обслуживать нельзя
бизнес-запросы с действующим токеном -> 503 unavailable (без SQL и stack trace в ответе)
без токена -> 401: аноним не становится доверенным
неизвестный токен -> 503: не подтверждается ни кэшем, ни базой
вход -> 503: сессию без базы не выдаём
регистрация -> 503
starting postgres again
after recovery: прежний токен работает, подтверждённые сообщения на месте
PASS: postgres outage handled without trusting anonymous requests
+7
View File
@@ -0,0 +1,7 @@
python student-tests/cache_revocation.py
pausing valkey (docker compose pause valkey): данные в кэше сохраняются
во время паузы: logout -> 204, тот же токен -> 401
unpausing valkey
после unpause: 23 проверок за 12 с, отозванный токен всегда 401 (и GET, и POST)
действующие токены других пользователей работают
PASS: revoked session stays revoked after Valkey comes back with stale data
+12
View File
@@ -0,0 +1,12 @@
python student-tests/dependency_failure.py valkey
stopping valkey (docker compose stop valkey)
/health/ready -> 200 (0 ms): Valkey не критичен, API готов
existing token: GET /users/me -> 200 (4016 ms), сессия проверена по PostgreSQL (этот запрос и обнаружил сбой кэша)
POST message -> 201, история читается
register + login new user -> 201
logout -> 204, затем тот же токен -> 401 (отзыв записан в PostgreSQL)
10 x GET /users/me без кэша: max 16 ms (кэш не ждём на каждом запросе)
через 6 с, ещё 10 x GET /users/me: max 31 ms (повторные попытки — в фоне)
starting valkey again
after recovery: прежний токен работает, подтверждённые сообщения на месте
PASS: valkey outage handled without trusting anonymous requests
+26
View File
@@ -0,0 +1,26 @@
python student-tests/load_profile.py
{␍
"lab": 3,␍
"workload": "closed-loop POST messages; no automatic retries",␍
"requested_duration_seconds": 30.0,␍
"elapsed_seconds": 30.203,␍
"concurrency": 4,␍
"successful_requests": 6347,␍
"failed_requests": 0,␍
"error_ratio": 0.0,␍
"successful_rps": 210.145,␍
"successful_latency_ms": {␍
"p50": 16.0,␍
"p95": 47.0,␍
"p99": 78.0␍
},␍
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."␍
}
service cpu % max RAM max / limit, MiB
api 103.4 139.6 / 512
api 98.2 93.8 / 512
lb 25.5 15.8 / 128
postgres 31.5 49.0 / 512
valkey 6.7 8.2 / 128
PASS: load profile saved to evidence/load.json and evidence/load-stats.json
+36
View File
@@ -0,0 +1,36 @@
{
"duration_seconds": 30,
"concurrency": 4,
"containers": [
{
"service": "api",
"cpu_percent_max": 103.4,
"mem_mib_max": 139.6,
"mem_limit_mib": 512
},
{
"service": "api",
"cpu_percent_max": 98.18,
"mem_mib_max": 93.8,
"mem_limit_mib": 512
},
{
"service": "lb",
"cpu_percent_max": 25.48,
"mem_mib_max": 15.8,
"mem_limit_mib": 128
},
{
"service": "postgres",
"cpu_percent_max": 31.52,
"mem_mib_max": 49.0,
"mem_limit_mib": 512
},
{
"service": "valkey",
"cpu_percent_max": 6.71,
"mem_mib_max": 8.2,
"mem_limit_mib": 128
}
]
}
+17
View File
@@ -0,0 +1,17 @@
{
"lab": 3,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.203,
"concurrency": 4,
"successful_requests": 6347,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 210.145,
"successful_latency_ms": {
"p50": 16.0,
"p95": 47.0,
"p99": 78.0
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+26
View File
@@ -0,0 +1,26 @@
python student-tests/run_persistence.py
hook: scripts/restart.cmd
=== containers before
SERVICE CONTAINER STATE STARTED AT (UTC)
api 4e5560c6d072 running (healthy) 2026-10-14T21:07:35.489
api 7740e49a1d8c running (healthy) 2026-10-14T21:07:12.761
lb 91c0051bd4c8 running (healthy) 2026-10-14T20:46:51.195
migrate 523965b912bb exited 2026-10-14T20:46:48.669
postgres 5c16b9b684f2 running (healthy) 2026-10-14T21:05:32.785
valkey c74935587700 running (healthy) 2026-10-14T21:05:11.672
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.␍
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
=== containers after (test took 18.5 s: hook + waiting for readiness + data checks)
SERVICE CONTAINER STATE STARTED AT (UTC)
api 4e5560c6d072 running (healthy) 2026-10-14T21:07:56.102
api 7740e49a1d8c running (healthy) 2026-10-14T21:07:56.434
lb 91c0051bd4c8 running (healthy) 2026-10-14T21:08:00.229
migrate 523965b912bb exited 2026-10-14T21:07:54.122
postgres 5c16b9b684f2 running (healthy) 2026-10-14T21:07:48.620
valkey c74935587700 running (healthy) 2026-10-14T21:07:48.474
api 7740e49a1d8c: same container, start time 21:07:12 -> 21:07:56
api 4e5560c6d072: same container, start time 21:07:35 -> 21:07:56
lb 91c0051bd4c8: same container, start time 20:46:51 -> 21:08:00
postgres 5c16b9b684f2: same container, start time 21:05:32 -> 21:07:48
valkey c74935587700: same container, start time 21:05:11 -> 21:07:48
PASS: api replicas, postgres, valkey and lb were restarted (same containers and volumes, new start time); data and the existing token survived
+6
View File
@@ -0,0 +1,6 @@
python student-tests/race.py
messages: sent 100 from 10 parallel clients in 0.88s
messages: read 100 in 4 pages, unique ids: 100
PASS: 100 concurrent messages stored without loss or duplicates
registration: 20 parallel requests for one username -> 201 x1, 409 x19
PASS: concurrent registration of the same username created exactly one user
+51
View File
@@ -0,0 +1,51 @@
{
"from_version": "dev",
"to_version": "rolling-20261015-000949",
"replicas": 2,
"profile": {
"writers": 4,
"readers": 1,
"client_timeout_seconds": 2
},
"steps": [
{
"old": "4e5560c6d072",
"new": "b021c4a75186",
"new_ready_seconds": 6.75,
"step_seconds": 11.38
},
{
"old": "7740e49a1d8c",
"new": "a1fe17dd4bd2",
"new_ready_seconds": 6.11,
"step_seconds": 11.2
}
],
"update_seconds": 22.59,
"before": {
"seconds": 3.0,
"write_rps": 162.3,
"reads": 34,
"errors": 0,
"error_codes": {},
"write_p50_ms": 16.0,
"write_p95_ms": 78.0,
"write_max_ms": 203.0
},
"during": {
"seconds": 22.59,
"write_rps": 144.2,
"reads": 266,
"errors": 0,
"error_codes": {},
"write_p50_ms": 16.0,
"write_p95_ms": 78.0,
"write_max_ms": 250.0
},
"integrity": {
"confirmed_writes": 4260,
"messages_in_history": 4260,
"duplicates": 0,
"lost": 0
}
}
+10
View File
@@ -0,0 +1,10 @@
python student-tests/rolling_update.py
old replicas ['4e5560c6d072', '7740e49a1d8c'], version dev; building version rolling-20261015-000949
image built in 3.0 s
migrations (one run, before replacing replicas): Миграции: новых нет, схема актуальна
replaced 4e5560c6d072 -> b021c4a75186: new replica healthy and UP in HAProxy after 6.8 s, then the old one drained and stopped; step 11.38 s (HAProxy: api1 UP, api2 DOWN, api3 UP)
replaced 7740e49a1d8c -> a1fe17dd4bd2: new replica healthy and UP in HAProxy after 6.1 s, then the old one drained and stopped; step 11.2 s (HAProxy: api1 DOWN, api2 UP, api3 UP)
now: replicas ['a1fe17dd4bd2', 'b021c4a75186'], versions ['rolling-20261015-000949']
under load: write RPS before 162.3, during the update 144.2; errors 0 {}; p95 78.0 ms, max 250.0 ms; update took 22.6 s
confirmed 4260, in history 4260, lost 0, duplicates 0
PASS: all 2 replicas replaced one by one under load, 0 errors, no lost or duplicated messages; saved evidence/rolling-update.json
+34
View File
@@ -0,0 +1,34 @@
python student-tests/check_stack.py
docker: 29.6.2
compose: 5.3.1
container_name: not set for any service (replicas of one service are possible)
api replicas running: 2 -> ['4e5560c6d072', '7740e49a1d8c'] (deploy.replicas = 2)
service container cpus memory published ports networks
api 4e5560c6d072 1.00 512Mi - backend, edge
postgres 5c16b9b684f2 1.00 512Mi - backend
api 7740e49a1d8c 1.00 512Mi - backend, edge
lb 91c0051bd4c8 0.50 128Mi 127.0.0.1:8080->8080/tcp, 127.0.0.1:8081->8081/tcp, 127.0.0.1:8404->8404/tcp edge
valkey c74935587700 0.50 128Mi - backend
published: only lb, only on 127.0.0.1 (api replicas have no ports)
limits: every running container has CPU and RAM limits
networks: lb -> edge; api -> edge + backend; postgres, valkey -> backend (internal: no way out)
secrets: api -> cache_url, database_url; migrate -> database_url; lb -> none; postgres -> postgres_password; valkey -> valkey_acl
images: lb haproxy:3.2.25-alpine; api mtusi-messenger:lab3; postgres postgres:17.10-bookworm; valkey valkey/valkey:8.1.9
PASS: one entry point (lb on 127.0.0.1), >= 2 api replicas without ports and container_name, CPU/RAM limits everywhere, stores only on the internal network
docker compose ps -a --format "table {{.Service}}\t{{.ID}}\t{{.Status}}"
SERVICE CONTAINER ID STATUS
api 4e5560c6d072 Up 17 minutes (healthy)
api 7740e49a1d8c Up 17 minutes (healthy)
lb 91c0051bd4c8 Up 17 minutes (healthy)
migrate 523965b912bb Exited (0) 17 minutes ago
postgres 5c16b9b684f2 Up 17 minutes (healthy)
valkey c74935587700 Up 17 minutes (healthy)
migrate-1 | 2026-10-14 20:46:49,990 INFO messenger.db: Миграции применены: 001_core, 002_sessions, 003_text_as_bytes, 004_message_idempotency
api-2 | 2026-10-14 20:46:52,427 INFO messenger.db: Схема БД актуальна (миграции применены сервисом migrate)
api-2 | 2026-10-14 20:46:52,430 INFO messenger: Реплика 7740e49a1d8c запущена: версия dev, env=lab, TTL сессии=3600 c, кэш сессий: Valkey
api-1 | 2026-10-14 20:46:52,226 INFO messenger.db: Схема БД актуальна (миграции применены сервисом migrate)
api-1 | 2026-10-14 20:46:52,229 INFO messenger: Реплика 4e5560c6d072 запущена: версия dev, env=lab, TTL сессии=3600 c, кэш сессий: Valkey
.gitignore:2:.env .env
.gitignore:5:secrets/ secrets/database_url
+70
View File
@@ -0,0 +1,70 @@
python -m unittest discover -s student-tests -p "test_*.py" -v
test_auth_checked_before_access_and_body (test_api.MessengerApiTest.test_auth_checked_before_access_and_body) ... ok
test_bad_cursor_returns_400 (test_api.MessengerApiTest.test_bad_cursor_returns_400) ... ok
test_chat_list_pagination (test_api.MessengerApiTest.test_chat_list_pagination) ... ok
test_chat_membership_rules (test_api.MessengerApiTest.test_chat_membership_rules) ... ok
test_duplicate_username_returns_409 (test_api.MessengerApiTest.test_duplicate_username_returns_409) ... ok
test_empty_blank_and_too_long_messages_return_400 (test_api.MessengerApiTest.test_empty_blank_and_too_long_messages_return_400) ... ok
test_malformed_json_returns_400 (test_api.MessengerApiTest.test_malformed_json_returns_400) ... ok
test_nul_character_is_stored (test_api.MessengerApiTest.test_nul_character_is_stored) ... ok
test_outsider_gets_404_for_foreign_chat (test_api.MessengerApiTest.test_outsider_gets_404_for_foreign_chat) ... ok
test_pagination_walks_several_pages (test_api.MessengerApiTest.test_pagination_walks_several_pages) ... ok
test_unicode_roundtrip (test_api.MessengerApiTest.test_unicode_roundtrip) ... ok
test_wrong_types_and_extra_fields_return_400 (test_api.MessengerApiTest.test_wrong_types_and_extra_fields_return_400) ... ok
test_bearer_required_on_business_endpoints (test_auth.AuthTest.test_bearer_required_on_business_endpoints) ... ok
test_login_returns_opaque_token_with_expiry (test_auth.AuthTest.test_login_returns_opaque_token_with_expiry) ... ok
test_logout_revokes_only_current_session (test_auth.AuthTest.test_logout_revokes_only_current_session) ... ok
test_malformed_basic_returns_401 (test_auth.AuthTest.test_malformed_basic_returns_401) ... ok
test_password_length_rules (test_auth.AuthTest.test_password_length_rules) ... ok
test_password_with_colon_and_unicode (test_auth.AuthTest.test_password_with_colon_and_unicode) ... ok
test_relogin_after_logout (test_auth.AuthTest.test_relogin_after_logout) ... ok
test_user_never_contains_password (test_auth.AuthTest.test_user_never_contains_password) ... ok
test_wrong_password_and_unknown_user_look_the_same (test_auth.AuthTest.test_wrong_password_and_unknown_user_look_the_same) ... ok
test_x_user_id_does_not_change_identity (test_auth.AuthTest.test_x_user_id_does_not_change_identity) ... ok
test_instance_id_on_errors_and_health (test_balancing.BalancingTest.test_instance_id_on_errors_and_health) ... ok
test_logout_applies_on_every_replica (test_balancing.BalancingTest.test_logout_applies_on_every_replica) ... ok
test_one_session_is_served_by_every_replica (test_balancing.BalancingTest.test_one_session_is_served_by_every_replica) ... ok
test_session_cache_is_shared_between_replicas (test_balancing.BalancingTest.test_session_cache_is_shared_between_replicas) ... ok
test_write_on_one_replica_read_on_another (test_balancing.BalancingTest.test_write_on_one_replica_read_on_another) ... ok
test_failed_request_does_not_burn_key (test_idempotency.IdempotencyTest.test_failed_request_does_not_burn_key) ... ok
test_json_formatting_does_not_matter (test_idempotency.IdempotencyTest.test_json_formatting_does_not_matter) ... ok
test_key_is_required_and_validated (test_idempotency.IdempotencyTest.test_key_is_required_and_validated) ... ok
test_key_scope_is_user_and_chat (test_idempotency.IdempotencyTest.test_key_scope_is_user_and_chat) ... ok
test_parallel_different_bodies_same_key (test_idempotency.IdempotencyTest.test_parallel_different_bodies_same_key) ... ok
test_parallel_same_key_through_replicas_creates_one_message (test_idempotency.IdempotencyTest.test_parallel_same_key_through_replicas_creates_one_message) ... ok
test_replay_rechecks_session_and_access (test_idempotency.IdempotencyTest.test_replay_rechecks_session_and_access) ... ok
test_replay_through_another_replica_returns_same_message (test_idempotency.IdempotencyTest.test_replay_through_another_replica_returns_same_message) ... ok
test_same_key_other_body_is_409 (test_idempotency.IdempotencyTest.test_same_key_other_body_is_409) ... ok
----------------------------------------------------------------------
Ran 36 tests in 6.481s
OK
X-Instance-Id есть в health, 404, 401 и 400
logout через одну реплику -> 401 на ['4e5560c6d072', '7740e49a1d8c']
20 x GET /users/me с одним токеном -> реплики {'7740e49a1d8c': 10, '4e5560c6d072': 10}; это ID запущенных контейнеров api, повторный вход не нужен
10 x GET /users/me через реплики {'7740e49a1d8c': 5, '4e5560c6d072': 5}: попаданий в кэш +20, промахов +0 — кэш общий
сообщение записала реплика 7740e49a1d8c, сразу прочитали ['4e5560c6d072', '7740e49a1d8c']
с тем же ключом: сначала 400 (пустой текст), потом 201 — ошибка ключ не заняла
тот же JSON с другими пробелами и переносами -> тот же 201 и то же сообщение
нет ключа, пустой, 129 символов, пробел, '/', кириллица -> 400; 128 символов и ._:- -> 201
тот же ключ у другого пользователя и в другом чате -> независимые сообщения
10 одновременных разных тел с одним ключом: 201 x1, 409 x9, в истории 1 сообщение
20 одновременных POST с одним ключом через реплики {'7740e49a1d8c': 10, '4e5560c6d072': 10}: все 201 с одним id, в истории 1 сообщение
повтор: посторонний -> 404, после logout -> 401, после нового входа -> то же сообщение
1 запрос + 4 повтора через реплики ['4e5560c6d072', '7740e49a1d8c']: 201 и то же сообщение, в истории 1
другой текст с тем же ключом -> 409 conflict, второе сообщение не создано
+2
View File
@@ -0,0 +1,2 @@
python tests/smoke.py --base-url "http://127.0.0.1:8080"
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
+8
View File
@@ -0,0 +1,8 @@
docker compose exec -T valkey valkey-cli --user health --pass none --no-auth-warning dbsize
6
docker compose exec -T valkey valkey-cli --user health --pass none --no-auth-warning info stats | grep -E "keyspace_(hits|misses)"
keyspace_hits:106
keyspace_misses:4
docker compose exec -T valkey valkey-cli --user health --pass none --no-auth-warning get sess:anything
NOPERM User health has no permissions to run the 'get' command