Preserve distributed job context and expose grade 4 operational signals

This commit is contained in:
Artyom
2026-11-06 12:57:10 +03:00
parent 1a171d0d0f
commit 44d81fd80e
32 changed files with 1098 additions and 35 deletions
@@ -1,2 +1,4 @@
schema: spec-driven
created: 2026-10-29
archived: 2026-11-06
lab: 6
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-06
@@ -0,0 +1,23 @@
## Context
SQLAlchemy async, transactional outbox и manual ack после COMMIT уже работают. SDK экспортирует асинхронно, Collector имеет memory_limiter, batch, ограниченные очереди и retry 60 s.
## Goals / Non-Goals
Закрыть все пункты уровня 4; не реализовывать трек 5 в этом change и не менять контракт API.
## Decisions
W3C traceparent/tracestate хранятся отдельно от нормативного payload в JSONB job и outbox. При retry берётся активный consumer context, при восстановлении аренды — сохранённый origin. Миграция добавляет поля с пустым default; прежние jobs остаются пригодными. Relay извлекает контекст и FastStream создаёт producer spans; ack остаётся после бизнес-COMMIT. S3 spans содержат только операцию/сервис, без ключей и exception payload.
Queue depth/age измеряют durable backlog queued/processing PostgreSQL, включая retry: это не размер AMQP очереди. Pool used/waiting/capacity измеряются у SQLAlchemy engine и в ObservedPool._do_get, без идентификаторов. Worker busy/capacity отражают конкурентность; time-to-ready отсчитывается от created_at job до done. CPU — процессорные секунды, RAM — текущий RSS из /proc. Все gauges отдаются OTLP; статические labels и resource service instance. Histogram seconds использует границы 0.05…60, включая SLO 30 s.
Availability SLO: >=99% успешных бизнес-HTTP за 1 h; ready SLO: >=95% done за 30 s на окне 1 h. Alerts: error ratio >5% за 1 m, for 15 s; backlog age >15 s, for 15 s. Thresholds короткие для воспроизводимой учебной демонстрации, не производственные рекомендации. Runbooks лежат в Git; внешняя доставка не требуется.
## Risks / Trade-offs
ObservedPool оборачивает получение connection, сохраняя ленивые sessions, timeout, autocommit и границы UoW. Waiting включает получение/создание соединения; используется закреплённая версия SQLAlchemy. Poller очереди работает отдельно, ошибки измерений не останавливают relay. Нулевой backlog возвращает age 0. При telemetry outage потеря сигналов допустима и измеряется; успешность сообщений обязательна. Проверки последовательны на собственном project, состояние Docker записывается; постоянные volumes не удаляются.
## Validation
Миграции legacy/fresh, тесты durable context и retry, make check/validate/lint/student-test. Реальные API→S3/DB→producer→consumer traces, retry, строгие dashboards, leak checks. Два инцидента с временной шкалой, queries и trace IDs, firing/resolved. Отказ хранилищ: smoke, RAM samples, Collector counters до/после, восстановление. Финальный REPORT делает следующий агент.
@@ -0,0 +1,18 @@
## Why
Уровень 3 доказан. Сейчас outbox теряет контекст HTTP, relay не создаёт producer spans, а наблюдаемость не объясняет накопление очереди и зависание БД. Это обязательные критерии уровня 4.
## What Changes
- Добавочная Alembic-миграция сохраняет W3C контекст job/outbox, FastStream связывает API, producer и consumer; S3 получает безопасные client spans.
- Добавляются queue age/depth, pool used/waiting, worker busy/capacity, time-to-ready и process CPU/RAM, dashboards и SLI/SLO с alerts.
- Реальные инциденты worker stop и PostgreSQL outage подтверждают firing/resolved; отдельный отказ хранилищ проверяет доступность API и ограничение памяти.
## Capabilities
### New Capabilities
- `lab6-observability-resilience`: сквозная диагностика и устойчивость наблюдаемости уровня 4.
## Impact
Меняются собственные адаптеры, миграции, инструменты и provisioning. API, нормативные файлы и REPORT не меняются. Следующему агенту передаются evidence и заметки. Данные существующих таблиц сохраняются.
@@ -0,0 +1,26 @@
## ADDED Requirements
### Requirement: Durable distributed context
The system SHALL preserve W3C context through API, transactional outbox, relay producer and worker consumer including retries, and expose safe database and S3 client spans.
#### Scenario: Deferred delivery and retry
- **WHEN** an accepted upload is delivered after relay restart or retried after S3 failure
- **THEN** its producer and consumer spans share the originating trace and causally valid parents, without adding fields to the normative job payload
### Requirement: Operational signals and SLO
The system SHALL expose queue depth and oldest age, database pool usage and waiting, worker saturation, process CPU/RAM and durable time-to-ready; dashboards SHALL show histogram percentiles and error ratio and define availability and ready SLO windows.
#### Scenario: Stopped worker
- **WHEN** queued uploads wait for a stopped worker
- **THEN** depth and age increase, a queue-lag alert fires and resolves after recovery
#### Scenario: Unavailable database
- **WHEN** PostgreSQL becomes unavailable
- **THEN** API failure metrics and database client spans distinguish the dependency failure and an error-rate alert fires and resolves
### Requirement: Bounded observability failure
Collector SHALL use memory limits, batching and bounded queues; unavailable telemetry storage SHALL NOT prevent business requests or cause unbounded memory growth.
#### Scenario: Storage outage
- **WHEN** telemetry storage is stopped during requests
- **THEN** business smoke passes, measured memory remains within container limits, losses are recorded, and exports resume after recovery
@@ -0,0 +1,10 @@
## Implementation
- [ ] 1. Durable context migration, repository and publisher wiring; propagation/retry tests
- [ ] 2. Safe S3 spans and process/pool/queue/worker/time-to-ready metrics; unit checks
- [ ] 3. Dashboards, SLO recording/alert rules and runbooks; configuration validation
## Verification
- [ ] 4. make check/validate/lint/student-test; real smoke, persistence and failover after changes
- [ ] 5. End-to-end and retry traces, dashboards, leaks and cardinality
- [ ] 6. Worker and database incidents: evidence, firing/resolved and diagnosis
- [ ] 7. Storage outage: availability, bounded memory, lost signals and recovery
- [ ] 8. Evidence notes, requirement sync and archive after all checks