From 27a3a6895f9ac4ac9d10e6a94f20a6414211338c Mon Sep 17 00:00:00 2001 From: gytall Date: Thu, 19 Nov 2026 19:09:19 +0300 Subject: [PATCH] created tasks for grade 4 --- .gitignore | 2 +- Makefile | 11 +- REPORT.md | 197 +++-- app/core/database.py | 25 + app/core/job_worker.py | 13 +- app/core/outbox_publisher.py | 17 +- app/core/telemetry.py | 39 +- app/domain/attachment_jobs.py | 88 +- app/main.py | 1 + app/models/job.py | 3 +- app/storage/broker.py | 4 + app/storage/jobs.py | 15 +- compose.local.yml | 45 + compose.yaml | 1 + evidence/observability.json | 810 ++++++++++++++---- evidence/verification.json | 360 +------- infra/otel/README.md | 8 +- infra/otel/alerts.yaml | 18 + infra/otel/collector.yaml | 8 + infra/otel/grafana/dashboards/messenger.json | 274 ++++++ infra/otel/prometheus.yaml | 4 + .../b55d0c6819ab_job_trace_context.py | 17 + scripts/check_jobs.py | 4 +- scripts/check_observability.py | 160 +++- scripts/deployment.py | 19 +- 25 files changed, 1492 insertions(+), 651 deletions(-) create mode 100644 compose.local.yml create mode 100644 infra/otel/alerts.yaml create mode 100644 migrations/versions/b55d0c6819ab_job_trace_context.py diff --git a/.gitignore b/.gitignore index acbb212e..24b6c977 100644 --- a/.gitignore +++ b/.gitignore @@ -32,7 +32,7 @@ coverage/ # Inspect git diff --cached: ignore rules are not a secret scanner. # Перенесённые исключения lab5 -venv/ +.venv/ .pytest_cache/ .ruff_cache/ /docs/ diff --git a/Makefile b/Makefile index b861b8a7..dba36285 100644 --- a/Makefile +++ b/Makefile @@ -8,6 +8,7 @@ SERVICE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) COMPOSE = docker compose --env-file .env +LOCAL_COMPOSE = $(COMPOSE) -f compose.yaml -f compose.local.yml TEST_PROJECT ?= messenger-test TEST_LB_PORT ?= 28080 @@ -27,13 +28,14 @@ TEST_REDIS_PASSWORD ?= $(if $(wildcard secrets/redis_password),$(file 5% 5xx за 30 с с выдержкой 5 с. +`MessengerQueueLag` срабатывает, если очередь непуста и возраст старейшего +задания >15 с с выдержкой 5 с. Состояние доступно в Prometheus через +`ALERTS{alertstate="firing"}`. Внешняя доставка отключена. + +## Диагностика инцидентов + +1. **Рост 5xx.** В Grafana сопоставить частоту запросов, долю 5xx и задержку. + По X-Request-Id найти связанный лог и открыть TraceID. Ошибка на + `postgres.checkout` вместе с событием `dependency.unavailable` + указывает на проблему получения соединения с БД. После восстановления + проверить `/health/ready` и исчезновение firing. +2. **Растёт очередь.** Сверить глубину, возраст и занятость worker. При + остановленном worker задания принимаются, а новые попытки не появляются. + После восстановления проверить уменьшение очереди и исчезновение firing. + В Tempo открыть трассу upload и сравнить исходы отдельных попыток, затем + проверить spans S3/БД и состояние ready. +3. **Недоступен Loki.** Prometheus продолжает собирать бизнес-метрики и + внутренние метрики Collector. Сравнить число успешных сообщений, RSS, + размер экспортной очереди и прирост счётчиков отказа экспорта/постановки + в очередь. После старта Loki проверить появление новых связанных логов. + +Collector использует memory limiter 192 MiB со spike 32 MiB, пакетирование до +256 записей, очередь 256 пакетов на экспортёр, по два потребителя +на очередь и до 30 с повторов доставки. Контейнер ограничен 256 MiB. SDK +имеет ограниченные очереди span/log и таймауты. Потери считаются по +счётчикам Collector для остановленного Loki. Общие потери вне Collector +этими счётчиками не измеряются. + +## Полный прогон + +`make verify` поднимает один отдельный стенд с телеметрией, выполняет регрессию, +smoke, нагрузку, проверку сквозных трасс, оповещений и восстановления после +отказов, а также persistence/failover. В конце удаляются контейнеры, сеть и +тома только проверочного проекта. Настройки, общий кэш образов и данные +основного стенда сохраняются. + +Результаты прогона от 19.11.2026 сохранены в [журнале проверок](evidence/verification.json) +и [доказательствах наблюдаемости](evidence/observability.json). +Итог **PASS**, с 18:50 до 19:03 МСК. Контракт, OpenAPI, конфигурация и запуск +Compose, публичный smoke, наблюдаемость, persistence и failover прошли. +Регрессия: 206 тестов за 98,89 с. Инвентаризация после очистки показала +0 контейнеров, 0 сетей и 0 томов проверочного проекта. + +Нагрузка: 100 успешных сообщений, 0 ошибок, 10,078 запроса/с. Клиентские +p50/p95/p99 — 18,036 / 39,623 / 45,954 мс. Проверены все запросы панелей, +корреляция логов и трасс, отсутствие запрещённых полей и сохранение истории +после перезапуска хранилищ. В выборке приватности 413 логов. + +| Сценарий | Что зафиксировал прогон | +| --- | --- | +| PostgreSQL остановлен | HTTP 503, связанный ERROR span `postgres.checkout` и `dependency.unavailable` с `TimeoutError`. Firing замечен через 32,4 с от начала сценария, снятие — через 67,5 с. Trace ID `020e820d68045ad3195e842244670b11`. | +| Worker остановлен | Глубина 1, возраст 25,6 с на момент проверки. Firing замечен через 28,6 с после приёма задания. После исчерпания пяти инъецированных временных ошибок оператор выполнил replay, шестая попытка завершилась `ready`, глубина вернулась к 0, оповещение снялось. | +| Loki остановлен | 204 сообщения записаны при недоступных логах. За 51 с измерено 6 записей, потерянных после повторов экспорта, и 0 отказов постановки в очередь. Пик очереди 48 из 256 пакетов, RSS 228–231 MiB при лимите 256 MiB. После запуска Loki найден новый лог со связанной трассой. | + +Трасса повтора в Tempo — `ff8352e27270fbc16fea7216c3ff45c0`. В ней проверены +родительские связи HTTP upload → `rabbitmq.publish` → `attachment.process.v1` +для всех попыток и spans `s3.read_staging`, `s3.write_result`, +`postgres.commit_ready` успешной попытки. Контрольная трасса без инъекции — +`ad41b35e5e8b02c32f7a7b74d7b6278a`. После очистки их идентификаторы и дерево +spans остаются в JSON с доказательствами. ## Ограничения -Один Docker-host, без HA и защиты от потери диска. HTTP и анонимный Grafana Viewer — -только для локального стенда; Tempo использует root для записи в volume. -Сейчас API/worker traces независимы, alerts и сквозная связь ещё не реализованы. -SDK и Collector имеют ограниченные очереди, но длительный отказ backend пока не измерялся. -По наблюдению автора, долгий запуск контейнеров нагревает CPU примерно до 80 °C и выше: -проверки выполняются последовательно на одном стенде с немедленной очисткой. +Один Docker-host без высокой доступности и защиты от потери диска. +Контролируемая нагрузка проверяет сценарии и пригодность диагностики. +Долговременное соблюдение SLO требует наблюдения за полным 24-часовым окном. +В сценарии Loki измерен краткий отказ. Замеры RSS показывают небольшой рост, +а верхняя граница памяти обеспечивается настройками очередей и лимитом контейнера. diff --git a/app/core/database.py b/app/core/database.py index c7a65381..10b2bf09 100644 --- a/app/core/database.py +++ b/app/core/database.py @@ -1,3 +1,6 @@ +from contextlib import nullcontext + +from sqlalchemy.pool import AsyncAdaptedQueuePool from sqlalchemy.ext.asyncio import ( AsyncEngine, AsyncSession, @@ -8,9 +11,31 @@ from sqlalchemy.ext.asyncio import ( from app.core.config import Settings +class ObservedPool(AsyncAdaptedQueuePool): + telemetry = None + waiting = 0 + + def __init__(self, *args, pool_size, max_overflow, **kwargs): + self.capacity = pool_size + max_overflow if pool_size and max_overflow >= 0 else None + super().__init__(*args, pool_size=pool_size, max_overflow=max_overflow, **kwargs) + + def _do_get(self): + waiting = self.capacity is not None and self.checkedout() >= self.capacity + self.waiting += int(waiting) + try: + return super()._do_get() + finally: + self.waiting -= int(waiting) + + def connect(self): + with self.telemetry.span("postgres.checkout") if self.telemetry else nullcontext(): + return super().connect() + + def create_db_engine(settings: Settings) -> AsyncEngine: return create_async_engine( settings.get_database_url(), + poolclass=ObservedPool, pool_size=settings.db_pool_size, max_overflow=settings.db_max_overflow, pool_timeout=settings.db_pool_timeout_seconds, diff --git a/app/core/job_worker.py b/app/core/job_worker.py index d524c092..6574b509 100644 --- a/app/core/job_worker.py +++ b/app/core/job_worker.py @@ -12,6 +12,7 @@ from uuid import UUID, uuid4 from PIL import features from opentelemetry.context import Context from opentelemetry.trace import SpanKind +from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator from pydantic import ValidationError from app.core.background import ( @@ -86,10 +87,11 @@ async def consume_connected( continue try: telemetry = telemetry or Telemetry("messenger-worker", enabled=False) - with telemetry.tracer.start_as_current_span( - "attachment.process.v1", context=Context(), kind=SpanKind.CONSUMER, - record_exception=False, set_status_on_exception=False, - attributes={"messaging.system": "rabbitmq", "job.type": message.type}, + parent = TraceContextTextMapPropagator().extract(delivery.id.headers or {}, context=Context()) + with telemetry.span( + "attachment.process.v1", context=parent, kind=SpanKind.CONSUMER, + attributes={"messaging.system": "rabbitmq", "job.type": message.type, + "job.attempt": message.attempt}, ): telemetry.event("job.received", job_id=str(message.job_id), attachment_id=str(message.attachment_id)) @@ -132,6 +134,9 @@ async def run_worker(faults: Faults) -> None: raise RuntimeError("WebP codec is unavailable") stop = shutdown_event() engine = create_db_engine(settings) + telemetry.observe_pool(engine.pool) + telemetry.gauge("messenger.worker.busy", lambda: telemetry.busy) + telemetry.gauge("messenger.worker.capacity", lambda: jobs.worker_concurrency) storage = None try: storage = create_s3_storage(settings.s3) diff --git a/app/core/outbox_publisher.py b/app/core/outbox_publisher.py index 54ef3a2c..993d206c 100644 --- a/app/core/outbox_publisher.py +++ b/app/core/outbox_publisher.py @@ -6,6 +6,7 @@ import json import logging import os import signal +import time from uuid import UUID from app.core.background import ( @@ -19,6 +20,8 @@ from app.core.database import create_db_engine, create_session_factory from app.core.jobs import JobSettings from app.domain.attachment_jobs import publish_next_job, recover_expired_jobs from app.storage.broker import JobBroker +from app.storage.jobs import queued_backlog +from app.core.telemetry import Telemetry def crash_before_publish(attachment_id: UUID) -> None: @@ -36,6 +39,13 @@ async def run_publisher(crash_attachment_id: UUID | None = None) -> None: logging.basicConfig(level=settings.log_level) stop = shutdown_event() engine = create_db_engine(settings) + telemetry = Telemetry("messenger-publisher") + telemetry.observe_pool(engine.pool) + backlog = (0, 0.0) + labels = {"queue.name": jobs.broker_queue} + telemetry.gauge("messenger.queue.depth", lambda: backlog[0], attributes=labels) + telemetry.gauge("messenger.queue.oldest", lambda: backlog[1], unit="s", attributes=labels) + next_sample = 0.0 broker = None try: broker = JobBroker(jobs) @@ -43,12 +53,16 @@ async def run_publisher(crash_attachment_id: UUID | None = None) -> None: while not stop.is_set(): published = False try: - await broker.ensure_ready() async with factory() as session: + if telemetry.enabled and time.monotonic() >= next_sample: + backlog = await queued_backlog(session) + next_sample = time.monotonic() + 2 + await broker.ensure_ready() await recover_expired_jobs(session, jobs) published = await publish_next_job( session, broker, + telemetry=telemetry, attachment_id=crash_attachment_id, before_publish=( crash_before_publish @@ -64,6 +78,7 @@ async def run_publisher(crash_attachment_id: UUID | None = None) -> None: if broker is not None: await broker.aclose() await engine.dispose() + await asyncio.to_thread(telemetry.shutdown) def main() -> None: diff --git a/app/core/telemetry.py b/app/core/telemetry.py index c2341434..1b61f804 100644 --- a/app/core/telemetry.py +++ b/app/core/telemetry.py @@ -4,6 +4,7 @@ from contextlib import contextmanager from datetime import datetime, timezone import json import os +from pathlib import Path import socket import time @@ -15,6 +16,7 @@ from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExp from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.sdk._logs import LoggerProvider from opentelemetry.sdk._logs.export import BatchLogRecordProcessor +from opentelemetry.metrics import Observation from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View @@ -32,6 +34,7 @@ class Telemetry: self.enabled = (os.getenv("OTEL_ENABLED", "false").lower() == "true" if enabled is None else enabled) self.service = service + self.busy = 0 if not self.enabled: self.tracer = trace.NoOpTracerProvider().get_tracer("messenger") return @@ -61,14 +64,42 @@ class Telemetry: ) ], views=[ View(instrument_name="messenger.http.duration", aggregation=ExplicitBucketHistogramAggregation(HTTP_BUCKETS)), + View(instrument_name="messenger.job.time_to_ready", aggregation=ExplicitBucketHistogramAggregation(JOB_BUCKETS)), View(instrument_name="messenger.job.duration", aggregation=ExplicitBucketHistogramAggregation(JOB_BUCKETS)), ]) - meter = self.metrics.get_meter("messenger", "1.6.0") + meter = self.meter = self.metrics.get_meter("messenger", "1.6.0") self.http_requests = meter.create_counter("messenger.http.requests", unit="1") self.http_duration = meter.create_histogram("messenger.http.duration", unit="s") self.jobs = meter.create_counter("messenger.job.attempts", unit="1") self.job_duration = meter.create_histogram("messenger.job.duration", unit="s") + self.time_to_ready = meter.create_histogram("messenger.job.time_to_ready", unit="s") + self.gauge("messenger.process.cpu", time.process_time, unit="s", counter=True) + self.gauge("messenger.process.rss", resident_bytes, unit="By") + + def gauge(self, name, sample, *, unit="1", attributes=None, counter=False): + if self.enabled: + create = (self.meter.create_observable_counter if counter + else self.meter.create_observable_gauge) + create(name, callbacks=[lambda _: [Observation(sample(), attributes)]], unit=unit) + + def observe_pool(self, pool): + if self.enabled: + pool.telemetry = self + self.gauge("messenger.db.pool.used", pool.checkedout) + self.gauge("messenger.db.pool.waiting", lambda: pool.waiting) + + @contextmanager + def span(self, name, **kwargs): + with self.tracer.start_as_current_span( + name, record_exception=False, set_status_on_exception=False, **kwargs, + ) as span: + try: + yield span + except BaseException: + span.set_status(Status(StatusCode.ERROR)) + raise + def event(self, event: str, *, error=False, **fields): if not self.enabled: return @@ -89,6 +120,7 @@ class Telemetry: @contextmanager def job_attempt(self): + self.busy += 1 started = time.monotonic() result = {"outcome": "success"} try: @@ -97,6 +129,7 @@ class Telemetry: result["outcome"] = "error" raise finally: + self.busy -= 1 if self.enabled: attrs = {"job.type": "attachment.process.v1", "outcome": result["outcome"]} elapsed = time.monotonic() - started @@ -115,6 +148,10 @@ class Telemetry: self.traces.shutdown() +def resident_bytes(): + return int(Path("/proc/self/statm").read_text().split()[1]) * os.sysconf("SC_PAGE_SIZE") + + class HttpTelemetryMiddleware: def __init__(self, app, telemetry: Telemetry): self.app = app diff --git a/app/domain/attachment_jobs.py b/app/domain/attachment_jobs.py index f1013db0..4b53fcd3 100644 --- a/app/domain/attachment_jobs.py +++ b/app/domain/attachment_jobs.py @@ -9,6 +9,9 @@ from tempfile import TemporaryDirectory from uuid import UUID, uuid4 from minio.error import MinioException +from opentelemetry.context import Context +from opentelemetry.trace import SpanKind +from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator from sqlalchemy.ext.asyncio import AsyncSession from urllib3.exceptions import HTTPError as StorageHTTPError @@ -44,6 +47,7 @@ async def publish_next_job( *, attachment_id: UUID | None = None, before_publish: Callable[[UUID], None] | None = None, + telemetry: Telemetry | None = None, ) -> bool: """Отметка publish следует за durable publisher confirm; crash допускает тот же job-дубль.""" job = await outbox.next_unpublished_job(session, attachment_id=attachment_id) @@ -51,15 +55,20 @@ async def publish_next_job( if job is not None: if before_publish is not None: before_publish(job.attachment_id) - await broker.publish_job( - JobMessage( - job_id=job.id, - attachment_id=job.attachment_id, - pipeline_version=job.pipeline_version, - attempt=job.attempt + 1, - created_at=job.created_at, + parent = TraceContextTextMapPropagator().extract(job.trace_context or {}, context=Context()) + with telemetry.span( + "rabbitmq.publish", context=parent, kind=SpanKind.PRODUCER, + attributes={"messaging.system": "rabbitmq", "job.attempt": job.attempt + 1}, + ) if telemetry else nullcontext(): + await broker.publish_job( + JobMessage( + job_id=job.id, + attachment_id=job.attachment_id, + pipeline_version=job.pipeline_version, + attempt=job.attempt + 1, + created_at=job.created_at, + ) ) - ) outbox.mark_published(job) await session.commit() return published @@ -145,11 +154,13 @@ async def build_result( storage: MinioStorage, work: JobWork, after_object: Callable[[UUID, str], None] | None = None, + telemetry: Telemetry | None = None, ) -> bool: """Фиксированные ключи и блокировка job защищают PUT от устаревшей попытки.""" with TemporaryDirectory(prefix="messenger-job-") as directory: source = Path(directory) / "original" - await fetch_original(storage, work, source) + with telemetry.span("s3.read_staging") if telemetry else nullcontext(): + await fetch_original(storage, work, source) result = await render_variants(storage, work, source, Path(directory)) row = await jobs.lock_job(session, work.job_id) if row is None: @@ -165,33 +176,39 @@ async def build_result( return False # Блокировка остаётся до завершения PUT/COMMIT; reaper использует SKIP LOCKED. # При отмене S3 adapter дожидается SDK-потока до освобождения блокировки. - await storage.put_file( - work.original_key, - source, - size_bytes=work.size_bytes, - content_type=work.content_type, - sha256=work.sha256, - ) - if after_object is not None: - after_object(work.attachment_id, "original") - for variant in result.variants: + with telemetry.span("s3.write_result") if telemetry else nullcontext(): await storage.put_file( - work.variant_key(variant.name), - Path(directory) / VARIANT_FILENAMES[variant.name], - size_bytes=variant.size_bytes, - content_type=variant.content_type, - sha256=variant.sha256, + work.original_key, + source, + size_bytes=work.size_bytes, + content_type=work.content_type, + sha256=work.sha256, ) if after_object is not None: - after_object(work.attachment_id, variant.name) - jobs.complete_job( - job, - attachment, - work, - [variant.model_dump() for variant in result.variants], - await jobs.database_time(session), - ) - await session.commit() + after_object(work.attachment_id, "original") + for variant in result.variants: + await storage.put_file( + work.variant_key(variant.name), + Path(directory) / VARIANT_FILENAMES[variant.name], + size_bytes=variant.size_bytes, + content_type=variant.content_type, + sha256=variant.sha256, + ) + if after_object is not None: + after_object(work.attachment_id, variant.name) + with telemetry.span("postgres.commit_ready") if telemetry else nullcontext(): + ready_at = await jobs.database_time(session) + accepted_at = job.created_at + jobs.complete_job( + job, + attachment, + work, + [variant.model_dump() for variant in result.variants], + ready_at, + ) + await session.commit() + if telemetry and telemetry.enabled: + telemetry.time_to_ready.record(max(0, (ready_at - accepted_at).total_seconds())) return True @@ -205,7 +222,8 @@ async def process_attachment_job( before_processing: Callable[[UUID], None] | None = None, telemetry: Telemetry | None = None, ) -> bool: - claim = await claim_job(session, message, settings) + with telemetry.span("postgres.claim_job") if telemetry else nullcontext(): + claim = await claim_job(session, message, settings) acknowledge = claim.acknowledge if claim.work is not None: work = claim.work @@ -214,7 +232,7 @@ async def process_attachment_job( async with asyncio.timeout(settings.job_timeout_seconds): if before_processing is not None: before_processing(work.attachment_id) - acknowledge = await build_result(session, storage, work, after_object) + acknowledge = await build_result(session, storage, work, after_object, telemetry) result["outcome"] = "success" if acknowledge else "deferred" except ( ProcessingError, diff --git a/app/main.py b/app/main.py index f4bb612e..4882359a 100644 --- a/app/main.py +++ b/app/main.py @@ -61,6 +61,7 @@ def create_app(settings: Settings | None = None) -> FastAPI: application.state.request_capacity = create_request_capacity(settings.max_in_flight) application.state.instance_id = resolve_instance_id(settings.instance_id) telemetry = Telemetry("messenger-api", application.state.instance_id) + telemetry.observe_pool(engine.pool) application.state.telemetry = telemetry application.state.lifecycle = Lifecycle() application.add_middleware(RequestIdMiddleware) diff --git a/app/models/job.py b/app/models/job.py index 01924ee8..b7723d07 100644 --- a/app/models/job.py +++ b/app/models/job.py @@ -3,7 +3,7 @@ from datetime import datetime from uuid import UUID, uuid4 -from sqlalchemy import CheckConstraint, ForeignKey, Index, String, func +from sqlalchemy import JSON, CheckConstraint, ForeignKey, Index, String, func from sqlalchemy.orm import Mapped, mapped_column from app.models.base import Base @@ -23,6 +23,7 @@ class AttachmentJob(Base): ForeignKey("attachments.id"), unique=True, ) + trace_context: Mapped[dict | None] = mapped_column(JSON, nullable=True) staging_key: Mapped[str | None] = mapped_column(String(128)) pipeline_version: Mapped[int] = mapped_column(server_default="1") attempt: Mapped[int] = mapped_column(server_default="0") diff --git a/app/storage/broker.py b/app/storage/broker.py index 1932ffda..2f5d2e41 100644 --- a/app/storage/broker.py +++ b/app/storage/broker.py @@ -6,6 +6,7 @@ from dataclasses import dataclass import aio_pika from aio_pika.abc import AbstractIncomingMessage +from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator from app.core.jobs import JobSettings from app.schemas.job import JobMessage @@ -54,10 +55,13 @@ class JobBroker: async def publish_job(self, message: JobMessage) -> None: await self.ensure_ready() + headers = {} + TraceContextTextMapPropagator().inject(headers) await self.channel.default_exchange.publish( aio_pika.Message( body=message.model_dump_json(exclude_none=True).encode(), content_type="application/json", + headers=headers, delivery_mode=aio_pika.DeliveryMode.PERSISTENT, message_id=f"{message.job_id}:{message.attempt}", ), diff --git a/app/storage/jobs.py b/app/storage/jobs.py index e0ca118b..ace4ba95 100644 --- a/app/storage/jobs.py +++ b/app/storage/jobs.py @@ -4,6 +4,7 @@ from dataclasses import dataclass from datetime import datetime, timedelta from uuid import UUID +from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator from sqlalchemy import and_, or_, func, select from sqlalchemy.ext.asyncio import AsyncSession @@ -35,7 +36,10 @@ class JobWork: async def create_job( session: AsyncSession, attachment_id: UUID, staging_key: str ) -> UUID: - job = AttachmentJob(attachment_id=attachment_id, staging_key=staging_key) + carrier = {} + TraceContextTextMapPropagator().inject(carrier) + job = AttachmentJob(attachment_id=attachment_id, staging_key=staging_key, + trace_context=carrier or None) session.add(job) await session.flush() return job.id @@ -56,6 +60,15 @@ async def database_time(session: AsyncSession) -> datetime: return await session.scalar(select(func.clock_timestamp())) +async def queued_backlog(session: AsyncSession) -> tuple[int, float]: + count, oldest = (await session.execute( + select(func.count(), func.min(AttachmentJob.created_at)) + .join(Attachment, Attachment.id == AttachmentJob.attachment_id) + .where(Attachment.status == "queued") + )).one() + return count, max(0, ((await database_time(session)) - oldest).total_seconds()) if oldest else 0.0 + + async def expired_jobs(session: AsyncSession, limit: int = 20): result = await session.execute( select(AttachmentJob, Attachment) diff --git a/compose.local.yml b/compose.local.yml new file mode 100644 index 00000000..c9176dd0 --- /dev/null +++ b/compose.local.yml @@ -0,0 +1,45 @@ +# Локальный доступ к сервисам из VS Code и браузера. +# docker compose -f compose.yaml -f compose.local.yml up -d --wait +# Все опубликованные порты доступны только с этого компьютера. +services: + api: + # Docker выделяет каждой реплике отдельный свободный порт диапазона. + ports: + - "127.0.0.1:8081-8090:8080" + postgres: + ports: + - "127.0.0.1:${POSTGRES_LOCAL_PORT:-5432}:5432" + redis: + ports: + - "127.0.0.1:${REDIS_LOCAL_PORT:-6379}:6379" + minio: + command: ["server", "/data", "--console-address", "0.0.0.0:9001"] + environment: + MINIO_BROWSER: "on" + # Добавляем обычную сеть для доступа через опубликованные порты; + # внутренняя objects сохраняется для приложения и bootstrap. + networks: [default, objects] + ports: + - "127.0.0.1:${MINIO_LOCAL_PORT:-9000}:9000" + - "127.0.0.1:${MINIO_CONSOLE_LOCAL_PORT:-9001}:9001" + broker: + volumes: + - ./infra/broker/enabled_plugins.local:/etc/rabbitmq/enabled_plugins:ro + ports: + - "127.0.0.1:${BROKER_LOCAL_PORT:-5672}:5672" + - "127.0.0.1:${BROKER_MANAGEMENT_LOCAL_PORT:-15672}:15672" + prometheus: + ports: + - "127.0.0.1:${PROMETHEUS_LOCAL_PORT:-9090}:9090" + loki: + ports: + - "127.0.0.1:${LOKI_LOCAL_PORT:-3100}:3100" + tempo: + ports: + - "127.0.0.1:${TEMPO_LOCAL_PORT:-3200}:3200" + - "127.0.0.1:${TEMPO_OTLP_LOCAL_PORT:-14318}:4318" + otel-collector: + ports: + - "127.0.0.1:${OTEL_HTTP_LOCAL_PORT:-4318}:4318" + - "127.0.0.1:${OTEL_METRICS_LOCAL_PORT:-8889}:8889" + - "127.0.0.1:${OTEL_HEALTH_LOCAL_PORT:-13133}:13133" diff --git a/compose.yaml b/compose.yaml index 8ddffa1f..f9808187 100644 --- a/compose.yaml +++ b/compose.yaml @@ -409,6 +409,7 @@ services: restart: unless-stopped volumes: - ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yml:ro + - ./infra/otel/alerts.yaml:/etc/prometheus/alerts.yaml:ro - prometheusdata:/prometheus healthcheck: test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:9090/-/ready"] diff --git a/evidence/observability.json b/evidence/observability.json index 7ddd5dbf..1078a1b7 100644 --- a/evidence/observability.json +++ b/evidence/observability.json @@ -1,21 +1,21 @@ { - "date_utc": "2026-11-14T01:54:09.593067+00:00", + "date_utc": "2026-11-19T15:56:59.724115+00:00", "project": "messenger-test", "load": { - "date_utc": "2026-11-14T01:54:04.006033+00:00", + "date_utc": "2026-11-19T15:56:52.469419+00:00", "workload": "synthetic POST messages; fixed arrival rate; no retries", "duration_seconds": 10, - "elapsed_seconds": 9.929, + "elapsed_seconds": 9.923, "arrival_rate": 10, "concurrency_limit": 2, "successful_requests": 100, "failed_requests": 0, "error_ratio": 0.0, - "successful_rps": 10.072, + "successful_rps": 10.078, "successful_latency_ms": { - "p50": 31.394, - "p95": 63.623, - "p99": 70.12 + "p50": 18.036, + "p95": 39.623, + "p99": 45.954 }, "dataset": { "users": 3, @@ -24,192 +24,192 @@ }, "resource_samples": [ { - "elapsed_seconds": 2.166, + "elapsed_seconds": 2.058, "containers": [ { "Name": "messenger-test-api-1", - "CPUPerc": "54.62%", - "MemUsage": "90.74MiB / 1.5GiB", - "MemPerc": "5.91%" + "CPUPerc": "40.63%", + "MemUsage": "94.64MiB / 1.5GiB", + "MemPerc": "6.16%" }, { "Name": "messenger-test-api-2", - "CPUPerc": "13.14%", - "MemUsage": "91.79MiB / 1.5GiB", - "MemPerc": "5.98%" + "CPUPerc": "5.96%", + "MemUsage": "87.06MiB / 1.5GiB", + "MemPerc": "5.67%" }, { "Name": "messenger-test-broker-1", - "CPUPerc": "0.16%", - "MemUsage": "112.5MiB / 768MiB", - "MemPerc": "14.64%" + "CPUPerc": "86.17%", + "MemUsage": "148.3MiB / 768MiB", + "MemPerc": "19.31%" }, { "Name": "messenger-test-cleanup-1", "CPUPerc": "0.00%", - "MemUsage": "74.46MiB / 256MiB", + "MemUsage": "74.44MiB / 256MiB", "MemPerc": "29.08%" }, { "Name": "messenger-test-grafana-1", - "CPUPerc": "0.85%", - "MemUsage": "373.6MiB / 512MiB", - "MemPerc": "72.96%" + "CPUPerc": "0.47%", + "MemUsage": "292.7MiB / 512MiB", + "MemPerc": "57.17%" }, { "Name": "messenger-test-loki-1", - "CPUPerc": "0.82%", - "MemUsage": "62.73MiB / 512MiB", - "MemPerc": "12.25%" + "CPUPerc": "0.58%", + "MemUsage": "69.43MiB / 512MiB", + "MemPerc": "13.56%" }, { "Name": "messenger-test-minio-1", - "CPUPerc": "66.11%", - "MemUsage": "155.6MiB / 512MiB", - "MemPerc": "30.39%" + "CPUPerc": "0.08%", + "MemUsage": "131.4MiB / 512MiB", + "MemPerc": "25.67%" }, { "Name": "messenger-test-nginx-1", - "CPUPerc": "0.35%", - "MemUsage": "4.312MiB / 128MiB", - "MemPerc": "3.37%" + "CPUPerc": "0.27%", + "MemUsage": "5.359MiB / 128MiB", + "MemPerc": "4.19%" }, { "Name": "messenger-test-otel-collector-1", - "CPUPerc": "0.86%", - "MemUsage": "55.17MiB / 256MiB", - "MemPerc": "21.55%" + "CPUPerc": "0.30%", + "MemUsage": "62.13MiB / 256MiB", + "MemPerc": "24.27%" }, { "Name": "messenger-test-postgres-1", - "CPUPerc": "20.53%", - "MemUsage": "77.13MiB / 512MiB", - "MemPerc": "15.06%" + "CPUPerc": "1.54%", + "MemUsage": "107.4MiB / 512MiB", + "MemPerc": "20.99%" }, { "Name": "messenger-test-prometheus-1", - "CPUPerc": "0.16%", - "MemUsage": "34.8MiB / 512MiB", - "MemPerc": "6.80%" + "CPUPerc": "0.14%", + "MemUsage": "37.91MiB / 512MiB", + "MemPerc": "7.41%" }, { "Name": "messenger-test-publisher-1", - "CPUPerc": "0.92%", - "MemUsage": "62.27MiB / 256MiB", - "MemPerc": "24.32%" + "CPUPerc": "0.73%", + "MemUsage": "65.48MiB / 256MiB", + "MemPerc": "25.58%" }, { "Name": "messenger-test-redis-1", - "CPUPerc": "0.45%", - "MemUsage": "8.496MiB / 512MiB", - "MemPerc": "1.66%" + "CPUPerc": "3.00%", + "MemUsage": "8.527MiB / 512MiB", + "MemPerc": "1.67%" }, { "Name": "messenger-test-tempo-1", - "CPUPerc": "0.62%", - "MemUsage": "224.5MiB / 512MiB", - "MemPerc": "43.85%" + "CPUPerc": "0.30%", + "MemUsage": "318.4MiB / 512MiB", + "MemPerc": "62.19%" }, { "Name": "messenger-test-worker-1", - "CPUPerc": "0.01%", - "MemUsage": "68.05MiB / 2GiB", - "MemPerc": "3.32%" + "CPUPerc": "0.19%", + "MemUsage": "73.34MiB / 2GiB", + "MemPerc": "3.58%" } ] }, { - "elapsed_seconds": 7.274, + "elapsed_seconds": 7.107, "containers": [ { "Name": "messenger-test-api-1", - "CPUPerc": "11.38%", - "MemUsage": "90.96MiB / 1.5GiB", - "MemPerc": "5.92%" + "CPUPerc": "7.55%", + "MemUsage": "94.69MiB / 1.5GiB", + "MemPerc": "6.16%" }, { "Name": "messenger-test-api-2", - "CPUPerc": "81.50%", - "MemUsage": "98.59MiB / 1.5GiB", - "MemPerc": "6.42%" + "CPUPerc": "39.26%", + "MemUsage": "87.07MiB / 1.5GiB", + "MemPerc": "5.67%" }, { "Name": "messenger-test-broker-1", - "CPUPerc": "0.25%", - "MemUsage": "112.5MiB / 768MiB", - "MemPerc": "14.64%" + "CPUPerc": "15.48%", + "MemUsage": "189.4MiB / 768MiB", + "MemPerc": "24.66%" }, { "Name": "messenger-test-cleanup-1", "CPUPerc": "0.00%", - "MemUsage": "74.46MiB / 256MiB", + "MemUsage": "74.44MiB / 256MiB", "MemPerc": "29.08%" }, { "Name": "messenger-test-grafana-1", - "CPUPerc": "0.91%", - "MemUsage": "373.6MiB / 512MiB", - "MemPerc": "72.96%" + "CPUPerc": "0.55%", + "MemUsage": "292.7MiB / 512MiB", + "MemPerc": "57.17%" }, { "Name": "messenger-test-loki-1", - "CPUPerc": "0.98%", - "MemUsage": "62.27MiB / 512MiB", - "MemPerc": "12.16%" + "CPUPerc": "0.56%", + "MemUsage": "69.18MiB / 512MiB", + "MemPerc": "13.51%" }, { "Name": "messenger-test-minio-1", - "CPUPerc": "0.18%", - "MemUsage": "155.6MiB / 512MiB", - "MemPerc": "30.39%" + "CPUPerc": "3.59%", + "MemUsage": "135.3MiB / 512MiB", + "MemPerc": "26.42%" }, { "Name": "messenger-test-nginx-1", - "CPUPerc": "0.75%", - "MemUsage": "3.852MiB / 128MiB", - "MemPerc": "3.01%" + "CPUPerc": "0.25%", + "MemUsage": "4.82MiB / 128MiB", + "MemPerc": "3.77%" }, { "Name": "messenger-test-otel-collector-1", - "CPUPerc": "1.71%", - "MemUsage": "54.97MiB / 256MiB", - "MemPerc": "21.47%" + "CPUPerc": "0.64%", + "MemUsage": "62.66MiB / 256MiB", + "MemPerc": "24.48%" }, { "Name": "messenger-test-postgres-1", - "CPUPerc": "21.91%", - "MemUsage": "77.45MiB / 512MiB", - "MemPerc": "15.13%" + "CPUPerc": "7.61%", + "MemUsage": "107.5MiB / 512MiB", + "MemPerc": "20.99%" }, { "Name": "messenger-test-prometheus-1", - "CPUPerc": "0.84%", - "MemUsage": "35.03MiB / 512MiB", - "MemPerc": "6.84%" + "CPUPerc": "0.21%", + "MemUsage": "38.25MiB / 512MiB", + "MemPerc": "7.47%" }, { "Name": "messenger-test-publisher-1", - "CPUPerc": "1.10%", - "MemUsage": "62.28MiB / 256MiB", - "MemPerc": "24.33%" + "CPUPerc": "0.65%", + "MemUsage": "65.73MiB / 256MiB", + "MemPerc": "25.68%" }, { "Name": "messenger-test-redis-1", - "CPUPerc": "9.35%", - "MemUsage": "8.848MiB / 512MiB", - "MemPerc": "1.73%" + "CPUPerc": "0.48%", + "MemUsage": "8.773MiB / 512MiB", + "MemPerc": "1.71%" }, { "Name": "messenger-test-tempo-1", - "CPUPerc": "0.63%", - "MemUsage": "224.7MiB / 512MiB", - "MemPerc": "43.89%" + "CPUPerc": "0.28%", + "MemUsage": "320.2MiB / 512MiB", + "MemPerc": "62.53%" }, { "Name": "messenger-test-worker-1", - "CPUPerc": "0.49%", - "MemUsage": "68.05MiB / 2GiB", - "MemPerc": "3.32%" + "CPUPerc": "0.01%", + "MemUsage": "73.34MiB / 2GiB", + "MemPerc": "3.58%" } ] } @@ -219,28 +219,28 @@ "api_replicas": 2, "dashboard_uid": "messenger-overview", "api_correlation": { - "trace_id": "0a0e27eba5d266cf6cdc3eb9bfc7f5ef", - "span_id": "a7638b6d19f2e057", + "trace_id": "b07429169c91eb6e67d211959181ab10", + "span_id": "96318acd3dddff53", "log": { - "timestamp": "2026-11-14T01:54:07.311535+00:00", + "timestamp": "2026-11-19T15:56:54.681885+00:00", "severity": "INFO", "service_name": "messenger-api", "event": "http.request", - "trace_id": "0a0e27eba5d266cf6cdc3eb9bfc7f5ef", - "span_id": "a7638b6d19f2e057", + "trace_id": "b07429169c91eb6e67d211959181ab10", + "span_id": "96318acd3dddff53", "method": "POST", "route": "/api/v1/chats/{chat_id}/messages", "status_code": 201, - "request_id": "e60a3114-3fa6-4aa5-a24b-e11f081f041b", - "duration_seconds": 0.015342902999691432 + "request_id": "171446ed-c27f-45e0-86b3-1b6e06420b4e", + "duration_seconds": 0.08245528700001614 }, "spans": [ { "name": "POST /api/v1/chats/{chat_id}/messages", "kind": "SPAN_KIND_SERVER", - "spanId": "p2OLbRny4Fc=", - "startTimeUnixNano": "1794621247296110185", - "endTimeUnixNano": "1794621247311696146", + "spanId": "ljGKzT3d/1M=", + "startTimeUnixNano": "1795103814599010618", + "endTimeUnixNano": "1795103814682418591", "status": { "code": "STATUS_CODE_OK" } @@ -248,25 +248,25 @@ ] }, "worker_correlation": { - "trace_id": "e0b8ad546fdfe9dfd5d7391424b2fc18", - "span_id": "47ccae94dff8f378", + "trace_id": "ad41b35e5e8b02c32f7a7b74d7b6278a", + "span_id": "ff9586c715f69b64", "log": { - "timestamp": "2026-11-14T01:54:07.762039+00:00", + "timestamp": "2026-11-19T15:56:55.880853+00:00", "severity": "INFO", "service_name": "messenger-worker", "event": "job.received", - "trace_id": "e0b8ad546fdfe9dfd5d7391424b2fc18", - "span_id": "47ccae94dff8f378", - "job_id": "49ce2d69-4237-4836-b23b-e34c45fe9b15", - "attachment_id": "0358f440-2f03-49ae-992d-53447bba3baa" + "trace_id": "ad41b35e5e8b02c32f7a7b74d7b6278a", + "span_id": "ff9586c715f69b64", + "job_id": "ce2dd02a-7263-43b3-9cdb-1caf53fcb262", + "attachment_id": "d49c525e-6cab-4a88-b348-867cc4185499" }, "spans": [ { "name": "attachment.process.v1", "kind": "SPAN_KIND_CONSUMER", - "spanId": "R8yulN/483g=", - "startTimeUnixNano": "1794621247762005178", - "endTimeUnixNano": "1794621248800203658", + "spanId": "/5WGxxX2m2Q=", + "startTimeUnixNano": "1795103815880827668", + "endTimeUnixNano": "1795103816744588122", "status": { "code": "STATUS_CODE_OK" } @@ -278,8 +278,8 @@ { "metric": {}, "value": [ - 1794621249.18, - "229" + 1795103819.091, + "383" ] } ], @@ -287,8 +287,8 @@ { "metric": {}, "value": [ - 1794621249.198, - "229" + 1795103819.104, + "383" ] } ], @@ -296,7 +296,7 @@ { "metric": {}, "value": [ - 1794621249.248, + 1795103819.119, "1" ] } @@ -305,39 +305,139 @@ { "metric": {}, "value": [ - 1794621249.264, + 1795103819.132, "1" ] } ] }, + "upload_trace": { + "trace_id": "ad41b35e5e8b02c32f7a7b74d7b6278a", + "chain": [ + { + "name": "POST /api/v1/chats/{chat_id}/attachments", + "kind": "SPAN_KIND_SERVER", + "span_id": "74b246705b53c840", + "parent_span_id": "", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "cf8900edf04666d0", + "parent_span_id": "74b246705b53c840", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "dc111544195865ab", + "parent_span_id": "74b246705b53c840", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "ea30143c06d7101a", + "parent_span_id": "74b246705b53c840", + "job": {} + }, + { + "name": "rabbitmq.publish", + "kind": "SPAN_KIND_PRODUCER", + "span_id": "9414f5609a1615fc", + "parent_span_id": "74b246705b53c840", + "job": { + "job.attempt": { + "intValue": "1" + } + } + }, + { + "name": "attachment.process.v1", + "kind": "SPAN_KIND_CONSUMER", + "span_id": "ff9586c715f69b64", + "parent_span_id": "9414f5609a1615fc", + "job": { + "job.attempt": { + "intValue": "1" + }, + "outcome": { + "stringValue": "success" + } + } + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "3a99027f12c54d14", + "parent_span_id": "ff9586c715f69b64", + "job": {} + }, + { + "name": "s3.write_result", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "7238fed2427ff2b5", + "parent_span_id": "ff9586c715f69b64", + "job": {} + }, + { + "name": "postgres.commit_ready", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "6228546b59c97cc1", + "parent_span_id": "ff9586c715f69b64", + "job": {} + }, + { + "name": "postgres.claim_job", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "d038f59546905b0d", + "parent_span_id": "ff9586c715f69b64", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "8ddfdeb23bfdca06", + "parent_span_id": "d038f59546905b0d", + "job": {} + }, + { + "name": "s3.read_staging", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "87438655356f817f", + "parent_span_id": "ff9586c715f69b64", + "job": {} + } + ] + }, "incidents": [ { "scenario": "postgres_unavailable", "http_status": 503, "correlation": { - "trace_id": "46bd5c67c04ee46676631207f4cdaaef", - "span_id": "9da26006f1e46fec", + "trace_id": "020e820d68045ad3195e842244670b11", + "span_id": "d100199e5812f6e3", "log": { - "timestamp": "2026-11-14T01:54:11.699761+00:00", + "timestamp": "2026-11-19T15:57:03.906932+00:00", "severity": "ERROR", "service_name": "messenger-api", "event": "http.request", - "trace_id": "46bd5c67c04ee46676631207f4cdaaef", - "span_id": "9da26006f1e46fec", + "trace_id": "020e820d68045ad3195e842244670b11", + "span_id": "d100199e5812f6e3", "method": "POST", "route": "/api/v1/users", "status_code": 503, - "request_id": "5b3b6549-a5b7-44d9-aaa4-883e7f7f82a6", - "duration_seconds": 0.31245764100094675 + "request_id": "420eae93-41a6-41af-8f37-09e76b8ec997", + "duration_seconds": 3.004546160000018 }, "spans": [ { "name": "POST /api/v1/users", "kind": "SPAN_KIND_SERVER", - "spanId": "naJgBvHkb+w=", - "startTimeUnixNano": "1794621251387164345", - "endTimeUnixNano": "1794621251699877506", + "spanId": "0QAZnlgS9uM=", + "startTimeUnixNano": "1795103820902285656", + "endTimeUnixNano": "1795103823907032467", "status": { "code": "STATUS_CODE_ERROR" } @@ -345,47 +445,437 @@ ] }, "diagnostic": { - "timestamp": "2026-11-14T01:54:11.698503+00:00", + "timestamp": "2026-11-19T15:57:03.905870+00:00", "severity": "ERROR", "service_name": "messenger-api", "event": "dependency.unavailable", - "trace_id": "46bd5c67c04ee46676631207f4cdaaef", - "span_id": "9da26006f1e46fec", - "request_id": "5b3b6549-a5b7-44d9-aaa4-883e7f7f82a6", - "exception_type": "gaierror" + "trace_id": "020e820d68045ad3195e842244670b11", + "span_id": "d100199e5812f6e3", + "request_id": "420eae93-41a6-41af-8f37-09e76b8ec997", + "exception_type": "TimeoutError" }, - "observed_after_seconds": 4.194, - "recovery_seconds": 5.664 + "db_span": "postgres.checkout", + "alert": "MessengerHighErrorRate", + "firing_after_seconds": 32.361, + "resolved_after_seconds": 67.526 }, { - "scenario": "permanent_processing_failure", - "recovered_status": "ready", - "log": { - "timestamp": "2026-11-14T01:54:18.958470+00:00", - "severity": "ERROR", - "service_name": "messenger-worker", - "event": "job.processed", - "trace_id": "c6bbd94e4fdbad5e5808a2655735b9ed", - "span_id": "40a757e89d4b1f76", - "job_type": "attachment.process.v1", - "duration_seconds": 0.009965533998183673, - "outcome": "error", - "error_code": "injected_permanent" + "scenario": "worker_stopped_then_transient_retry", + "alert": "MessengerQueueLag", + "queue": { + "depth": 1.0, + "oldest_seconds": 25.641574, + "firing_after_seconds": 28.639, + "resolved": true, + "final_depth": 0 }, - "failed_jobs_metric": [ + "recovered_status": "ready", + "trace_id": "ff8352e27270fbc16fea7216c3ff45c0", + "chain": [ { - "metric": {}, - "value": [ - 1794621294.923, - "1" - ] + "name": "POST /api/v1/chats/{chat_id}/attachments", + "kind": "SPAN_KIND_SERVER", + "span_id": "a8daa5d1e858d802", + "parent_span_id": "", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "1bfe66add09278e5", + "parent_span_id": "a8daa5d1e858d802", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "cf5bdfb14aca0e03", + "parent_span_id": "a8daa5d1e858d802", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "fe476468bb06d3f2", + "parent_span_id": "a8daa5d1e858d802", + "job": {} + }, + { + "name": "rabbitmq.publish", + "kind": "SPAN_KIND_PRODUCER", + "span_id": "07218fe96edd8a9f", + "parent_span_id": "a8daa5d1e858d802", + "job": { + "job.attempt": { + "intValue": "1" + } + } + }, + { + "name": "rabbitmq.publish", + "kind": "SPAN_KIND_PRODUCER", + "span_id": "93984e580b7e86d5", + "parent_span_id": "a8daa5d1e858d802", + "job": { + "job.attempt": { + "intValue": "2" + } + } + }, + { + "name": "rabbitmq.publish", + "kind": "SPAN_KIND_PRODUCER", + "span_id": "a458e41372613973", + "parent_span_id": "a8daa5d1e858d802", + "job": { + "job.attempt": { + "intValue": "3" + } + } + }, + { + "name": "rabbitmq.publish", + "kind": "SPAN_KIND_PRODUCER", + "span_id": "bbf04d7c40b14fb3", + "parent_span_id": "a8daa5d1e858d802", + "job": { + "job.attempt": { + "intValue": "4" + } + } + }, + { + "name": "attachment.process.v1", + "kind": "SPAN_KIND_CONSUMER", + "span_id": "3c0af738c589e75e", + "parent_span_id": "07218fe96edd8a9f", + "job": { + "job.attempt": { + "intValue": "1" + }, + "outcome": { + "stringValue": "error" + } + } + }, + { + "name": "postgres.claim_job", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "36993e3e09207c51", + "parent_span_id": "3c0af738c589e75e", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "ea60348b52b97e80", + "parent_span_id": "36993e3e09207c51", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "a6ce9125f0f2b69a", + "parent_span_id": "3c0af738c589e75e", + "job": {} + }, + { + "name": "attachment.process.v1", + "kind": "SPAN_KIND_CONSUMER", + "span_id": "f7b2eab20244c154", + "parent_span_id": "93984e580b7e86d5", + "job": { + "job.attempt": { + "intValue": "2" + }, + "outcome": { + "stringValue": "error" + } + } + }, + { + "name": "postgres.claim_job", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "06c6bcc9ba7a345d", + "parent_span_id": "f7b2eab20244c154", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "83c7a52ecd57f72f", + "parent_span_id": "06c6bcc9ba7a345d", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "0310e2dd03331cb3", + "parent_span_id": "f7b2eab20244c154", + "job": {} + }, + { + "name": "attachment.process.v1", + "kind": "SPAN_KIND_CONSUMER", + "span_id": "f2c43df28f9d7a39", + "parent_span_id": "a458e41372613973", + "job": { + "job.attempt": { + "intValue": "3" + }, + "outcome": { + "stringValue": "error" + } + } + }, + { + "name": "postgres.claim_job", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "b81945a1dac3e54e", + "parent_span_id": "f2c43df28f9d7a39", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "206ffc2a7aaafca5", + "parent_span_id": "b81945a1dac3e54e", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "f6f62fbcc37d065f", + "parent_span_id": "f2c43df28f9d7a39", + "job": {} + }, + { + "name": "attachment.process.v1", + "kind": "SPAN_KIND_CONSUMER", + "span_id": "caf2f1cf5ab31318", + "parent_span_id": "bbf04d7c40b14fb3", + "job": { + "job.attempt": { + "intValue": "4" + }, + "outcome": { + "stringValue": "error" + } + } + }, + { + "name": "postgres.claim_job", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "0e0bdca52b68b3d7", + "parent_span_id": "caf2f1cf5ab31318", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "ff6de1ac78d07a28", + "parent_span_id": "0e0bdca52b68b3d7", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "2f459882491c3a7c", + "parent_span_id": "caf2f1cf5ab31318", + "job": {} + }, + { + "name": "rabbitmq.publish", + "kind": "SPAN_KIND_PRODUCER", + "span_id": "0a79dcefe6527245", + "parent_span_id": "a8daa5d1e858d802", + "job": { + "job.attempt": { + "intValue": "5" + } + } + }, + { + "name": "rabbitmq.publish", + "kind": "SPAN_KIND_PRODUCER", + "span_id": "a4e8cf406651958d", + "parent_span_id": "a8daa5d1e858d802", + "job": { + "job.attempt": { + "intValue": "6" + } + } + }, + { + "name": "attachment.process.v1", + "kind": "SPAN_KIND_CONSUMER", + "span_id": "6d709c8f5827479d", + "parent_span_id": "0a79dcefe6527245", + "job": { + "job.attempt": { + "intValue": "5" + }, + "outcome": { + "stringValue": "error" + } + } + }, + { + "name": "postgres.claim_job", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "0a5ed8ae1cdac4bd", + "parent_span_id": "6d709c8f5827479d", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "a6452306465ac351", + "parent_span_id": "0a5ed8ae1cdac4bd", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "d5c93140a00b63ab", + "parent_span_id": "6d709c8f5827479d", + "job": {} + }, + { + "name": "attachment.process.v1", + "kind": "SPAN_KIND_CONSUMER", + "span_id": "45c2e49b6f6471bf", + "parent_span_id": "a4e8cf406651958d", + "job": { + "job.attempt": { + "intValue": "6" + }, + "outcome": { + "stringValue": "success" + } + } + }, + { + "name": "postgres.claim_job", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "6d995da536f4d248", + "parent_span_id": "45c2e49b6f6471bf", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "ab6ddaa6b67c5663", + "parent_span_id": "6d995da536f4d248", + "job": {} + }, + { + "name": "s3.read_staging", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "ec1037446c0d5918", + "parent_span_id": "45c2e49b6f6471bf", + "job": {} + }, + { + "name": "postgres.checkout", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "4059610a72cf3cd0", + "parent_span_id": "45c2e49b6f6471bf", + "job": {} + }, + { + "name": "s3.write_result", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "741f62682fa8057f", + "parent_span_id": "45c2e49b6f6471bf", + "job": {} + }, + { + "name": "postgres.commit_ready", + "kind": "SPAN_KIND_INTERNAL", + "span_id": "17c7adc7b583eeda", + "parent_span_id": "45c2e49b6f6471bf", + "job": {} + } + ] + }, + { + "scenario": "loki_unavailable", + "successful_messages": 204, + "dropped_after_export_failure": 6.0, + "dropped_at_enqueue": 0.0, + "samples": [ + { + "seconds": 0.06, + "rss_bytes": 239079424.0, + "queued_batches": 0.0, + "capacity_batches": 256.0 + }, + { + "seconds": 5.14, + "rss_bytes": 239288320.0, + "queued_batches": 5.0, + "capacity_batches": 256.0 + }, + { + "seconds": 10.08, + "rss_bytes": 239292416.0, + "queued_batches": 10.0, + "capacity_batches": 256.0 + }, + { + "seconds": 15.12, + "rss_bytes": 240283648.0, + "queued_batches": 15.0, + "capacity_batches": 256.0 + }, + { + "seconds": 20.07, + "rss_bytes": 241635328.0, + "queued_batches": 20.0, + "capacity_batches": 256.0 + }, + { + "seconds": 25.09, + "rss_bytes": 241795072.0, + "queued_batches": 24.0, + "capacity_batches": 256.0 + }, + { + "seconds": 30.07, + "rss_bytes": 241836032.0, + "queued_batches": 29.0, + "capacity_batches": 256.0 + }, + { + "seconds": 35.09, + "rss_bytes": 241856512.0, + "queued_batches": 33.0, + "capacity_batches": 256.0 + }, + { + "seconds": 40.09, + "rss_bytes": 241860608.0, + "queued_batches": 38.0, + "capacity_batches": 256.0 + }, + { + "seconds": 45.09, + "rss_bytes": 242176000.0, + "queued_batches": 43.0, + "capacity_batches": 256.0 + }, + { + "seconds": 50.07, + "rss_bytes": 242384896.0, + "queued_batches": 48.0, + "capacity_batches": 256.0 } ], - "metric_query": "sum(messenger_job_attempts_total{outcome=\"error\",service_instance_id=\"3b4f96f13e48\"})", - "failure_to_ready_seconds": 19.356 + "log_export_recovered": true } ], - "privacy_checked_logs": 72, + "privacy_checked_logs": 413, "checks": { "three_backends": true, "dashboard_queries": true, diff --git a/evidence/verification.json b/evidence/verification.json index 4c6b71db..6a491eed 100644 --- a/evidence/verification.json +++ b/evidence/verification.json @@ -1,5 +1,5 @@ { - "date_utc": "2026-11-14T01:50:28.592547+00:00", + "date_utc": "2026-11-19T15:50:02.598982+00:00", "checks": [ { "name": "contract", @@ -8,7 +8,7 @@ "scripts/check_contract.py" ], "exit_code": 0, - "duration_seconds": 0.101, + "duration_seconds": 0.112, "result": "PASS" }, { @@ -18,7 +18,7 @@ "scripts/validate_openapi.py" ], "exit_code": 0, - "duration_seconds": 1.111, + "duration_seconds": 1.068, "result": "PASS" }, { @@ -32,7 +32,7 @@ "--quiet" ], "exit_code": 0, - "duration_seconds": 0.131, + "duration_seconds": 0.113, "result": "PASS" }, { @@ -43,7 +43,7 @@ "test-stand-up" ], "exit_code": 0, - "duration_seconds": 77.116, + "duration_seconds": 70.403, "result": "PASS" }, { @@ -54,9 +54,9 @@ "test-unit" ], "exit_code": 0, - "duration_seconds": 115.183, + "duration_seconds": 322.597, "result": "PASS", - "summary": "206 passed in 112.44s (0:01:52)" + "summary": "206 passed in 98.89s (0:01:38)" }, { "name": "api", @@ -67,7 +67,7 @@ "http://localhost:28080" ], "exit_code": 0, - "duration_seconds": 8.349, + "duration_seconds": 4.112, "result": "PASS" }, { @@ -84,7 +84,7 @@ "--restart-telemetry" ], "exit_code": 0, - "duration_seconds": 79.231, + "duration_seconds": 292.686, "result": "PASS" }, { @@ -100,7 +100,7 @@ "http://localhost:28080" ], "exit_code": 0, - "duration_seconds": 62.485, + "duration_seconds": 61.526, "result": "PASS" }, { @@ -116,7 +116,7 @@ "http://localhost:28080" ], "exit_code": 0, - "duration_seconds": 17.998, + "duration_seconds": 19.039, "result": "PASS" } ], @@ -128,345 +128,13 @@ }, "result": "PASS", "cleanup": { - "projects": [ - "messenger", - "messenger-test" - ], - "resources": { - "containers": [ - "062d88c22d6c", - "5653c0121264", - "6e2b3ca3c86c", - "ac60f4044ea7", - "e633226993b5", - "1e21fe44a453", - "126c76cff388", - "76901c1e8b60", - "85731e19d4c6", - "79077e49c5ee", - "80a7e7e36fd1", - "69f42359b3e3", - "1a3d86fafd53", - "9f00acc93186", - "bd366e53bf42", - "b4f81e6b52c3", - "a9f375b0b17b" - ], - "networks": [ - "04eba990b02c", - "ff8d81906905" - ], - "volumes": [ - "messenger-test_grafanadata", - "messenger-test_lokidata", - "messenger-test_miniodata", - "messenger-test_pgdata", - "messenger-test_prometheusdata", - "messenger-test_rabbitmqdata", - "messenger-test_redisdata", - "messenger-test_tempodata" - ] - }, - "application_image_ids": [ - "490c0e5b26df", - "669227412939", - "af2ab3c10330" - ], - "local_settings_preserved": true, + "project": "messenger-test", "remaining": { "containers": [], "networks": [], "volumes": [] }, - "application_images_remaining": [], - "result": "PASS", - "verified": { - "containers_remaining": 0, - "volumes_remaining": 0, - "application_images_remaining": 0, - "local_settings_preserved": true - } + "result": "PASS" }, - "finished_at_utc": "2026-11-14T01:56:33.228789+00:00", - "source": { - "base_commit": "498ce1e0d20c7ffc45ef71b81f5ce3cfa56208ec", - "working_tree_modified": true - }, - "runtime": { - "python": "3.12.14", - "docker_engine": "29.9.3", - "compose": "5.7.0" - }, - "container_lifecycle": [ - { - "time_unix": 1794621212, - "action": "stop", - "service": "redis" - }, - { - "time_unix": 1794621212, - "action": "start", - "service": "redis" - }, - { - "time_unix": 1794621251, - "action": "stop", - "service": "postgres" - }, - { - "time_unix": 1794621251, - "action": "start", - "service": "publisher" - }, - { - "time_unix": 1794621254, - "action": "start", - "service": "postgres" - }, - { - "time_unix": 1794621255, - "action": "stop", - "service": "worker" - }, - { - "time_unix": 1794621256, - "action": "start", - "service": "worker" - }, - { - "time_unix": 1794621267, - "action": "start", - "service": "worker" - }, - { - "time_unix": 1794621269, - "action": "start", - "service": "worker" - }, - { - "time_unix": 1794621271, - "action": "start", - "service": "minio-bootstrap" - }, - { - "time_unix": 1794621272, - "action": "start", - "service": "migrate" - }, - { - "time_unix": 1794621275, - "action": "start", - "service": "worker" - }, - { - "time_unix": 1794621281, - "action": "start", - "service": "worker" - }, - { - "time_unix": 1794621284, - "action": "start", - "service": "worker" - }, - { - "time_unix": 1794621292, - "action": "start", - "service": "worker" - }, - { - "time_unix": 1794621295, - "action": "stop", - "service": "prometheus" - }, - { - "time_unix": 1794621295, - "action": "stop", - "service": "grafana" - }, - { - "time_unix": 1794621295, - "action": "start", - "service": "prometheus" - }, - { - "time_unix": 1794621295, - "action": "start", - "service": "grafana" - }, - { - "time_unix": 1794621295, - "action": "stop", - "service": "loki" - }, - { - "time_unix": 1794621296, - "action": "start", - "service": "loki" - }, - { - "time_unix": 1794621305, - "action": "stop", - "service": "tempo" - }, - { - "time_unix": 1794621305, - "action": "start", - "service": "tempo" - }, - { - "time_unix": 1794621314, - "action": "stop", - "service": "worker" - }, - { - "time_unix": 1794621314, - "action": "stop", - "service": "publisher" - }, - { - "time_unix": 1794621324, - "action": "stop", - "service": "cleanup" - }, - { - "time_unix": 1794621324, - "action": "stop", - "service": "otel-collector" - }, - { - "time_unix": 1794621325, - "action": "stop", - "service": "minio" - }, - { - "time_unix": 1794621325, - "action": "stop", - "service": "prometheus" - }, - { - "time_unix": 1794621325, - "action": "stop", - "service": "grafana" - }, - { - "time_unix": 1794621325, - "action": "stop", - "service": "broker" - }, - { - "time_unix": 1794621325, - "action": "stop", - "service": "redis" - }, - { - "time_unix": 1794621325, - "action": "stop", - "service": "postgres" - }, - { - "time_unix": 1794621325, - "action": "stop", - "service": "loki" - }, - { - "time_unix": 1794621325, - "action": "start", - "service": "minio" - }, - { - "time_unix": 1794621325, - "action": "start", - "service": "otel-collector" - }, - { - "time_unix": 1794621325, - "action": "start", - "service": "prometheus" - }, - { - "time_unix": 1794621325, - "action": "start", - "service": "grafana" - }, - { - "time_unix": 1794621325, - "action": "start", - "service": "broker" - }, - { - "time_unix": 1794621325, - "action": "start", - "service": "redis" - }, - { - "time_unix": 1794621325, - "action": "start", - "service": "postgres" - }, - { - "time_unix": 1794621325, - "action": "start", - "service": "loki" - }, - { - "time_unix": 1794621334, - "action": "stop", - "service": "tempo" - }, - { - "time_unix": 1794621335, - "action": "start", - "service": "tempo" - }, - { - "time_unix": 1794621335, - "action": "stop", - "service": "nginx" - }, - { - "time_unix": 1794621336, - "action": "start", - "service": "nginx" - }, - { - "time_unix": 1794621337, - "action": "stop", - "service": "api" - }, - { - "time_unix": 1794621337, - "action": "stop", - "service": "api" - }, - { - "time_unix": 1794621337, - "action": "start", - "service": "api" - }, - { - "time_unix": 1794621337, - "action": "start", - "service": "api" - }, - { - "time_unix": 1794621344, - "action": "start", - "service": "cleanup" - }, - { - "time_unix": 1794621344, - "action": "start", - "service": "publisher" - }, - { - "time_unix": 1794621345, - "action": "start", - "service": "worker" - }, - { - "time_unix": 1794621377, - "action": "stop", - "service": "api" - } - ] + "finished_at_utc": "2026-11-19T16:03:05.425775+00:00" } diff --git a/infra/otel/README.md b/infra/otel/README.md index 6f27be25..bd43ee63 100644 --- a/infra/otel/README.md +++ b/infra/otel/README.md @@ -1,6 +1,6 @@ # Наблюдаемость Messenger -API и worker экспортируют OTLP HTTP/protobuf в Collector (:4318). +API, publisher и worker экспортируют OTLP HTTP/protobuf в Collector (:4318). Метрики выдаются Prometheus на :8889, логи отправляются в native OTLP Loki, traces — в Tempo. Grafana читает три хранилища через provisioned datasources. @@ -15,6 +15,6 @@ grafanadata содержит настройки Grafana. Внешний порт по умолчанию 127.0.0.1:13000. Её healthcheck проверяет также Loki, Tempo и Collector. Бизнес-readiness API от этих сервисов не зависит. -Проверка: `make test-observability`. Полный прогон с очисткой: `make verify`. -Инструкция запуска — в [RUNNING.md](../../RUNNING.md), ограничения и планы — в -[REPORT.md](../../REPORT.md). +`make test-observability` запускает контролируемые отказы на указанном стенде. +`make verify` создаёт отдельный проект и удаляет его ресурсы после прогона. +Правила Prometheus, запуск и порядок диагностики описаны в [REPORT.md](../../REPORT.md). diff --git a/infra/otel/alerts.yaml b/infra/otel/alerts.yaml new file mode 100644 index 00000000..95319e6f --- /dev/null +++ b/infra/otel/alerts.yaml @@ -0,0 +1,18 @@ +groups: + - name: messenger + interval: 5s + rules: + - alert: MessengerHighErrorRate + expr: | + sum(increase(messenger_http_requests_total{http_response_status_class="5xx",http_route!~"/health/.*"}[30s])) + / clamp_min(sum(increase(messenger_http_requests_total{http_route!~"/health/.*"}[30s])), 1) > 0.05 + for: 5s + annotations: + summary: "Более 5% бизнес-запросов завершились HTTP 5xx за 30 секунд" + runbook: "REPORT.md#диагностика-инцидентов" + - alert: MessengerQueueLag + expr: max(messenger_queue_oldest_seconds) > 15 and max(messenger_queue_depth_ratio) > 0 + for: 5s + annotations: + summary: "Старейшее ожидающее задание находится в очереди более 15 секунд" + runbook: "REPORT.md#диагностика-инцидентов" diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml index 892f65c2..93a5e723 100644 --- a/infra/otel/collector.yaml +++ b/infra/otel/collector.yaml @@ -37,6 +37,14 @@ extensions: health_check: endpoint: 0.0.0.0:13133 service: + telemetry: + metrics: + readers: + - pull: + exporter: + prometheus: + host: 0.0.0.0 + port: 8888 extensions: [health_check] pipelines: metrics: diff --git a/infra/otel/grafana/dashboards/messenger.json b/infra/otel/grafana/dashboards/messenger.json index 11c1d638..b21cf376 100644 --- a/infra/otel/grafana/dashboards/messenger.json +++ b/infra/otel/grafana/dashboards/messenger.json @@ -332,6 +332,280 @@ } }, "description": "Накопленное число 5xx: показывает и первую ошибку нового ряда, когда rate ещё не имеет двух разных точек." + }, + { + "id": 11, + "title": "Очередь: ожидающие задания", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 45 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "expr": "max by (queue_name) (messenger_queue_depth_ratio)", + "legendFormat": "Глубина {{service_name}}{{queue_name}}{{exporter}}", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + } + } + ] + }, + { + "id": 12, + "title": "Очередь: возраст старейшей задачи", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 45 + }, + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "expr": "max by (queue_name) (messenger_queue_oldest_seconds)", + "legendFormat": "Возраст {{service_name}}{{queue_name}}{{exporter}}", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + } + } + ] + }, + { + "id": 13, + "title": "PostgreSQL: соединения и ожидающие", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 53 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (service_name) (messenger_db_pool_used_ratio)", + "legendFormat": "Занято {{service_name}}{{queue_name}}{{exporter}}", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + } + }, + { + "refId": "B", + "expr": "sum by (service_name) (messenger_db_pool_waiting_ratio)", + "legendFormat": "Ожидают {{service_name}}{{queue_name}}{{exporter}}", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + } + } + ] + }, + { + "id": 14, + "title": "Worker: доля занятых слотов", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 53 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "expr": "sum(messenger_worker_busy_ratio) / sum(messenger_worker_capacity_ratio)", + "legendFormat": "Загрузка {{service_name}}{{queue_name}}{{exporter}}", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + } + } + ] + }, + { + "id": 15, + "title": "Процессы: CPU в ядрах", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 61 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (service_name) (rate(messenger_process_cpu_seconds_total[1m]))", + "legendFormat": "CPU {{service_name}}{{queue_name}}{{exporter}}", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + } + } + ] + }, + { + "id": 16, + "title": "Процессы: резидентная память", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 61 + }, + "fieldConfig": { + "defaults": { + "unit": "bytes" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (service_name) (messenger_process_rss_bytes)", + "legendFormat": "RSS {{service_name}}{{queue_name}}{{exporter}}", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + } + } + ] + }, + { + "id": 17, + "title": "Вложения: p95 времени до ready", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 69 + }, + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket[5m])))", + "legendFormat": "p95 {{service_name}}{{queue_name}}{{exporter}}", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + } + } + ] + }, + { + "id": 18, + "title": "Collector: очереди экспорта", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 69 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "expr": "max by (exporter) (otelcol_exporter_queue_size)", + "legendFormat": "Размер {{service_name}}{{queue_name}}{{exporter}}", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + } + }, + { + "refId": "B", + "expr": "max by (exporter) (otelcol_exporter_queue_capacity)", + "legendFormat": "Ёмкость {{service_name}}{{queue_name}}{{exporter}}", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + } + } + ] } ], "annotations": { diff --git a/infra/otel/prometheus.yaml b/infra/otel/prometheus.yaml index 8997d87b..95b65b85 100644 --- a/infra/otel/prometheus.yaml +++ b/infra/otel/prometheus.yaml @@ -5,3 +5,7 @@ scrape_configs: - job_name: messenger static_configs: - targets: [otel-collector:8889] + - job_name: collector + static_configs: + - targets: [otel-collector:8888] +rule_files: [/etc/prometheus/alerts.yaml] diff --git a/migrations/versions/b55d0c6819ab_job_trace_context.py b/migrations/versions/b55d0c6819ab_job_trace_context.py new file mode 100644 index 00000000..079dd075 --- /dev/null +++ b/migrations/versions/b55d0c6819ab_job_trace_context.py @@ -0,0 +1,17 @@ +"""Сохранить W3C context между HTTP-транзакцией и publisher.""" + +import sqlalchemy as sa +from alembic import op + +revision = "b55d0c6819ab" +down_revision = "a62c950e18b3" +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column("attachment_jobs", sa.Column("trace_context", sa.JSON(), nullable=True)) + + +def downgrade(): + op.drop_column("attachment_jobs", "trace_context") diff --git a/scripts/check_jobs.py b/scripts/check_jobs.py index 5bea24b1..b82e7208 100644 --- a/scripts/check_jobs.py +++ b/scripts/check_jobs.py @@ -179,7 +179,7 @@ def crash(client, actor, chat, mode): ) -def retry_replay(client, actor, chat, permanent, on_failed=None): +def retry_replay(client, actor, chat, permanent, on_failed=None, on_queued=None): name = "messenger-retry-fault-" + uuid4().hex samples = [] configuration = ComposeProject().config["services"]["worker"]["environment"] @@ -188,6 +188,8 @@ def retry_replay(client, actor, chat, permanent, on_failed=None): try: require_compose("stop", "worker") attachment, original = client.attachment(actor, chat) + if on_queued is not None: + on_queued(attachment) mode = "fail-permanent" if permanent else "fail-transient" require_compose( "run", diff --git a/scripts/check_observability.py b/scripts/check_observability.py index 330138e7..a9a93ae1 100644 --- a/scripts/check_observability.py +++ b/scripts/check_observability.py @@ -1,6 +1,6 @@ """Проверка наблюдаемости через реальные запросы Grafana к трём backend. ---incidents явно разрешает два ограниченных отказа на выбранном Compose-проекте. +--incidents явно разрешает ограниченные отказы на выбранном Compose-проекте. В evidence сохраняются только агрегаты и выбранные технические поля. """ @@ -168,6 +168,84 @@ def run_load(args): return report +def metric(grafana, expression): + rows = grafana.query(expression) + return float(rows[0]['value'][1]) if rows else None + + +def alert_firing(grafana, name): + return bool(grafana.query(f'ALERTS{{alertname="{name}",alertstate="firing"}}')) + + +def trace_chain(grafana, trace_id, *, retry=False): + def inspect(): + spans = spans_in(grafana.trace(trace_id)) + by_id = {identifier_hex(span['spanId'], 8): span for span in spans} + workers = [span for span in spans if span['name'] == 'attachment.process.v1' + and span.get('kind') in ('SPAN_KIND_CONSUMER', 5)] + for worker in workers: + publisher = by_id.get(identifier_hex(worker.get('parentSpanId', ''), 8), {}) + if publisher.get('kind') not in ('SPAN_KIND_PRODUCER', 4): + return None + upload = by_id.get(identifier_hex(publisher.get('parentSpanId', ''), 8), {}) + if upload.get('name') != 'POST /api/v1/chats/{chat_id}/attachments': + return None + names = {span['name'] for span in spans} + if not workers or not {'s3.read_staging', 's3.write_result', 'postgres.commit_ready'} <= names: + return None + if retry: + outcomes = set() + for span in workers: + attrs = {row['key']: row['value'] for row in span.get('attributes', [])} + outcomes.add((int(attrs['job.attempt']['intValue']), attrs.get('outcome', {}).get('stringValue'))) + if not {(1, 'error'), (2, 'error')} <= outcomes or not any(n > 2 and outcome == 'success' for n, outcome in outcomes): + return None + return [{'name': span['name'], 'kind': span.get('kind'), + 'span_id': identifier_hex(span['spanId'], 8), + 'parent_span_id': identifier_hex(span.get('parentSpanId', ''), 8), + 'job': {entry['key']: entry['value'] for entry in span.get('attributes', []) + if entry['key'] in {'job.attempt', 'outcome'}}} for span in spans] + return eventually(inspect, 'Missing upload -> producer -> consumer -> S3/DB chain') + + +def telemetry_outage(project, client, grafana, actor, chat): + failed = 'sum({__name__=~"otelcol_exporter_send_failed_log_records(_total)?",exporter="otlphttp/loki"}) or vector(0)' + refused = 'sum({__name__=~"otelcol_exporter_enqueue_failed_log_records(_total)?",exporter="otlphttp/loki"}) or vector(0)' + baseline = [metric(grafana, expr) for expr in (failed, refused)] + rss = 'sum({__name__=~"otelcol_process_memory_rss(_bytes)?"})' + samples = [] + successful = 0 + try: + project.run('stop', 'loki') + start = time.monotonic() + for second in range(51): + for index in range(4): + client.message(actor, chat, f'outage-{second}-{index}') + successful += 1 + if second % 5 == 0: + samples.append({ + 'seconds': round(time.monotonic() - start, 2), + 'rss_bytes': metric(grafana, rss), + 'queued_batches': metric(grafana, 'sum(otelcol_exporter_queue_size{exporter="otlphttp/loki"})'), + 'capacity_batches': metric(grafana, 'sum(otelcol_exporter_queue_capacity{exporter="otlphttp/loki"})'), + }) + time.sleep(max(0, start + second + 1 - time.monotonic())) + losses = [metric(grafana, expr) - count for expr, count in zip((failed, refused), baseline)] + check(sum(losses) > 0, 'No measured Collector log loss during prolonged outage') + check(all(0 <= row['queued_batches'] <= row['capacity_batches'] == 256 for row in samples), 'Unexpected queue bound') + check(max(row['rss_bytes'] for row in samples) < 256 * 1024**2, 'Collector crossed container memory limit') + finally: + project.run('start', 'loki') + eventually(lambda: grafana.proxy('loki', '/loki/api/v1/labels').get('status') == 'success', + 'Loki did not recover') + restored = client.message(actor, chat, 'telemetry-backend-restored') + correlation(grafana, 'messenger-api', time.time_ns() - 30 * 10**9, + trace_id=restored['headers']['X-Trace-Id']) + return {'scenario':'loki_unavailable', 'successful_messages': successful, + 'dropped_after_export_failure': losses[0], 'dropped_at_enqueue': losses[1], + 'samples': samples, 'log_export_recovered': True} + + def main(): parser = argparse.ArgumentParser() parser.add_argument('--base-url', required=True) @@ -201,6 +279,7 @@ def main(): client.wait_ready(actor, attachment) api, api_trace = correlation(grafana, 'messenger-api', start, trace_id=controlled_trace, request_id=response['headers']['X-Request-Id']) worker, worker_trace = correlation(grafana, 'messenger-worker', start, attachment_id=attachment['id']) + accepted_chain = trace_chain(grafana, worker['trace_id']) check(api['log']['request_id'] == response['headers']['X-Request-Id'], 'Request id correlation lost') check(any(span['kind'] in ('SPAN_KIND_SERVER', 2) for span in api['spans']), 'No server span') check(any(span['kind'] in ('SPAN_KIND_CONSUMER', 5) for span in worker['spans']), 'No consumer span') @@ -225,42 +304,67 @@ def main(): check(not any(forbidden_labels & set(row['metric']) for row in series), 'High cardinality metric label') report = {'date_utc': datetime.now(timezone.utc).isoformat(), 'project': project.name, 'load': load, 'api_replicas': len(aliases), 'dashboard_uid': dashboard['uid'], - 'api_correlation': api, 'worker_correlation': worker, 'metrics': metrics, 'incidents': []} + 'api_correlation': api, 'worker_correlation': worker, 'metrics': metrics, 'upload_trace': {'trace_id':worker['trace_id'], 'chain':accepted_chain}, 'incidents': []} if args.incidents: - # Восстановление выполняется даже при ошибке проверки. + def fail_request(): + return client.call('POST', '/api/v1/users', expected=503, + body={'username':'fault_' + uuid4().hex[:12], + 'display_name':'Synthetic', 'password':'not-exported-' + uuid4().hex}) + + before = time.monotonic() try: - before = time.monotonic() project.run('stop', 'postgres') - failed = client.call('POST', '/api/v1/users', expected=503, - body={'username':'fault_' + uuid4().hex[:12], 'display_name':'Synthetic', 'password':'not-exported-' + uuid4().hex}) + failed = fail_request() error_trace = failed['headers'].get('X-Trace-Id') - error, _ = correlation(grafana, 'messenger-api', start, trace_id=error_trace, request_id=failed['headers']['X-Request-Id']) - diagnostics = eventually(lambda: grafana.logs('{service_name="messenger-api"} | json | event="dependency.unavailable" | trace_id="' + error_trace + '"', start), 'No dependency diagnostic log') - check(error['log'].get('status_code') == 503 or any(s['status'].get('code') in ('STATUS_CODE_ERROR', 2) for s in error['spans']), 'DB failure not reflected in trace') - report['incidents'].append({'scenario':'postgres_unavailable','http_status':503,'correlation':error,'diagnostic':diagnostics[0], 'observed_after_seconds':round(time.monotonic()-before,3)}) + error, db_trace = correlation(grafana, 'messenger-api', start, trace_id=error_trace, + request_id=failed['headers']['X-Request-Id']) + diagnostics = eventually(lambda: grafana.logs( + '{service_name="messenger-api"} | json | event="dependency.unavailable" | trace_id="' + error_trace + '"', start), + 'No dependency diagnostic log') + checkout = next(span for span in spans_in(db_trace) if span['name'] == 'postgres.checkout' + and span.get('status', {}).get('code') in ('STATUS_CODE_ERROR', 2)) + + def db_alert(): + for _ in range(4): + fail_request() + return alert_firing(grafana, 'MessengerHighErrorRate') + + eventually(db_alert, 'Error rate alert did not fire', timeout=75) + report['incidents'].append({'scenario':'postgres_unavailable','http_status':503,'correlation':error, + 'diagnostic':diagnostics[0], 'db_span':checkout['name'], + 'alert':'MessengerHighErrorRate', 'firing_after_seconds':round(time.monotonic()-before,3)}) finally: project.run('start', 'postgres') eventually(lambda: _ready(client), 'API did not recover after PostgreSQL') - report['incidents'][-1]['recovery_seconds'] = round(time.monotonic() - before, 3) - # Явный fault hook обработки заданий: один permanent processing failure, затем replay. + eventually(lambda: not alert_firing(grafana, 'MessengerHighErrorRate'), 'Error rate alert not resolved') + report['incidents'][-1]['resolved_after_seconds'] = round(time.monotonic() - before, 3) + from scripts.check_jobs import retry_replay - failed_instance = [] - def wait_failed_metric(sample, container_name): - instance = project.docker('inspect', '--format', '{{.Config.Hostname}}', container_name) - failed_instance.append(instance) - expression = 'sum(messenger_job_attempts_total{outcome="error",service_instance_id="' + instance + '"})' - eventually(lambda: grafana.query(expression), 'Failed job metric not exported before recovery') - incident = retry_replay(client, actor, chat, permanent=True, on_failed=wait_failed_metric) - error_logs = eventually(lambda: grafana.logs('{service_name="messenger-worker"} | json | event="job.processed" | outcome="error" | error_code="injected_permanent"', start), 'No failed job telemetry') - error_trace = eventually(lambda: grafana.trace(error_logs[-1]['trace_id']), 'No failed job trace') - check(any(span.get('status', {}).get('code') in ('STATUS_CODE_ERROR', 2) for span in spans_in(error_trace)), 'Worker error trace status lost') - expression = 'sum(messenger_job_attempts_total{outcome="error",service_instance_id="' + failed_instance[0] + '"})' - errors = eventually(lambda: grafana.query(expression), 'No failed jobs counter') - recovery = (datetime.fromisoformat(incident['after']['updated_at']) - datetime.fromisoformat(incident['samples'][-1]['updated_at'])).total_seconds() - report['incidents'].append({'scenario':'permanent_processing_failure','recovered_status':incident['after']['status'], 'log':error_logs[-1], 'failed_jobs_metric':errors, 'metric_query':expression, 'failure_to_ready_seconds':round(recovery,3)}) + queue = {} + + def observe_queue(_): + observed = time.monotonic() + eventually(lambda: alert_firing(grafana, 'MessengerQueueLag'), 'Queue lag alert did not fire') + queue.update(depth=metric(grafana, 'max(messenger_queue_depth_ratio)'), + oldest_seconds=metric(grafana, 'max(messenger_queue_oldest_seconds)'), + firing_after_seconds=round(time.monotonic()-observed,3)) + + incident = retry_replay(client, actor, chat, permanent=False, on_queued=observe_queue) + retried_worker, retry_trace = correlation(grafana, 'messenger-worker', start, + attachment_id=incident['attachment_id']) + chain = trace_chain(grafana, retried_worker['trace_id'], retry=True) + eventually(lambda: not alert_firing(grafana, 'MessengerQueueLag') + and metric(grafana, 'max(messenger_queue_depth_ratio)') == 0, 'Backlog did not drain') + queue.update(resolved=True, final_depth=0) + report['incidents'].append({'scenario':'worker_stopped_then_transient_retry', + 'alert':'MessengerQueueLag', 'queue':queue, 'recovered_status':incident['after']['status'], + 'trace_id':retried_worker['trace_id'], 'chain':chain}) + report['incidents'].append(telemetry_outage(project, client, grafana, actor, chat)) + else: + retry_trace = {} # Не сохраняем API bodies или SDK exceptions; проверяем реальные выбранные сигналы. logs = grafana.logs('{service_name=~"messenger-api|messenger-worker"}', start) - exported = json.dumps([logs, api_trace, worker_trace]) + exported = json.dumps([logs, api_trace, worker_trace, retry_trace]) private = [sentinel, *(person['token'] for person in (actor,bob,eve)), *(person['registration']['password'] for person in (actor,bob,eve))] private.extend(path.read_text().strip() for path in (ROOT / 'secrets').iterdir() if path.is_file()) check(not any(secret and secret in exported for secret in private), 'Private value found in telemetry') @@ -280,7 +384,7 @@ def main(): destination = ROOT / args.output destination.parent.mkdir(parents=True, exist_ok=True) destination.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n') - print('PASS: telemetry, dashboard, privacy, correlations' + ('; two incidents recovered' if args.incidents else '')) + print('PASS: telemetry, dashboard, privacy, correlations' + ('; alerts and outage recovery verified' if args.incidents else '')) def _ready(client): diff --git a/scripts/deployment.py b/scripts/deployment.py index 6572e90d..90ca14e3 100644 --- a/scripts/deployment.py +++ b/scripts/deployment.py @@ -137,20 +137,23 @@ def verify(): import time project_name = os.getenv('TEST_PROJECT', 'messenger-test') + if any(inventory([project_name]).values()): + raise RuntimeError(f'Choose an unused TEST_PROJECT; {project_name} already has resources') os.environ.update(COMPOSE_PROJECT_NAME=project_name, COMPOSE_FILE='compose.yaml:compose.test.yaml', GRAFANA_HOST_PORT='23000', LB_HOST_PORT='28080', - DOCKER_TESTS='1') + DOCKER_TESTS='1', OTEL_ENABLED='true') report = {'date_utc': datetime.now(timezone.utc).isoformat(), 'checks': [], 'profile': {'single_stack': True, 'load_duration_seconds': 10, 'load_requests_per_second': 10, 'load_concurrency': 2}} destination = ROOT / 'evidence/verification.json' destination.parent.mkdir(exist_ok=True) - def run(name, command, timeout=600): + def run(name, command, timeout=600, *, env=None): print('RUN: ' + name, flush=True) started = time.monotonic() - result = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, timeout=timeout) + result = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, timeout=timeout, + env={**os.environ, **(env or {})}) executable = Path(command[0]) display_command = [str(executable.relative_to(ROOT)) if executable.is_relative_to(ROOT) else command[0], *command[1:]] @@ -175,7 +178,9 @@ def verify(): run('openapi', [sys.executable, 'scripts/validate_openapi.py']) run('compose', ['docker', 'compose', '--env-file', '.env', 'config', '--quiet']) run('startup', ['make', '--no-print-directory', 'test-stand-up'], timeout=600) - run('regression', ['make', '--no-print-directory', 'test-unit']) + # Локальные ASGI fixtures не находятся в сети Compose. Проверки SDK + # используют exporters в памяти, интеграционный стенд экспортирует OTLP. + run('regression', ['make', '--no-print-directory', 'test-unit'], env={'OTEL_ENABLED': 'false'}) run('api', [sys.executable, 'tests/smoke.py', '--base-url', 'http://localhost:28080']) run('observability', [sys.executable, '-m', 'scripts.check_observability', '--base-url', 'http://localhost:28080', @@ -192,7 +197,11 @@ def verify(): finally: try: print('RUN: cleanup', flush=True) - report['cleanup'] = clean_stands(apply=True) + ComposeProject().run('down', '--volumes', '--remove-orphans', timeout=120) + remaining = inventory([project_name]) + if any(remaining.values()): + raise RuntimeError('Verification project cleanup incomplete') + report['cleanup'] = {'project': project_name, 'remaining': remaining, 'result': 'PASS'} print('PASS: cleanup', flush=True) finally: report['finished_at_utc'] = datetime.now(timezone.utc).isoformat()