Lab2
This commit is contained in:
+42
-3
@@ -1,5 +1,44 @@
|
||||
# Доказательства
|
||||
# Доказательства Lab2
|
||||
|
||||
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
|
||||
## Контекст
|
||||
|
||||
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
|
||||
- Дата: 2026-09-29.
|
||||
- Commit: `<COMMIT_HASH>` (заполнить после commit).
|
||||
- Хост: Windows 11, Docker Desktop 29.3 (WSL2); тесты запускались из WSL Ubuntu, Python 3.14.
|
||||
- API: FastAPI/Uvicorn в образе `python:3.12.7-slim`.
|
||||
- Хранилище: PostgreSQL `postgres:16.4-alpine`, named volume `postgres_data`.
|
||||
- Кэш сессий: Valkey `valkey/valkey:8.0.1-alpine`, без persistence (источник истины — PostgreSQL).
|
||||
- API URL: `http://localhost:8080`; стенд с коротким TTL: `http://localhost:8081`.
|
||||
- Session TTL: 3600 s (основной API), 3 s (`api_short_ttl`); TTL записи в кэше ≤ 60 s.
|
||||
- Restart hook: `scripts/restart.sh` → `docker compose restart db valkey api`, volumes не удаляются.
|
||||
|
||||
Все файлы собраны одной командой `sh scripts/run_evidence.sh` на поднятом стенде
|
||||
(`docker compose --profile tests up -d --build api api_short_ttl`).
|
||||
|
||||
## Файлы
|
||||
|
||||
| Файл | Команда | Назначение |
|
||||
|-------------------------|-------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
|
||||
| `check_contract.txt` | `python3 scripts/check_contract.py` | Структура репозитория, OpenAPI refs и Python syntax |
|
||||
| `validate_openapi.txt` | `python3 scripts/validate_openapi.py` | OpenAPI 3.1 и JSON Schema validation |
|
||||
| `smoke.txt` | `python3 tests/smoke.py --base-url http://localhost:8080` | Basic/Bearer, users, chats, messages, pagination, logout |
|
||||
| `persistence.txt` | `python3 tests/resilience.py --mode persistence --action-script scripts/restart.sh` | Restart API, PostgreSQL и Valkey; состояние контейнеров до и после hook |
|
||||
| `migrations_repeat.txt` | `docker compose run --rm migrate` | Повторный запуск migrations без дублирования |
|
||||
| `level4.txt` | `python3 student-tests/level4.py` | Неверный пароль, logout, expiry, кэш, гонка регистрации, отказ Valkey/PostgreSQL |
|
||||
| `explain.txt` | `docker compose --profile tools run --rm db_checks` | Rollback создания чата; `EXPLAIN (ANALYZE, BUFFERS)` на 10 000 сообщений |
|
||||
| `load.txt`, `load.json` | `python3 tests/load.py --duration 15 --concurrency 4` | Closed-loop нагрузка на создание сообщений |
|
||||
|
||||
## Нагрузка
|
||||
|
||||
Профиль: 4 concurrent клиента, 15 seconds, closed-loop `POST /api/v1/chats/{chat_id}/messages`, без automatic retries.
|
||||
Результат: 4374 успешных запроса, 0 ошибок, ≈291 RPS, p50/p95/p99 = 13.0/18.5/30.3 ms.
|
||||
|
||||
Это локальное измерение на Docker Desktop/WSL2, а не production SLA.
|
||||
Latency включает client overhead; closed-loop нагрузка подвержена coordinated omission.
|
||||
|
||||
## Безопасность
|
||||
|
||||
Evidence содержит только синтетические данные и агрегированные результаты.
|
||||
В папку не добавляются `.env`, Docker secrets, session tokens, Basic credentials,
|
||||
cookies, private keys, database dumps, реальные сообщения и raw HTTP headers.
|
||||
UUID в `explain.txt` относятся к синтетическому чату `explain-bench-0`.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
@@ -0,0 +1,68 @@
|
||||
== rollback of composite chat creation
|
||||
expected failure: IntegrityError
|
||||
PASS: create_chat_with_members fails on a missing member
|
||||
PASS: chat row was rolled back together with members
|
||||
PASS: no chats without members exist in the database
|
||||
|
||||
== EXPLAIN for message history pagination
|
||||
messages total: 81809; in explained chat: 10000
|
||||
PASS: explained chat has >= 10 000 messages
|
||||
|
||||
-- first page
|
||||
Limit (actual time=0.026..0.042 rows=51 loops=1)
|
||||
Buffers: shared hit=4
|
||||
-> Index Scan using messages_keyset_idx on messages (actual time=0.025..0.034 rows=51 loops=1)
|
||||
Index Cond: (chat_id = 'd00c8d51-a786-404d-aea9-c8447ec0614b'::uuid)
|
||||
Buffers: shared hit=4
|
||||
Planning:
|
||||
Buffers: shared hit=6
|
||||
Planning Time: 0.208 ms
|
||||
Execution Time: 0.079 ms
|
||||
|
||||
-- keyset page after position 9000
|
||||
Limit (actual time=0.063..0.084 rows=51 loops=1)
|
||||
Buffers: shared hit=4 read=1
|
||||
-> Index Scan using messages_keyset_idx on messages (actual time=0.062..0.076 rows=51 loops=1)
|
||||
Index Cond: ((chat_id = 'd00c8d51-a786-404d-aea9-c8447ec0614b'::uuid) AND (ROW(created_at, id) > ROW('2026-09-28 16:11:52.757537+00'::timestamp with time zone, 'cab6bb16-0f15-46a0-8f5e-13cb8416fd5e'::uuid)))
|
||||
Buffers: shared hit=4 read=1
|
||||
Planning Time: 0.135 ms
|
||||
Execution Time: 0.215 ms
|
||||
|
||||
-- OFFSET 9000 (not used by the API)
|
||||
Limit (actual time=8.594..8.607 rows=51 loops=1)
|
||||
Buffers: shared hit=265
|
||||
-> Sort (actual time=7.284..8.013 rows=9051 loops=1)
|
||||
Sort Key: created_at, id
|
||||
Sort Method: quicksort Memory: 1713kB
|
||||
Buffers: shared hit=265
|
||||
-> Bitmap Heap Scan on messages (actual time=0.651..2.145 rows=10000 loops=1)
|
||||
Recheck Cond: (chat_id = 'd00c8d51-a786-404d-aea9-c8447ec0614b'::uuid)
|
||||
Heap Blocks: exact=134
|
||||
Buffers: shared hit=265
|
||||
-> Bitmap Index Scan on messages_keyset_idx (actual time=0.615..0.616 rows=10000 loops=1)
|
||||
Index Cond: (chat_id = 'd00c8d51-a786-404d-aea9-c8447ec0614b'::uuid)
|
||||
Buffers: shared hit=131
|
||||
Planning Time: 0.150 ms
|
||||
Execution Time: 9.005 ms
|
||||
|
||||
-- keyset page WITHOUT messages_keyset_idx (rolled back)
|
||||
Limit (actual time=7.478..7.490 rows=51 loops=1)
|
||||
Buffers: shared hit=1076
|
||||
-> Sort (actual time=7.475..7.479 rows=51 loops=1)
|
||||
Sort Key: created_at, id
|
||||
Sort Method: top-N heapsort Memory: 31kB
|
||||
Buffers: shared hit=1076
|
||||
-> Seq Scan on messages (actual time=2.279..7.304 rows=999 loops=1)
|
||||
Filter: ((chat_id = 'd00c8d51-a786-404d-aea9-c8447ec0614b'::uuid) AND (ROW(created_at, id) > ROW('2026-09-28 16:11:52.757537+00'::timestamp with time zone, 'cab6bb16-0f15-46a0-8f5e-13cb8416fd5e'::uuid)))
|
||||
Rows Removed by Filter: 80810
|
||||
Buffers: shared hit=1076
|
||||
Planning:
|
||||
Buffers: shared hit=4
|
||||
Planning Time: 0.204 ms
|
||||
Execution Time: 7.569 ms
|
||||
PASS: first page reads the index in order, no Sort
|
||||
PASS: keyset cursor is an Index Cond, not a filter over the history
|
||||
PASS: keyset deep page touches fewer buffers than OFFSET (5 < 265)
|
||||
PASS: index reduces buffers for the deep page (5 < 1076)
|
||||
|
||||
PASS: db checks
|
||||
@@ -0,0 +1,72 @@
|
||||
|
||||
== credentials and anonymous requests
|
||||
PASS: wrong password -> 401 with Basic challenge
|
||||
PASS: unknown user -> 401
|
||||
PASS: no Authorization -> 401 with Bearer challenge
|
||||
PASS: X-User-Id alone gives no access
|
||||
PASS: Basic is not accepted on business endpoints
|
||||
PASS: unknown Bearer token -> 401
|
||||
|
||||
== logout and Valkey session cache
|
||||
PASS: no cache entry before first use
|
||||
PASS: fresh token works (cache miss -> PostgreSQL)
|
||||
PASS: session is cached in Valkey under sha256(token)
|
||||
PASS: second request works (cache hit)
|
||||
PASS: logout -> 204
|
||||
PASS: revoked token -> 401 right after logout
|
||||
PASS: revoked token stays 401 (cache tombstone)
|
||||
PASS: second logout with same token -> 401
|
||||
PASS: another session of the user is unaffected
|
||||
|
||||
== expiry with SESSION_TTL_SECONDS=3 (api_short_ttl)
|
||||
PASS: login on short-TTL instance
|
||||
PASS: token valid before expiry (now cached)
|
||||
PASS: token rejected after expiry, cache too
|
||||
PASS: logout of expired token -> 401
|
||||
|
||||
== registration race: 20 parallel requests, one username
|
||||
statuses: {201: 1, 409: 19}
|
||||
PASS: exactly one registration wins
|
||||
PASS: all others get 409, no 500
|
||||
|
||||
== Valkey stop: cache is bypassed, PostgreSQL decides
|
||||
PASS: token cached before outage
|
||||
PASS: login works without Valkey
|
||||
PASS: Bearer request works without Valkey
|
||||
PASS: write works without Valkey
|
||||
PASS: forged token still 401 without Valkey
|
||||
PASS: anonymous still 401 without Valkey
|
||||
PASS: logout works without Valkey
|
||||
PASS: token revoked during outage -> 401
|
||||
PASS: bounded latency during outage (max 0.27s)
|
||||
PASS: token revoked during outage stays 401 after Valkey returns (stale cache flushed)
|
||||
PASS: live session works after recovery
|
||||
|
||||
== Valkey pause: cache is bypassed, PostgreSQL decides
|
||||
PASS: token cached before outage
|
||||
PASS: login works without Valkey
|
||||
PASS: Bearer request works without Valkey
|
||||
PASS: write works without Valkey
|
||||
PASS: forged token still 401 without Valkey
|
||||
PASS: anonymous still 401 without Valkey
|
||||
PASS: logout works without Valkey
|
||||
PASS: token revoked during outage -> 401
|
||||
PASS: bounded latency during outage (max 0.26s)
|
||||
PASS: token revoked during outage stays 401 after Valkey returns (stale cache flushed)
|
||||
PASS: live session works after recovery
|
||||
|
||||
== PostgreSQL stop: limited 503, anonymous is never trusted
|
||||
PASS: token cached before outage
|
||||
PASS: write -> 503 unavailable with request id (3.01s)
|
||||
PASS: 503 is returned within the configured timeouts
|
||||
PASS: /health/ready -> 503
|
||||
PASS: /health/live -> 200
|
||||
PASS: login -> 503
|
||||
PASS: anonymous -> 401 without touching the DB
|
||||
PASS: unverifiable token -> 503, never 2xx
|
||||
PASS: X-User-Id -> 401 during outage
|
||||
PASS: cached valid session still identifies the user
|
||||
PASS: API ready again after PostgreSQL start
|
||||
PASS: writes work again with the old session
|
||||
|
||||
PASS: level 4 checks
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 2,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 15.0,
|
||||
"elapsed_seconds": 15.06,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 1850,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 122.839,
|
||||
"successful_latency_ms": {
|
||||
"p50": 31.423,
|
||||
"p95": 41.656,
|
||||
"p99": 55.931
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 2,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 15.0,
|
||||
"elapsed_seconds": 15.06,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 1850,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 122.839,
|
||||
"successful_latency_ms": {
|
||||
"p50": 31.423,
|
||||
"p95": 41.656,
|
||||
"p99": 55.931
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
SKIP 001_initial_schema.sql
|
||||
SKIP 002_indexes.sql
|
||||
PASS: migrations applied
|
||||
@@ -0,0 +1,14 @@
|
||||
## containers before restart hook
|
||||
api running Up About a minute 2026-09-30 11:30:01 +0300 MSK
|
||||
api_short_ttl running Up 3 minutes 2026-09-30 11:30:01 +0300 MSK
|
||||
db running Up 39 seconds (healthy) 2026-09-29 20:09:08 +0300 MSK
|
||||
migrate exited Exited (0) 3 minutes ago 2026-09-30 11:30:01 +0300 MSK
|
||||
valkey running Up About a minute (healthy) 2026-09-29 20:09:08 +0300 MSK
|
||||
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 restart hook (Status shows new uptime)
|
||||
api running Up 3 seconds 2026-09-30 11:30:01 +0300 MSK
|
||||
api_short_ttl running Up 3 minutes 2026-09-30 11:30:01 +0300 MSK
|
||||
db running Up 4 seconds (health: starting) 2026-09-29 20:09:08 +0300 MSK
|
||||
migrate exited Exited (0) 3 minutes ago 2026-09-30 11:30:01 +0300 MSK
|
||||
valkey running Up 4 seconds (health: starting) 2026-09-29 20:09:08 +0300 MSK
|
||||
@@ -0,0 +1 @@
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1 @@
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
Reference in New Issue
Block a user