:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(metrics): add investigate() orchestrator for metric incidents (#66879)
Daniel Visca2477e2c3ffd2
diff --git a/products/metrics/backend/anomaly.py b/products/metrics/backend/anomaly.pyindex 854c21f4544e..120f15c25f84 100644--- a/products/metrics/backend/anomaly.py+++ b/products/metrics/backend/anomaly.py@@ -258,6 +258,18 @@ def _discover_candidate_keys(return tuple(keys[:MAX_CANDIDATE_KEYS])+def dimension_magnitude(mover: MetricAnomalyDimension) -> float:+ """How much a label value actually moved, blending relative change with+ scale: a tiny series that tripled and a large series that barely budged+ should not rank — nor be judged the dominant cause — on ratio alone. The+ blast-radius classifier must compare movers on this same measure they were+ ranked by, or the top mover by magnitude can lose a raw-ratio comparison.+ """+ if mover.baseline_value == 0 or mover.change_ratio <= 0:+ return abs(mover.anomaly_value - mover.baseline_value)+ return abs(math.log(mover.change_ratio)) * max(abs(mover.anomaly_value), abs(mover.baseline_value))++def _find_top_movers(*,run: Callable[..., list[dict[str, Any]]],@@ -302,10 +314,5 @@ def _find_top_movers())- def _magnitude(mover: MetricAnomalyDimension) -> float:- if mover.baseline_value == 0 or mover.change_ratio <= 0:- return abs(mover.anomaly_value - mover.baseline_value)- return abs(math.log(mover.change_ratio)) * max(abs(mover.anomaly_value), abs(mover.baseline_value))-- movers.sort(key=lambda m: (-_magnitude(m), m.key, m.label))+ movers.sort(key=lambda m: (-dimension_magnitude(m), m.key, m.label))return tuple(movers[:MAX_TOP_MOVERS])diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex 2dad1314a2be..808d2dd39ca6 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -12,6 +12,8 @@ from posthog.models import Teamfrom products.metrics.backend.anomaly import characterize_anomaly as _characterize_anomalyfrom products.metrics.backend.facade.contracts import (+ CompanionMetric,+ InvestigationResult,MetricAnomalyReport,MetricEventSample,MetricFilter,@@ -23,6 +25,7 @@ from products.metrics.backend.facade.contracts import (from products.metrics.backend.facade.enums import MetricAggregationfrom products.metrics.backend.formula import evaluate, parse_formulafrom products.metrics.backend.has_metrics_query_runner import team_has_metrics as _team_has_metrics+from products.metrics.backend.investigation import investigate as _investigatefrom products.metrics.backend.metric_event_samples_query_runner import MetricEventSamplesQueryRunnerfrom products.metrics.backend.metric_names_query_runner import MetricNamesQueryRunnerfrom products.metrics.backend.metric_query_runner import MetricQueryRunner@@ -264,3 +267,44 @@ def characterize_metric_anomaly(filters=filters,candidate_keys=candidate_keys,)+++def investigate(+ *,+ team: Team,+ metric_name: str,+ anomaly_from: dt.datetime,+ anomaly_to: dt.datetime,+ baseline_from: dt.datetime | None = None,+ baseline_to: dt.datetime | None = None,+ aggregation: str | None = None,+ quantile: float | None = None,+ filters: tuple[MetricFilter, ...] = (),+ candidate_keys: tuple[str, ...] | None = None,+ companions: tuple[CompanionMetric, ...] = (),+) -> InvestigationResult:+ """Investigate a metric symptom end to end and return one structured result.++ Builds on `characterize_metric_anomaly`: it characterizes the metric over+ the anomaly window, then characterizes each `companion` over the SAME window+ to confirm or rule it out (e.g. throughput flat -> not a traffic surge),+ classifies blast radius from the movers, implicates a service for the+ logs/traces pivot, and emits re-runnable chart specs.++ The result is the single shape the agent narrates, the in-app explorer+ renders, and the incident report serializes. Raises `ValueError` for invalid+ windows/aggregations — the presentation layer surfaces these as 400s.+ """+ return _investigate(+ team=team,+ metric_name=metric_name,+ anomaly_from=anomaly_from,+ anomaly_to=anomaly_to,+ baseline_from=baseline_from,+ baseline_to=baseline_to,+ aggregation=aggregation,+ quantile=quantile,+ filters=filters,+ candidate_keys=candidate_keys,+ companions=companions,+ )diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.pyindex b1eedba87efe..479abf947e95 100644--- a/products/metrics/backend/facade/contracts.py+++ b/products/metrics/backend/facade/contracts.py@@ -181,3 +181,95 @@ class MetricEventSample:span_id: strattributes: dict[str, str]resource_attributes: dict[str, str]+++@dataclass(frozen=True, slots=True)+class CompanionMetric:+ """A metric to check alongside the primary one to confirm or rule out a+ cause. `role` is a short hint ('traffic', 'saturation', 'processing') shown+ in the narrative. `aggregation`/`quantile` default by the metric's OTel type.+ """++ metric_name: str+ role: str+ aggregation: str | None = None+ quantile: float | None = None+++@dataclass(frozen=True, slots=True)+class CompanionVerdict:+ """How a companion metric behaved over the same window as the symptom — the+ basis for 'it wasn't a traffic surge' / 'processing kept up' reasoning.+ """++ metric_name: str+ role: str+ aggregation: str+ direction: str # "up" | "down" | "flat"+ change_ratio: float+ # True when the companion moved materially in the symptom window (so it+ # plausibly relates to the cause); False rules it out.+ moved_with_symptom: bool+ # Quantile the companion was aggregated at (histogram_quantile only); carried+ # so a re-runnable chart spec can reproduce the same aggregation.+ quantile: float | None = None+++@dataclass(frozen=True, slots=True)+class InvestigationChartSpec:+ """A metric query plus the frozen window to render it over. Re-runnable —+ the report re-runs the same query over the same window for live data —+ never baked, the opposite of snapshotting datapoints into constants.+ """++ title: str+ metric_name: str+ aggregation: str+ anomaly_from: str # ISO 8601+ anomaly_to: str+ filters: tuple[MetricFilter, ...] = ()+ quantile: float | None = None+++@dataclass(frozen=True, slots=True)+class TraceExemplar:+ """A pointer from a metric sample into a concrete trace at the anomaly, for+ the metric->trace pivot. Populated by the trace-pivot primitive once the+ `metric_samples` table is live; empty until then.+ """++ trace_id: str+ span_id: str+ timestamp: str # ISO 8601+ value: float+++@dataclass(frozen=True, slots=True)+class InvestigationEvidence:+ """Cross-signal pointers gathered around onset: trace exemplars to pivot+ into, and a ready-to-run log filter for the implicated service/window.+ `log_filter` is None when no service could be implicated.+ """++ service_name: str | None+ trace_exemplars: tuple[TraceExemplar, ...] = ()+ log_filter: dict[str, str] | None = None+++@dataclass(frozen=True, slots=True)+class InvestigationResult:+ """The structured outcome of investigating a metric symptom. Produced once+ by `investigate()` and consumed three ways: the agent narrates it, the+ in-app explorer renders it interactively, and the incident report+ serializes it. This shared shape is the seam between investigate and+ display.+ """++ metric_name: str+ symptom: MetricAnomalyReport+ blast_radius: str # "localized" | "shared" | "unknown"+ companions: tuple[CompanionVerdict, ...]+ chart_specs: tuple[InvestigationChartSpec, ...]+ evidence: InvestigationEvidence+ confidence: str # "high" | "medium" | "low"+ narrative: strdiff --git a/products/metrics/backend/investigation.py b/products/metrics/backend/investigation.pynew file mode 100644index 000000000000..e5ff2d5462d8--- /dev/null+++ b/products/metrics/backend/investigation.py@@ -0,0 +1,277 @@+"""Orchestrates a metric-symptom investigation into one structured result.++Composes the existing primitives — characterize the primary metric, check each+companion metric over the same window, classify blast radius from the movers —+into a single `InvestigationResult`. That result is the seam between investigate+and display: the agent narrates it, the in-app explorer renders it, and the+incident report serializes it, all from the same shape.++The metric->trace pivot (`evidence.trace_exemplars`) is left empty until the+`metric_samples` table lands; the seam is defined here so wiring it in later+doesn't change the result shape.+"""++from __future__ import annotations++import datetime as dt++from posthog.models import Team++from products.metrics.backend.anomaly import characterize_anomaly, dimension_magnitude+from products.metrics.backend.facade.contracts import (+ CompanionMetric,+ CompanionVerdict,+ InvestigationChartSpec,+ InvestigationEvidence,+ InvestigationResult,+ MetricAnomalyReport,+ MetricFilter,+)++# A companion counts as "moved with the symptom" once it changes by more than+# this fraction over the window (matches the eye test of "basically flat"+# throughput vs a real shift).+COMPANION_MOVE_THRESHOLD = 0.25++# One mover dominates (-> localized cause) when its change is at least this+# multiple of the next mover's.+DOMINANT_MOVER_RATIO = 2.0++# histogram_quantile defaults to p95 when the caller names no quantile (matching+# characterize_anomaly); every other aggregation carries none.+_DEFAULT_HISTOGRAM_QUANTILE = 0.95++# Label keys that name the emitting service, used to implicate one for the+# logs/traces pivot.+_SERVICE_KEYS = ("service_name", "service.name")+++def investigate(+ *,+ team: Team,+ metric_name: str,+ anomaly_from: dt.datetime,+ anomaly_to: dt.datetime,+ baseline_from: dt.datetime | None = None,+ baseline_to: dt.datetime | None = None,+ aggregation: str | None = None,+ quantile: float | None = None,+ filters: tuple[MetricFilter, ...] = (),+ candidate_keys: tuple[str, ...] | None = None,+ companions: tuple[CompanionMetric, ...] = (),+) -> InvestigationResult:+ """Investigate a metric symptom and return a structured result.++ Characterizes `metric_name` over the anomaly window (vs the preceding window+ by default), characterizes each companion over the SAME window to confirm or+ rule it out, classifies blast radius from the movers, and builds re-runnable+ chart specs. Raises `ValueError` for invalid windows (surfaced as 400 by+ callers).+ """+ symptom = characterize_anomaly(+ team=team,+ metric_name=metric_name,+ anomaly_from=anomaly_from,+ anomaly_to=anomaly_to,+ baseline_from=baseline_from,+ baseline_to=baseline_to,+ aggregation=aggregation,+ quantile=quantile,+ filters=filters,+ candidate_keys=candidate_keys,+ )++ companion_verdicts = tuple(+ _assess_companion(+ team=team,+ companion=companion,+ anomaly_from=anomaly_from,+ anomaly_to=anomaly_to,+ baseline_from=baseline_from,+ baseline_to=baseline_to,+ filters=filters,+ )+ for companion in companions+ )++ blast_radius = _classify_blast_radius(symptom)+ service_name = _implicated_service(symptom)+ evidence = InvestigationEvidence(+ service_name=service_name,+ trace_exemplars=(), # filled by the trace-pivot primitive once samples land+ log_filter=_log_filter(service_name, symptom) if service_name else None,+ )+ chart_specs = _build_chart_specs(symptom, companion_verdicts, filters, quantile)+ confidence = _confidence(symptom, companion_verdicts, blast_radius)+ narrative = _narrate(symptom, companion_verdicts, blast_radius)++ return InvestigationResult(+ metric_name=metric_name,+ symptom=symptom,+ blast_radius=blast_radius,+ companions=companion_verdicts,+ chart_specs=chart_specs,+ evidence=evidence,+ confidence=confidence,+ narrative=narrative,+ )+++def _assess_companion(+ *,+ team: Team,+ companion: CompanionMetric,+ anomaly_from: dt.datetime,+ anomaly_to: dt.datetime,+ baseline_from: dt.datetime | None,+ baseline_to: dt.datetime | None,+ filters: tuple[MetricFilter, ...],+) -> CompanionVerdict:+ report = characterize_anomaly(+ team=team,+ metric_name=companion.metric_name,+ anomaly_from=anomaly_from,+ anomaly_to=anomaly_to,+ baseline_from=baseline_from,+ baseline_to=baseline_to,+ aggregation=companion.aggregation,+ quantile=companion.quantile,+ filters=filters,+ )+ moved = report.direction != "flat" and abs(report.change_ratio - 1.0) >= COMPANION_MOVE_THRESHOLD+ return CompanionVerdict(+ metric_name=companion.metric_name,+ role=companion.role,+ aggregation=report.aggregation,+ direction=report.direction,+ change_ratio=report.change_ratio,+ moved_with_symptom=moved,+ quantile=companion.quantile,+ )+++def _classify_blast_radius(symptom: MetricAnomalyReport) -> str:+ """One mover that dwarfs the rest is a localized culprit; several moving+ together is a shared cause; no movers leaves it unknown. Movers arrive+ ranked by magnitude (relative change blended with scale), so the dominance+ test must use that same measure — comparing raw change_ratio here can rank+ a high-magnitude mover below a tiny but explosive one and flip the verdict."""+ movers = symptom.top_movers+ if not movers:+ return "unknown"+ if len(movers) == 1:+ return "localized"+ top, second = dimension_magnitude(movers[0]), dimension_magnitude(movers[1])+ if second == 0.0 or top >= second * DOMINANT_MOVER_RATIO:+ return "localized"+ return "shared"+++def _implicated_service(symptom: MetricAnomalyReport) -> str | None:+ for mover in symptom.top_movers:+ if mover.key in _SERVICE_KEYS:+ return mover.label+ return None+++def _log_filter(service_name: str, symptom: MetricAnomalyReport) -> dict[str, str]:+ """A ready-to-run query-logs filter bracketing onset (or the window start)+ through the anomaly end, errors first."""+ return {+ "service_name": service_name,+ "severity": "error",+ "date_from": symptom.onset_time or symptom.anomaly_from,+ "date_to": symptom.anomaly_to,+ }+++def _chart_quantile(aggregation: str, quantile: float | None) -> float | None:+ """The quantile a chart re-run needs to reproduce the aggregation: only+ histogram_quantile uses one, defaulting to p95 when unspecified."""+ if aggregation == "histogram_quantile":+ return quantile if quantile is not None else _DEFAULT_HISTOGRAM_QUANTILE+ return None+++def _build_chart_specs(+ symptom: MetricAnomalyReport,+ companions: tuple[CompanionVerdict, ...],+ filters: tuple[MetricFilter, ...],+ symptom_quantile: float | None,+) -> tuple[InvestigationChartSpec, ...]:+ """The hero chart (the symptom) plus one per companion, all on the symptom's+ window so the grids line up when rendered side by side. Each spec carries the+ quantile its aggregation needs so a re-run reproduces the same line."""+ specs = [+ InvestigationChartSpec(+ title=f"{symptom.metric_name} ({symptom.aggregation})",+ metric_name=symptom.metric_name,+ aggregation=symptom.aggregation,+ anomaly_from=symptom.anomaly_from,+ anomaly_to=symptom.anomaly_to,+ filters=filters,+ quantile=_chart_quantile(symptom.aggregation, symptom_quantile),+ )+ ]+ specs.extend(+ InvestigationChartSpec(+ title=f"{companion.role}: {companion.metric_name} ({companion.aggregation})",+ metric_name=companion.metric_name,+ aggregation=companion.aggregation,+ anomaly_from=symptom.anomaly_from,+ anomaly_to=symptom.anomaly_to,+ filters=filters,+ quantile=_chart_quantile(companion.aggregation, companion.quantile),+ )+ for companion in companions+ )+ return tuple(specs)+++def _confidence(+ symptom: MetricAnomalyReport,+ companions: tuple[CompanionVerdict, ...],+ blast_radius: str,+) -> str:+ if symptom.direction == "flat":+ return "low"+ explained = any(companion.moved_with_symptom for companion in companions)+ if blast_radius == "localized" or explained:+ return "high"+ return "medium"+++def _narrate(+ symptom: MetricAnomalyReport,+ companions: tuple[CompanionVerdict, ...],+ blast_radius: str,+) -> str:+ parts: list[str] = []+ if symptom.direction == "flat":+ parts.append(f"{symptom.metric_name} held flat over the window — no clear anomaly.")+ else:+ onset = f" starting around {symptom.onset_time}" if symptom.onset_time else ""+ parts.append(+ f"{symptom.metric_name} {_direction_phrase(symptom)}{onset} "+ f"(peak {symptom.anomaly_peak:g} vs baseline {symptom.baseline_mean:g})."+ )+ if blast_radius == "localized" and symptom.top_movers:+ mover = symptom.top_movers[0]+ parts.append(f"Localized to {mover.key}={mover.label}.")+ elif blast_radius == "shared":+ parts.append("Several labels moved together — a shared cause.")+ for companion in companions:+ if companion.moved_with_symptom:+ moved = "moved with it"+ elif companion.direction == "flat":+ moved = "stayed flat"+ else:+ moved = "did not move significantly"+ parts.append(f"{companion.role.capitalize()} ({companion.metric_name}) {moved}.")+ return " ".join(parts)+++def _direction_phrase(symptom: MetricAnomalyReport) -> str:+ if symptom.direction == "down":+ return f"fell to {symptom.change_ratio:.2f}x baseline"+ return f"rose {symptom.change_ratio:.1f}x"diff --git a/products/metrics/backend/tests/test_investigation.py b/products/metrics/backend/tests/test_investigation.pynew file mode 100644index 000000000000..dde6a22835f8--- /dev/null+++ b/products/metrics/backend/tests/test_investigation.py@@ -0,0 +1,129 @@+import datetime as dt+from typing import Any++from posthog.test.base import APIBaseTest, ClickhouseTestMixin++from django.utils import timezone++from posthog.clickhouse.client import sync_execute++from products.metrics.backend.facade.api import investigate+from products.metrics.backend.facade.contracts import CompanionMetric, CompanionVerdict+from products.metrics.backend.tests._seeder import seed_metric+++class TestInvestigate(ClickhouseTestMixin, APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = True++ def setUp(self):+ super().setUp()+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")+ # 20-minute window: minutes 0-9 baseline, 10-19 anomaly (spike from 12).+ self.start = (timezone.now() - dt.timedelta(hours=1)).replace(second=0, microsecond=0)+ self.anomaly_from = self.start + dt.timedelta(minutes=10)+ self.anomaly_to = self.start + dt.timedelta(minutes=20)++ def _spike(self, baseline: float, peak: float) -> list[tuple[dt.datetime, float]]:+ baseline_pts = [(self.start + dt.timedelta(minutes=m), baseline) for m in range(12)]+ spike_pts = [(self.start + dt.timedelta(minutes=m), peak) for m in range(12, 20)]+ return baseline_pts + spike_pts++ def _flat(self, value: float) -> list[tuple[dt.datetime, float]]:+ return [(self.start + dt.timedelta(minutes=m), value) for m in range(20)]++ def _investigate(self, **overrides: Any):+ defaults: dict[str, Any] = {+ "team": self.team,+ "metric_name": "ingestion_lag",+ "anomaly_from": self.anomaly_from,+ "anomaly_to": self.anomaly_to,+ }+ defaults.update(overrides)+ return investigate(**defaults)++ def _verdict(self, result: Any, metric_name: str) -> CompanionVerdict:+ return next(c for c in result.companions if c.metric_name == metric_name)++ def test_localized_spike_rules_companions_in_and_out(self):+ # The metric spikes on one service; a second service stays flat → localized.+ seed_metric(+ team_id=self.team.id,+ metric_name="ingestion_lag",+ points=self._spike(10.0, 100.0),+ service_name="logs-ingestion",+ )+ seed_metric(team_id=self.team.id, metric_name="ingestion_lag", points=self._flat(10.0), service_name="other")+ # Throughput held flat (not a traffic surge); error rate moved with it.+ seed_metric(+ team_id=self.team.id, metric_name="throughput", points=self._flat(120.0), service_name="logs-ingestion"+ )+ seed_metric(+ team_id=self.team.id, metric_name="error_rate", points=self._spike(1.0, 40.0), service_name="logs-ingestion"+ )++ result = self._investigate(+ companions=(+ CompanionMetric(metric_name="throughput", role="traffic"),+ CompanionMetric(metric_name="error_rate", role="saturation"),+ ),+ )++ self.assertEqual(result.symptom.direction, "up")+ self.assertEqual(result.blast_radius, "localized")+ self.assertEqual(result.evidence.service_name, "logs-ingestion")+ assert result.evidence.log_filter is not None+ self.assertEqual(result.evidence.log_filter["service_name"], "logs-ingestion")+ self.assertEqual(result.evidence.log_filter["severity"], "error")++ self.assertFalse(self._verdict(result, "throughput").moved_with_symptom)+ self.assertTrue(self._verdict(result, "error_rate").moved_with_symptom)++ self.assertEqual(result.confidence, "high")+ self.assertIn("logs-ingestion", result.narrative)+ # Hero chart + one per companion, each on the symptom's (non-empty) window.+ self.assertEqual([c.metric_name for c in result.chart_specs], ["ingestion_lag", "throughput", "error_rate"])+ self.assertTrue(all(c.anomaly_from and c.anomaly_to for c in result.chart_specs))+ # Non-histogram aggregations carry no quantile on their chart specs.+ self.assertTrue(all(c.quantile is None for c in result.chart_specs))++ def test_many_services_moving_together_is_a_shared_cause(self):+ seed_metric(+ team_id=self.team.id, metric_name="ingestion_lag", points=self._spike(10.0, 100.0), service_name="svc-a"+ )+ seed_metric(+ team_id=self.team.id, metric_name="ingestion_lag", points=self._spike(10.0, 90.0), service_name="svc-b"+ )++ result = self._investigate()++ self.assertEqual(result.symptom.direction, "up")+ self.assertEqual(result.blast_radius, "shared")++ def test_dominant_scale_mover_is_localized_not_shared(self):+ # A large-footprint service shifts modestly while a tiny one triples. By+ # magnitude the big service dominates (-> localized); a raw change_ratio+ # compare would rank the tiny explosive one above it and mislabel the+ # blast radius "shared".+ seed_metric(+ team_id=self.team.id, metric_name="ingestion_lag", points=self._spike(1000.0, 1100.0), service_name="big"+ )+ seed_metric(+ team_id=self.team.id, metric_name="ingestion_lag", points=self._spike(1.0, 3.0), service_name="small"+ )++ result = self._investigate()++ self.assertEqual(result.symptom.direction, "up")+ self.assertEqual(result.blast_radius, "localized")+ self.assertEqual(result.symptom.top_movers[0].label, "big")++ def test_flat_metric_yields_low_confidence(self):+ seed_metric(+ team_id=self.team.id, metric_name="ingestion_lag", points=self._flat(50.0), service_name="logs-ingestion"+ )++ result = self._investigate()++ self.assertEqual(result.symptom.direction, "flat")+ self.assertEqual(result.confidence, "low")+ self.assertIn("held flat", result.narrative)