Files
mtusi2026lab3/evidence/tests/student-test-lb.md
T
ricoromaandClaude Opus 5.5 cb14586a19 docs: retake replicas-lb evidence from a4ca9ef after verify
The stand was recreated from a4ca9ef (make down, make run_docker) and
all evidence of the change was taken again on it: stand, distribution,
LB errors, test-persistence, test-failover for each replica (stop and
kill), stop-one refusals, make test and student_test through the LB,
test_isolated, failure_checks and bench self-checks.

New evidence closes scenarios verify found without proof: a real git
clone on non-default ports, a hung replica (docker pause: DOWN after
7.7 s, in-flight request 504), PostgreSQL outage behind the LB, replica
tests failing against one process, aborted responses via
driver.py kill-inflight. REPORT.md gets the corrected detection
formula, the measured cost of the 1 CPU limit for Argon2id and the new
rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 22:09:15 +03:00

123 lines
9.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# `make test` и `make student_test` через балансировщик: тесты реплик
| | |
|---|---|
| Спеки | `student-tests` «Тесты реплик через балансировщик» — «Против стенда с балансировщиком», «Реплик меньше ожидаемого»; `idempotency` «Гонка одного ключа через реплики», «Повтор через другую реплику»; `load-balancing` «Одна сессия на разных репликах», «Запись видна через другую реплику»; `api-conventions` «Одно значение на процесс»; `container-run` «Запуск через compose» — «Штатный запуск» (часть «make student_test проходит») |
| Change | `replicas-lb`, задачи 6.1 и 7.2 (`make test` через LB и раздел «Реплик меньше ожидаемого» добавлены в verify) |
| Дата | 2026-10-10 15:50:28 UTC (через LB, 22 с вместе со smoke); 15:51:13 UTC (против одного процесса) |
| Commit | `a4ca9ef`, рабочее дерево чистое (стенд пересоздан с этого commit, `../replicas/stand.md`) |
| Стенд | `make run_docker`: проект `mtusi-lab3`, HAProxy на `127.0.0.1:8080` (`BASE_URL` по умолчанию), `api` × 2; `EXPECT_REPLICAS=2` из `API_REPLICAS` по умолчанию. Против одного процесса — `driver.py start` (консоль, `127.0.0.1:18080`, та же база) |
| Хост | Docker Desktop 29.8.1, macOS arm64; ВМ Docker: 12 CPU, 7,7 GiB RAM; ноутбук от батареи; лимит реплики 1 CPU / 512 MiB |
## Публичный smoke через LB
```text
$ make test
python3 tests/smoke.py --base-url "http://localhost:8080"
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
exit=0
```
## Свой набор через LB
```text
$ make student_test # exit 0
BASE_URL=http://localhost:8080 EXPECT_REPLICAS=2 uv run pytest
collecting ... collected 146 items / 15 deselected / 131 selected
...
coverage: 135 scenarios in 11 specs, 123 tested (16 by make failure_checks), 12 excluded
===================== 131 passed, 15 deselected in 21.03s ======================
# строк в рабочей базе до и после make test + make student_test
users, sessions: 1581, 1727 → 1770, 1913
```
Smoke и набор зарегистрировали 189 пользователей и создали 186 сессий:
около 375 хэшей Argon2id. На двух репликах по 1 CPU это 21 с, на одной
(`make test_isolated`) — около минуты (`../replicas/stand.md`, «Цена
лимита 1 CPU для входа»).
### Тесты реплик и их вывод
```text
student-tests/test_api_conventions.py::test_one_instance_id_per_process PASSED
two series of 18 requests: {'3681880fc55f': 18, '8100f940a5fa': 18}
student-tests/test_idempotency.py::test_replay_on_other_replica PASSED
sent via 8100f940a5fa, replayed via ['3681880fc55f']
409 via ['3681880fc55f', '8100f940a5fa']
student-tests/test_load_balancing.py::test_one_session_on_several_replicas PASSED
one session, 20 requests: {'3681880fc55f': 10, '8100f940a5fa': 10}
student-tests/test_load_balancing.py::test_write_visible_through_other_replica PASSED
written via 8100f940a5fa, read via {'3681880fc55f': 3, '8100f940a5fa': 3}
student-tests/test_race.py::test_same_key_at_once PASSED
key race: 10 clients, statuses {201: 10}, max in flight 10; history: 1 messages
student-tests/test_race.py::test_same_key_through_replicas PASSED
key race: 10 clients, statuses {201: 10}, max in flight 10; history: 1 messages
key race through replicas: {'8100f940a5fa': 5, '3681880fc55f': 5}
student-tests/test_race.py::test_hundred_messages_from_ten_clients PASSED
race: 10 clients x 10 messages, statuses {201: 100}, max in flight 10; history: 100 messages, 100 unique ids, 4 pages by 30
student-tests/test_race.py::test_same_username_at_once PASSED
username race: 10 clients, statuses {409: 9, 201: 1}, max in flight 10
```
- **Гонка одного ключа через реплики** (уровень «4»): 10 клиентов за
`threading.Barrier`, одно тело и один ключ. Все 10 ответов 201 с
одинаковым `Message`, в истории одно сообщение. Ответы дали обе
реплики, по 5, и среди них есть пара запросов разных реплик,
пересекавшихся по времени: повторы действительно шли одновременно
через разные процессы, а не по очереди.
- **Повтор через другую реплику**: отправка обслужена `8100f940a5fa`,
повтор с тем же ключом — `3681880fc55f`, тот же JSON; другое тело с
этим ключом — 409 от обеих реплик.
- **Одна сессия на разных репликах**: один вход, 20 запросов
`GET /users/me` с одним токеном — поровну на обе реплики.
- **Запись видна через другую реплику**: сообщение записано через
одну реплику и есть в каждом из 6 чтений истории, в том числе через
другую.
- **Одно значение на процесс**: две серии по 18 запросов — у каждой
реплики одно значение, оно повторяется, новых во второй серии нет.
Против одного процесса (`make test_isolated`) четыре теста реплик
пропускаются с причиной (`test-isolated.md`). Ожидания «через разные
реплики» проверены и на ошибочной конфигурации LB: временный `balance
first` в `haproxy.cfg` (весь трафик на одну реплику) — все четыре теста
реплик упали, увидев одно значение `X-Instance-Id` (задача 3.3, проверка
на рабочем дереве до коммита `ab71c3b`, конфиг возвращён; вывод не
сохранялся).
## Реплик меньше ожидаемого: один процесс без `EXPECT_REPLICAS=1`
Тот же набор против одного процесса API в консоли, но с ожиданием по
умолчанию (`EXPECT_REPLICAS` = `API_REPLICAS` = 2). Тесты реплик должны
упасть с числом увиденных значений, а не пропуститься.
```text
$ python3 .claude/skills/run-mtusi-messenger/driver.py start
up on http://127.0.0.1:18080 pgid=… log=/tmp/mtusi-api-18080.log
$ make student_test BASE_URL=http://localhost:18080 # exit 2 (pytest — 1)
BASE_URL=http://localhost:18080 EXPECT_REPLICAS=2 uv run pytest
collecting ... collected 146 items / 15 deselected / 131 selected
student-tests/test_idempotency.py::test_replay_on_other_replica FAILED [ 53%]
student-tests/test_load_balancing.py::test_one_session_on_several_replicas FAILED [ 61%]
student-tests/test_load_balancing.py::test_write_visible_through_other_replica FAILED [ 62%]
student-tests/test_race.py::test_same_key_through_replicas FAILED [ 78%]
E AssertionError: saw 1 X-Instance-Id ['<hostname>'] behind BASE_URL, EXPECT_REPLICAS=2: no load balancing across replicas; against one API process run with EXPECT_REPLICAS=1
E AssertionError: saw 1 X-Instance-Id ['<hostname>'] behind BASE_URL, EXPECT_REPLICAS=2: no load balancing across replicas; against one API process run with EXPECT_REPLICAS=1
E AssertionError: saw 1 X-Instance-Id ['<hostname>'] behind BASE_URL, EXPECT_REPLICAS=2: no load balancing across replicas; against one API process run with EXPECT_REPLICAS=1
E AssertionError: saw 1 X-Instance-Id ['<hostname>'] behind BASE_URL, EXPECT_REPLICAS=2: no load balancing across replicas; against one API process run with EXPECT_REPLICAS=1
two series of 18 requests: {'<hostname>': 36}
================ 4 failed, 127 passed, 15 deselected in 15.59s =================
$ python3 .claude/skills/run-mtusi-messenger/driver.py stop
stopped 18080
```
- Четыре теста реплик упали, сообщение называет число увиденных
значений (1) и ожидание (`EXPECT_REPLICAS=2`); остальные 127 прошли.
Сломанный LB (одна живая реплика или sticky) дал бы тот же результат,
а не пропуск.
- «Одно значение на процесс» здесь проходит: против одного процесса
все 36 ответов несут одно значение, а такой процесс и через LB
отвечал бы одним значением на все свои ответы.
- `X-Instance-Id` консольного процесса — имя машины, в evidence заменено
на `<hostname>`.