|
| 1 | +""" |
| 2 | +Metrics instrumentation for the task-event SSE stream lifecycle. |
| 3 | +
|
| 4 | +Mirrors the dual-emit pattern in ``src/utils/cache_metrics.py``: |
| 5 | +
|
| 6 | +- When an OTLP endpoint is configured (``OTEL_EXPORTER_OTLP_ENDPOINT``), the |
| 7 | + instruments are recorded through the OpenTelemetry SDK. |
| 8 | +- When the Datadog Agent is reachable (``DD_AGENT_HOST``), the same events are |
| 9 | + emitted as StatsD metrics. |
| 10 | +- When neither is configured, every function here is a cheap no-op. |
| 11 | +
|
| 12 | +**Why this exists (see AGX1-616/AGX1-618):** HTTP request-level RED for |
| 13 | +``GET /tasks/{task_id}/stream`` is already covered by auto-instrumentation — the |
| 14 | +route records into ``http_server_request_duration_seconds`` at connection close. |
| 15 | +But a single SSE request produces exactly one duration sample, which says nothing |
| 16 | +about what happened *during* the stream's life: how many were concurrently open, |
| 17 | +whether a stream ended normally vs. by client disconnect vs. by error, or whether |
| 18 | +a stream went quiet (no events pushed) for a stretch. Those are the stream- |
| 19 | +lifecycle signals request-level instrumentation cannot express, and they are what |
| 20 | +this module adds. |
| 21 | +
|
| 22 | +Instrument names are deliberately dotted (``agentex.task_stream.*``); the OTLP → |
| 23 | +Prometheus translation flattens dots to underscores, appends ``_total`` to |
| 24 | +monotonic counters, and appends the unit (``s`` → ``_seconds``) to the histogram, |
| 25 | +so the series land in Mimir as ``agentex_task_stream_opened_total``, |
| 26 | +``agentex_task_stream_closed_total``, ``agentex_task_stream_duration_seconds``, |
| 27 | +``agentex_task_stream_active`` and ``agentex_task_stream_stall_total``. These |
| 28 | +hand-instrumented series carry only bounded attributes (``outcome``) and no |
| 29 | +``http_route`` label — group by ``outcome``, not ``http_route``. |
| 30 | +""" |
| 31 | + |
| 32 | +from __future__ import annotations |
| 33 | + |
| 34 | +import os |
| 35 | +from typing import TYPE_CHECKING, Literal |
| 36 | + |
| 37 | +from datadog import statsd |
| 38 | + |
| 39 | +from src.utils.logging import make_logger |
| 40 | +from src.utils.otel_metrics import get_meter |
| 41 | + |
| 42 | +if TYPE_CHECKING: |
| 43 | + from opentelemetry.metrics import Counter, Histogram, UpDownCounter |
| 44 | + |
| 45 | +logger = make_logger(__name__) |
| 46 | + |
| 47 | +# StatsD is only emitted if the Datadog Agent host is configured. |
| 48 | +_STATSD_ENABLED = bool(os.environ.get("DD_AGENT_HOST")) |
| 49 | + |
| 50 | +# How a stream ended. "completed" = the generator returned normally; |
| 51 | +# "client_disconnect" = the client went away (asyncio.CancelledError); |
| 52 | +# "error" = the stream loop raised a fatal, non-recoverable exception. HTTP |
| 53 | +# status 200 at connection close cannot tell these three apart, which is why the |
| 54 | +# distinction lives here as a bounded label rather than on the request metric. |
| 55 | +StreamOutcome = Literal["completed", "client_disconnect", "error"] |
| 56 | + |
| 57 | +# Lazily-created OTel instruments (created once, on first use). |
| 58 | +_opened_counter: Counter | None = None |
| 59 | +_closed_counter: Counter | None = None |
| 60 | +_duration_histogram: Histogram | None = None |
| 61 | +_active_updown: UpDownCounter | None = None |
| 62 | +_stall_counter: Counter | None = None |
| 63 | +_instruments_initialized = False |
| 64 | + |
| 65 | + |
| 66 | +def _ensure_instruments() -> None: |
| 67 | + """Create the OTel instruments on first use. No-op if OTel is not configured.""" |
| 68 | + global _opened_counter, _closed_counter, _duration_histogram |
| 69 | + global _active_updown, _stall_counter, _instruments_initialized |
| 70 | + |
| 71 | + if _instruments_initialized: |
| 72 | + return |
| 73 | + _instruments_initialized = True |
| 74 | + |
| 75 | + meter = get_meter("agentex.task_stream") |
| 76 | + if meter is None: |
| 77 | + # OTel not configured; OTel path stays disabled. StatsD may still emit. |
| 78 | + return |
| 79 | + |
| 80 | + _opened_counter = meter.create_counter( |
| 81 | + name="agentex.task_stream.opened", |
| 82 | + description="Task-event SSE streams opened", |
| 83 | + unit="{stream}", |
| 84 | + ) |
| 85 | + _closed_counter = meter.create_counter( |
| 86 | + name="agentex.task_stream.closed", |
| 87 | + description="Task-event SSE streams closed, tagged by outcome", |
| 88 | + unit="{stream}", |
| 89 | + ) |
| 90 | + _duration_histogram = meter.create_histogram( |
| 91 | + name="agentex.task_stream.duration", |
| 92 | + description="Task-event SSE stream lifetime", |
| 93 | + unit="s", |
| 94 | + ) |
| 95 | + _active_updown = meter.create_up_down_counter( |
| 96 | + name="agentex.task_stream.active", |
| 97 | + description="Currently open task-event SSE streams", |
| 98 | + unit="{stream}", |
| 99 | + ) |
| 100 | + _stall_counter = meter.create_counter( |
| 101 | + name="agentex.task_stream.stall", |
| 102 | + description="Task-event SSE streams that went idle (no event pushed) past the stall threshold", |
| 103 | + unit="{stream}", |
| 104 | + ) |
| 105 | + |
| 106 | + |
| 107 | +def record_stream_opened() -> None: |
| 108 | + """ |
| 109 | + Record a task-event stream opening: bumps the opened counter and the active gauge. |
| 110 | +
|
| 111 | + Pair every call with exactly one ``record_stream_closed`` so the active gauge |
| 112 | + stays balanced. Never raises: see ``record_stream_closed``. |
| 113 | + """ |
| 114 | + try: |
| 115 | + _ensure_instruments() |
| 116 | + |
| 117 | + if _opened_counter is not None: |
| 118 | + _opened_counter.add(1) |
| 119 | + if _active_updown is not None: |
| 120 | + _active_updown.add(1) |
| 121 | + |
| 122 | + if _STATSD_ENABLED: |
| 123 | + statsd.increment("agentex.task_stream.opened") |
| 124 | + statsd.increment("agentex.task_stream.active") |
| 125 | + except Exception: |
| 126 | + logger.debug("Failed to emit agentex.task_stream.opened metric", exc_info=True) |
| 127 | + |
| 128 | + |
| 129 | +def record_stream_closed(outcome: StreamOutcome, duration_seconds: float) -> None: |
| 130 | + """ |
| 131 | + Record a task-event stream closing: bumps the closed counter (tagged by |
| 132 | + outcome), records the stream lifetime, and decrements the active gauge. |
| 133 | +
|
| 134 | + Args: |
| 135 | + outcome: One of "completed", "client_disconnect", "error". |
| 136 | + duration_seconds: How long the stream was open. |
| 137 | +
|
| 138 | + Never raises: emission failures (e.g. a StatsD UDP socket error or an OTel |
| 139 | + SDK fault) are swallowed so instrumentation can never disrupt the SSE path. |
| 140 | + """ |
| 141 | + try: |
| 142 | + _ensure_instruments() |
| 143 | + |
| 144 | + if _closed_counter is not None: |
| 145 | + _closed_counter.add(1, {"outcome": outcome}) |
| 146 | + if _duration_histogram is not None: |
| 147 | + _duration_histogram.record(duration_seconds) |
| 148 | + if _active_updown is not None: |
| 149 | + _active_updown.add(-1) |
| 150 | + |
| 151 | + if _STATSD_ENABLED: |
| 152 | + statsd.increment("agentex.task_stream.closed", tags=[f"outcome:{outcome}"]) |
| 153 | + # Datadog histograms conventionally take milliseconds for durations. |
| 154 | + statsd.histogram("agentex.task_stream.duration", duration_seconds * 1000) |
| 155 | + statsd.decrement("agentex.task_stream.active") |
| 156 | + except Exception: |
| 157 | + logger.debug("Failed to emit agentex.task_stream.closed metric", exc_info=True) |
| 158 | + |
| 159 | + |
| 160 | +def record_stream_stall() -> None: |
| 161 | + """ |
| 162 | + Record that an open stream went idle — no event pushed to the client for |
| 163 | + longer than the configured stall threshold. Emit once per stall episode |
| 164 | + (the caller de-dupes) so the counter measures stall onsets, not idle cycles. |
| 165 | +
|
| 166 | + Never raises: see ``record_stream_closed``. |
| 167 | + """ |
| 168 | + try: |
| 169 | + _ensure_instruments() |
| 170 | + |
| 171 | + if _stall_counter is not None: |
| 172 | + _stall_counter.add(1) |
| 173 | + |
| 174 | + if _STATSD_ENABLED: |
| 175 | + statsd.increment("agentex.task_stream.stall") |
| 176 | + except Exception: |
| 177 | + logger.debug("Failed to emit agentex.task_stream.stall metric", exc_info=True) |
0 commit comments