Реализовать уровень 4: сквозные трассы, SLO, отказы и отчёт

This commit is contained in:
2026-11-21 12:18:33 +03:00
parent d0a062e2d2
commit 12181fa893
69 changed files with 52258 additions and 47 deletions
+114
View File
@@ -0,0 +1,114 @@
"""Low-cardinality saturation/backlog signals and safe dependency spans (lab6/4)."""
from __future__ import annotations
import asyncio
from datetime import datetime, timezone
import os
import resource
import time
from opentelemetry import metrics
from opentelemetry.metrics import Observation
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
from app.telemetry import span
meter = metrics.get_meter("messenger")
waiting = 0
busy = 0
snapshot: dict[str, float] = {}
ready_duration = meter.create_histogram("messenger.attachment.time_to_ready", unit="s")
retries = meter.create_counter("messenger.jobs.retries", unit="{retry}")
class ObservedSession(AsyncSession):
async def execute(self, statement, params=None, **kwargs):
global waiting
# Number of acquisition requests in progress (includes new connects).
# Acquisition is separate from query execution to diagnose pool waits.
waiting += 1
try:
with span("db.acquire", {"db.system": "postgresql"}):
await self.connection()
finally:
waiting -= 1
operation = str(statement).lstrip().split(None, 1)[0].upper()
if operation not in {"SELECT", "INSERT", "UPDATE", "DELETE", "SET"}:
operation = "OTHER"
with span("db.query", {"db.system": "postgresql", "db.operation": operation}):
return await super().execute(statement, params, **kwargs)
async def commit(self):
with span("db.commit", {"db.system": "postgresql"}):
return await super().commit()
def install_gauges(engine) -> None:
pool = engine.sync_engine.pool
meter.create_observable_gauge("messenger.db.pool.used",
callbacks=[lambda _: [Observation(pool.checkedout())]])
meter.create_observable_gauge("messenger.db.pool.waiting",
callbacks=[lambda _: [Observation(waiting)]])
meter.create_observable_gauge("messenger.db.pool.capacity",
callbacks=[lambda _: [Observation(pool.size() + pool._max_overflow)]])
meter.create_observable_gauge("messenger.worker.busy",
callbacks=[lambda _: [Observation(busy)]])
capacity = 1 if os.getenv("OTEL_SERVICE_NAME") == "messenger-worker" else 0
meter.create_observable_gauge("messenger.worker.capacity",
callbacks=[lambda _: [Observation(capacity)]])
if capacity:
meter.create_observable_gauge("messenger.worker.heartbeat", unit="s",
callbacks=[lambda _: [Observation(time.time())]])
meter.create_observable_counter("messenger.process.cpu", unit="s",
callbacks=[lambda _: [Observation(time.process_time())]])
def rss(_):
# Linux /proc resident pages, current RSS (not ru_maxrss high watermark).
try:
with open("/proc/self/statm", encoding="ascii") as statm:
value = int(statm.read().split()[1]) * os.sysconf("SC_PAGE_SIZE")
except OSError:
value = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * 1024
return [Observation(value)]
meter.create_observable_gauge("messenger.process.memory", unit="By", callbacks=[rss])
if os.getenv("OTEL_SERVICE_NAME") == "messenger-publisher":
for name, unit, key in (("depth", "", "depth"),
("oldest_age", "s", "oldest_age"),
("sample_age", "s", "sample_age")):
def observe(_, key=key):
if "sampled_at" not in snapshot:
return []
value = (time.monotonic() - snapshot["sampled_at"]
if key == "sample_age" else snapshot[key])
return [Observation(value, {"queue": "attachments"})]
meter.create_observable_gauge("messenger.queue." + name, unit=unit,
callbacks=[observe])
async def backlog_loop(session_factory) -> None:
# Authoritative logical queue = queued + processing, including durable
# outbox and delayed retries. Remains observable when worker is stopped.
while True:
try:
async with session_factory() as db:
result = await db.execute(text("""
SELECT count(*) AS depth,
COALESCE(EXTRACT(EPOCH FROM now()-min(created_at)),0) AS oldest_age
FROM attachments WHERE status IN ('queued','processing')
"""))
row = result.mappings().one()
snapshot.update(depth=float(row["depth"]), oldest_age=float(row["oldest_age"]),
sampled_at=time.monotonic())
except asyncio.CancelledError:
raise
except Exception:
# Retain last sample; sample_age makes stale observations explicit.
pass
await asyncio.sleep(2)
def observe_ready(row) -> None:
elapsed = (datetime.now(timezone.utc) - row["created_at"]).total_seconds()
ready_duration.record(max(0, elapsed), {"job_type": "attachment.process.v1"})
+8 -2
View File
@@ -7,6 +7,8 @@ from sqlalchemy.ext.asyncio import (
)
from app.config import settings
from app.advanced import ObservedSession, install_gauges
from app.telemetry import span
database_url = settings.database_url.replace(
@@ -38,10 +40,13 @@ engine = create_async_engine(
SessionLocal = async_sessionmaker(
bind=engine,
class_=ObservedSession,
expire_on_commit=False,
autoflush=False,
)
install_gauges(engine)
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with SessionLocal() as session:
@@ -50,8 +55,9 @@ async def get_db() -> AsyncGenerator[AsyncSession, None]:
async def check_database_ready() -> bool:
try:
async with engine.connect() as connection:
await connection.exec_driver_sql("SELECT 1")
with span("db.health", {"db.system": "postgresql"}):
async with engine.connect() as connection:
await connection.exec_driver_sql("SELECT 1")
return True
except Exception:
return False
+4 -1
View File
@@ -15,6 +15,7 @@ from app.pipeline import (RETENTION_SECONDS, arm_from_env, broker_channel,
crash_if_armed, envelope, publish, retry_or_fail)
from app.storage import storage
from app.telemetry import configure, emit, install_termination_handler, shutdown
from app import advanced
logger = logging.getLogger("messenger.jobs")
@@ -87,7 +88,6 @@ async def relay_one(channel) -> bool:
{"id": row["id"]})
await db.commit()
logger.info("published job=%s attempt=%s", row["job_id"], row["attempt"])
emit("job.published", job_id=str(row["job_id"]), attempt=row["attempt"])
return True
@@ -98,6 +98,7 @@ async def main() -> None:
for name in ("aio_pika", "aiormq"):
logging.getLogger(name).setLevel(logging.CRITICAL)
await storage.start()
backlog = asyncio.create_task(advanced.backlog_loop(SessionLocal))
connection = None
try:
await arm_from_env("PUBLISHER_FAULT")
@@ -128,6 +129,8 @@ async def main() -> None:
connection = None
await asyncio.sleep(1)
finally:
backlog.cancel()
await asyncio.gather(backlog, return_exceptions=True)
if connection:
await connection.close()
await storage.close()
+2 -2
View File
@@ -60,8 +60,8 @@ async def run(args) -> None:
# Ready effects are checked in PG by the worker and acked.
await event(db, row, "operator_redeliver")
await db.execute(text("""
INSERT INTO outbox(job_id,attachment_id,attempt,available_at)
SELECT job_id,id,attempt,GREATEST(now(),next_attempt_at)
INSERT INTO outbox(job_id,attachment_id,attempt,available_at,traceparent,tracestate)
SELECT job_id,id,attempt,GREATEST(now(),next_attempt_at),traceparent,tracestate
FROM attachments WHERE id=:id
"""), {"id": row["id"]})
await db.commit()
+32 -10
View File
@@ -15,6 +15,10 @@ from sqlalchemy import text
from app.config import read_value
from app.db import SessionLocal
from app import advanced
from app.telemetry import emit, span
from app.trace_context import carrier, parent_context
from opentelemetry.trace import SpanKind
logger = logging.getLogger("messenger.pipeline")
QUEUE = "attachments"
@@ -56,13 +60,15 @@ async def broker_channel():
def envelope(row) -> dict:
return {
job = {
"schema_version": 1, "job_id": str(row["job_id"]),
"type": "attachment.process.v1", "attachment_id": str(row["attachment_id"]),
"pipeline_version": int(row.get("pipeline_version", 1)),
"attempt": int(row["attempt"]),
"created_at": row["created_at"].isoformat().replace("+00:00", "Z"),
}
job.update({name: row[name] for name in ("traceparent", "tracestate") if row.get(name)})
return job
def parse_envelope(raw: bytes) -> dict:
@@ -94,12 +100,20 @@ def parse_envelope(raw: bytes) -> dict:
async def publish(channel, job: dict) -> None:
await channel.default_exchange.publish(
aio_pika.Message(json.dumps(job).encode("utf-8"), content_type="application/json",
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
message_id=job["job_id"]),
routing_key=QUEUE, mandatory=True, timeout=5,
)
with span("attachments publish", kind=SpanKind.PRODUCER, parent=parent_context(job), attributes={
"messaging.system": "rabbitmq", "messaging.destination.name": QUEUE,
"messaging.operation": "publish", "job_id": job["job_id"], "attempt": job["attempt"],
}):
# The confirmed envelope names this producer span as the consumer's
# parent. Durable outbox remains unchanged if confirmation is lost.
outgoing = {**job, **carrier()}
await channel.default_exchange.publish(
aio_pika.Message(json.dumps(outgoing).encode("utf-8"), content_type="application/json",
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
message_id=job["job_id"]),
routing_key=QUEUE, mandatory=True, timeout=5,
)
emit("job.published", job_id=job["job_id"], attempt=job["attempt"], queue=QUEUE)
async def event(db, row, name: str, detail: str = "") -> None:
@@ -146,15 +160,23 @@ async def retry_or_fail(db, row, code: str, *, permanent: bool = False) -> None:
logger.warning("failed attachment=%s code=%s", row["id"], final_code)
return
delay = retry_delay(row["attempts_run"])
# A consumer retry continues from its active span. Lease recovery may have
# no active span, so retain the context durably recorded by the old claim.
context = carrier() or {name: row.get(name) for name in ("traceparent", "tracestate")}
await db.execute(text("""
UPDATE attachments SET status='queued',error_code=NULL,attempt=attempt+1,
lease_token=NULL,lease_until=NULL,
traceparent=:traceparent,tracestate=:tracestate,
next_attempt_at=now()+make_interval(secs => CAST(:delay AS double precision)),
updated_at=now() WHERE id=:id
"""), {"id": row["id"], "delay": delay})
"""), {"id": row["id"], "delay": delay,
"traceparent": context.get("traceparent"), "tracestate": context.get("tracestate")})
await db.execute(text("""
INSERT INTO outbox(job_id,attachment_id,attempt,available_at)
SELECT job_id,id,attempt,next_attempt_at FROM attachments WHERE id=:id
INSERT INTO outbox(job_id,attachment_id,attempt,available_at,traceparent,tracestate)
SELECT job_id,id,attempt,next_attempt_at,traceparent,tracestate FROM attachments WHERE id=:id
"""), {"id": row["id"]})
await event(db, row, "retry", f"{code}; delay={delay:.3f}s")
logger.info("retry attachment=%s after=%.3fs", row["id"], delay)
advanced.retries.add(1, {"job_type": "attachment.process.v1"})
emit("job.retry", job_id=str(row["job_id"]), attachment_id=str(row["id"]),
attempt=row["attempt"] + 1, outcome="retry", queue=QUEUE)
+12 -4
View File
@@ -9,6 +9,7 @@ from uuid import UUID, uuid4
from sqlalchemy import text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.trace_context import carrier
async def create_user(
@@ -580,14 +581,17 @@ async def finalize_attachment(
job_id = uuid4()
final_key = f"originals/{attachment_id}/v1/original"
context = carrier()
result = await db.execute(
text(
f"""
INSERT INTO attachments AS a
(id, chat_id, owner_id, filename, content_type, size_bytes,
sha256, width, height, object_key, staging_key, job_id, status)
sha256, width, height, object_key, staging_key, job_id, status,
traceparent, tracestate)
VALUES (:id, :chat_id, :owner_id, :filename, :content_type,
:size_bytes, :sha256, :width, :height, :final_key, :object_key, :job_id, 'queued')
:size_bytes, :sha256, :width, :height, :final_key, :object_key, :job_id, 'queued',
:traceparent, :tracestate)
RETURNING {ATTACHMENT_COLUMNS}
"""
),
@@ -604,12 +608,16 @@ async def finalize_attachment(
"object_key": object_key,
"final_key": final_key,
"job_id": job_id,
"traceparent": context.get("traceparent"),
"tracestate": context.get("tracestate"),
},
)
row = dict(result.mappings().one())
await db.execute(
text("INSERT INTO outbox (job_id, attachment_id, attempt) VALUES (:job_id, :id, 1)"),
{"job_id": job_id, "id": attachment_id},
text("""INSERT INTO outbox (job_id, attachment_id, attempt, traceparent, tracestate)
VALUES (:job_id, :id, 1, :traceparent, :tracestate)"""),
{"job_id": job_id, "id": attachment_id,
"traceparent": context.get("traceparent"), "tracestate": context.get("tracestate")},
)
await db.commit()
return row
+17
View File
@@ -16,12 +16,25 @@ from collections.abc import AsyncIterator
from contextlib import AsyncExitStack
from dataclasses import dataclass
from typing import Any, BinaryIO
from functools import wraps
from aiobotocore.config import AioConfig
from aiobotocore.session import get_session
from botocore.exceptions import BotoCoreError, ClientError
from app.config import settings
from app.telemetry import span
def observed(operation):
"""Export operation/outcome only, never S3 URL, key or credentials."""
def decorate(method):
@wraps(method)
async def run(*args, **kwargs):
with span("s3." + operation, {"rpc.system": "aws-api", "rpc.method": operation}):
return await method(*args, **kwargs)
return run
return decorate
logger = logging.getLogger("messenger.storage")
@@ -89,6 +102,7 @@ class ObjectStorage:
raise StorageUnavailable("S3 client is not started")
return self._client
@observed("PutObject")
async def put(
self,
key: str,
@@ -112,6 +126,7 @@ class ObjectStorage:
except (BotoCoreError, ClientError, OSError, asyncio.TimeoutError) as exc:
raise StorageUnavailable(type(exc).__name__) from exc
@observed("GetObject")
async def open_download(self, key: str) -> tuple[AsyncIterator[bytes], int]:
"""GET the object; S3 errors surface here, before any byte is sent."""
client = self._require_client()
@@ -136,6 +151,7 @@ class ObjectStorage:
return chunks(), int(response["ContentLength"])
@observed("DeleteObject")
async def delete(self, key: str) -> None:
"""Idempotent: deleting a missing key succeeds in S3."""
client = self._require_client()
@@ -145,6 +161,7 @@ class ObjectStorage:
except (BotoCoreError, ClientError, OSError, asyncio.TimeoutError) as exc:
raise StorageUnavailable(type(exc).__name__) from exc
@observed("HeadObject")
async def exists(self, key: str) -> bool:
client = self._require_client()
try:
+40
View File
@@ -0,0 +1,40 @@
"""W3C context carried durably alongside a job, never its HTTP credentials.
The upload transaction stores ``carrier()``; publisher and retries restore it
with ``parent_context``. Only a new producer/consumer span changes the parent
span ID. Context-less legacy jobs deliberately start a new trace.
"""
from __future__ import annotations
from collections.abc import Mapping
from opentelemetry.context import Context
from opentelemetry.trace import get_current_span
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
_PROPAGATOR = TraceContextTextMapPropagator()
_FIELDS = ("traceparent", "tracestate")
def carrier() -> dict[str, str]:
"""Return the active span's W3C fields, or {} outside a valid span."""
headers: dict[str, str] = {}
_PROPAGATOR.inject(headers)
return {name: headers[name] for name in _FIELDS if headers.get(name)}
def parent_context(row_or_job: Mapping | None) -> Context:
"""Extract nullable DB/envelope fields without inheriting ambient context.
W3C parsing validates version, nonzero trace/span IDs, flags and tracestate.
Malformed or missing parent IDs become a new root, even if a publisher's
unrelated maintenance span happens to be active.
"""
headers: dict[str, str] = {}
if isinstance(row_or_job, Mapping):
for name in _FIELDS:
value = row_or_job.get(name)
if isinstance(value, str) and value:
headers[name] = value
context = _PROPAGATOR.extract(headers, context=Context())
return context if get_current_span(context).get_span_context().is_valid else Context()
+12 -3
View File
@@ -22,6 +22,8 @@ from app.storage import ObjectMissing, storage
from app.telemetry import (configure, emit, install_termination_handler, jobs_duration,
jobs_processed, shutdown, span)
from opentelemetry.trace import SpanKind, Status, StatusCode
from app import advanced
from app.trace_context import carrier, parent_context
logger = logging.getLogger("messenger.worker")
@@ -46,9 +48,11 @@ async def claim(job: dict) -> dict | None:
result = await db.execute(text("""
UPDATE attachments SET status='processing',attempts_run=attempts_run+1,
lease_token=:token,lease_until=now()+make_interval(secs => :lease),
traceparent=:traceparent,tracestate=:tracestate,
updated_at=now()
WHERE id=:id AND next_attempt_at<=now() RETURNING *
"""), {"id": row["id"], "token": uuid4(), "lease": LEASE_SECONDS})
"""), {"id": row["id"], "token": uuid4(), "lease": LEASE_SECONDS,
"traceparent": carrier().get("traceparent"), "tracestate": carrier().get("tracestate")})
claimed = result.mappings().first()
if claimed is None:
await db.rollback()
@@ -107,7 +111,8 @@ async def build_objects(row: dict) -> list[dict]:
await chunks.aclose()
if size != declared_length or size != row["size_bytes"] or digest.hexdigest() != row["sha256"]:
raise PermanentFailure("source_checksum_mismatch")
variants = await generate(source, directory)
with span("image.generate"):
variants = await generate(source, directory)
# API never publishes directly to this final prefix. Repeating one
# v1 job writes the same bytes to the same four keys, never appends.
with source.open("rb") as body:
@@ -146,6 +151,8 @@ async def finish(row: dict, *, variants=None, code: str | None = None,
"""), {"id": row["id"], "variants": json.dumps(variants)})
await event(db, current, "ready")
await db.commit()
if code is None:
advanced.observe_ready(current)
return True
@@ -195,13 +202,15 @@ async def handle(message) -> None:
pass
started = time.perf_counter()
outcome = "error"
with span("attachments process", kind=SpanKind.CONSUMER, attributes={
with span("attachments process", kind=SpanKind.CONSUMER, parent=parent_context(job), attributes={
"messaging.system": "rabbitmq", "messaging.destination.name": "attachments",
"messaging.operation": "process", "job_type": "attachment.process.v1",
}) as active:
try:
advanced.busy = 1
outcome = await _handle(message)
finally:
advanced.busy = 0
duration = time.perf_counter() - started
attrs = {"job_type": "attachment.process.v1", "outcome": outcome}
jobs_processed.add(1, attrs)