Skip to content

: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.

feat(metrics): add investigate_incident() alert-context entry (#66884)

Daniel Visca433cfe9b74a8
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index 55c9a00594a7..84abf956f4f7 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -14,6 +14,7 @@ from posthog.models import Team
from products.metrics.backend.anomaly import characterize_anomaly as _characterize_anomaly
from products.metrics.backend.facade.contracts import (
CompanionMetric,
+ IncidentContext,
InvestigationResult,
MetricAnomalyReport,
MetricEventSample,
@@ -23,7 +24,7 @@ from products.metrics.backend.facade.contracts import (
MetricQueryRequest,
MetricSeries,
)
-from products.metrics.backend.facade.enums import MetricAggregation
+from products.metrics.backend.facade.enums import FilterOp, MetricAggregation
from products.metrics.backend.formula import evaluate, parse_formula
from products.metrics.backend.has_metrics_query_runner import team_has_metrics as _team_has_metrics
from products.metrics.backend.investigation import investigate as _investigate
@@ -372,3 +373,25 @@ def investigate(
candidate_keys=candidate_keys,
companions=companions,
)
+
+
+def investigate_incident(*, team: Team, context: IncidentContext) -> InvestigationResult:
+ """Investigate a fired alert's metric with no timestamp math on the caller.
+
+ Derives the anomaly window straight from `context.fired_at` (an explicit
+ UTC instant) — no parsing a fire time out of prose, no timezone guesswork —
+ scopes to the implicated service, and runs the full investigation. Returns
+ the same `InvestigationResult` as `investigate()`. This is the entry point
+ an alert's "Investigate" action calls.
+ """
+ filters: tuple[MetricFilter, ...] = ()
+ if context.service_name:
+ filters = (MetricFilter(key="service_name", op=FilterOp.EQ, value=context.service_name),)
+ return _investigate(
+ team=team,
+ metric_name=context.metric_name,
+ anomaly_from=context.fired_at - context.lookback,
+ anomaly_to=context.fired_at + context.leadout,
+ filters=filters,
+ companions=context.companions,
+ )
diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.py
index 435c66e2435a..c1110fcc4930 100644
--- a/products/metrics/backend/facade/contracts.py
+++ b/products/metrics/backend/facade/contracts.py
@@ -275,3 +275,29 @@ class InvestigationResult:
evidence: InvestigationEvidence
confidence: str # "high" | "medium" | "low"
narrative: str
+
+
+@dataclass(frozen=True, slots=True)
+class IncidentContext:
+ """Structured context from a fired alert (or a manual "this looks wrong"),
+ so an investigation never has to parse a timestamp out of prose. `fired_at`
+ must be timezone-aware and is normalized to UTC at construction; the
+ anomaly window is derived as [fired_at - lookback, fired_at + leadout],
+ and `service_name` scopes the investigation to the implicated service.
+ """
+
+ metric_name: str
+ fired_at: dt.datetime
+ lookback: dt.timedelta = dt.timedelta(minutes=15)
+ leadout: dt.timedelta = dt.timedelta(minutes=15)
+ service_name: str | None = None
+ companions: tuple[CompanionMetric, ...] = ()
+
+ def __post_init__(self) -> None:
+ # A naive datetime would be taken as UTC by the window math and
+ # silently mis-bucket a local-time fire; fail fast at construction.
+ # Aware non-UTC instants are fine — normalize them so downstream
+ # window math always operates on UTC.
+ if self.fired_at.tzinfo is None:
+ raise ValueError("fired_at must be timezone-aware")
+ object.__setattr__(self, "fired_at", self.fired_at.astimezone(dt.UTC))
diff --git a/products/metrics/backend/tests/test_investigation.py b/products/metrics/backend/tests/test_investigation.py
index dde6a22835f8..5e475b88a141 100644
--- a/products/metrics/backend/tests/test_investigation.py
+++ b/products/metrics/backend/tests/test_investigation.py
@@ -7,8 +7,8 @@ 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.facade.api import investigate, investigate_incident
+from products.metrics.backend.facade.contracts import CompanionMetric, CompanionVerdict, IncidentContext
from products.metrics.backend.tests._seeder import seed_metric
@@ -127,3 +127,58 @@ class TestInvestigate(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result.symptom.direction, "flat")
self.assertEqual(result.confidence, "low")
self.assertIn("held flat", result.narrative)
+
+ def test_incident_derives_window_from_fire_time(self):
+ # No timestamp math on the caller: the window comes from fired_at alone.
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="ingestion_lag",
+ points=self._spike(10.0, 100.0),
+ service_name="logs-ingestion",
+ )
+
+ result = investigate_incident(
+ team=self.team,
+ context=IncidentContext(
+ metric_name="ingestion_lag",
+ fired_at=self.start + dt.timedelta(minutes=20),
+ lookback=dt.timedelta(minutes=10),
+ leadout=dt.timedelta(minutes=5),
+ ),
+ )
+
+ self.assertEqual(result.symptom.anomaly_from, (self.start + dt.timedelta(minutes=10)).isoformat())
+ self.assertEqual(result.symptom.anomaly_to, (self.start + dt.timedelta(minutes=25)).isoformat())
+ self.assertEqual(result.symptom.direction, "up")
+
+ def test_incident_scopes_to_the_implicated_service(self):
+ # svc-a is flat, svc-b spikes; scoping to svc-a must hide svc-b's spike.
+ seed_metric(team_id=self.team.id, metric_name="ingestion_lag", points=self._flat(10.0), service_name="svc-a")
+ seed_metric(
+ team_id=self.team.id, metric_name="ingestion_lag", points=self._spike(10.0, 100.0), service_name="svc-b"
+ )
+
+ result = investigate_incident(
+ team=self.team,
+ context=IncidentContext(
+ metric_name="ingestion_lag",
+ fired_at=self.start + dt.timedelta(minutes=20),
+ lookback=dt.timedelta(minutes=10),
+ leadout=dt.timedelta(0),
+ service_name="svc-a",
+ ),
+ )
+
+ self.assertEqual(result.symptom.direction, "flat")
+
+ def test_incident_context_normalizes_fired_at_to_utc(self):
+ # fired_at must be an explicit instant: naive datetimes are rejected at
+ # construction rather than silently mis-bucketed as UTC, and aware
+ # non-UTC instants are normalized so window math always runs in UTC.
+ with self.assertRaises(ValueError):
+ IncidentContext(metric_name="ingestion_lag", fired_at=dt.datetime(2026, 1, 1, 12, 0))
+
+ ist = dt.timezone(dt.timedelta(hours=5, minutes=30))
+ context = IncidentContext(metric_name="ingestion_lag", fired_at=dt.datetime(2026, 1, 1, 17, 30, tzinfo=ist))
+ self.assertEqual(context.fired_at, dt.datetime(2026, 1, 1, 12, 0, tzinfo=dt.UTC))
+ self.assertEqual(context.fired_at.tzinfo, dt.UTC)