forked from mtusi2026/mtusi2026lab6
feat(lab6): add observability and SLO burn-rate alerts
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
# Lab 6 — final audit
|
||||
|
||||
Date: 2026-11-12.
|
||||
|
||||
## Confirmed fixes from the audit
|
||||
|
||||
1. SLO policy window previously said 30 days while Prometheus retained 7 days. The policy is now explicitly 7 days and has verifiable `messenger:slo_*_ratio_7d` recording rules.
|
||||
2. The skeleton-only CI had no application job. CI now builds the complete Compose stack, waits for readiness, runs the public smoke and telemetry-path tests, prints logs on failure and removes ephemeral volumes.
|
||||
3. Histogram calibration was added to guard against seconds/milliseconds and default-bucket mistakes.
|
||||
4. `govulncheck` found 19 reachable vulnerabilities in the original AMQP and image dependencies. `github.com/rabbitmq/amqp091-go` was upgraded to v1.14.0 and `golang.org/x/image` to v0.45.0. Fixed transitive versions of `grpc`, `x/net`, `x/crypto` and `klauspost/compress` removed six additional non-reachable findings.
|
||||
|
||||
## Verification
|
||||
|
||||
- `git diff --check`: PASS.
|
||||
- `git add --dry-run .`: `.env`, `secrets/`, `__pycache__` and build artifacts excluded.
|
||||
- Secret scan: no committed local credential value found.
|
||||
- `go test -race -count=1 ./...`: PASS.
|
||||
- `go vet ./...`, `go build ./...`, `go mod verify`: PASS.
|
||||
- `govulncheck -show verbose ./...`: PASS; no symbol, package or module vulnerabilities found.
|
||||
- Python compileall: PASS.
|
||||
- frontend `npm ci`, `npm test`, `npm run build`: PASS; npm reported 0 vulnerabilities.
|
||||
- Compose config and all dashboard JSON files: PASS.
|
||||
- Prometheus `promtool`: PASS, 17 rules.
|
||||
- Public smoke, grade-4 telemetry regression, grade-5 SLO experiment: PASS.
|
||||
- Histogram calibration: PASS; HTTP client/Prometheus p95 3.570/4.910 ms, ready p95 1.013/0.946 s, worker p95 97.5 ms.
|
||||
|
||||
## Remaining limitations
|
||||
|
||||
- The seven-day SLO policy is locally verifiable but the burn windows are intentionally compressed for the laboratory experiment.
|
||||
- No independent human performed the runbook drill; the black-box scenario follows it automatically.
|
||||
- Repository shell scripts passed `bash -n` and ShellCheck 0.11.0 after resolving four SC1007 warnings.
|
||||
@@ -0,0 +1,132 @@
|
||||
# Lab6 — доказательства уровня 3
|
||||
|
||||
Дата прогона: 2026-11-10. Стенд: WSL2, Docker Compose, ветка `solution/bvt2301-churilin`. Чтобы не останавливать lab5, lab6 проверялась на loopback-портах 18080/13000/19090/13100/13200.
|
||||
|
||||
## Сборка и базовые проверки
|
||||
|
||||
```text
|
||||
make check
|
||||
PASS
|
||||
|
||||
make validate PYTHON=/home/d1frend/HL/mtusi2026lab5/.venv/bin/python
|
||||
PASS
|
||||
|
||||
go test -count=1 ./...
|
||||
PASS
|
||||
|
||||
go vet ./...
|
||||
PASS
|
||||
|
||||
go build ./...
|
||||
PASS
|
||||
|
||||
docker compose --env-file .env config --quiet
|
||||
exit 0
|
||||
```
|
||||
|
||||
После `docker compose --env-file .env up -d --build` healthy: обе API-реплики, load balancer, frontend, PostgreSQL, Redis, MinIO, RabbitMQ, Collector, Prometheus, Loki, Tempo и Grafana. Одноразовые migrate/minio-bootstrap завершились успешно.
|
||||
|
||||
## Публичный smoke
|
||||
|
||||
```text
|
||||
make test BASE_URL=http://127.0.0.1:18080
|
||||
PASS: signup/signin/session/me/search/chats/messages/cursors/attachments/auth/error format
|
||||
```
|
||||
|
||||
## Наблюдаемость
|
||||
|
||||
Команда:
|
||||
|
||||
```sh
|
||||
python3 tests/observability_grade3.py \
|
||||
--prometheus-url http://127.0.0.1:19090 \
|
||||
--loki-url http://127.0.0.1:13100 \
|
||||
--tempo-url http://127.0.0.1:13200 \
|
||||
--grafana-url http://127.0.0.1:13000 \
|
||||
--timeout 90
|
||||
```
|
||||
|
||||
Фактический итог:
|
||||
|
||||
```text
|
||||
PASS: grade-3 metrics, structured logs, traces and Grafana dashboard verified.
|
||||
api_metric_series=14
|
||||
worker_metric_series=2
|
||||
api_trace_id=e18612a970f7515c85473ed980f0fa12
|
||||
worker_trace_id=5af46620fe843e5448bf60562ca92b0e
|
||||
dashboard_uid=mtusi-lab6-grade3
|
||||
```
|
||||
|
||||
После `make test` сценарий проверяет сохранённые сигналы:
|
||||
|
||||
1. проверяет API counter/histogram и worker counter/histogram в Prometheus;
|
||||
2. проверяет `service_name`, `service_version`, `service_instance_id`, `deployment_environment_name=lab`;
|
||||
3. отклоняет forbidden high-cardinality labels;
|
||||
4. находит структурированные API/worker events в Loki и извлекает trace ID;
|
||||
5. запрашивает соответствующие traces в Tempo;
|
||||
6. проверяет health Grafana и provisioned dashboard UID.
|
||||
|
||||
Trace ID — диагностические идентификаторы, не секреты. В доказательства не включены credentials, токены, тела сообщений или байты вложений.
|
||||
|
||||
## Проверка сохранности бизнес-функций
|
||||
|
||||
Проверка выполнена после подключения instrumentation и после финального recreate сервисов. Публичный smoke прошёл повторно; Collector был перезапущен отдельно, при этом API оставался healthy. После восстановления Collector observability test снова увидел метрики, логи и трассы. Это подтверждает неблокирующий экспорт в проверенной модели кратковременной недоступности Collector.
|
||||
|
||||
## Два контролируемых отказа
|
||||
|
||||
Воспроизводимая команда для чистого стенда:
|
||||
|
||||
```sh
|
||||
make test-observability-incidents
|
||||
```
|
||||
|
||||
Она последовательно запускает `test-async-resilience`, `test-storage-outage` и затем проверяет сохранённые сигналы. На стенде с альтернативными портами финальный verifier дал:
|
||||
|
||||
```text
|
||||
PASS
|
||||
api_5xx_total=1
|
||||
worker_failed_total=5
|
||||
storage event=http_request_completed
|
||||
storage route=POST /api/v1/chats/{chat_id}/attachments
|
||||
storage status_code=503
|
||||
storage trace_id=7773146a1f76d4048d2eca50f54a7443
|
||||
worker event=attachment_job_failed
|
||||
worker outcome=failed
|
||||
worker attempt=1
|
||||
worker trace_id=6a131a33b296ca076056c08015dc2a9e
|
||||
```
|
||||
|
||||
Обе trace ID запрошены через Tempo API и содержат реальные batches/spans. Диагноз первого инцидента: S3/MinIO недоступен на upload-path, потому что API route одновременно дал 503/5xx и trace. Диагноз второго: worker не завершил attachment job и дошёл до bounded failure; это одновременно видно по `outcome=failed`, warn event и consumer trace.
|
||||
|
||||
Фактический fault injection MinIO:
|
||||
|
||||
```text
|
||||
readiness_503_seconds=2.005
|
||||
upload_503_seconds=5.009
|
||||
original_bytes_verified=111817
|
||||
PASS: MinIO outage returns bounded JSON 503 and preserves existing originals.
|
||||
```
|
||||
|
||||
Фактический async resilience:
|
||||
|
||||
```text
|
||||
PASS: durable recovery, idempotent redelivery and bounded final failure verified.
|
||||
```
|
||||
|
||||
После этих экспериментов `go test -race -count=1 ./...` прошёл для всех пакетов.
|
||||
|
||||
## Контрольная нагрузка
|
||||
|
||||
```text
|
||||
workload=closed-loop POST messages; no automatic retries
|
||||
duration=30.016 s
|
||||
concurrency=4
|
||||
successful_requests=11556
|
||||
failed_requests=0
|
||||
successful_rps=384.99
|
||||
p50=7.426 ms
|
||||
p95=32.466 ms
|
||||
p99=51.370 ms
|
||||
```
|
||||
|
||||
Percentile относятся только к успешным запросам. Closed-loop создаёт coordinated omission, результат включает client overhead и служит проверкой генерации/наблюдаемости сигналов, а не переносимым performance benchmark.
|
||||
@@ -0,0 +1,95 @@
|
||||
# Lab 6 — evidence for grade 4
|
||||
|
||||
Environment: local Docker Compose, alternate loopback ports `18080/13000/19090/13100/13200`, 2026-11-12.
|
||||
|
||||
## Static and configuration checks
|
||||
|
||||
- `go test -count=1 ./...`: PASS.
|
||||
- `docker compose config --quiet`: PASS.
|
||||
- Collector `validate`: PASS.
|
||||
- `promtool check config` and `promtool check rules`: PASS, 3 rules.
|
||||
- Grafana dashboard UID `mtusi-lab6-grade4`: provisioned.
|
||||
|
||||
## End-to-end W3C trace
|
||||
|
||||
`make test-observability-grade4 ...`: PASS.
|
||||
|
||||
```json
|
||||
{
|
||||
"trace_id": "e219baae473d961c30c97857bbfb19dd",
|
||||
"services": ["messenger-api", "messenger-dispatcher", "messenger-worker"],
|
||||
"span_kinds": ["CLIENT", "CONSUMER", "PRODUCER", "SERVER"],
|
||||
"span_count": 36,
|
||||
"queue_metric_series": 2,
|
||||
"db_pool_series": 12,
|
||||
"dashboard_uid": "mtusi-lab6-grade4"
|
||||
}
|
||||
```
|
||||
|
||||
## Retry in the same trace
|
||||
|
||||
`make test-observability-retry-trace ...`: PASS.
|
||||
|
||||
```json
|
||||
{
|
||||
"trace_id": "0df6d4041008c05e5c2c77b0c2bd2ddf",
|
||||
"attachment_status": "ready",
|
||||
"attempts": [1, 2],
|
||||
"producer_spans": 2,
|
||||
"consumer_spans": 2,
|
||||
"span_count": 46
|
||||
}
|
||||
```
|
||||
|
||||
The first attempt observed MinIO unavailable. After MinIO recovery, the second attempt succeeded. Both attempts, DB spans and S3 spans use the original upload trace ID.
|
||||
|
||||
## Alert firing and resolution
|
||||
|
||||
`make test-observability-alerts ...`: PASS.
|
||||
|
||||
```json
|
||||
{
|
||||
"queue_lag": {
|
||||
"firing_after_seconds": 26.075,
|
||||
"depth": 1,
|
||||
"oldest_age_seconds": 21.156533,
|
||||
"resolved_after_seconds": 8.009
|
||||
},
|
||||
"database_outage": {
|
||||
"firing_after_seconds": 19.044,
|
||||
"failed_requests": 8,
|
||||
"trace_id": "db176205d463b89b73c737780e58cf06",
|
||||
"error_span": "postgresql.acquire",
|
||||
"resolved_after_seconds": 44.049
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Telemetry backend outage
|
||||
|
||||
`make test-telemetry-backend-outage ...`: PASS.
|
||||
|
||||
```json
|
||||
{
|
||||
"business_requests": 400,
|
||||
"attachment_status": "ready",
|
||||
"accepted_signal_delta": 3170,
|
||||
"dropped_signal_delta": 75,
|
||||
"collector_queue_size": 34,
|
||||
"collector_queue_capacity": 256,
|
||||
"collector_peak_memory_bytes": 261305139,
|
||||
"collector_container_limit_bytes": 268435456,
|
||||
"recovery_trace_id": "01806671c8d2cee14dc504f63a60197b"
|
||||
}
|
||||
```
|
||||
|
||||
No business request failed and the attachment reached `ready`. Telemetry loss began only after the bounded 30-second retry budget. Loki/Tempo recovery was confirmed by a fresh correlated log and Tempo trace.
|
||||
|
||||
## Lifecycle cleanup
|
||||
|
||||
At the end of the grade-4 work, `make cleanup-lab` completed successfully. Verified postcondition:
|
||||
|
||||
- no running/stopped `mtusi2026lab6-*` Compose containers;
|
||||
- no locally built `mtusi2026lab6-*` images;
|
||||
- named volumes remain for an intentional later resume: `broker_data`, `grafana_data`, `loki_data`, `minio_data`, `postgres_data`, `prometheus_data`, `tempo_data`;
|
||||
- pulled third-party images and other labs are untouched.
|
||||
@@ -0,0 +1,97 @@
|
||||
# Lab 6 — evidence for grade 5, track 2
|
||||
|
||||
Date: 2026-11-12. Environment: local Docker Compose, alternate loopback ports `18080/13000/19090/13100/13200`.
|
||||
|
||||
## Configuration
|
||||
|
||||
- Track: SLO and incident detection.
|
||||
- Policy window: 7 days, matching Prometheus retention.
|
||||
- API SLO: 99% non-5xx, 1% error budget, recording rule `messenger:slo_api_success_ratio_7d`.
|
||||
- Attachment SLO: 99% ready in no more than 10 seconds, 1% error budget, recording rule `messenger:slo_attachment_ready_ratio_7d`.
|
||||
- Fast burn: 14.4x, 30s + 2m, `for: 10s`.
|
||||
- Slow burn: 6x, 1m + 5m, `for: 20s`.
|
||||
- Prometheus validation: PASS, 17 rules after the final audit.
|
||||
- Grafana dashboard: `mtusi-lab6-grade5` provisioned.
|
||||
- Runbook: `infrastructure/telemetry/runbooks/level5.md`.
|
||||
|
||||
The windows are intentionally compressed for a repeatable laboratory experiment. Burn factors remain dimensionless; production windows would be substantially longer.
|
||||
|
||||
## Reproducible command
|
||||
|
||||
```sh
|
||||
make test-slo-burn-rate \
|
||||
BASE_URL=http://127.0.0.1:18080 \
|
||||
PROMETHEUS_URL=http://127.0.0.1:19090 \
|
||||
LOKI_URL=http://127.0.0.1:13100 \
|
||||
TEMPO_URL=http://127.0.0.1:13200 \
|
||||
GRAFANA_URL=http://127.0.0.1:13000
|
||||
```
|
||||
|
||||
Result: PASS.
|
||||
|
||||
```json
|
||||
{
|
||||
"api_slo": {
|
||||
"brief_spike_failures": 4,
|
||||
"false_positive": {
|
||||
"pending_or_firing": 0,
|
||||
"max_30s_ratio": 0.038461538461538464,
|
||||
"max_5m_ratio": 0.007827788649706457
|
||||
},
|
||||
"sustained_failures": 136,
|
||||
"detection_seconds": {
|
||||
"MessengerAPIBurnRateSlow": 42.194,
|
||||
"MessengerAPIBurnRateFast": 52.212
|
||||
},
|
||||
"recovery_seconds": 38.851,
|
||||
"trace_id": "abac9b8b51c9b4bd3d05c26dab3e37ea",
|
||||
"root_cause_span": "postgresql.acquire"
|
||||
},
|
||||
"attachment_ready_slo": {
|
||||
"baseline_fast": 20,
|
||||
"slow_over_10s": 5,
|
||||
"recovery_fast": 100,
|
||||
"detection_seconds": {
|
||||
"MessengerAttachmentReadyBurnRateFast": 20.039,
|
||||
"MessengerAttachmentReadyBurnRateSlow": 30.056
|
||||
},
|
||||
"recovery_seconds": 8.016,
|
||||
"final_5m_slow_ratio": 0.04794240000000012
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Interpretation
|
||||
|
||||
The bounded four-error spike remained below both burn thresholds and produced no pending/firing state during the observation window. Sustained PostgreSQL unavailability fired both API alerts; Loki correlation and Tempo identified `postgresql.acquire`, so the runbook distinguishes pool/backend failure from handler latency.
|
||||
|
||||
Five delayed jobs consumed the ready SLO budget and fired both ready alerts. One hundred fast completions reduced the five-minute slow ratio below 6%, after which both alerts resolved.
|
||||
|
||||
False-positive evidence covers this controlled workload only. It is not a statistically significant production false-positive rate. No independent human runbook drill was performed; the black-box script follows the same steps automatically.
|
||||
|
||||
## Histogram calibration
|
||||
|
||||
`make test-histogram-calibration ...`: PASS.
|
||||
|
||||
```json
|
||||
{
|
||||
"samples": {"http": 400, "attachments": 12},
|
||||
"http_p95_seconds": {
|
||||
"client": 0.003569880000213743,
|
||||
"prometheus": 0.004909843739733048,
|
||||
"ratio": 1.375352599930271
|
||||
},
|
||||
"ready_p95_seconds": {
|
||||
"client_polling_upper_bound": 1.0131328810002742,
|
||||
"prometheus": 0.9458333333333333,
|
||||
"ratio": 0.9335728324200716
|
||||
},
|
||||
"worker_p95_seconds": 0.0975
|
||||
}
|
||||
```
|
||||
|
||||
Exported HTTP buckets begin at 5 ms, worker buckets at 50 ms and ready buckets at 100 ms. The client/Prometheus values have the same order of magnitude and use seconds consistently.
|
||||
|
||||
## Lifecycle cleanup
|
||||
|
||||
`make cleanup-lab` completed successfully after the grade-5 regression. A Docker inventory confirmed no lab1–lab6 containers, locally built images or Compose networks remain. Lab5 and lab6 named volumes were intentionally preserved; no pulled third-party image or unrelated Docker resource was selected for removal.
|
||||
Reference in New Issue
Block a user