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.

fix(alerts): ground anomaly investigations in the alerted series (#80381)

posthog[bot]2dbe0e11f146
diff --git a/posthog/temporal/ai/anomaly_investigation/metric_definition.py b/posthog/temporal/ai/anomaly_investigation/metric_definition.py
new file mode 100644
index 000000000000..9b212354d051
--- /dev/null
+++ b/posthog/temporal/ai/anomaly_investigation/metric_definition.py
@@ -0,0 +1,310 @@
+"""Plain-English rendering of the alerted insight's query definition.
+
+Without this the investigation agent only sees the insight's *name* plus the
+numbers, so a series called "Error tracking active users" reads as a count of
+people hitting errors even when it is a `$pageview` DAU series filtered to a set
+of app URLs — and the agent then reaches for an outage to explain an engagement
+change. Naming the event, aggregation, and filters the alerted series is built
+from keeps every hypothesis tied to what the number actually measures.
+
+Deliberately dependency-light (stdlib only): it renders the stored query dict
+rather than routing through HogQL machinery, which must stay off the Temporal
+workflow module's import path.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import structlog
+
+logger = structlog.get_logger(__name__)
+
+# The block is prompt context, so it is capped rather than trusting query size —
+# a query can carry hundreds of filter values.
+MAX_DEFINITION_CHARS = 2500
+MAX_DESCRIBED_SERIES = 6
+MAX_DESCRIBED_FILTERS = 8
+MAX_VALUE_CHARS = 120
+MAX_SQL_CHARS = 800
+# Property groups nest (AND of ORs); anything deeper is malformed rather than real.
+MAX_FILTER_DEPTH = 4
+
+UNAVAILABLE = (
+ "Metric definition: unavailable — this insight's query could not be read. Do not infer what the "
+ "metric counts from its name; check the underlying data with your tools before proposing a cause."
+)
+
+_WRAPPER_KINDS = frozenset({"InsightVizNode", "DataTableNode", "DataVisualizationNode"})
+
+_MATH_LABELS = {
+ "total": "total event count",
+ "dau": "unique users (DAU)",
+ "weekly_active": "weekly active users",
+ "monthly_active": "monthly active users",
+ "unique_session": "unique sessions",
+ "first_time_for_user": "count of first-ever occurrences per user",
+ "first_matching_event_for_user": "count of first matching occurrences per user",
+}
+
+_FILTER_SCOPE_LABELS = {
+ "event": "event property",
+ "event_metadata": "event metadata",
+ "person": "person property",
+ "element": "element",
+ "session": "session property",
+ "group": "group property",
+ "feature": "feature flag",
+ "hogql": "HogQL expression",
+ "data_warehouse": "warehouse property",
+ "data_warehouse_person_property": "warehouse person property",
+ "recording": "recording property",
+ "log_entry": "log entry property",
+ "error_tracking_issue": "error tracking issue property",
+}
+
+_OPERATOR_LABELS = {
+ "exact": "is",
+ "is_not": "is not",
+ "icontains": "contains",
+ "not_icontains": "does not contain",
+ "starts_with": "starts with",
+ "not_starts_with": "does not start with",
+ "ends_with": "ends with",
+ "not_ends_with": "does not end with",
+ "regex": "matches regex",
+ "not_regex": "does not match regex",
+ "gt": ">",
+ "gte": ">=",
+ "lt": "<",
+ "lte": "<=",
+ "is_set": "is set",
+ "is_not_set": "is not set",
+ "in": "is one of",
+ "not_in": "is not one of",
+}
+
+_VALUELESS_OPERATORS = frozenset({"is_set", "is_not_set"})
+
+
+def describe_metric_definition(query: Any, *, series_index: int = 0) -> str:
+ """A plain-text block naming what the alerted series measures.
+
+ Never raises: this only enriches the agent's context, so an unrecognized or
+ malformed query degrades to a "couldn't read it" line rather than failing an
+ investigation that would otherwise have run.
+ """
+ try:
+ described = _describe(query, series_index)
+ except Exception:
+ logger.warning("anomaly_investigation.metric_definition_failed", exc_info=True)
+ return UNAVAILABLE
+ return described[:MAX_DEFINITION_CHARS]
+
+
+def _describe(query: Any, series_index: int) -> str:
+ source = _unwrap(query)
+ if not source:
+ return UNAVAILABLE
+
+ kind = source.get("kind") or "unknown"
+ lines = [f"Metric definition — what the alerted number is actually built from (query kind: {kind}):"]
+
+ series = source.get("series")
+ clauses = source.get("clauses")
+ if isinstance(series, list) and series:
+ lines.extend(_describe_series(series, series_index))
+ elif isinstance(clauses, list) and clauses:
+ lines.extend(_describe_clauses(clauses))
+ elif source.get("query"):
+ lines.append(f"- SQL: {_clip(str(source['query']), MAX_SQL_CHARS)}")
+ else:
+ lines.append("- Series: could not be read from the stored query.")
+
+ lines.extend(_describe_query_scope(source))
+ return "\n".join(lines)
+
+
+def _unwrap(query: Any) -> dict[str, Any] | None:
+ """Peel InsightVizNode/DataTable/DataVisualization wrappers off the stored query."""
+ current = query
+ for _ in range(len(_WRAPPER_KINDS) + 1):
+ if not isinstance(current, dict):
+ return None
+ source = current.get("source")
+ if current.get("kind") in _WRAPPER_KINDS and isinstance(source, dict):
+ current = source
+ continue
+ return current
+ return None
+
+
+def _describe_series(series: list[Any], series_index: int) -> list[str]:
+ lines: list[str] = []
+ for index, node in enumerate(series[:MAX_DESCRIBED_SERIES]):
+ label = "Alerted series" if index == series_index else "Other series in this insight"
+ lines.append(f"- {label} (index {index}): {_describe_series_node(node)}")
+ if len(series) > MAX_DESCRIBED_SERIES:
+ lines.append(f"- ({len(series) - MAX_DESCRIBED_SERIES} further series omitted.)")
+ return lines
+
+
+def _describe_series_node(node: Any) -> str:
+ if not isinstance(node, dict):
+ return "unreadable series definition"
+ parts = [f"{_math_label(node)} of {_series_subject(node)}"]
+ filters = _describe_filters(node.get("properties"))
+ if filters:
+ parts.append(f"filtered to {filters}")
+ return ", ".join(parts)
+
+
+def _series_subject(node: dict[str, Any]) -> str:
+ kind = node.get("kind")
+ if kind == "ActionsNode":
+ name = node.get("name")
+ return f'action "{name}" (id {node.get("id")})' if name else f"action id {node.get('id')}"
+ if kind == "DataWarehouseNode":
+ return f'warehouse table "{node.get("table_name") or node.get("id")}"'
+ event = node.get("event")
+ if event is None:
+ # An EventsNode with a null event matches every event, which is easy to
+ # misread as "no filter configured yet".
+ return "all events"
+ return f'event "{event}"'
+
+
+def _math_label(node: dict[str, Any]) -> str:
+ math = node.get("math") or "total"
+ if math == "hogql":
+ return f"custom HogQL aggregation ({_clip(str(node.get('math_hogql') or ''), MAX_VALUE_CHARS)})"
+ if math == "unique_group":
+ return f"unique groups (group type index {node.get('math_group_type_index')})"
+ label = _MATH_LABELS.get(math)
+ if label:
+ return label
+ math_property = node.get("math_property")
+ if math_property:
+ return f'{math} of property "{math_property}"'
+ return str(math)
+
+
+def _describe_clauses(clauses: list[Any]) -> list[str]:
+ lines: list[str] = []
+ for index, clause in enumerate(clauses[:MAX_DESCRIBED_SERIES]):
+ if not isinstance(clause, dict):
+ continue
+ described = f'- Clause {index}: metric "{clause.get("metricName")}"'
+ filters = _describe_filters(clause.get("filters"))
+ if filters:
+ described += f", filtered to {filters}"
+ lines.append(described)
+ return lines
+
+
+def _describe_query_scope(source: dict[str, Any]) -> list[str]:
+ lines: list[str] = []
+
+ global_filters = _describe_filters(source.get("properties"))
+ if global_filters:
+ lines.append(f"- Filters applied to every series: {global_filters}")
+
+ breakdown = _describe_breakdown(source.get("breakdownFilter"))
+ if breakdown:
+ lines.append(f"- Breakdown: {breakdown}")
+
+ trends_filter = source.get("trendsFilter")
+ if isinstance(trends_filter, dict):
+ formula = trends_filter.get("formula") or trends_filter.get("formulas")
+ if formula:
+ lines.append(f"- Formula combining the series: {_format_value(formula)}")
+
+ date_range = source.get("dateRange")
+ if isinstance(date_range, dict) and (date_range.get("date_from") or date_range.get("date_to")):
+ lines.append(
+ f"- Insight date range: {date_range.get('date_from') or 'default'} to {date_range.get('date_to') or 'now'}"
+ )
+
+ interval = source.get("interval")
+ if interval:
+ lines.append(f"- Bucket interval: {interval}")
+
+ if source.get("filterTestAccounts"):
+ lines.append("- Internal and test accounts are excluded.")
+
+ sampling_factor = source.get("samplingFactor")
+ if sampling_factor is not None:
+ lines.append(f"- Sampling factor: {sampling_factor}")
+
+ return lines
+
+
+def _describe_breakdown(breakdown_filter: Any) -> str | None:
+ if not isinstance(breakdown_filter, dict):
+ return None
+ breakdowns = breakdown_filter.get("breakdowns")
+ if isinstance(breakdowns, list) and breakdowns:
+ described = [
+ f"{item.get('type') or 'event'} {item.get('property')}" for item in breakdowns if isinstance(item, dict)
+ ]
+ return ", ".join(described) or None
+ breakdown = breakdown_filter.get("breakdown")
+ if breakdown:
+ return f"{breakdown_filter.get('breakdown_type') or 'event'} {_format_value(breakdown)}"
+ return None
+
+
+def _describe_filters(properties: Any) -> str:
+ leaves = _flatten_filters(properties, 0)
+ described = [text for filter_ in leaves[:MAX_DESCRIBED_FILTERS] if (text := _describe_filter(filter_))]
+ # Say what was dropped — an unannounced cut reads as "those are all the filters",
+ # which is the same misreading of scope this block exists to prevent.
+ if len(leaves) > MAX_DESCRIBED_FILTERS:
+ described.append(f"and {len(leaves) - MAX_DESCRIBED_FILTERS} more filters not shown here")
+ return "; ".join(described)
+
+
+def _flatten_filters(properties: Any, depth: int) -> list[dict[str, Any]]:
+ """Flatten property groups (AND/OR nestings) into a flat list of leaf filters.
+
+ The nesting operators are dropped: for grounding the agent in what the metric
+ covers, which properties are involved matters more than their boolean shape.
+ """
+ if depth > MAX_FILTER_DEPTH or properties is None:
+ return []
+ if isinstance(properties, list):
+ return [leaf for item in properties for leaf in _flatten_filters(item, depth + 1)]
+ if isinstance(properties, dict):
+ values = properties.get("values")
+ if isinstance(values, list):
+ return [leaf for item in values for leaf in _flatten_filters(item, depth + 1)]
+ return [properties] if properties.get("key") is not None or properties.get("type") == "cohort" else []
+ return []
+
+
+def _describe_filter(filter_: dict[str, Any]) -> str | None:
+ filter_type = filter_.get("type") or "event"
+ if filter_type == "cohort":
+ return f"person is in cohort {_format_value(filter_.get('value'))}"
+ key = filter_.get("key")
+ if key is None:
+ return None
+ scope = _FILTER_SCOPE_LABELS.get(filter_type, f"{filter_type} property")
+ if filter_type == "hogql":
+ return f"{scope} {_clip(str(key), MAX_VALUE_CHARS)}"
+ operator = filter_.get("operator") or "exact"
+ operator_label = _OPERATOR_LABELS.get(operator, operator)
+ if operator in _VALUELESS_OPERATORS:
+ return f"{scope} {key} {operator_label}"
+ return f"{scope} {key} {operator_label} {_format_value(filter_.get('value'))}"
+
+
+def _format_value(value: Any) -> str:
+ if isinstance(value, str):
+ return _clip(value, MAX_VALUE_CHARS)
+ return _clip(json.dumps(value, default=str), MAX_VALUE_CHARS)
+
+
+def _clip(text: str, limit: int) -> str:
+ return text if len(text) <= limit else text[: limit - 1] + "…"
diff --git a/posthog/temporal/ai/anomaly_investigation/notebook.py b/posthog/temporal/ai/anomaly_investigation/notebook.py
index 40fa2237ece3..c743c2cdbc93 100644
--- a/posthog/temporal/ai/anomaly_investigation/notebook.py
+++ b/posthog/temporal/ai/anomaly_investigation/notebook.py
@@ -48,6 +48,12 @@ def build_investigation_notebook(ctx: NotebookRenderContext) -> dict[str, Any]:
content.append(create_paragraph_with_text(f"{verdict_text} — {ctx.report.summary}"))
content.append(create_empty_paragraph())
+ metric_meaning = ctx.report.metric_meaning.strip()
+ if metric_meaning:
+ content.append(create_heading_with_text("What this metric measures", level=2))
+ content.append(create_paragraph_with_text(metric_meaning))
+ content.append(create_empty_paragraph())
+
content.append(create_heading_with_text("Source insight", level=2))
content.append(_saved_insight_query_node(ctx.insight))
content.append(create_empty_paragraph())
diff --git a/posthog/temporal/ai/anomaly_investigation/prompts.py b/posthog/temporal/ai/anomaly_investigation/prompts.py
index e9153e6d3dba..7d75c8cb321d 100644
--- a/posthog/temporal/ai/anomaly_investigation/prompts.py
+++ b/posthog/temporal/ai/anomaly_investigation/prompts.py
@@ -19,7 +19,9 @@ Tools (be frugal — hard call budget, the user is waiting):
access for segmenting by property or grabbing raw events.
Workflow:
-1. Read the anomaly context and look at the attached chart.
+1. Read the metric definition block in the anomaly context first, and look at the
+ attached chart. Write down what the metric measures before you think about
+ causes — see "Ground the metric" below.
2. Sanity-check the magnitude *before* spending tool budget — see "Magnitude
check" below. If the absolute counts and relative deviation both look small,
lean toward `false_positive` or `inconclusive` and use any remaining budget
@@ -32,6 +34,7 @@ Workflow:
Final JSON schema (emit exactly these keys):
{
"verdict": "true_positive" | "false_positive" | "inconclusive",
+ "metric_meaning": "One sentence: what the alerted number counts, read off the metric definition.",
"summary": "1-3 sentence plain-English summary of what happened.",
"hypotheses": [
{
@@ -43,6 +46,37 @@ Final JSON schema (emit exactly these keys):
"recommendations": ["Suggested next action.", "Another action."]
}
+Ground the metric (do this before forming any hypothesis):
+- The insight's name is a label a person typed. It is not the definition, and it
+ is often shorthand that says something different from what the query counts.
+ Read the event, aggregation, and filters in the metric definition block, and
+ put what the metric measures into `metric_meaning` in your own words.
+- A common trap: a series named for a problem domain — "errors", "failures",
+ "outages" — that is really a `$pageview` count filtered to the URLs of the
+ 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 ordinary
+ engagement change into a fabricated incident.
+- Every hypothesis has to work against the metric as defined. If a hypothesis
+ only makes sense when the metric means something the definition does not
+ support, drop it — do not soften it into a maybe.
+- The definition also tells you what the metric cannot see. A metric filtered to
+ one page, one event, or one property value carries no information about
+ anything outside that filter.
+
+Corroborating with a second data stream:
+- When you cite another event stream as the cause (exception volume, error
+ counts, a backend signal), high absolute volume is not evidence. A busy
+ project has streams running at thousands per hour all day.
+- Compare that stream inside the alert window against the same stream before the
+ window. Only cite it if it *changed* when the metric changed. If it was
+ already at that level hours before the anomaly started, it is background
+ noise, and blaming the anomaly on it sends the on-call engineer to chase an
+ incident that is not there.
+- If you cannot check the before-window baseline within budget, say the stream
+ is unverified rather than presenting it as the cause.
+- Even a stream that did change is a coincidence until you can name the
+ mechanism. Say "coincides with" unless you have evidence for causation.
+
Magnitude check (do this before classifying):
- Compare the triggered point against the typical baseline for the series (the
median and rough spread of recent buckets), not just against "is this the
@@ -100,6 +134,7 @@ def build_anomaly_context(
triggered_metadata: dict | None,
calculated_value: float | None,
interval: str | None,
+ metric_definition: str,
) -> str:
"""First user message — packs the alert context the agent needs to act."""
md = triggered_metadata or {}
@@ -111,12 +146,15 @@ def build_anomaly_context(
return (
f"Alert: {alert_name}\n"
- f"Metric: {metric_description}\n"
+ f"Insight name (a label someone typed, not the definition): {metric_description}\n"
f"Detector: {detector_type}\n"
f"Interval: {interval or 'unknown'}\n"
f"Calculated value at fire: {calculated_value}\n"
f"Triggered dates: {', '.join(triggered_dates) if triggered_dates else 'n/a'}\n"
f"{metadata_line}\n\n"
+ f"{metric_definition}\n\n"
"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`. "
"Submit the final InvestigationReport using the submit_investigation_report tool."
)
diff --git a/posthog/temporal/ai/anomaly_investigation/report.py b/posthog/temporal/ai/anomaly_investigation/report.py
index e0abe8bb7d48..4d3f194dcf89 100644
--- a/posthog/temporal/ai/anomaly_investigation/report.py
+++ b/posthog/temporal/ai/anomaly_investigation/report.py
@@ -151,6 +151,14 @@ class InvestigationReport(BaseModel):
"evidence to decide."
),
)
+ metric_meaning: str = Field(
+ default="",
+ description=(
+ "One sentence, read off the metric definition in the context: what the alerted number "
+ "counts — the event, the aggregation, and the filters that scope it. Write this before "
+ "reasoning about causes, and never infer it from the insight's name."
+ ),
+ )
summary: str = Field(description="1-3 sentence plain-English summary of what happened.")
hypotheses: list[InvestigationHypothesis] = Field(
default_factory=list,
@@ -200,4 +208,7 @@ def salvage_report(args: Any) -> InvestigationReport | None:
recommendations = data.get("recommendations")
if isinstance(recommendations, list):
report.recommendations = [item for item in recommendations if isinstance(item, str)]
+ metric_meaning = data.get("metric_meaning")
+ if isinstance(metric_meaning, str):
+ report.metric_meaning = metric_meaning
return report
diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.py
index c764a0efc52a..c471eb1db2c0 100644
--- a/posthog/temporal/ai/anomaly_investigation/workflow.py
+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py
@@ -25,6 +25,7 @@ from temporalio.common import RetryPolicy
from posthog.models import Team, User
from posthog.tasks.alerts.utils import dispatch_alert_notification, record_alert_delivery
from posthog.temporal.ai.anomaly_investigation.charts import png_to_b64, render_series_chart
+from posthog.temporal.ai.anomaly_investigation.metric_definition import describe_metric_definition
from posthog.temporal.ai.anomaly_investigation.notebook import NotebookRenderContext, build_investigation_notebook
from posthog.temporal.ai.anomaly_investigation.prompts import build_anomaly_context
from posthog.temporal.ai.anomaly_investigation.report import InvestigationReport
@@ -140,6 +141,10 @@ async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInput
triggered_metadata=alert_check.triggered_metadata,
calculated_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)
+ ),
)
# Render a chart of the metric with the detector's anomaly points marked and
@@ -341,6 +346,9 @@ def _build_signal_description(
f"Insight: {insight_ref}.",
report.summary,
]
+ if report.metric_meaning.strip():
+ # Grouping and triage both hinge on what the metric counts, which its name often misstates.
+ lines.append(f"What the metric measures: {report.metric_meaning.strip()}")
if report.hypotheses:
lines.append("Hypotheses:")
lines.extend(f"- {h.title}: {h.rationale}" for h in report.hypotheses)
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_metric_definition.py b/posthog/temporal/tests/ai/test_anomaly_investigation_metric_definition.py
new file mode 100644
index 000000000000..500eb6a5e6a8
--- /dev/null
+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_metric_definition.py
@@ -0,0 +1,118 @@
+from parameterized import parameterized
+
+from posthog.temporal.ai.anomaly_investigation.metric_definition import UNAVAILABLE, describe_metric_definition
+from posthog.temporal.ai.anomaly_investigation.prompts import build_anomaly_context
+
+# A $pageview DAU series filtered to the app's error tracking pages — an insight whose
+# name ("Error tracking active users") reads as an error count but which measures page visits.
+PAGEVIEW_DAU_ON_ERROR_TRACKING_PAGES = {
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "interval": "hour",
+ "series": [
+ {
+ "kind": "EventsNode",
+ "event": "$pageview",
+ "math": "dau",
+ "properties": [
+ {
+ "key": "$pathname",
+ "type": "event",
+ "value": "^/project/\\d+/error_tracking(/|$)",
+ "operator": "regex",
+ }
+ ],
+ }
+ ],
+ },
+}
+
+
+ [
+ ("event", '"$pageview"'),
+ ("aggregation", "unique users (DAU)"),
+ ("filter_operator", "matches regex"),
+ ("filter_key", "$pathname"),
+ ("filter_value", "error_tracking"),
+ ("interval", "hour"),
+ ]
+)
+def test_describes_what_the_alerted_series_counts(_name: str, expected: str) -> None:
+ described = describe_metric_definition(PAGEVIEW_DAU_ON_ERROR_TRACKING_PAGES)
+
+ assert expected in described
+
+
+def test_marks_the_alerted_series_by_index() -> None:
+ query = {
+ "kind": "TrendsQuery",
+ "series": [
+ {"kind": "EventsNode", "event": "$pageview", "math": "dau"},
+ {"kind": "EventsNode", "event": "$exception", "math": "total"},
+ ],
+ }
+
+ described = describe_metric_definition(query, series_index=1)
+
+ assert 'Alerted series (index 1): total event count of event "$exception"' in described
+ assert 'Other series in this insight (index 0): unique users (DAU) of event "$pageview"' in described
+
+
+def test_flattens_nested_property_groups() -> None:
+ query = {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview", "math": "dau"}],
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [{"key": "$host", "type": "event", "value": "eu.posthog.com", "operator": "exact"}],
+ }
+ ],
+ },
+ }
+
+ described = describe_metric_definition(query)
+
+ assert "event property $host is eu.posthog.com" in described
+
+
+ [
+ ("none", None),
+ ("empty_dict", {}),
+ ("wrong_type", "not a query"),
+ ]
+)
+def test_unreadable_query_says_the_definition_is_unavailable(_name: str, query: object) -> None:
+ assert describe_metric_definition(query) == UNAVAILABLE
+
+
+ [
+ ("series_not_a_list", {"kind": "TrendsQuery", "series": "broken"}),
+ ("series_entries_not_dicts", {"kind": "TrendsQuery", "series": [None, 7]}),
+ ("filters_not_a_list", {"kind": "TrendsQuery", "series": [{"event": "$pageview", "properties": 3}]}),
+ ]
+)
+def test_malformed_query_degrades_instead_of_raising(_name: str, query: object) -> None:
+ assert describe_metric_definition(query)
+
+
+def test_anomaly_context_carries_the_metric_definition() -> None:
+ context = build_anomaly_context(
+ alert_name="Error tracking users spike",
+ metric_description="Headline: Error tracking active users",
+ detector_type="zscore",
+ triggered_dates=["2026-08-10"],
+ triggered_metadata=None,
+ calculated_value=474.0,
+ interval="hour",
+ metric_definition=describe_metric_definition(PAGEVIEW_DAU_ON_ERROR_TRACKING_PAGES),
+ )
+
+ assert '"$pageview"' in context
+ assert "unique users (DAU)" in context
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py b/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py
index e15decb2a109..13bb781e1c2b 100644
--- a/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py
+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_notebook.py
@@ -27,6 +27,7 @@ class TestAnomalyInvestigationNotebook(BaseTest):
def test_builds_well_formed_tiptap_doc(self) -> None:
report = InvestigationReport(
verdict="true_positive",
+ metric_meaning="Unique users who loaded a page under /pricing each day.",
summary="Traffic doubled after a marketing campaign launch.",
hypotheses=[
InvestigationHypothesis(
@@ -47,6 +48,7 @@ class TestAnomalyInvestigationNotebook(BaseTest):
headings = [node for node in doc["content"] if node.get("type") == "heading"]
heading_texts = [node["content"][0]["text"] for node in headings if node.get("content")]
assert any("Verdict" == t for t in heading_texts)
+ assert any("What this metric measures" == t for t in heading_texts)
assert any("Hypotheses" == t for t in heading_texts)
assert any("Recommendations" == t for t in heading_texts)
@@ -71,4 +73,5 @@ class TestAnomalyInvestigationNotebook(BaseTest):
]
assert "Hypotheses" not in heading_texts
assert "Recommendations" not in heading_texts
+ assert "What this metric measures" not in heading_texts
assert "Verdict" in heading_texts