: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
fix(alerts): ground the anomaly agent in who emits the alerted event (#92832)
posthog[bot]6bd4d1368055
diff --git a/posthog/temporal/ai/anomaly_investigation/event_provenance.py b/posthog/temporal/ai/anomaly_investigation/event_provenance.pynew file mode 100644index 000000000000..d7f914fe97bd--- /dev/null+++ b/posthog/temporal/ai/anomaly_investigation/event_provenance.py@@ -0,0 +1,132 @@+"""Facts about who emits the alerted event, measured from the event stream.++The metric definition block names the event the alerted series counts, but an event+name says nothing about how the event is produced. A series called "AI summaries"+reads as the output of a backend pipeline, and is just as often a per-person action+recorded from a request handler. With no evidence either way the investigation agent+fills the gap from the name, then recommends checking queue depth, worker errors and+model rate limits on infrastructure that does not exist.++Actor cardinality settles it: an event that thousands of separate actors emit does not+come from one background job, whichever SDK sent it. The numbers are cheap, so they go+into the agent's first message instead of costing it a tool call.++Deliberately unfiltered — this describes the event, not the alerted series.+"""++from __future__ import annotations++from typing import Any++import structlog++from posthog.hogql import ast+from posthog.hogql.query import execute_hogql_query++from posthog.dataclasses import frozen+from posthog.models import Team+from posthog.temporal.ai.anomaly_investigation.metric_definition import unwrap_query_source++logger = structlog.get_logger(__name__)+++@frozen+class _LibProvenance:+ """Per-SDK emission counts for one event: how much one `$lib` sent, and by how many actors."""++ lib: str+ events: int+ actors: int+++PROVENANCE_WINDOW_DAYS = 7+# `$lib` cardinality for a single event is a handful of values, so this only ever trims+# a long tail. The block says when it trimmed one.+MAX_DESCRIBED_LIBS = 6++_GUIDANCE = (+ "How to read this block:\n"+ "- Distinct actors is the ground truth about the emitter. Thousands of separate actors do not\n"+ " come from one background job, one worker pool or one pipeline, whatever the event name\n"+ " suggests. A handful of actors emitting a large volume is the shape a system process makes.\n"+ "- `$lib` names the SDK that sent the event, not the reason it was sent. A server-side SDK\n"+ " records what a person did in a request handler as often as it reports a background job, so\n"+ " it does not on its own make the event a system event.\n"+ "- The counts above are unfiltered, so they can differ from the alerted series."+)+++def alerted_series_event(query: Any, *, series_index: int = 0) -> str | None:+ """The event name the alerted series counts, or None when there isn't a single one.++ Returns None for actions, warehouse tables, SQL insights and the null-event node that+ matches every event — none of those name one event whose emitter can be measured.+ """+ try:+ source = unwrap_query_source(query)+ if not source:+ return None+ series = source.get("series")+ if not isinstance(series, list) or not 0 <= series_index < len(series):+ return None+ node = series[series_index]+ if not isinstance(node, dict) or node.get("kind") != "EventsNode":+ return None+ event = node.get("event")+ return event if isinstance(event, str) and event else None+ except Exception:+ logger.warning("anomaly_investigation.alerted_series_event_failed", exc_info=True)+ return None+++def describe_event_provenance(*, team: Team, event: str) -> str:+ """A plain-text block counting the actors that emit ``event``, broken down by SDK.++ Never raises, and returns an empty string when there is nothing to say: this only+ enriches the agent's context, so a failed query must not fail an investigation that+ would otherwise have run.+ """+ try:+ rows = _query_provenance(team=team, event=event)+ except Exception:+ logger.warning("anomaly_investigation.event_provenance_failed", exc_info=True)+ return ""+ if not rows:+ return ""++ lines = [+ f'Event provenance — who emits event "{event}", measured over the last {PROVENANCE_WINDOW_DAYS} days:',+ ]+ lines.extend(f"- {_describe_row(row)}" for row in rows[:MAX_DESCRIBED_LIBS])+ if len(rows) > MAX_DESCRIBED_LIBS:+ lines.append(f"- ({len(rows) - MAX_DESCRIBED_LIBS} further `$lib` values omitted.)")+ lines.append(_GUIDANCE)+ return "\n".join(lines)+++def _query_provenance(*, team: Team, event: str) -> list[_LibProvenance]:+ response = execute_hogql_query(+ query=(+ "SELECT properties.$lib AS lib, count() AS events, uniq(distinct_id) AS actors "+ "FROM events "+ "WHERE event = {event} AND timestamp >= now() - toIntervalDay({days}) "+ "GROUP BY lib ORDER BY events DESC LIMIT {limit}"+ ),+ team=team,+ placeholders={+ "event": ast.Constant(value=event),+ "days": ast.Constant(value=PROVENANCE_WINDOW_DAYS),+ "limit": ast.Constant(value=MAX_DESCRIBED_LIBS + 1),+ },+ )+ return [+ _LibProvenance(lib=str(row[0] or "unset"), events=int(row[1]), actors=int(row[2]))+ for row in response.results or []+ ]+++def _describe_row(row: _LibProvenance) -> str:+ return (+ f"`$lib` {row.lib}: {row.events:,} events from {row.actors:,} distinct actors "+ f"({row.events / row.actors:.1f} events per actor)"+ )diff --git a/posthog/temporal/ai/anomaly_investigation/metric_definition.py b/posthog/temporal/ai/anomaly_investigation/metric_definition.pyindex 9b212354d051..5cb5f8f821a8 100644--- a/posthog/temporal/ai/anomaly_investigation/metric_definition.py+++ b/posthog/temporal/ai/anomaly_investigation/metric_definition.py@@ -104,7 +104,7 @@ def describe_metric_definition(query: Any, *, series_index: int = 0) -> str:def _describe(query: Any, series_index: int) -> str:- source = _unwrap(query)+ source = unwrap_query_source(query)if not source:return UNAVAILABLE@@ -126,7 +126,7 @@ def _describe(query: Any, series_index: int) -> str:return "\n".join(lines)-def _unwrap(query: Any) -> dict[str, Any] | None:+def unwrap_query_source(query: Any) -> dict[str, Any] | None:"""Peel InsightVizNode/DataTable/DataVisualization wrappers off the stored query."""current = queryfor _ in range(len(_WRAPPER_KINDS) + 1):diff --git a/posthog/temporal/ai/anomaly_investigation/prompts.py b/posthog/temporal/ai/anomaly_investigation/prompts.pyindex 7d75c8cb321d..c9042645f076 100644--- a/posthog/temporal/ai/anomaly_investigation/prompts.py+++ b/posthog/temporal/ai/anomaly_investigation/prompts.py@@ -56,6 +56,14 @@ Ground the metric (do this before forming any hypothesis):page where users look at that domain. That counts people *visiting a page*,not people *hitting the problem*. Reading it the other way turns an ordinaryengagement change into a fabricated incident.+- The name also says nothing about *how* the event is produced. A name like+ "summaries generated" or "jobs processed" reads as the output of a backend+ pipeline, and just as often marks a person's action recorded from a request+ handler. Never assert a producing mechanism — a pipeline, a queue, a worker+ pool, a cron, a model call — that you have no evidence for. The event+ provenance block, when present, measures the emitter: many distinct actors+ means many separate actors each emit the event, which no single background job+ produces. Without that evidence, say the mechanism is unknown.- Every hypothesis has to work against the metric as defined. If a hypothesisonly makes sense when the metric means something the definition does notsupport, drop it — do not soften it into a maybe.@@ -119,6 +127,11 @@ Guidelines:or repeated near-threshold firings on the same metric), flag thatexplicitly as a recommendation — e.g. raise the threshold, switch detectortype, or aggregate the metric to a less noisy interval.+- Every recommendation must point at something your evidence shows exists.+ Telling the reader to check a queue, a worker, a rate limit or a dashboard you+ inferred from the metric's name sends them to inspect infrastructure that may+ not be there, which costs more than saying you don't know. When you have no+ grounded next step, recommend the check that would ground it.- Keep summaries concrete and short. No filler. No apologies. No hedgingbeyond what the data supports. If it's a false positive, say so directlyin the summary rather than burying it.@@ -135,6 +148,7 @@ def build_anomaly_context(calculated_value: float | None,interval: str | None,metric_definition: str,+ event_provenance: str = "",) -> str:"""First user message — packs the alert context the agent needs to act."""md = triggered_metadata or {}@@ -144,6 +158,8 @@ def build_anomaly_context(if parts:metadata_line = "Trigger metadata: " + ", ".join(parts) + "."+ provenance_block = f"{event_provenance}\n\n" if event_provenance else ""+return (f"Alert: {alert_name}\n"f"Insight name (a label someone typed, not the definition): {metric_description}\n"@@ -153,6 +169,7 @@ def build_anomaly_context(f"Triggered dates: {', '.join(triggered_dates) if triggered_dates else 'n/a'}\n"f"{metadata_line}\n\n"f"{metric_definition}\n\n"+ f"{provenance_block}""Use your tools to validate the anomaly and investigate the likely cause. ""Read the metric definition above before forming a hypothesis, and state what the ""metric measures in `metric_meaning`. "diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.pyindex e37694be520c..8cc33cfc6f25 100644--- a/posthog/temporal/ai/anomaly_investigation/workflow.py+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py@@ -24,6 +24,7 @@ from temporalio.common import RetryPolicyfrom posthog.models import Team, Userfrom posthog.tasks.alerts.utils import INSIGHT_ALERT_FIRING_EVENT, dispatch_alert_notification, record_alert_deliveryfrom posthog.temporal.ai.anomaly_investigation.charts import png_to_b64, render_series_chart+from posthog.temporal.ai.anomaly_investigation.event_provenance import alerted_series_event, describe_event_provenancefrom posthog.temporal.ai.anomaly_investigation.metric_definition import describe_metric_definitionfrom posthog.temporal.ai.anomaly_investigation.notebook import NotebookRenderContext, build_investigation_notebookfrom posthog.temporal.ai.anomaly_investigation.prompts import build_anomaly_context@@ -152,6 +153,16 @@ async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInputinsight = alert.insightmetric_description = insight.name or f"Insight {insight.short_id}"detector_type = (alert.detector_config or {}).get("type") or "threshold"+ series_index = (alert.config or {}).get("series_index", 0)++ # Measured up front rather than left to a tool call: without it the agent has only the+ # event's name to go on, and an opaque name invites it to invent the machinery behind it.+ event = alerted_series_event(insight.query, series_index=series_index)+ event_provenance = ""+ if event:+ event_provenance = await sync_to_async(describe_event_provenance, thread_sensitive=False)(+ team=team, event=event+ )anomaly_context_text = build_anomaly_context(alert_name=alert.name or "Unnamed alert",@@ -162,9 +173,8 @@ async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInputcalculated_value=alert_check.calculated_value,interval=alert_check.interval,# The alerted series, not series 0 — matching how the check and the chart pick it.- metric_definition=describe_metric_definition(- insight.query, series_index=(alert.config or {}).get("series_index", 0)- ),+ metric_definition=describe_metric_definition(insight.query, series_index=series_index),+ event_provenance=event_provenance,)# Render a chart of the metric with the detector's anomaly points marked anddiff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_event_provenance.py b/posthog/temporal/tests/ai/test_anomaly_investigation_event_provenance.pynew file mode 100644index 000000000000..ec9fbdaa14f6--- /dev/null+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_event_provenance.py@@ -0,0 +1,105 @@+from typing import Any++from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.temporal.ai.anomaly_investigation.event_provenance import alerted_series_event, describe_event_provenance+from posthog.temporal.ai.anomaly_investigation.prompts import build_anomaly_context++# A bare hourly count of an opaquely named custom event — the shape whose name tells the+# agent nothing about whether a person or a background job emits it.+BARE_EVENT_COUNT = {+ "kind": "InsightVizNode",+ "source": {+ "kind": "TrendsQuery",+ "interval": "hour",+ "series": [{"kind": "EventsNode", "event": "recording analyzed", "math": "total"}],+ },+}++TWO_SERIES = {+ "kind": "TrendsQuery",+ "series": [+ {"kind": "EventsNode", "event": "$pageview", "math": "dau"},+ {"kind": "EventsNode", "event": "recording analyzed", "math": "total"},+ ],+}+++ [+ ("through_the_insight_viz_wrapper", BARE_EVENT_COUNT, 0),+ ("for_the_alerted_series_not_series_zero", TWO_SERIES, 1),+ ]+)+def test_reads_the_event_the_alerted_series_counts(_name: str, query: Any, series_index: int) -> None:+ assert alerted_series_event(query, series_index=series_index) == "recording analyzed"+++ [+ ("action", {"kind": "TrendsQuery", "series": [{"kind": "ActionsNode", "id": 12, "name": "Signed up"}]}, 0),+ ("all_events", {"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": None}]}, 0),+ ("sql_insight", {"kind": "HogQLQuery", "query": "SELECT count() FROM events"}, 0),+ ("index_out_of_range", {"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]}, 1),+ ("unreadable", "not a query", 0),+ ]+)+def test_returns_no_event_when_the_series_does_not_name_one(_name: str, query: Any, series_index: int) -> None:+ assert alerted_series_event(query, series_index=series_index) is None++[email protected]([("query_failed", RuntimeError("ClickHouse is down")), ("no_rows", None)])+@patch("posthog.temporal.ai.anomaly_investigation.event_provenance.execute_hogql_query")+def test_says_nothing_rather_than_failing_the_investigation(+ _name: str, failure: Exception | None, mock_query: MagicMock+) -> None:+ if failure is not None:+ mock_query.side_effect = failure+ else:+ response = MagicMock()+ response.results = []+ mock_query.return_value = response++ assert describe_event_provenance(team=MagicMock(), event="recording analyzed") == ""+++def test_context_carries_the_provenance_block() -> None:+ context = build_anomaly_context(+ alert_name="Headline metric dipped",+ metric_description="Recording AI summaries",+ detector_type="zscore",+ triggered_dates=["2026-08-30"],+ triggered_metadata=None,+ calculated_value=3896.0,+ interval="hour",+ metric_definition="Metric definition — ...",+ event_provenance='Event provenance — who emits event "recording analyzed"',+ )++ assert 'Event provenance — who emits event "recording analyzed"' in context+ assert "Submit the final InvestigationReport" in context+++class TestEventProvenanceAgainstClickHouse(ClickhouseTestMixin, BaseTest):+ def test_counts_the_actors_that_emit_the_event(self) -> None:+ for index in range(3):+ distinct_id = f"person-{index}"+ _create_person(team_id=self.team.pk, distinct_ids=[distinct_id])+ for _ in range(2):+ _create_event(+ team=self.team,+ event="recording analyzed",+ distinct_id=distinct_id,+ properties={"$lib": "posthog-python"},+ )+ _create_person(team_id=self.team.pk, distinct_ids=["other"])+ _create_event(team=self.team, event="recording viewed", distinct_id="other", properties={"$lib": "web"})+ flush_persons_and_events()++ described = describe_event_provenance(team=self.team, event="recording analyzed")++ assert "`$lib` posthog-python: 6 events from 3 distinct actors (2.0 events per actor)" in described+ assert "recording viewed" not in described