Заполнить отчёт и добавить доказательства

This commit is contained in:
2026-10-30 21:51:48 +03:00
parent c8a51379a4
commit 9b9487d83f
16 changed files with 1025 additions and 13 deletions
+89
View File
@@ -0,0 +1,89 @@
# Запуск из чистого clone на пустых volumes, публичный smoke
# дата: 2026-10-30T18:43Z, commit: 269b449
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
$ make env
./scripts/init-env.sh
пароли записаны в .env
$ docker compose --env-file .env config --quiet
$ docker compose --env-file .env up -d --build
Image mtusi-messenger:lab3 Built
Image mtusi-messenger:lab3 Built
Image mtusi-messenger-lb:lab3 Built
Network mtusi-messenger-lab3_data Creating
Network mtusi-messenger-lab3_data Created
Network mtusi-messenger-lab3_edge Creating
Network mtusi-messenger-lab3_edge Created
Volume mtusi-messenger-lab3_redisdata Creating
Volume mtusi-messenger-lab3_redisdata Created
Volume mtusi-messenger-lab3_pgdata Creating
Volume mtusi-messenger-lab3_pgdata Created
Container mtusi-messenger-lab3-redis-1 Creating
Container mtusi-messenger-lab3-postgres-1 Creating
Container mtusi-messenger-lab3-redis-1 Created
Container mtusi-messenger-lab3-postgres-1 Created
Container mtusi-messenger-lab3-migrate-1 Creating
Container mtusi-messenger-lab3-migrate-1 Created
Container mtusi-messenger-lab3-api-2 Creating
Container mtusi-messenger-lab3-api-1 Creating
Container mtusi-messenger-lab3-api-2 Created
Container mtusi-messenger-lab3-api-1 Created
Container mtusi-messenger-lab3-lb-1 Creating
Container mtusi-messenger-lab3-lb-1 Created
Container mtusi-messenger-lab3-redis-1 Starting
Container mtusi-messenger-lab3-postgres-1 Starting
Container mtusi-messenger-lab3-postgres-1 Started
Container mtusi-messenger-lab3-postgres-1 Waiting
Container mtusi-messenger-lab3-redis-1 Started
Container mtusi-messenger-lab3-postgres-1 Healthy
Container mtusi-messenger-lab3-migrate-1 Starting
Container mtusi-messenger-lab3-migrate-1 Started
Container mtusi-messenger-lab3-migrate-1 Waiting
Container mtusi-messenger-lab3-redis-1 Waiting
Container mtusi-messenger-lab3-redis-1 Healthy
Container mtusi-messenger-lab3-migrate-1 Exited
Container mtusi-messenger-lab3-api-2 Starting
Container mtusi-messenger-lab3-api-2 Started
Container mtusi-messenger-lab3-api-1 Starting
Container mtusi-messenger-lab3-api-1 Started
Container mtusi-messenger-lab3-lb-1 Starting
Container mtusi-messenger-lab3-lb-1 Started
$ ./scripts/wait-ready.sh
готов: http://localhost:8080
$ docker compose --env-file .env ps -a
SERVICE IMAGE STATE STATUS PORTS
api mtusi-messenger:lab3 running Up 4 seconds (healthy) 8080/tcp
api mtusi-messenger:lab3 running Up 4 seconds (healthy) 8080/tcp
lb mtusi-messenger-lb:lab3 running Up 4 seconds (health: starting) 127.0.0.1:8080->8080/tcp
migrate mtusi-messenger:lab3 exited Exited (0) 5 seconds ago
postgres postgres:17.11-alpine running Up 11 seconds (healthy) 5432/tcp
redis redis:7.4.11-alpine running Up 11 seconds (healthy) 6379/tcp
$ docker compose --env-file .env logs migrate
migrate-1 | применена: 0001_init.sql
migrate-1 | применена: 0002_idempotency.sql
$ make check
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
$ make test
python3 tests/smoke.py --base-url "http://localhost:8080"
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
# одна сессия обслуживается разными репликами
$ 6 раз curl /health/live, заголовок X-Instance-Id
x-instance-id: 3a8c5ed61bd5
x-instance-id: b7c5235a859f
x-instance-id: 3a8c5ed61bd5
x-instance-id: b7c5235a859f
x-instance-id: 3a8c5ed61bd5
x-instance-id: b7c5235a859f
# id контейнеров сервиса api
3a8c5ed61bd5
b7c5235a859f
+102
View File
@@ -0,0 +1,102 @@
# Собственные тесты API
# дата: 2026-10-30T18:43Z, commit: 269b449
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
$ make student-test
BASE_URL="http://localhost:8080" python3 -m unittest discover -s student-tests -v
test_blank_title (test_access.CreateChatTest.test_blank_title) ... ok
test_creator_must_be_member (test_access.CreateChatTest.test_creator_must_be_member) ... ok
test_duplicate_members (test_access.CreateChatTest.test_duplicate_members) ... ok
test_empty_members (test_access.CreateChatTest.test_empty_members) ... ok
test_failed_create_leaves_no_chat (test_access.CreateChatTest.test_failed_create_leaves_no_chat) ... ok
test_unknown_member (test_access.CreateChatTest.test_unknown_member) ... ok
test_bad_chat_id (test_access.ForeignChatTest.test_bad_chat_id) ... ok
test_chat_is_not_listed_for_outsider (test_access.ForeignChatTest.test_chat_is_not_listed_for_outsider) ... ok
test_foreign_chat_looks_like_missing_chat (test_access.ForeignChatTest.test_foreign_chat_looks_like_missing_chat) ... ok
test_member_id_must_be_canonical_uuid (test_access.ForeignChatTest.test_member_id_must_be_canonical_uuid) ... ok
test_members_can_read_and_write (test_access.ForeignChatTest.test_members_can_read_and_write) ... ok
test_outsider_gets_404_everywhere (test_access.ForeignChatTest.test_outsider_gets_404_everywhere) ... ok
test_outsider_message_is_not_saved (test_access.ForeignChatTest.test_outsider_message_is_not_saved) ... ok
test_basic_is_not_accepted_on_business_endpoints (test_auth.BearerTest.test_basic_is_not_accepted_on_business_endpoints) ... ok
test_garbage_token_is_401_not_500 (test_auth.BearerTest.test_garbage_token_is_401_not_500) ... ok
test_no_token (test_auth.BearerTest.test_no_token) ... ok
test_token_is_checked_before_anything_else (test_auth.BearerTest.test_token_is_checked_before_anything_else) ... ok
test_unknown_tokens (test_auth.BearerTest.test_unknown_tokens) ... ok
test_x_user_id_does_not_change_identity (test_auth.BearerTest.test_x_user_id_does_not_change_identity) ... ok
test_x_user_id_gives_no_access (test_auth.BearerTest.test_x_user_id_gives_no_access) ... ok
test_colon_and_unicode_in_password (test_auth.LoginTest.test_colon_and_unicode_in_password) ... ok
test_garbage_after_basic_is_401_not_500 (test_auth.LoginTest.test_garbage_after_basic_is_401_not_500) ... ok
test_login (test_auth.LoginTest.test_login) ... ok
test_malformed_credentials (test_auth.LoginTest.test_malformed_credentials) ... ok
test_token_is_opaque_and_unique (test_auth.LoginTest.test_token_is_opaque_and_unique) ... ok
test_username_that_cannot_exist (test_auth.LoginTest.test_username_that_cannot_exist) ... ok
test_wrong_password_and_unknown_user_look_the_same (test_auth.LoginTest.test_wrong_password_and_unknown_user_look_the_same) ... ok
test_login_again_after_logout (test_auth.LogoutTest.test_login_again_after_logout) ... ok
test_logout_requires_token (test_auth.LogoutTest.test_logout_requires_token) ... ok
test_logout_revokes_only_current_session (test_auth.LogoutTest.test_logout_revokes_only_current_session) ... ok
test_invalid_http (test_balancing.ErrorsFromBalancerTest.test_invalid_http) ... ok
test_too_large_headers (test_balancing.ErrorsFromBalancerTest.test_too_large_headers) ... ok
test_too_long_uri (test_balancing.ErrorsFromBalancerTest.test_too_long_uri) ... ok
test_every_answer_has_instance_id (test_balancing.ReplicasTest.test_every_answer_has_instance_id) ... ok
test_logout_works_on_all_replicas (test_balancing.ReplicasTest.test_logout_works_on_all_replicas) ... ok
test_no_sticky_cookie (test_balancing.ReplicasTest.test_no_sticky_cookie) ... ok
test_one_session_is_served_by_different_replicas (test_balancing.ReplicasTest.test_one_session_is_served_by_different_replicas) ... ok
test_read_after_write_on_any_replica (test_balancing.ReplicasTest.test_read_after_write_on_any_replica) ... ok
test_session_created_on_one_replica_works_on_all (test_balancing.ReplicasTest.test_session_created_on_one_replica_works_on_all) ... ok
test_100_messages_from_10_clients (test_concurrency.ConcurrencyTest.test_100_messages_from_10_clients) ... ok
test_same_username_registered_once (test_concurrency.ConcurrencyTest.test_same_username_registered_once) ... ok
test_bad_keys (test_idempotency.IdempotencyTest.test_bad_keys) ... ok
test_good_key_alphabet (test_idempotency.IdempotencyTest.test_good_key_alphabet) ... ok
test_invalid_body_does_not_take_key (test_idempotency.IdempotencyTest.test_invalid_body_does_not_take_key) ... ok
test_key_is_required (test_idempotency.IdempotencyTest.test_key_is_required) ... ok
test_key_order_in_json_does_not_matter (test_idempotency.IdempotencyTest.test_key_order_in_json_does_not_matter) ... ok
test_other_text_with_same_key_is_409 (test_idempotency.IdempotencyTest.test_other_text_with_same_key_is_409) ... ok
test_parallel_repeat_through_different_replicas (test_idempotency.IdempotencyTest.test_parallel_repeat_through_different_replicas) ... ok
test_repeat_checks_access_again (test_idempotency.IdempotencyTest.test_repeat_checks_access_again) ... ok
test_repeat_returns_same_message (test_idempotency.IdempotencyTest.test_repeat_returns_same_message) ... ok
test_same_key_for_other_user_and_other_chat (test_idempotency.IdempotencyTest.test_same_key_for_other_user_and_other_chat) ... ok
test_chat_cursor_belongs_to_user (test_pagination.ChatPaginationTest.test_chat_cursor_belongs_to_user) ... ok
test_walk_chat_list (test_pagination.ChatPaginationTest.test_walk_chat_list) ... ok
test_bad_cursor (test_pagination.MessagePaginationTest.test_bad_cursor) ... ok
test_bad_limit (test_pagination.MessagePaginationTest.test_bad_limit) ... ok
test_cursor_format_is_checked (test_pagination.MessagePaginationTest.test_cursor_format_is_checked) ... ok
test_cursor_from_another_chat (test_pagination.MessagePaginationTest.test_cursor_from_another_chat) ... ok
test_default_limit (test_pagination.MessagePaginationTest.test_default_limit) ... ok
test_exact_page_has_no_cursor (test_pagination.MessagePaginationTest.test_exact_page_has_no_cursor) ... ok
test_limit_can_change_between_pages (test_pagination.MessagePaginationTest.test_limit_can_change_between_pages) ... ok
test_new_message_appears_after_last_page (test_pagination.MessagePaginationTest.test_new_message_appears_after_last_page) ... ok
test_no_duplicates_and_order (test_pagination.MessagePaginationTest.test_no_duplicates_and_order) ... ok
test_walk_several_pages (test_pagination.MessagePaginationTest.test_walk_several_pages) ... ok
test_broken_json_without_token_is_401 (test_validation.InvalidJsonTest.test_broken_json_without_token_is_401) ... ok
test_content_type_must_be_json (test_validation.InvalidJsonTest.test_content_type_must_be_json) ... ok
test_deeply_nested_json (test_validation.InvalidJsonTest.test_deeply_nested_json) ... ok
test_extra_field (test_validation.InvalidJsonTest.test_extra_field) ... ok
test_malformed_json (test_validation.InvalidJsonTest.test_malformed_json) ... ok
test_malformed_json_in_message (test_validation.InvalidJsonTest.test_malformed_json_in_message) ... ok
test_missing_field (test_validation.InvalidJsonTest.test_missing_field) ... ok
test_not_an_object (test_validation.InvalidJsonTest.test_not_an_object) ... ok
test_only_utf8_is_accepted (test_validation.InvalidJsonTest.test_only_utf8_is_accepted) ... ok
test_wrong_type (test_validation.InvalidJsonTest.test_wrong_type) ... ok
test_empty_message (test_validation.MessageValidationTest.test_empty_message) ... ok
test_nul_character (test_validation.MessageValidationTest.test_nul_character) ... ok
test_sender_id_is_not_accepted (test_validation.MessageValidationTest.test_sender_id_is_not_accepted) ... ok
test_text_limit (test_validation.MessageValidationTest.test_text_limit) ... ok
test_unicode_is_kept (test_validation.MessageValidationTest.test_unicode_is_kept) ... ok
test_whitespace_message (test_validation.MessageValidationTest.test_whitespace_message) ... ok
test_bad_display_names (test_validation.UserValidationTest.test_bad_display_names) ... ok
test_bad_passwords (test_validation.UserValidationTest.test_bad_passwords) ... ok
test_bad_usernames (test_validation.UserValidationTest.test_bad_usernames) ... ok
test_display_name_length_is_counted_in_code_points (test_validation.UserValidationTest.test_display_name_length_is_counted_in_code_points) ... ok
test_duplicate_username (test_validation.UserValidationTest.test_duplicate_username) ... ok
test_password_is_never_returned (test_validation.UserValidationTest.test_password_is_never_returned) ... ok
test_password_length_limits (test_validation.UserValidationTest.test_password_length_limits) ... ok
----------------------------------------------------------------------
Ran 86 tests in 2.969s
OK
отправлено 100, подтверждено 100, в истории 100, уникальных id 100
10 ключей по 8 параллельных запросов: реплик 2, сообщений в истории 10
+48
View File
@@ -0,0 +1,48 @@
# Сохранность: перезапуск балансировщика, реплик, PostgreSQL и Redis с сохранением volumes
# дата: 2026-10-30T18:43Z, commit: 269b449
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
# до перезапуска
/mtusi-messenger-lab3-api-1 StartedAt=2026-10-30T18:43:31.186405878Z
/mtusi-messenger-lab3-api-2 StartedAt=2026-10-30T18:43:31.097777795Z
/mtusi-messenger-lab3-lb-1 StartedAt=2026-10-30T18:43:31.260557462Z
/mtusi-messenger-lab3-postgres-1 StartedAt=2026-10-30T18:43:24.360103334Z
/mtusi-messenger-lab3-redis-1 StartedAt=2026-10-30T18:43:24.358376875Z
$ cat scripts/restart.sh
#!/bin/sh
# Перезапускает балансировщик, все реплики API и оба хранилища. Volumes не трогает.
set -eu
cd "$(dirname "$0")/.."
docker compose --env-file .env restart postgres redis api lb
$ 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.
# после перезапуска: новое время старта у всех контейнеров
/mtusi-messenger-lab3-api-1 StartedAt=2026-10-30T18:43:40.663879758Z
/mtusi-messenger-lab3-api-2 StartedAt=2026-10-30T18:43:40.704967008Z
/mtusi-messenger-lab3-lb-1 StartedAt=2026-10-30T18:43:40.433273008Z
/mtusi-messenger-lab3-postgres-1 StartedAt=2026-10-30T18:43:40.567209883Z
/mtusi-messenger-lab3-redis-1 StartedAt=2026-10-30T18:43:40.48552355Z
$ docker volume ls --filter name=mtusi-messenger-lab3
DRIVER VOLUME NAME
local mtusi-messenger-lab3_pgdata
local mtusi-messenger-lab3_redisdata
# повторный запуск миграций
$ docker compose --env-file .env run --rm migrate
Container mtusi-messenger-lab3-postgres-1 Running
Container mtusi-messenger-lab3-postgres-1 Waiting
Container mtusi-messenger-lab3-postgres-1 Healthy
Container mtusi-messenger-lab3-migrate-run-87950778e980 Creating
Container mtusi-messenger-lab3-migrate-run-87950778e980 Created
уже применена: 0001_init.sql
уже применена: 0002_idempotency.sql
$ psql: SELECT version FROM schema_migrations
0001_init.sql
0002_idempotency.sql
+85
View File
@@ -0,0 +1,85 @@
# Публичный failover: два прогона подряд с восстановлением реплики между ними
# дата: 2026-10-30T18:43Z, commit: 269b449
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
## прогон 1
# реплики до отказа
NAME STATE STATUS
mtusi-messenger-lab3-api-1 running Up 10 seconds (healthy)
mtusi-messenger-lab3-api-2 running Up 10 seconds (healthy)
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 120, "failed_attempts": 0, "first_recovery_seconds": 1.822}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
# какой контейнер реально остановлен
NAME STATE STATUS
mtusi-messenger-lab3-api-1 running Up 26 seconds (healthy)
mtusi-messenger-lab3-api-2 exited Exited (0) 14 seconds ago
$ docker compose logs lb | grep 'is DOWN' | tail -2
lb-1 | Server api/api2 is DOWN, reason: Layer4 connection problem, info: "Connection refused", check duration: 0ms. 1 active and 0 backup servers lef
$ make restore
docker compose --env-file .env up -d --no-recreate --no-build api
Container mtusi-messenger-lab3-redis-1 Running
Container mtusi-messenger-lab3-postgres-1 Running
Container mtusi-messenger-lab3-api-1 Running
Container mtusi-messenger-lab3-postgres-1 Waiting
Container mtusi-messenger-lab3-postgres-1 Healthy
Container mtusi-messenger-lab3-migrate-1 Starting
Container mtusi-messenger-lab3-migrate-1 Started
Container mtusi-messenger-lab3-redis-1 Waiting
Container mtusi-messenger-lab3-migrate-1 Waiting
Container mtusi-messenger-lab3-redis-1 Healthy
Container mtusi-messenger-lab3-migrate-1 Exited
Container mtusi-messenger-lab3-api-2 Starting
Container mtusi-messenger-lab3-api-2 Started
BASE_URL="http://localhost:8080" ./scripts/wait-ready.sh
готов: http://localhost:8080
## прогон 2
# реплики до отказа
NAME STATE STATUS
mtusi-messenger-lab3-api-1 running Up 32 seconds (healthy)
mtusi-messenger-lab3-api-2 running Up 4 seconds (healthy)
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 120, "failed_attempts": 0, "first_recovery_seconds": 1.585}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
# какой контейнер реально остановлен
NAME STATE STATUS
mtusi-messenger-lab3-api-1 running Up 47 seconds (healthy)
mtusi-messenger-lab3-api-2 exited Exited (0) 14 seconds ago
$ docker compose logs lb | grep 'is DOWN' | tail -2
lb-1 | Server api/api2 is DOWN, reason: Layer4 connection problem, info: "Connection refused", check duration: 0ms. 1 active and 0 backup servers lef
lb-1 | Server api/api2 is DOWN, reason: Layer4 connection problem, info: "Connection refused", check duration: 0ms. 1 active and 0 backup servers lef
$ make restore
docker compose --env-file .env up -d --no-recreate --no-build api
Container mtusi-messenger-lab3-postgres-1 Running
Container mtusi-messenger-lab3-redis-1 Running
Container mtusi-messenger-lab3-api-1 Running
Container mtusi-messenger-lab3-postgres-1 Waiting
Container mtusi-messenger-lab3-postgres-1 Healthy
Container mtusi-messenger-lab3-migrate-1 Starting
Container mtusi-messenger-lab3-migrate-1 Started
Container mtusi-messenger-lab3-redis-1 Waiting
Container mtusi-messenger-lab3-migrate-1 Waiting
Container mtusi-messenger-lab3-redis-1 Healthy
Container mtusi-messenger-lab3-migrate-1 Exited
Container mtusi-messenger-lab3-api-2 Starting
Container mtusi-messenger-lab3-api-2 Started
BASE_URL="http://localhost:8080" ./scripts/wait-ready.sh
готов: http://localhost:8080
# реплики в конце
NAME STATE STATUS
mtusi-messenger-lab3-api-1 running Up 53 seconds (healthy)
mtusi-messenger-lab3-api-2 running Up 4 seconds (healthy)
+10
View File
@@ -0,0 +1,10 @@
# Остановка каждой реплики под нагрузкой (SIGTERM), полные данные в failover-each.json
# дата: 2026-10-30T18:44Z, commit: 269b449
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
$ make failover-each
BASE_URL="http://localhost:8080" python3 scripts/chaos.py stop --output evidence/failover-each.json
{"seconds": 19.65, "successful_requests": 12992, "failed_attempts": 1, "failed_statuses": [502], "successful_rps": 661.0, "longest_gap_between_successes_s": 1.013, "first_success_after_action_s": 0.0, "last_success_on_target_after_action_s": 14.65, "instances_seen": 2, "target": "3a8c5ed61bd5", "signal": "SIGTERM", "stop_command_s": 0.48, "excluded_by_lb_after_s": 0.59, "verify": {"confirmed": 12992, "in_history": 12992, "lost_confirmed": 0, "duplicate_ids": 0, "duplicate_texts": 0, "unconfirmed_but_saved": 0}}
{"seconds": 19.49, "successful_requests": 13416, "failed_attempts": 0, "failed_statuses": [], "successful_rps": 688.4, "longest_gap_between_successes_s": 1.003, "first_success_after_action_s": 0.0, "last_success_on_target_after_action_s": 14.488, "instances_seen": 2, "target": "b7c5235a859f", "signal": "SIGTERM", "stop_command_s": 0.5, "excluded_by_lb_after_s": 1.32, "verify": {"confirmed": 13416, "in_history": 13416, "lost_confirmed": 0, "duplicate_ids": 0, "duplicate_texts": 0, "unconfirmed_but_saved": 0}}
PASS: подтверждённые сообщения на месте, дублей нет
+14
View File
@@ -0,0 +1,14 @@
# SIGKILL и зависшая реплика (docker pause) под нагрузкой, полные данные в failover-kill.json и failover-pause.json
# дата: 2026-10-30T18:45Z, commit: 269b449
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
$ make failover-hard
BASE_URL="http://localhost:8080" python3 scripts/chaos.py kill --output evidence/failover-kill.json
{"seconds": 18.08, "successful_requests": 12553, "failed_attempts": 2, "failed_statuses": [502], "successful_rps": 694.1, "longest_gap_between_successes_s": 1.009, "first_success_after_action_s": 0.003, "last_success_on_target_after_action_s": 13.081, "instances_seen": 2, "target": "3a8c5ed61bd5", "signal": "SIGKILL", "stop_command_s": 0.25, "excluded_by_lb_after_s": 1.07, "verify": {"confirmed": 12553, "in_history": 12553, "lost_confirmed": 0, "duplicate_ids": 0, "duplicate_texts": 0, "unconfirmed_but_saved": 0}}
{"seconds": 19.69, "successful_requests": 13654, "failed_attempts": 3, "failed_statuses": [502], "successful_rps": 693.4, "longest_gap_between_successes_s": 1.018, "first_success_after_action_s": 0.003, "last_success_on_target_after_action_s": 14.688, "instances_seen": 2, "target": "b7c5235a859f", "signal": "SIGKILL", "stop_command_s": 0.25, "excluded_by_lb_after_s": 0.36, "verify": {"confirmed": 13654, "in_history": 13654, "lost_confirmed": 0, "duplicate_ids": 0, "duplicate_texts": 0, "unconfirmed_but_saved": 0}}
PASS: подтверждённые сообщения на месте, дублей нет
BASE_URL="http://localhost:8080" python3 scripts/chaos.py pause --output evidence/failover-pause.json
{"seconds": 18.19, "successful_requests": 11314, "failed_attempts": 4, "failed_statuses": [0], "successful_rps": 621.9, "longest_gap_between_successes_s": 3.075, "first_success_after_action_s": 0.004, "last_success_on_target_after_action_s": 13.19, "instances_seen": 2, "target": "3a8c5ed61bd5", "signal": "HANG", "stop_command_s": 0.04, "excluded_by_lb_after_s": 3.16, "verify": {"confirmed": 11314, "in_history": 11314, "lost_confirmed": 0, "duplicate_ids": 0, "duplicate_texts": 0, "unconfirmed_but_saved": 0}}
{"seconds": 18.4, "successful_requests": 9341, "failed_attempts": 8, "failed_statuses": [0], "successful_rps": 507.6, "longest_gap_between_successes_s": 3.062, "first_success_after_action_s": 0.0, "last_success_on_target_after_action_s": 13.4, "instances_seen": 2, "target": "b7c5235a859f", "signal": "HANG", "stop_command_s": 0.04, "excluded_by_lb_after_s": 3.46, "verify": {"confirmed": 9341, "in_history": 9341, "lost_confirmed": 0, "duplicate_ids": 0, "duplicate_texts": 0, "unconfirmed_but_saved": 0}}
PASS: подтверждённые сообщения на месте, дублей нет
+19
View File
@@ -0,0 +1,19 @@
# Поочерёдная замена реплик под нагрузкой, полные данные в rolling-update.json
# дата: 2026-10-30T18:46Z, commit: 269b449
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
# образы до замены
/mtusi-messenger-lab3-api-1 sha256:b20937fe39bd43979dd8d82acf328ac5f52
/mtusi-messenger-lab3-api-2 sha256:b20937fe39bd43979dd8d82acf328ac5f52
$ make rolling-update APP_VERSION=2
BASE_URL="http://localhost:8080" python3 scripts/chaos.py rolling --output evidence/rolling-update.json
{"seconds": 22.41, "successful_requests": 18344, "failed_attempts": 0, "failed_statuses": [], "successful_rps": 818.7, "longest_gap_between_successes_s": 1.007, "first_success_after_action_s": 0.003, "last_success_on_target_after_action_s": null, "instances_seen": 4, "update_seconds": 12.4, "containers_before": {"3a8c5ed61bd5": "sha256:b20937fe39bd", "b7c5235a859f": "sha256:b20937fe39bd"}, "containers_after": {"fb399bd141ea": "sha256:1cfd729d7e32", "69ad5d43951c": "sha256:1cfd729d7e32"}, "app_version": "2", "verify": {"confirmed": 18344, "in_history": 18344, "lost_confirmed": 0, "duplicate_ids": 0, "duplicate_texts": 0, "unconfirmed_but_saved": 0}}
PASS: подтверждённые сообщения на месте, дублей нет
# образы и версия после замены
/mtusi-messenger-lab3-api-3 sha256:1cfd729d7e3265f364f31481205f1a0b9a4 APP_VERSION=2
/mtusi-messenger-lab3-api-4 sha256:1cfd729d7e3265f364f31481205f1a0b9a4 APP_VERSION=2
$ docker compose logs lb | grep -c "status=5" # ответов 5xx через балансировщик за всё время жизни этого lb
5
+37
View File
@@ -0,0 +1,37 @@
# Тесты отказов: истечение сессии и ключа, остановка Redis и PostgreSQL, откат транзакции, гонки
# дата: 2026-10-30T18:50Z, commit: c8a5137
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
$ make test-failures
BASE_URL="http://localhost:8080" python3 -m unittest discover -s student-tests/failures -v
test_postgres_down (test_dependencies.DependencyDownTest.test_postgres_down) ... ok
test_redis_down (test_dependencies.DependencyDownTest.test_redis_down) ... ok
test_uncertain_write_can_be_repeated_with_same_key (test_dependencies.DependencyDownTest.test_uncertain_write_can_be_repeated_with_same_key) ... ok
test_expires_at_matches_ttl (test_expiry.SessionExpiryTest.test_expires_at_matches_ttl) ... ok
test_idempotency_key_is_free_after_ttl (test_expiry.SessionExpiryTest.test_idempotency_key_is_free_after_ttl) ... ok
test_login_after_expiry (test_expiry.SessionExpiryTest.test_login_after_expiry) ... ok
test_requests_do_not_extend_session (test_expiry.SessionExpiryTest.test_requests_do_not_extend_session) ... ok
test_session_expires (test_expiry.SessionExpiryTest.test_session_expires) ... ok
test_chat_with_unknown_member_is_rolled_back (test_transactions.TransactionTest.test_chat_with_unknown_member_is_rolled_back) ... ok
test_failed_message_leaves_no_key (test_transactions.TransactionTest.test_failed_message_leaves_no_key) ... ok
test_migrations_can_be_repeated (test_transactions.TransactionTest.test_migrations_can_be_repeated) ... ok
test_password_is_stored_as_argon2id_hash (test_transactions.TransactionTest.test_password_is_stored_as_argon2id_hash) ... ok
test_same_key_in_parallel_creates_one_row (test_transactions.TransactionTest.test_same_key_in_parallel_creates_one_row) ... ok
test_username_race_creates_one_row (test_transactions.TransactionTest.test_username_race_creates_one_row) ... ok
test_valid_chat_is_committed_whole (test_transactions.TransactionTest.test_valid_chat_is_committed_whole) ... ok
----------------------------------------------------------------------
Ran 15 tests in 63.124s
OK
# время ответа при отказе
$ docker compose stop redis; curl /api/v1/users/me с Bearer-токеном
{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"fd1ba9633a1f45b2b32edbe8fabcdfc0"}}
HTTP 503 за 0.014943 с
$ docker compose stop postgres; curl /health/ready
{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"60cb3d48d62f46e08603858885711899"}}
HTTP 503 за 3.005406 с
$ через 4 секунды: реплики исключены, отвечает балансировщик
{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"16ca6124-f073-41f0-be0d-f510ed4c067b"}}
HTTP 503 за 0.003489 с
+81
View File
@@ -0,0 +1,81 @@
# Контейнеры: лимиты, порты, пользователи, секреты, масштабирование
# дата: 2026-10-30T18:48Z, commit: 269b449
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
$ docker compose ps --format "table {{.Service}} {{.Ports}}" # опубликован только lb
SERVICE PORTS
api 8080/tcp
api 8080/tcp
lb 127.0.0.1:8080->8080/tcp
postgres 5432/tcp
redis 6379/tcp
$ grep -c container_name compose.yaml
0
# лимиты CPU (в наносекундах на секунду) и памяти (байт)
/mtusi-messenger-lab3-api-3 cpus=1000000000 memory=268435456
/mtusi-messenger-lab3-api-4 cpus=1000000000 memory=268435456
/mtusi-messenger-lab3-lb-1 cpus=500000000 memory=134217728
/mtusi-messenger-lab3-postgres-1 cpus=1000000000 memory=536870912
/mtusi-messenger-lab3-redis-1 cpus=500000000 memory=134217728
# сети: балансировщик не видит хранилища
lb mtusi-messenger-lab3_edge
api mtusi-messenger-lab3_data mtusi-messenger-lab3_edge
postgres mtusi-messenger-lab3_data
redis mtusi-messenger-lab3_data
$ docker exec fb399bd141ea id
uid=10001(app) gid=10001(app) groups=10001(app)
$ docker exec <api> ls -l /run/secrets
total 8
-r--r--r-- 1 root root 70 Oct 30 18:46 cache_url
-r--r--r-- 1 root root 95 Oct 30 18:46 database_url
$ docker exec <api> env | grep -ci "password\|postgresql://\|redis://" # секретов в окружении нет
0
$ docker compose --env-file .env images
CONTAINER REPOSITORY TAG PLATFORM IMAGE ID SIZE CREATED
mtusi-messenger-lab3-api-3 mtusi-messenger lab3 linux/arm64 1cfd729d7e32 203MB 18 minutes ago
mtusi-messenger-lab3-api-4 mtusi-messenger lab3 linux/arm64 1cfd729d7e32 203MB 18 minutes ago
mtusi-messenger-lab3-lb-1 mtusi-messenger-lb lab3 linux/arm64 31d9bea36444 38.8MB 6 minutes ago
mtusi-messenger-lab3-migrate-1 sha256 b20937fe39bd43979dd8d82acf328ac5f52c2229fa5711acd76cacb16666703f linux/arm64 b20937fe39bd 203MB 18 minutes ago
mtusi-messenger-lab3-postgres-1 postgres 17.11-alpine linux/arm64/v8 25a89970a832 291MB 6 weeks ago
mtusi-messenger-lab3-redis-1 redis 7.4.11-alpine linux/arm64/v8 ec4f171e9ff0 39.5MB 6 weeks ago
$ docker exec <api> pip freeze
annotated-doc==0.0.5
annotated-types==0.8.0
anyio==4.15.1
argon2-cffi==25.1.0
argon2-cffi-bindings==26.1.0
cffi==2.1.1
click==8.5.0
fastapi==0.143.0
h11==0.16.0
idna==3.20
opentelemetry-api==1.45.1
psycopg==3.3.6
psycopg-binary==3.3.6
psycopg-pool==3.3.3
pycparser==3.1
pydantic==2.13.5
pydantic_core==2.46.5
redis==8.1.0
starlette==1.7.0
typing-inspection==0.4.4
typing_extensions==4.16.0
uvicorn==0.54.0
$ git ls-files | grep -E "^\.env$|secrets" # в Git секретов нет
(пусто)
# масштабирование до 3 реплик: балансировщик находит новую через DNS
$ docker compose up -d --no-deps --no-recreate --no-build --scale api=3 api
$ 9 раз curl /health/live, число ответов каждой реплики
3 x-instance-id: 69ad5d43951c
3 x-instance-id: fb399bd141ea
3 x-instance-id: fb7499a486c0
+12
View File
@@ -0,0 +1,12 @@
# SIGTERM через балансировщик
# дата: 2026-10-30T18:48Z, commit: 269b449
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
$ python3 scripts/sigterm_check.py
$ docker kill --signal=SIGTERM fb399bd141ea
новых запросов после SIGTERM: 20, попало на останавливаемую реплику: 0
начатые до SIGTERM запросы: ['HTTP/1.1 201 Created']
из них завершила останавливаемая реплика: 3
процесс завершился за 1.43 с, код выхода 0
PASS: остановка корректная и укладывается в 10 секунд
+87
View File
@@ -0,0 +1,87 @@
# Индекс истории: EXPLAIN (ANALYZE, BUFFERS) на 152 048 сообщениях (сид 60 000 плюс записи нагрузочных прогонов), 10 000 в исследуемом чате
# дата: 2026-10-30T18:49Z, commit: 269b449
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
$ make explain
./scripts/explain_history.sh
== Объём данных
messages_total | messages_in_chat | table_size | index_size
----------------+------------------+------------+------------
152048 | 10000 | 16 MB | 15 MB
(1 row)
== 1. Первая страница (limit 50, запрос берёт 51 строку)
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.42..39.54 rows=51 width=79) (actual time=0.010..0.026 rows=51 loops=1)
Buffers: shared hit=10
-> Index Scan using messages_chat_history_idx on messages (cost=0.42..7708.63 rows=10050 width=79) (actual time=0.009..0.023 rows=51 loops=1)
Index Cond: (chat_id = '00000000-0000-4000-8000-000000000100'::uuid)
Buffers: shared hit=10
Planning:
Buffers: shared hit=33
Planning Time: 0.113 ms
Execution Time: 0.037 ms
(9 rows)
== 2. Страница из середины истории: keyset после 5000-го сообщения
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.42..48.43 rows=51 width=79) (actual time=0.006..0.015 rows=51 loops=1)
Buffers: shared hit=8
-> Index Scan using messages_chat_history_idx on messages (cost=0.42..7585.63 rows=8058 width=79) (actual time=0.006..0.013 rows=51 loops=1)
Index Cond: ((chat_id = '00000000-0000-4000-8000-000000000100'::uuid) AND (ROW(created_at, id) > ROW('2026-10-30 10:29:04.094702+00'::timestamp with time zone, 'c58c75ac-5b55-4d4d-b27e-370b05239644'::uuid)))
Buffers: shared hit=8
Planning Time: 0.022 ms
Execution Time: 0.036 ms
(7 rows)
== 3. Та же страница через OFFSET (так делать не стали)
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=3481.50..3481.63 rows=51 width=79) (actual time=2.228..2.232 rows=51 loops=1)
Buffers: shared hit=992
-> Sort (cost=3469.00..3494.13 rows=10050 width=79) (actual time=1.984..2.116 rows=5051 loops=1)
Sort Key: created_at, id
Sort Method: quicksort Memory: 1713kB
Buffers: shared hit=992
-> Bitmap Heap Scan on messages (cost=598.31..2800.93 rows=10050 width=79) (actual time=0.339..1.164 rows=10000 loops=1)
Recheck Cond: (chat_id = '00000000-0000-4000-8000-000000000100'::uuid)
Heap Blocks: exact=856
Buffers: shared hit=986
-> Bitmap Index Scan on messages_chat_history_idx (cost=0.00..595.79 rows=10050 width=0) (actual time=0.281..0.281 rows=10000 loops=1)
Index Cond: (chat_id = '00000000-0000-4000-8000-000000000100'::uuid)
Buffers: shared hit=130
Planning Time: 0.028 ms
Execution Time: 2.277 ms
(15 rows)
== 4. Запрос из пункта 2 без индекса messages_chat_history_idx (DROP INDEX внутри транзакции с ROLLBACK)
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=4800.35..4806.21 rows=51 width=79) (actual time=3.835..4.779 rows=51 loops=1)
Buffers: shared hit=2092
-> Gather Merge (cost=4800.35..5345.45 rows=4740 width=79) (actual time=3.834..4.776 rows=51 loops=1)
Workers Planned: 1
Workers Launched: 1
Buffers: shared hit=2092
-> Sort (cost=3800.34..3812.19 rows=4740 width=79) (actual time=2.952..2.953 rows=39 loops=2)
Sort Key: created_at, id
Sort Method: top-N heapsort Memory: 31kB
Buffers: shared hit=2092
Worker 0: Sort Method: top-N heapsort Memory: 31kB
-> Parallel Seq Scan on messages (cost=0.00..3642.20 rows=4740 width=79) (actual time=2.091..2.813 rows=2500 loops=2)
Filter: ((chat_id = '00000000-0000-4000-8000-000000000100'::uuid) AND (ROW(created_at, id) > ROW('2026-10-30 10:29:04.094702+00'::timestamp with time zone, 'c58c75ac-5b55-4d4d-b27e-370b05239644'::uuid)))
Rows Removed by Filter: 73524
Buffers: shared hit=2077
Planning:
Buffers: shared hit=4
Planning Time: 0.042 ms
Execution Time: 4.793 ms
(19 rows)
+54
View File
@@ -0,0 +1,54 @@
{
"workload": "4 клиента, closed loop, POST сообщений через балансировщик, повтор с тем же ключом",
"mode": "stop",
"rounds": [
{
"seconds": 19.65,
"successful_requests": 12992,
"failed_attempts": 1,
"failed_statuses": [
502
],
"successful_rps": 661.0,
"longest_gap_between_successes_s": 1.013,
"first_success_after_action_s": 0.0,
"last_success_on_target_after_action_s": 14.65,
"instances_seen": 2,
"target": "3a8c5ed61bd5",
"signal": "SIGTERM",
"stop_command_s": 0.48,
"excluded_by_lb_after_s": 0.59,
"verify": {
"confirmed": 12992,
"in_history": 12992,
"lost_confirmed": 0,
"duplicate_ids": 0,
"duplicate_texts": 0,
"unconfirmed_but_saved": 0
}
},
{
"seconds": 19.49,
"successful_requests": 13416,
"failed_attempts": 0,
"failed_statuses": [],
"successful_rps": 688.4,
"longest_gap_between_successes_s": 1.003,
"first_success_after_action_s": 0.0,
"last_success_on_target_after_action_s": 14.488,
"instances_seen": 2,
"target": "b7c5235a859f",
"signal": "SIGTERM",
"stop_command_s": 0.5,
"excluded_by_lb_after_s": 1.32,
"verify": {
"confirmed": 13416,
"in_history": 13416,
"lost_confirmed": 0,
"duplicate_ids": 0,
"duplicate_texts": 0,
"unconfirmed_but_saved": 0
}
}
]
}
+56
View File
@@ -0,0 +1,56 @@
{
"workload": "4 клиента, closed loop, POST сообщений через балансировщик, повтор с тем же ключом",
"mode": "kill",
"rounds": [
{
"seconds": 18.08,
"successful_requests": 12553,
"failed_attempts": 2,
"failed_statuses": [
502
],
"successful_rps": 694.1,
"longest_gap_between_successes_s": 1.009,
"first_success_after_action_s": 0.003,
"last_success_on_target_after_action_s": 13.081,
"instances_seen": 2,
"target": "3a8c5ed61bd5",
"signal": "SIGKILL",
"stop_command_s": 0.25,
"excluded_by_lb_after_s": 1.07,
"verify": {
"confirmed": 12553,
"in_history": 12553,
"lost_confirmed": 0,
"duplicate_ids": 0,
"duplicate_texts": 0,
"unconfirmed_but_saved": 0
}
},
{
"seconds": 19.69,
"successful_requests": 13654,
"failed_attempts": 3,
"failed_statuses": [
502
],
"successful_rps": 693.4,
"longest_gap_between_successes_s": 1.018,
"first_success_after_action_s": 0.003,
"last_success_on_target_after_action_s": 14.688,
"instances_seen": 2,
"target": "b7c5235a859f",
"signal": "SIGKILL",
"stop_command_s": 0.25,
"excluded_by_lb_after_s": 0.36,
"verify": {
"confirmed": 13654,
"in_history": 13654,
"lost_confirmed": 0,
"duplicate_ids": 0,
"duplicate_texts": 0,
"unconfirmed_but_saved": 0
}
}
]
}
+56
View File
@@ -0,0 +1,56 @@
{
"workload": "4 клиента, closed loop, POST сообщений через балансировщик, повтор с тем же ключом",
"mode": "pause",
"rounds": [
{
"seconds": 18.19,
"successful_requests": 11314,
"failed_attempts": 4,
"failed_statuses": [
0
],
"successful_rps": 621.9,
"longest_gap_between_successes_s": 3.075,
"first_success_after_action_s": 0.004,
"last_success_on_target_after_action_s": 13.19,
"instances_seen": 2,
"target": "3a8c5ed61bd5",
"signal": "HANG",
"stop_command_s": 0.04,
"excluded_by_lb_after_s": 3.16,
"verify": {
"confirmed": 11314,
"in_history": 11314,
"lost_confirmed": 0,
"duplicate_ids": 0,
"duplicate_texts": 0,
"unconfirmed_but_saved": 0
}
},
{
"seconds": 18.4,
"successful_requests": 9341,
"failed_attempts": 8,
"failed_statuses": [
0
],
"successful_rps": 507.6,
"longest_gap_between_successes_s": 3.062,
"first_success_after_action_s": 0.0,
"last_success_on_target_after_action_s": 13.4,
"instances_seen": 2,
"target": "b7c5235a859f",
"signal": "HANG",
"stop_command_s": 0.04,
"excluded_by_lb_after_s": 3.46,
"verify": {
"confirmed": 9341,
"in_history": 9341,
"lost_confirmed": 0,
"duplicate_ids": 0,
"duplicate_texts": 0,
"unconfirmed_but_saved": 0
}
}
]
}
+35
View File
@@ -0,0 +1,35 @@
{
"workload": "4 клиента, closed loop, POST сообщений через балансировщик, повтор с тем же ключом",
"mode": "rolling",
"rounds": [
{
"seconds": 22.41,
"successful_requests": 18344,
"failed_attempts": 0,
"failed_statuses": [],
"successful_rps": 818.7,
"longest_gap_between_successes_s": 1.007,
"first_success_after_action_s": 0.003,
"last_success_on_target_after_action_s": null,
"instances_seen": 4,
"update_seconds": 12.4,
"containers_before": {
"3a8c5ed61bd5": "sha256:b20937fe39bd",
"b7c5235a859f": "sha256:b20937fe39bd"
},
"containers_after": {
"fb399bd141ea": "sha256:1cfd729d7e32",
"69ad5d43951c": "sha256:1cfd729d7e32"
},
"app_version": "2",
"verify": {
"confirmed": 18344,
"in_history": 18344,
"lost_confirmed": 0,
"duplicate_ids": 0,
"duplicate_texts": 0,
"unconfirmed_but_saved": 0
}
}
]
}