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): support threshold alerts on metrics insights (#70603)

Daniel Viscadce9a7449cfb
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index d94c7f645a6c..0a87e9c110d1 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -223,6 +223,7 @@ export function InsightMeta({
const canCreateAlertForInsight = areAlertsSupportedForInsight(query, {
hogqlAlertsEnabled: !!featureFlags[FEATURE_FLAGS.HOGQL_INSIGHT_ALERTS],
funnelAlertsEnabled: !!featureFlags[FEATURE_FLAGS.FUNNEL_INSIGHT_ALERTS],
+ metricsAlertsEnabled: !!featureFlags[FEATURE_FLAGS.METRICS],
})
const canCreateAnomalyAlertForInsight = areAnomalyAlertsSupportedForInsight(query, {
hogqlAlertsEnabled: !!featureFlags[FEATURE_FLAGS.HOGQL_INSIGHT_ALERTS],
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index f162e1df9eb5..0b71df6e1117 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -31675,6 +31675,22 @@
"enum": ["sum", "avg", "count", "min", "max", "quantile", "rate", "increase", "histogram_quantile"],
"type": "string"
},
+ "MetricsAlertConfig": {
+ "additionalProperties": false,
+ "description": "Alert config for metrics insights. Every series the query returns is evaluated; the alert fires if any breaches.",
+ "properties": {
+ "check_ongoing_interval": {
+ "description": "When true, anchor on the trailing (possibly still accumulating) bucket instead of the last complete one.",
+ "type": "boolean"
+ },
+ "type": {
+ "const": "MetricsAlertConfig",
+ "type": "string"
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ },
"MetricsAttributeScope": {
"description": "Which attribute map a metric label key lives in; `auto` resolves resource attributes first, then datapoint attributes.",
"enum": ["resource", "attribute", "auto"],
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 8fb8ff03a2f0..554ca6ea96f4 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -5306,6 +5306,13 @@ export interface FunnelsAlertConfig {
check_ongoing_interval?: boolean
}
+/** Alert config for metrics insights. Every series the query returns is evaluated; the alert fires if any breaches. */
+export interface MetricsAlertConfig {
+ type: 'MetricsAlertConfig'
+ /** When true, anchor on the trailing (possibly still accumulating) bucket instead of the last complete one. */
+ check_ongoing_interval?: boolean
+}
+
/** One blocked period for quiet hours: 24-hour HH:MM in the project timezone; interval is half-open [start, end). */
export interface AlertScheduleRestrictionWindow {
start: string
diff --git a/frontend/src/scenes/insights/InsightModals.tsx b/frontend/src/scenes/insights/InsightModals.tsx
index 6668dff3f524..e987afacbf72 100644
--- a/frontend/src/scenes/insights/InsightModals.tsx
+++ b/frontend/src/scenes/insights/InsightModals.tsx
@@ -93,7 +93,12 @@ function InsightAlertsModals({ insightLogicProps }: { insightLogicProps: Insight
const hogqlAlertsEnabled = useFeatureFlag('HOGQL_INSIGHT_ALERTS')
const funnelAlertsEnabled = useFeatureFlag('FUNNEL_INSIGHT_ALERTS')
- const canCreateAlertForInsight = areAlertsSupportedForInsight(query, { hogqlAlertsEnabled, funnelAlertsEnabled })
+ const metricsAlertsEnabled = useFeatureFlag('METRICS')
+ const canCreateAlertForInsight = areAlertsSupportedForInsight(query, {
+ hogqlAlertsEnabled,
+ funnelAlertsEnabled,
+ metricsAlertsEnabled,
+ })
return (
<>
diff --git a/frontend/src/scenes/insights/InsightPageHeader.tsx b/frontend/src/scenes/insights/InsightPageHeader.tsx
index 9ae50e8ae773..5e09e0a1f37a 100644
--- a/frontend/src/scenes/insights/InsightPageHeader.tsx
+++ b/frontend/src/scenes/insights/InsightPageHeader.tsx
@@ -83,7 +83,12 @@ export function InsightPageHeader({ insightLogicProps }: { insightLogicProps: In
const hogqlAlertsEnabled = useFeatureFlag('HOGQL_INSIGHT_ALERTS')
const funnelAlertsEnabled = useFeatureFlag('FUNNEL_INSIGHT_ALERTS')
- const canCreateAlertForInsight = areAlertsSupportedForInsight(query, { hogqlAlertsEnabled, funnelAlertsEnabled })
+ const metricsAlertsEnabled = useFeatureFlag('METRICS')
+ const canCreateAlertForInsight = areAlertsSupportedForInsight(query, {
+ hogqlAlertsEnabled,
+ funnelAlertsEnabled,
+ metricsAlertsEnabled,
+ })
const insightDisplayName = insight?.name || insight?.derived_name
diff --git a/posthog/schema.py b/posthog/schema.py
index cc6cb8a227ce..716636103b06 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -2012,6 +2012,19 @@ class MaxProductInfo(BaseModel):
usage_limit: float | None = None
+class MetricsAlertConfig(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ check_ongoing_interval: bool | None = Field(
+ default=None,
+ description=(
+ "When true, anchor on the trailing (possibly still accumulating) bucket instead of the last complete one."
+ ),
+ )
+ type: Literal["MetricsAlertConfig"] = "MetricsAlertConfig"
+
+
class MetricsQueryFilter(BaseModel):
model_config = ConfigDict(
extra="forbid",
diff --git a/posthog/tasks/alerts/test/test_metrics_alerts.py b/posthog/tasks/alerts/test/test_metrics_alerts.py
new file mode 100644
index 000000000000..7695c2fa85b3
--- /dev/null
+++ b/posthog/tasks/alerts/test/test_metrics_alerts.py
@@ -0,0 +1,342 @@
+import datetime as dt
+from typing import Any, Optional
+
+from freezegun import freeze_time
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from unittest.mock import MagicMock, patch
+
+import dateutil.parser
+from parameterized import parameterized
+
+from posthog.schema import AlertCalculationInterval, AlertState
+
+from posthog.api.test.dashboards import DashboardAPI
+from posthog.models.instance_setting import set_instance_setting
+from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
+from posthog.models.utils import generate_random_token_personal
+from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
+
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+from products.metrics.backend.facade.testing import seed_metric
+
+# 08:55 — the 08:00 hourly bucket is still accumulating; 07:00 is the last complete one.
+FROZEN_TIME = dateutil.parser.parse("2026-07-01T08:55:00.000Z")
+
+
+def _metrics_flag_only(flag: str, *args: Any, **kwargs: Any) -> bool:
+ return flag == "metrics"
+
+
+@freeze_time(FROZEN_TIME)
+@patch("products.alerts.backend.api.alert.posthoganalytics.feature_enabled", side_effect=_metrics_flag_only)
+@patch("posthog.tasks.alerts.utils.send_notifications_for_errors")
+@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches")
+class TestMetricsAlerts(APIBaseTest, ClickhouseTestMixin):
+ def setUp(self) -> None:
+ super().setUp()
+ set_instance_setting("EMAIL_HOST", "fake_host")
+ set_instance_setting("EMAIL_ENABLED", True)
+ self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)
+ # metrics1 is not truncated between tests, so a per-test metric name keeps tests isolated.
+ self.metric_name = f"queue.depth.{self._testMethodName}"
+
+ def create_metrics_insight(self, group_by: Optional[list[str]] = None) -> dict:
+ clause: dict[str, Any] = {"name": "a", "metricName": self.metric_name, "aggregation": "avg"}
+ if group_by:
+ clause["groupBy"] = [{"key": key} for key in group_by]
+ query_dict = {"kind": "MetricsQuery", "clauses": [clause]}
+ return self.dashboard_api.create_insight(data={"name": "metrics insight", "query": query_dict})[1]
+
+ def create_alert(
+ self,
+ insight: dict,
+ lower: Optional[float] = None,
+ upper: Optional[float] = None,
+ condition_type: str = "absolute_value",
+ config: Optional[dict] = None,
+ expected_status: int = 201,
+ **alert_overrides: Any,
+ ) -> dict:
+ data = {
+ "name": "metrics alert",
+ "insight": insight["id"],
+ "subscribed_users": [self.user.id],
+ "config": config or {"type": "MetricsAlertConfig"},
+ "condition": {"type": condition_type},
+ "calculation_interval": AlertCalculationInterval.DAILY,
+ "threshold": {"configuration": {"type": "absolute", "bounds": {"lower": lower, "upper": upper}}},
+ **alert_overrides,
+ }
+ response = self.client.post(f"/api/projects/{self.team.id}/alerts", data=data)
+ assert response.status_code == expected_status, response.json()
+ return response.json()
+
+ def seed_gauge(self, values_by_hour: dict[int, float], labels: Optional[dict[str, str]] = None) -> None:
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name=self.metric_name,
+ metric_type="gauge",
+ points=[
+ (dt.datetime(2026, 7, 1, hour, 30, tzinfo=dt.UTC), value) for hour, value in values_by_hour.items()
+ ],
+ labels=labels or {},
+ )
+
+ @parameterized.expand(
+ [
+ # (name, seeded value, lower, upper, expected_state, expected_message_fragment)
+ ("lower_breach_fires", 5.0, 10.0, None, AlertState.FIRING, "is less than lower threshold (10.0)"),
+ ("upper_breach_fires", 50.0, None, 20.0, AlertState.FIRING, "is more than upper threshold (20.0)"),
+ ("within_bounds_not_firing", 15.0, 10.0, 20.0, AlertState.NOT_FIRING, None),
+ ]
+ )
+ def test_absolute_threshold(
+ self,
+ mock_send_breaches: MagicMock,
+ mock_send_errors: MagicMock,
+ mock_feature_enabled: MagicMock,
+ _name: str,
+ seeded_value: float,
+ lower: Optional[float],
+ upper: Optional[float],
+ expected_state: AlertState,
+ expected_fragment: Optional[str],
+ ) -> None:
+ # Two complete hourly buckets; the default anchor is the second-to-last observed bucket (07:00).
+ self.seed_gauge({6: seeded_value, 7: seeded_value, 8: seeded_value})
+ insight = self.create_metrics_insight()
+ alert = self.create_alert(insight, lower=lower, upper=upper)
+ assert alert["state"] == AlertState.NOT_FIRING
+
+ run_alert_check(alert["id"])
+
+ updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
+ assert updated_alert.state == expected_state
+ alert_check = AlertCheck.objects.filter(alert_configuration=alert["id"]).latest("created_at")
+ assert alert_check.calculated_value == seeded_value
+ if expected_fragment is None:
+ mock_send_breaches.assert_not_called()
+ else:
+ mock_send_breaches.assert_called_once()
+ breach_messages = mock_send_breaches.call_args.args[1]
+ assert any(expected_fragment in message for message in breach_messages), breach_messages
+
+ def test_empty_metrics_result_evaluates_as_zero(
+ self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock
+ ) -> None:
+ # No data at all: the alert must still evaluate (as 0) and fire a lower-bound breach,
+ # not error out or silently skip.
+ insight = self.create_metrics_insight()
+ alert = self.create_alert(insight, lower=1.0)
+
+ run_alert_check(alert["id"])
+
+ updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
+ assert updated_alert.state == AlertState.FIRING
+ alert_check = AlertCheck.objects.filter(alert_configuration=alert["id"]).latest("created_at")
+ assert alert_check.calculated_value == 0
+ assert alert_check.error is None
+
+ def test_group_by_fires_on_any_breaching_series(
+ self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock
+ ) -> None:
+ # Two label-sets; only one breaches. Catches an extractor that evaluates only the first series.
+ self.seed_gauge({6: 5.0, 7: 5.0}, labels={"container": "small"})
+ self.seed_gauge({6: 50.0, 7: 50.0}, labels={"container": "big"})
+ insight = self.create_metrics_insight(group_by=["container"])
+ alert = self.create_alert(insight, upper=20.0)
+
+ run_alert_check(alert["id"])
+
+ updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
+ assert updated_alert.state == AlertState.FIRING
+ mock_send_breaches.assert_called_once()
+ breach_messages = mock_send_breaches.call_args.args[1]
+ assert any("big" in message for message in breach_messages), breach_messages
+
+ def test_relative_increase_fires(
+ self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock
+ ) -> None:
+ # Anchor bucket (06:00) is 5 above the previous bucket (05:00); catches wrong
+ # anchor/previous index wiring on the observed-bucket grid.
+ self.seed_gauge({5: 10.0, 6: 15.0, 7: 15.0})
+ insight = self.create_metrics_insight()
+ alert = self.create_alert(insight, upper=4.0, condition_type="relative_increase")
+
+ run_alert_check(alert["id"])
+
+ updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
+ assert updated_alert.state == AlertState.FIRING
+ alert_check = AlertCheck.objects.filter(alert_configuration=alert["id"]).latest("created_at")
+ assert alert_check.calculated_value == 5.0
+
+ def test_create_rejected_when_metrics_flag_disabled(
+ self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock
+ ) -> None:
+ mock_feature_enabled.side_effect = None
+ mock_feature_enabled.return_value = False
+ insight = self.create_metrics_insight()
+ response = self.create_alert(insight, lower=1.0, expected_status=400)
+ assert "not enabled" in response["detail"].lower() or "not supported" in response["detail"].lower()
+
+ def test_simulate_rejected_when_metrics_flag_disabled(
+ self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock
+ ) -> None:
+ # The simulate endpoint must apply the same feature gate as create/update — otherwise a
+ # flag-off account gets the ungated unsupported-detector error instead of the gated one.
+ insight = self.create_metrics_insight()
+ mock_feature_enabled.side_effect = None
+ mock_feature_enabled.return_value = False
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/alerts/simulate",
+ data={
+ "insight": insight["id"],
+ "detector_config": {"type": "zscore", "threshold": 0.9, "window": 10},
+ },
+ )
+ assert response.status_code == 400, response.json()
+ assert "not enabled" in str(response.json()).lower()
+
+ def test_simulate_rejects_metrics_insight_with_flag_on(
+ self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock
+ ) -> None:
+ # Metrics has no detector extractor: simulation must 400 cleanly via the registry, not 500.
+ insight = self.create_metrics_insight()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/alerts/simulate",
+ data={
+ "insight": insight["id"],
+ "detector_config": {"type": "zscore", "threshold": 0.9, "window": 10},
+ },
+ )
+ assert response.status_code == 400, response.json()
+ assert "isn't supported for MetricsQuery" in str(response.json())
+
+ @parameterized.expand(
+ [
+ # An alert executes the metrics query as created_by and delivers values in
+ # notifications, so a programmatic token needs the metrics data scope too —
+ # without this, alert:write alone is a metrics-read oracle.
+ ("alert_write_only_rejected", ["alert:write"], 403),
+ ("alert_write_with_metrics_read_allowed", ["alert:write", "metrics:read"], 201),
+ ]
+ )
+ def test_api_key_metrics_scope_enforcement(
+ self,
+ mock_send_breaches: MagicMock,
+ mock_send_errors: MagicMock,
+ mock_feature_enabled: MagicMock,
+ _name: str,
+ scopes: list[str],
+ expected_status: int,
+ ) -> None:
+ insight = self.create_metrics_insight()
+ key_value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="metrics alerts test",
+ user=self.user,
+ secure_value=hash_key_value(key_value),
+ scopes=scopes,
+ )
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ data={
+ "name": "metrics alert",
+ "insight": insight["id"],
+ "subscribed_users": [self.user.id],
+ "config": {"type": "MetricsAlertConfig"},
+ "condition": {"type": "absolute_value"},
+ "calculation_interval": AlertCalculationInterval.DAILY,
+ "threshold": {"configuration": {"type": "absolute", "bounds": {"lower": 1.0, "upper": None}}},
+ },
+ HTTP_AUTHORIZATION=f"Bearer {key_value}",
+ )
+ assert response.status_code == expected_status, response.json()
+ if expected_status == 403:
+ assert "metrics:read" in str(response.json())
+
+ @parameterized.expand(
+ [
+ # Read paths must hide metric alert results (last_value, check history, breach labels)
+ # from tokens lacking the metrics data scope — otherwise alert:read alone reads values
+ # from alerts a session user scheduled, bypassing the write-side gate.
+ ("alert_read_only_hidden", ["alert:read"], False),
+ ("alert_read_with_metrics_read_visible", ["alert:read", "metrics:read"], True),
+ ]
+ )
+ def test_api_key_read_paths_gate_metrics_alerts(
+ self,
+ mock_send_breaches: MagicMock,
+ mock_send_errors: MagicMock,
+ mock_feature_enabled: MagicMock,
+ _name: str,
+ scopes: list[str],
+ visible: bool,
+ ) -> None:
+ insight = self.create_metrics_insight()
+ alert = self.create_alert(insight, lower=1.0) # session-created, so no write-side scope gate
+ key_value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="metrics alerts read test",
+ user=self.user,
+ secure_value=hash_key_value(key_value),
+ scopes=scopes,
+ )
+ authorization = f"Bearer {key_value}"
+
+ list_response = self.client.get(f"/api/projects/{self.team.id}/alerts", HTTP_AUTHORIZATION=authorization)
+ assert list_response.status_code == 200, list_response.json()
+ listed_ids = {result["id"] for result in list_response.json()["results"]}
+ assert (alert["id"] in listed_ids) is visible
+
+ detail_response = self.client.get(
+ f"/api/projects/{self.team.id}/alerts/{alert['id']}", HTTP_AUTHORIZATION=authorization
+ )
+ assert detail_response.status_code == (200 if visible else 404), detail_response.json()
+
+ # Thresholds (nested under the insight) embed full alerts including check values, so they
+ # must be gated the same way.
+ thresholds_response = self.client.get(
+ f"/api/projects/{self.team.id}/insights/{insight['id']}/thresholds", HTTP_AUTHORIZATION=authorization
+ )
+ assert thresholds_response.status_code == 200, thresholds_response.json()
+ threshold_alert_ids = {
+ nested["id"] for result in thresholds_response.json()["results"] for nested in result.get("alerts", [])
+ }
+ assert (alert["id"] in threshold_alert_ids) is visible
+
+ @parameterized.expand(
+ [
+ (
+ "trends_config_on_metrics_insight",
+ {"type": "TrendsAlertConfig", "series_index": 0},
+ {},
+ "not supported",
+ ),
+ (
+ "detector_config_rejected",
+ {"type": "MetricsAlertConfig"},
+ {"detector_config": {"type": "zscore", "threshold": 0.9, "window": 10}},
+ "anomaly detection",
+ ),
+ (
+ "ongoing_interval_requires_upper_bound",
+ {"type": "MetricsAlertConfig", "check_ongoing_interval": True},
+ {},
+ "upper threshold",
+ ),
+ ]
+ )
+ def test_invalid_configs_rejected(
+ self,
+ mock_send_breaches: MagicMock,
+ mock_send_errors: MagicMock,
+ mock_feature_enabled: MagicMock,
+ _name: str,
+ config: dict,
+ alert_overrides: dict,
+ expected_fragment: str,
+ ) -> None:
+ insight = self.create_metrics_insight()
+ response = self.create_alert(insight, lower=1.0, config=config, expected_status=400, **alert_overrides)
+ assert expected_fragment in str(response).lower(), response
diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.py
index f228d4d2ee1e..73b1d28a9a37 100644
--- a/products/alerts/backend/api/alert.py
+++ b/products/alerts/backend/api/alert.py
@@ -2,7 +2,7 @@ import uuid
from typing import Annotated, Any, cast
from zoneinfo import ZoneInfo
-from django.db.models import OuterRef, QuerySet, Subquery
+from django.db.models import OuterRef, Q, QuerySet, Subquery
import posthoganalytics
from drf_spectacular.utils import OpenApiParameter, OpenApiTypes, extend_schema, extend_schema_view
@@ -12,7 +12,7 @@ from pydantic import (
)
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
-from rest_framework.exceptions import ValidationError
+from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.response import Response
from posthog.schema import (
@@ -23,6 +23,7 @@ from posthog.schema import (
FunnelsAlertConfig,
HogQLAlertConfig,
InsightThreshold,
+ MetricsAlertConfig,
NodeKind,
TrendsAlertConfig,
)
@@ -39,6 +40,7 @@ from posthog.helpers.trigram_search import (
drop_similar_when_exact_exists,
)
from posthog.models import User
+from posthog.permissions import get_authenticator_scopes
from posthog.resource_limits import LimitKey, check_count_limit
from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.tasks.alerts.detector import MAX_DETECTOR_BREAKDOWN_VALUES
@@ -87,11 +89,71 @@ class AlertConditionField(serializers.JSONField):
pass
+def _insight_alert_flag_enabled(context: dict[str, Any], flag: str) -> bool:
+ # Scope the flag to the alert's organization (via team scope), not the user's current
+ # organization — otherwise a user in multiple orgs could flip their current org to a
+ # flag-on org and create an alert in a team where the flag is disabled. get_organization is
+ # always injected by TeamAndOrgViewSetMixin; access it unconditionally so the org-scoping
+ # invariant can't silently degrade to an unscoped check.
+ user = context["request"].user
+ org = context["get_organization"]()
+ return bool(
+ posthoganalytics.feature_enabled(
+ flag,
+ str(user.distinct_id),
+ groups={"organization": str(org.id)},
+ )
+ )
+
+
+def _enforce_alert_feature_flags(context: dict[str, Any], insight: Insight) -> None:
+ # Shared by create/update (AlertSerializer) and simulate (AlertSimulateSerializer), so a
+ # flag-gated insight kind gets the same rejection on every alerts entry point.
+ kind = insight.alertable_query_kind
+ if kind is None:
+ raise ValidationError("Alerts are not supported for this insight.")
+ if kind == NodeKind.HOG_QL_QUERY and not _insight_alert_flag_enabled(context, "hogql-insight-alerts"):
+ raise ValidationError("SQL insight alerts are not enabled for your account.")
+ if kind == NodeKind.FUNNELS_QUERY and not _insight_alert_flag_enabled(context, "funnel-insight-alerts"):
+ raise ValidationError("Funnel insight alerts are not enabled for your account.")
+ # Gated on the Metrics product flag itself: anyone who can see the product can alert on it.
+ if kind == NodeKind.METRICS_QUERY and not _insight_alert_flag_enabled(context, "metrics"):
+ raise ValidationError("Metrics insight alerts are not enabled for your account.")
+
+
+# Matches insights whose (bare or one-level-wrapped) query is a MetricsQuery — the shapes the
+# product persists today. Used to hide metric alert data from tokens lacking the metrics scope.
+_METRICS_INSIGHT_QUERY_FILTER = Q(insight__query__kind="MetricsQuery") | Q(insight__query__source__kind="MetricsQuery")
+
+
+def _token_lacks_metrics_scope(request) -> bool:
+ # Session auth (no token scopes) is exempt: those users are gated by team membership and
+ # insight viewer access instead.
+ key_scopes = get_authenticator_scopes(request.successful_authenticator)
+ if key_scopes is None or "*" in key_scopes:
+ return False
+ return not any(scope in key_scopes for scope in ("metrics:read", "metrics:write"))
+
+
+def _require_metrics_scope_for_programmatic_auth(context: dict[str, Any], insight: Insight) -> None:
+ # An alert on a metrics insight executes the query as `created_by` and delivers the computed
+ # value and labels in notifications, so a programmatic token must also carry the metrics data
+ # scope — otherwise `alert:write` alone becomes a metrics-read oracle bypassing the explicit
+ # product-scope gate on the query endpoints.
+ if insight.alertable_query_kind != NodeKind.METRICS_QUERY:
+ return
+ if _token_lacks_metrics_scope(context["request"]):
+ raise PermissionDenied("API key missing required scope 'metrics:read'")
+
+
class AlertConfigUnion(RootModel):
"""Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the
generated frontend types and MCP tool schemas) in sync with every kind alerts support."""
- root: Annotated[TrendsAlertConfig | HogQLAlertConfig | FunnelsAlertConfig, PydanticField(discriminator="type")]
+ root: Annotated[
+ TrendsAlertConfig | HogQLAlertConfig | FunnelsAlertConfig | MetricsAlertConfig,
+ PydanticField(discriminator="type"),
+ ]
@extend_schema_field(AlertConfigUnion) # type: ignore[arg-type]
@@ -546,44 +608,9 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
if not value:
return value
_require_insight_viewer_access(self.context, value)
- self._enforce_alert_feature_flags(value)
+ _enforce_alert_feature_flags(self.context, value)
return value
- def _enforce_alert_feature_flags(self, insight) -> None:
- # Enforced from the object-level validate() so it runs on every create and update — including
- # a PATCH that omits `insight` (which skips this field-level validator), so an alert can't be
- # repointed at a flag-gated insight kind in an account where the flag is off. The model stays
- # flag-agnostic so existing alerts keep working when the flag is off.
- kind = insight.alertable_query_kind
- if kind is None:
- raise ValidationError("Alerts are not supported for this insight.")
- if kind == NodeKind.HOG_QL_QUERY and not self._hogql_alerts_enabled():
- raise ValidationError("SQL insight alerts are not enabled for your account.")
- if kind == NodeKind.FUNNELS_QUERY and not self._funnel_alerts_enabled():
- raise ValidationError("Funnel insight alerts are not enabled for your account.")
-
- def _hogql_alerts_enabled(self) -> bool:
- return self._insight_alert_flag_enabled("hogql-insight-alerts")
-
- def _funnel_alerts_enabled(self) -> bool:
- return self._insight_alert_flag_enabled("funnel-insight-alerts")
-
- def _insight_alert_flag_enabled(self, flag: str) -> bool:
- # Scope the flag to the alert's organization (via team scope), not the user's current
- # organization — otherwise a user in multiple orgs could flip their current org to a
- # flag-on org and create an alert in a team where the flag is disabled. get_organization is
- # always injected by TeamAndOrgViewSetMixin; access it unconditionally so the org-scoping
- # invariant can't silently degrade to an unscoped check.
- user = self.context["request"].user
- org = self.context["get_organization"]()
- return bool(
- posthoganalytics.feature_enabled(
- flag,
- str(user.distinct_id),
- groups={"organization": str(org.id)},
- )
- )
-
def validate_subscribed_users(self, value):
for user in value:
if not user.teams.filter(pk=self.context["team_id"]).exists():
@@ -605,7 +632,13 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
insight = attrs.get("insight") or (self.instance.insight if self.instance else None)
if insight is None:
raise ValidationError({"insight": ["Insight is required."]})
- self._enforce_alert_feature_flags(insight)
+ # Enforced from the object-level validate() so it runs on every create and update — including
+ # a PATCH that omits `insight` (which skips the field-level validator), so an alert can't be
+ # repointed at a flag-gated insight kind (or a scope-gated one) in an account where the flag
+ # is off or the token lacks the data scope. The model stays flag-agnostic so existing alerts
+ # keep working when the flag is off.
+ _enforce_alert_feature_flags(self.context, insight)
+ _require_metrics_scope_for_programmatic_auth(self.context, insight)
with upgrade_query(insight):
query = insight.query
if query is None:
@@ -762,6 +795,9 @@ class AlertSimulateSerializer(serializers.Serializer):
def validate_insight(self, value):
_require_insight_viewer_access(self.context, value)
+ # Same feature gate as create/update: a flag-gated insight kind must get the gated
+ # rejection here too, not fall through to the unsupported-detector error.
+ _enforce_alert_feature_flags(self.context, value)
return value
def validate_detector_config(self, value):
@@ -914,6 +950,15 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
queryset = queryset.filter(insight_id__in=viewable_insights.values("id"))
+ # Read-side twin of the write-side metrics scope gate: a programmatic token without the
+ # metrics data scope must not read metric alert results (last_value, check history, breach
+ # labels) that a session user scheduled. Filtering here covers list, retrieve, update,
+ # delete, and the embedded checks, since get_object() resolves from this queryset.
+ # filter-then-exclude-by-id rather than exclude(Q) — NOT over a JSON path is three-valued,
+ # so a plain exclude also drops rows whose query lacks the key entirely.
+ if _token_lacks_metrics_scope(self.request):
+ queryset = queryset.exclude(id__in=queryset.filter(_METRICS_INSIGHT_QUERY_FILTER).values("id"))
+
latest_check = AlertCheck.objects.filter(alert_configuration=OuterRef("pk")).order_by("-created_at")
queryset = queryset.annotate(last_value=Subquery(latest_check.values("calculated_value")[:1]))
@@ -1086,3 +1131,10 @@ class ThresholdViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelViewSet):
scope_object = "alert"
queryset = Threshold.objects.all()
serializer_class = ThresholdWithAlertSerializer
+
+ def safely_get_queryset(self, queryset) -> QuerySet:
+ # Thresholds embed full alerts (including check values), so they get the same read-side
+ # metrics scope gate as the alerts endpoints. Same null-safe filter-then-exclude shape.
+ if _token_lacks_metrics_scope(self.request):
+ queryset = queryset.exclude(id__in=queryset.filter(_METRICS_INSIGHT_QUERY_FILTER).values("id"))
+ return queryset
diff --git a/products/alerts/backend/evaluation/dispatcher.py b/products/alerts/backend/evaluation/dispatcher.py
index 5cf0f196bf1f..0b7148a3e7c8 100644
--- a/products/alerts/backend/evaluation/dispatcher.py
+++ b/products/alerts/backend/evaluation/dispatcher.py
@@ -10,6 +10,7 @@ from products.alerts.backend.evaluation.contract import DetectorExtractor, Extra
from products.alerts.backend.evaluation.detector import TrendsDetectorExtractor, evaluate_with_detector
from products.alerts.backend.evaluation.funnels import FunnelsExtractor
from products.alerts.backend.evaluation.hogql import HogQLDetectorExtractor, HogQLExtractor
+from products.alerts.backend.evaluation.metrics import MetricsExtractor
from products.alerts.backend.evaluation.trends import TrendsExtractor
from products.alerts.backend.models.alert import AlertConfiguration
from products.product_analytics.backend.models.insight import Insight
@@ -19,6 +20,7 @@ EXTRACTORS: dict[NodeKind, Extractor] = {
NodeKind.TRENDS_QUERY: TrendsExtractor(),
NodeKind.HOG_QL_QUERY: HogQLExtractor(),
NodeKind.FUNNELS_QUERY: FunnelsExtractor(),
+ NodeKind.METRICS_QUERY: MetricsExtractor(),
}
# The anomaly-detector path mirrors EXTRACTORS: one detector extractor per kind, scored by the shared
diff --git a/products/alerts/backend/evaluation/metrics.py b/products/alerts/backend/evaluation/metrics.py
new file mode 100644
index 000000000000..1ec5e701c0cd
--- /dev/null
+++ b/products/alerts/backend/evaluation/metrics.py
@@ -0,0 +1,116 @@
+from typing import Any
+
+from posthog.schema import InsightThreshold, MetricsAlertConfig, MetricsQuery
+
+from posthog.api.services.query import ExecutionMode
+from posthog.caching.calculate_results import calculate_for_query_based_insight
+from posthog.event_usage import EventSource
+
+from products.alerts.backend.evaluation.contract import (
+ ComparableSeries,
+ ExtractionResult,
+ SeriesPoint,
+ zero_sentinel_series,
+)
+from products.alerts.backend.models.alert import AlertConfiguration
+from products.product_analytics.backend.models.insight import Insight
+
+_SUBJECT = "The metric value"
+
+
+def _series_label(row: dict[str, Any]) -> str:
+ name = row.get("metricName") or row.get("clause") or "metric"
+ labels = row.get("labels") or {}
+ if labels:
+ rendered = ", ".join(f"{key}={value}" for key, value in sorted(labels.items()))
+ return f"{name} {{{rendered}}}"
+ return str(name)
+
+
+class MetricsExtractor:
+ """Execute a metrics insight and normalize the result into ``ComparableSeries``.
+
+ Every series the query returns is evaluated (group-by label-sets, multiple clauses, or the
+ formula series) and the alert fires if any breaches — there is no series picker. The bucket
+ grid is the union of observed buckets (zero-filled), so the anchor is positional: the last
+ observed bucket with ``check_ongoing_interval``, otherwise the one before it, which skips the
+ possibly still-accumulating trailing bucket.
+ """
+
+ def extract(
+ self, alert: AlertConfiguration, insight: Insight, query: Any, execution_mode: ExecutionMode
+ ) -> ExtractionResult:
+ MetricsQuery.model_validate(query)
+ if not (alert.config and alert.config.get("type") == "MetricsAlertConfig"):
+ raise ValueError(f"Unsupported alert config type: {alert.config}")
+ config = MetricsAlertConfig.model_validate(alert.config)
+ # Dispatcher short-circuits when threshold/bounds are missing, so both are present here.
+ # Config/condition compatibility (e.g. check_ongoing_interval needs an upper bound) is
+ # _validate_metrics_alert_config's job — enforced at save time and re-run by prepare_alert
+ # before every check — so it isn't re-checked here.
+ if alert.threshold is None:
+ raise ValueError("MetricsExtractor requires a threshold — dispatcher invariant violated")
+ threshold = InsightThreshold.model_validate(alert.threshold.configuration)
+ if threshold.bounds is None:
+ raise ValueError("MetricsExtractor requires threshold bounds — dispatcher invariant violated")
+
+ check_ongoing_interval = bool(config.check_ongoing_interval)
+
+ calculation_result = calculate_for_query_based_insight(
+ insight,
+ team=alert.team,
+ execution_mode=execution_mode,
+ # Scheduled alert check (no request user); attribute the read to the alert owner.
+ user=alert.created_by,
+ analytics_props={"source": EventSource.ALERT},
+ )
+ if calculation_result.result is None:
+ raise RuntimeError(f"No results found for insight with alert id = {alert.id}")
+
+ series = self._to_series(
+ calculation_result.result,
+ anchor_last_point=check_ongoing_interval,
+ is_current_interval=check_ongoing_interval,
+ )
+ if not series:
+ # No observed buckets at all: the metric is genuinely absent, evaluated as 0 so a
+ # lower-bound alert on a dead metric still fires.
+ return ExtractionResult(
+ series=[zero_sentinel_series()],
+ subject=_SUBJECT,
+ empty_query_result=True,
+ )
+
+ return ExtractionResult(
+ series=series,
+ is_breakdown=len(series) > 1,
+ subject=_SUBJECT,
+ )
+
+ def _to_series(
+ self,
+ results: list[Any],
+ *,
+ anchor_last_point: bool,
+ is_current_interval: bool,
+ ) -> list[ComparableSeries]:
+ series: list[ComparableSeries] = []
+ for row in results:
+ if not isinstance(row, dict):
+ continue
+ raw_points = row.get("points") or []
+ points = [SeriesPoint(date=point.get("time"), value=point.get("value")) for point in raw_points]
+ if not points:
+ continue
+ # Anchor on the last observed bucket (ongoing mode) or the one before it. A single-point
+ # series anchors on its only point; relative conditions then skip it (no previous point).
+ current_index = len(points) - 1 if anchor_last_point else max(0, len(points) - 2)
+ series.append(
+ ComparableSeries(
+ label=_series_label(row),
+ points=points,
+ current_index=current_index,
+ is_current_interval=is_current_interval,
+ )
+ )
+ return series
diff --git a/products/alerts/backend/evaluation/validation.py b/products/alerts/backend/evaluation/validation.py
index 141659942b77..bce557531241 100644
--- a/products/alerts/backend/evaluation/validation.py
+++ b/products/alerts/backend/evaluation/validation.py
@@ -14,6 +14,8 @@ from posthog.schema import (
InsightThreshold,
InsightThresholdType,
IntervalType,
+ MetricsAlertConfig,
+ MetricsQuery,
NodeKind,
TrendsAlertConfig,
TrendsQuery,
@@ -172,12 +174,41 @@ def _validate_funnels_alert_config(ctx: _AlertConfigValidationContext) -> None:
validate_threshold_bounds_required(ctx.threshold_config)
+def _validate_metrics_alert_config(ctx: _AlertConfigValidationContext) -> None:
+ if ctx.query_kind != NodeKind.METRICS_QUERY:
+ raise ValueError(f"Metrics alert config requires a MetricsQuery insight, got '{ctx.query_kind}'")
+ try:
+ parsed = MetricsAlertConfig.model_validate(ctx.config)
+ except Exception:
+ raise ValueError(f"Alert has invalid MetricsAlertConfig: {ctx.config}")
+ try:
+ MetricsQuery.model_validate(ctx.query)
+ except Exception as e:
+ raise ValueError(f"Alert's insight has an invalid MetricsQuery: {e}")
+ threshold = _validate_condition_threshold_compatibility(ctx.parsed_condition, ctx.threshold_config)
+ # An ongoing (still accumulating) bucket only under-counts, so a lower bound would false-fire
+ # on every partial bucket — same guard as trends.
+ if (
+ threshold is not None
+ and parsed.check_ongoing_interval
+ and ctx.parsed_condition.type in (AlertConditionType.ABSOLUTE_VALUE, AlertConditionType.RELATIVE_INCREASE)
+ and (not threshold.bounds or threshold.bounds.upper is None)
+ ):
+ raise ValueError(
+ f"check_ongoing_interval is only supported for alert condition {ctx.parsed_condition.type} "
+ "when upper threshold is specified"
+ )
+ if ctx.require_threshold_bounds and ctx.detector_config is None:
+ validate_threshold_bounds_required(ctx.threshold_config)
+
+
# Per-config-type validators, mirroring the extractor registry in dispatcher.py: one entry per
# config type the threshold path supports. Adding a kind = adding an entry here and an extractor.
_ALERT_CONFIG_VALIDATORS: dict[str, Callable[[_AlertConfigValidationContext], None]] = {
"HogQLAlertConfig": _validate_hogql_alert_config,
"TrendsAlertConfig": _validate_trends_alert_config,
"FunnelsAlertConfig": _validate_funnels_alert_config,
+ "MetricsAlertConfig": _validate_metrics_alert_config,
}
diff --git a/products/alerts/frontend/components/AlertsButton.tsx b/products/alerts/frontend/components/AlertsButton.tsx
index 79488a277391..03a8d053da00 100644
--- a/products/alerts/frontend/components/AlertsButton.tsx
+++ b/products/alerts/frontend/components/AlertsButton.tsx
@@ -24,14 +24,19 @@ export function AlertsButton({ insight, insightLogicProps, text, ...props }: Ale
const { alerts } = useValues(logic)
const hogqlAlertsEnabled = useFeatureFlag('HOGQL_INSIGHT_ALERTS')
const funnelAlertsEnabled = useFeatureFlag('FUNNEL_INSIGHT_ALERTS')
+ const metricsAlertsEnabled = useFeatureFlag('METRICS')
- const supported = areAlertsSupportedForInsight(insight.query, { hogqlAlertsEnabled, funnelAlertsEnabled })
+ const supported = areAlertsSupportedForInsight(insight.query, {
+ hogqlAlertsEnabled,
+ funnelAlertsEnabled,
+ metricsAlertsEnabled,
+ })
// Existing alerts must stay manageable even if the gating flag is later disabled —
// they keep evaluating server-side, so the user needs a way in to edit or disable them.
const disabledReason =
supported || (alerts?.length ?? 0) > 0
? undefined
- : alertsUnsupportedReason({ hogqlAlertsEnabled, funnelAlertsEnabled }, insight.query)
+ : alertsUnsupportedReason({ hogqlAlertsEnabled, funnelAlertsEnabled, metricsAlertsEnabled }, insight.query)
return (
<LemonButton
diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.ts
index 8c4b7d14b041..1e62a0daaea7 100644
--- a/products/alerts/frontend/generated/api.schemas.ts
+++ b/products/alerts/frontend/generated/api.schemas.ts
@@ -238,11 +238,27 @@ export interface FunnelsAlertConfigApi {
type: FunnelsAlertConfigApiType
}
+export type MetricsAlertConfigApiType = (typeof MetricsAlertConfigApiType)[keyof typeof MetricsAlertConfigApiType]
+
+export const MetricsAlertConfigApiType = {
+ MetricsAlertConfig: 'MetricsAlertConfig',
+} as const
+
+export interface MetricsAlertConfigApi {
+ /** When true, anchor on the trailing (possibly still accumulating) bucket instead of the last complete one. */
+ check_ongoing_interval?: boolean | null
+ type: MetricsAlertConfigApiType
+}
+
/**
* Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the
* generated frontend types and MCP tool schemas) in sync with every kind alerts support.
*/
-export type AlertConfigUnionApi = TrendsAlertConfigApi | HogQLAlertConfigApi | FunnelsAlertConfigApi
+export type AlertConfigUnionApi =
+ | TrendsAlertConfigApi
+ | HogQLAlertConfigApi
+ | FunnelsAlertConfigApi
+ | MetricsAlertConfigApi
export interface PreprocessingConfigApi {
/** Order of differencing. 0 = raw values, 1 = first-order diffs (default: 0) */
diff --git a/products/alerts/frontend/generated/api.zod.ts b/products/alerts/frontend/generated/api.zod.ts
index 2f084cc97a0e..18de19a98cb7 100644
--- a/products/alerts/frontend/generated/api.zod.ts
+++ b/products/alerts/frontend/generated/api.zod.ts
@@ -53,6 +53,7 @@ export const alertsSimulateCreateBodySeriesIndexDefault = 0
export const alertsSimulateCreateBodyConfigOneOneTypeDefault = `TrendsAlertConfig`
export const alertsSimulateCreateBodyConfigOneTwoTypeDefault = `HogQLAlertConfig`
export const alertsSimulateCreateBodyConfigOneThreeTypeDefault = `FunnelsAlertConfig`
+export const alertsSimulateCreateBodyConfigOneFourTypeDefault = `MetricsAlertConfig`
export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({
insight: zod.number().describe('Insight ID to simulate the detector on.'),
@@ -1122,6 +1123,17 @@ export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({
.enum(['FunnelsAlertConfig'])
.default(alertsSimulateCreateBodyConfigOneThreeTypeDefault),
}),
+ zod.object({
+ check_ongoing_interval: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'When true, anchor on the trailing (possibly still accumulating) bucket instead of the last complete one.'
+ ),
+ type: zod
+ .enum(['MetricsAlertConfig'])
+ .default(alertsSimulateCreateBodyConfigOneFourTypeDefault),
+ }),
])
.describe(
'Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support.'
diff --git a/products/alerts/frontend/logic/alertFormLogic.ts b/products/alerts/frontend/logic/alertFormLogic.ts
index 40198ad55a54..1599e4913e1e 100644
--- a/products/alerts/frontend/logic/alertFormLogic.ts
+++ b/products/alerts/frontend/logic/alertFormLogic.ts
@@ -21,6 +21,7 @@ import {
InsightThresholdType,
InsightsThresholdBounds,
} from '~/queries/schema/schema-general'
+import { containsHogQLQuery, isFunnelsQuery, isInsightVizNode, isMetricsQuery } from '~/queries/utils'
import { AvailableFeature, InsightLogicProps, IntervalType, QueryBasedInsightModel } from '~/types'
import {
@@ -120,7 +121,23 @@ export function ongoingIntervalField(config: AlertConfig | null | undefined, can
}
/** The insight query kind an alert is built for; selects the default config type for new alerts. */
-export type InsightAlertKind = 'trends' | 'hogql' | 'funnels'
+export type InsightAlertKind = 'trends' | 'hogql' | 'funnels' | 'metrics'
+
+/** Resolve which alert kind an insight's query produces. Trends is the fallback: it's the one
+ * always-on kind, so an unrecognized query gets the trends config and fails validation there. */
+export function insightAlertKindForQuery(query?: Record<string, any> | null): InsightAlertKind {
+ if (containsHogQLQuery(query)) {
+ return 'hogql'
+ }
+ if (isInsightVizNode(query) && isFunnelsQuery(query.source)) {
+ return 'funnels'
+ }
+ // Metrics insights persist a bare MetricsQuery node (no InsightVizNode wrapper).
+ if (isMetricsQuery(query)) {
+ return 'metrics'
+ }
+ return 'trends'
+}
export interface AlertFormLogicProps {
alert: AlertType | null
@@ -147,6 +164,9 @@ const defaultConfigForInsight = (kind: AlertFormLogicProps['insightAlertKind']):
if (kind === 'funnels') {
return { type: 'FunnelsAlertConfig', funnel_step: null, metric: 'conversion_from_start' }
}
+ if (kind === 'metrics') {
+ return { type: 'MetricsAlertConfig', check_ongoing_interval: false }
+ }
return {
type: 'TrendsAlertConfig',
series_index: 0,
diff --git a/products/alerts/frontend/logic/insightAlertsLogic.test.ts b/products/alerts/frontend/logic/insightAlertsLogic.test.ts
index f63205e9e678..07f0639446e4 100644
--- a/products/alerts/frontend/logic/insightAlertsLogic.test.ts
+++ b/products/alerts/frontend/logic/insightAlertsLogic.test.ts
@@ -36,6 +36,12 @@ const FUNNEL_QUERY = {
},
}
+// Metrics insights persist their query as a bare MetricsQuery node — no InsightVizNode wrapper.
+const METRICS_QUERY = {
+ kind: NodeKind.MetricsQuery,
+ clauses: [{ name: 'a', metricName: 'queue.depth', aggregation: 'avg' }],
+}
+
describe('insightAlertsLogic', () => {
let listSpy: jest.SpyInstance
@@ -250,6 +256,11 @@ describe('areAlertsSupportedForInsight', () => {
expect(areAlertsSupportedForInsight(FUNNEL_QUERY)).toBe(false)
})
+ it('supports bare metrics query nodes only when metricsAlertsEnabled', () => {
+ expect(areAlertsSupportedForInsight(METRICS_QUERY, { metricsAlertsEnabled: true })).toBe(true)
+ expect(areAlertsSupportedForInsight(METRICS_QUERY)).toBe(false)
+ })
+
it('returns true for funnel insight viz when funnelAlertsEnabled', () => {
expect(areAlertsSupportedForInsight(FUNNEL_QUERY, { funnelAlertsEnabled: true })).toBe(true)
})
@@ -285,10 +296,16 @@ describe('areAlertsSupportedForInsight', () => {
describe('alertsUnsupportedReason', () => {
it.each([
- ['only trends (no flags)', {}, ['trends'], ['SQL', 'funnel']],
- ['trends + SQL', { hogqlAlertsEnabled: true }, ['trends', 'SQL'], ['funnel']],
- ['trends + funnel', { funnelAlertsEnabled: true }, ['trends', 'funnel'], ['SQL']],
- ['all three', { hogqlAlertsEnabled: true, funnelAlertsEnabled: true }, ['trends', 'SQL', 'funnel'], []],
+ ['only trends (no flags)', {}, ['trends'], ['SQL', 'funnel', 'metrics']],
+ ['trends + SQL', { hogqlAlertsEnabled: true }, ['trends', 'SQL'], ['funnel', 'metrics']],
+ ['trends + funnel', { funnelAlertsEnabled: true }, ['trends', 'funnel'], ['SQL', 'metrics']],
+ ['trends + metrics', { metricsAlertsEnabled: true }, ['trends', 'metrics'], ['SQL', 'funnel']],
+ [
+ 'all four',
+ { hogqlAlertsEnabled: true, funnelAlertsEnabled: true, metricsAlertsEnabled: true },
+ ['trends', 'SQL', 'funnel', 'metrics'],
+ [],
+ ],
])('lists only enabled types: %s', (_name, options, included, excluded) => {
const reason = alertsUnsupportedReason(options)
expect(included.every((type) => reason.includes(type))).toBe(true)
diff --git a/products/alerts/frontend/logic/insightAlertsLogic.ts b/products/alerts/frontend/logic/insightAlertsLogic.ts
index 4be31502be38..3c5148da3e1e 100644
--- a/products/alerts/frontend/logic/insightAlertsLogic.ts
+++ b/products/alerts/frontend/logic/insightAlertsLogic.ts
@@ -13,6 +13,7 @@ import {
hasBreakdownFilter,
isFunnelsQuery,
isInsightVizNode,
+ isMetricsQuery,
isTrendsQuery,
} from '~/queries/utils'
import { FunnelVizType, InsightLogicProps } from '~/types'
@@ -31,9 +32,16 @@ export interface InsightAlertsLogicProps {
deferInitialAlertsLoad?: boolean
}
+/** Per-kind feature-flag state threaded from call sites into the alert-support predicates. */
+export interface AlertSupportFlagOptions {
+ hogqlAlertsEnabled?: boolean
+ funnelAlertsEnabled?: boolean
+ metricsAlertsEnabled?: boolean
+}
+
export const areAlertsSupportedForInsight = (
query?: Record<string, any> | null,
- options: { hogqlAlertsEnabled?: boolean; funnelAlertsEnabled?: boolean } = {}
+ options: AlertSupportFlagOptions = {}
): boolean => {
if (!query) {
return false
@@ -47,12 +55,16 @@ export const areAlertsSupportedForInsight = (
const vizType = query.source.funnelsFilter?.funnelVizType
return vizType !== FunnelVizType.TimeToConvert && vizType !== FunnelVizType.Flow
}
+ // Metrics insights persist a bare MetricsQuery node (no InsightVizNode wrapper).
+ if (options.metricsAlertsEnabled && isMetricsQuery(query)) {
+ return true
+ }
return !!options.hogqlAlertsEnabled && containsHogQLQuery(query)
}
export const areAnomalyAlertsSupportedForInsight = (
query?: Record<string, any> | null,
- options: { hogqlAlertsEnabled?: boolean } = {}
+ options: AlertSupportFlagOptions = {}
): boolean => {
if (!areAlertsSupportedForInsight(query, options)) {
return false
@@ -66,14 +78,18 @@ export const areAnomalyAlertsSupportedForInsight = (
// List only the insight types this account can actually alert on — naming a flag-gated type the
// user doesn't have would disclose an unreleased feature.
-const alertableInsightTypesLabel = (options: { hogqlAlertsEnabled?: boolean; funnelAlertsEnabled?: boolean }): string =>
- ['trends', options.hogqlAlertsEnabled && 'SQL', options.funnelAlertsEnabled && 'funnel'].filter(Boolean).join(', ')
+const alertableInsightTypesLabel = (options: AlertSupportFlagOptions): string =>
+ [
+ 'trends',
+ options.hogqlAlertsEnabled && 'SQL',
+ options.funnelAlertsEnabled && 'funnel',
+ options.metricsAlertsEnabled && 'metrics',
+ ]
+ .filter(Boolean)
+ .join(', ')
export const alertsUnsupportedReason = (
- options: {
- hogqlAlertsEnabled?: boolean
- funnelAlertsEnabled?: boolean
- },
+ options: AlertSupportFlagOptions,
query?: Record<string, any> | null
): string => {
// A funnel on a viz type without a conversion-rate metric otherwise reads as a contradiction —
diff --git a/products/alerts/frontend/types.ts b/products/alerts/frontend/types.ts
index c166b40f2461..fc40d4c3a69a 100644
--- a/products/alerts/frontend/types.ts
+++ b/products/alerts/frontend/types.ts
@@ -8,11 +8,12 @@ import {
FunnelsAlertConfig,
HogQLAlertConfig,
InsightThreshold,
+ MetricsAlertConfig,
TrendsAlertConfig,
} from '~/queries/schema/schema-general'
import { QueryBasedInsightModel, UserBasicType } from '~/types'
-export type AlertConfig = TrendsAlertConfig | HogQLAlertConfig | FunnelsAlertConfig
+export type AlertConfig = TrendsAlertConfig | HogQLAlertConfig | FunnelsAlertConfig | MetricsAlertConfig
export const isTrendsAlertConfig = (config: AlertConfig | null | undefined): config is TrendsAlertConfig =>
config?.type === 'TrendsAlertConfig'
@@ -23,6 +24,9 @@ export const isHogQLAlertConfig = (config: AlertConfig | null | undefined): conf
export const isFunnelsAlertConfig = (config: AlertConfig | null | undefined): config is FunnelsAlertConfig =>
config?.type === 'FunnelsAlertConfig'
+export const isMetricsAlertConfig = (config: AlertConfig | null | undefined): config is MetricsAlertConfig =>
+ config?.type === 'MetricsAlertConfig'
+
/** SQL alert in any-row mode: every result row is checked (one entity per row), which changes
* row labeling and history rendering versus the single-value modes. */
export const isAnyRowHogQLConfig = (config: AlertConfig | null | undefined): boolean =>
@@ -32,14 +36,15 @@ export const isAnyRowHogQLConfig = (config: AlertConfig | null | undefined): boo
// checks, so the intent ("does this alert kind support X") is explicit. Kept separate even where
// they coincide today (all trends-only) because the capabilities are independent and may diverge.
-/** Trends alerts and historical-trend funnels evaluate a time-bucketed series, so they can check the
- * current (incomplete) interval. SQL alerts evaluate whatever the query returns — no partial interval.
- * Type guard so call sites can read `check_ongoing_interval` after the check. This is config-level: a
- * steps funnel also matches (it carries the field), so the UI additionally gates the funnel case on
- * whether it's a trends funnel — only those are a time series. */
+/** Trends alerts, historical-trend funnels, and metrics alerts evaluate a time-bucketed series, so
+ * they can check the current (incomplete) interval. SQL alerts evaluate whatever the query returns —
+ * no partial interval. Type guard so call sites can read `check_ongoing_interval` after the check.
+ * This is config-level: a steps funnel also matches (it carries the field), so the UI additionally
+ * gates the funnel case on whether it's a trends funnel — only those are a time series. */
export const supportsOngoingInterval = (
config: AlertConfig | null | undefined
-): config is TrendsAlertConfig | FunnelsAlertConfig => isTrendsAlertConfig(config) || isFunnelsAlertConfig(config)
+): config is TrendsAlertConfig | FunnelsAlertConfig | MetricsAlertConfig =>
+ isTrendsAlertConfig(config) || isFunnelsAlertConfig(config) || isMetricsAlertConfig(config)
/** Trends and funnel alerts evaluate over the insight's time window/interval; SQL alerts own their
* own window inside the query, so there's no interval to echo in the UI. */
diff --git a/products/alerts/frontend/views/EditAlertModal.tsx b/products/alerts/frontend/views/EditAlertModal.tsx
index 274074a23184..5a81690f963b 100644
--- a/products/alerts/frontend/views/EditAlertModal.tsx
+++ b/products/alerts/frontend/views/EditAlertModal.tsx
@@ -19,7 +19,7 @@ import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
import { urls } from 'scenes/urls'
import { AlertCalculationInterval, AlertState } from '~/queries/schema/schema-general'
-import { containsHogQLQuery, isFunnelsQuery, isInsightVizNode } from '~/queries/utils'
+import { isFunnelsQuery, isInsightVizNode } from '~/queries/utils'
import { FunnelVizType, InsightLogicProps, InsightShortId, QueryBasedInsightModel } from '~/types'
import { AlertAdvancedOptionsSection } from 'products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection'
@@ -29,7 +29,7 @@ import { AlertNotificationSection } from 'products/alerts/frontend/components/ed
import { isSubDailyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'
import { SnoozeButton } from '../components/SnoozeButton'
-import { alertFormLogic, canCheckOngoingInterval } from '../logic/alertFormLogic'
+import { alertFormLogic, canCheckOngoingInterval, insightAlertKindForQuery } from '../logic/alertFormLogic'
import { alertLogic } from '../logic/alertLogic'
import { alertNotificationLogic } from '../logic/alertNotificationLogic'
import { isNextPlannedEvaluationStale } from '../logic/alertSchedulingStale'
@@ -84,7 +84,6 @@ export function EditAlertModal({
const { query } = useValues(insightVizDataLogic(insightLogicProps))
const funnelSource = !!query && isInsightVizNode(query) && isFunnelsQuery(query.source) ? query.source : null
- const isFunnelInsight = funnelSource !== null
// Trends funnels alert on the overall conversion rate over time, so they skip the step picker and
// the preview reads the latest period instead of a step snapshot. The backend dispatches on the
// same viz type — see funnel_strategies.py.
@@ -92,11 +91,7 @@ export function EditAlertModal({
const funnelStepLabels = (funnelSource?.series ?? []).map(
(node, index) => getDisplayNameFromEntityNode(node) ?? `Step ${index + 1}`
)
- const insightAlertKind: 'hogql' | 'funnels' | 'trends' = containsHogQLQuery(query)
- ? 'hogql'
- : isFunnelInsight
- ? 'funnels'
- : 'trends'
+ const insightAlertKind = insightAlertKindForQuery(query)
const formLogicProps = {
alert,
diff --git a/products/metrics/backend/facade/testing.py b/products/metrics/backend/facade/testing.py
new file mode 100644
index 000000000000..742f26873eb8
--- /dev/null
+++ b/products/metrics/backend/facade/testing.py
@@ -0,0 +1,10 @@
+"""Test-support facade for metrics.
+
+Other products' tests (e.g. alerts) plant metric fixtures through this module so
+they never import metrics internals; the seeder writes rows shaped like real
+ingest output directly into ClickHouse.
+"""
+
+from products.metrics.backend.tests._seeder import seed_metric
+
+__all__ = ["seed_metric"]
diff --git a/products/product_analytics/backend/models/insight.py b/products/product_analytics/backend/models/insight.py
index d205ab0e268d..be74facbf565 100644
--- a/products/product_analytics/backend/models/insight.py
+++ b/products/product_analytics/backend/models/insight.py
@@ -414,9 +414,13 @@ class Insight(RootTeamMixin, FileSystemSyncMixin, models.Model):
from posthog.schema import NodeKind # noqa: PLC0415
kind = self._unwrapped_query_kind()
- return (
- NodeKind(kind) if kind in (NodeKind.TRENDS_QUERY, NodeKind.HOG_QL_QUERY, NodeKind.FUNNELS_QUERY) else None
+ alertable_kinds = (
+ NodeKind.TRENDS_QUERY,
+ NodeKind.HOG_QL_QUERY,
+ NodeKind.FUNNELS_QUERY,
+ NodeKind.METRICS_QUERY,
)
+ return NodeKind(kind) if kind in alertable_kinds else None
def generate_query_metadata(self):
from posthog.hogql_queries.query_metadata import extract_query_metadata
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c5953ec4829b..0221ef16a8f3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -9097,11 +9097,24 @@ export namespace Schemas {
type: FunnelsAlertConfigType;
}
+ export type MetricsAlertConfigType = typeof MetricsAlertConfigType[keyof typeof MetricsAlertConfigType];
+
+
+ export const MetricsAlertConfigType = {
+ MetricsAlertConfig: 'MetricsAlertConfig',
+ } as const;
+
+ export interface MetricsAlertConfig {
+ /** When true, anchor on the trailing (possibly still accumulating) bucket instead of the last complete one. */
+ check_ongoing_interval?: boolean | null;
+ type: MetricsAlertConfigType;
+ }
+
/**
* Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the
* generated frontend types and MCP tool schemas) in sync with every kind alerts support.
*/
- export type AlertConfigUnion = TrendsAlertConfig | HogQLAlertConfig | FunnelsAlertConfig;
+ export type AlertConfigUnion = TrendsAlertConfig | HogQLAlertConfig | FunnelsAlertConfig | MetricsAlertConfig;
export interface PreprocessingConfig {
/** Order of differencing. 0 = raw values, 1 = first-order diffs (default: 0) */
diff --git a/services/mcp/src/generated/alerts/api.ts b/services/mcp/src/generated/alerts/api.ts
index 6900310b48e7..798a4d7a5f16 100644
--- a/services/mcp/src/generated/alerts/api.ts
+++ b/services/mcp/src/generated/alerts/api.ts
@@ -47,6 +47,7 @@ export const alertsCreateBodyThresholdOneNameMax = 255
export const alertsCreateBodyConfigOneOneTypeDefault = `TrendsAlertConfig`
export const alertsCreateBodyConfigOneTwoTypeDefault = `HogQLAlertConfig`
export const alertsCreateBodyConfigOneThreeTypeDefault = `FunnelsAlertConfig`
+export const alertsCreateBodyConfigOneFourTypeDefault = `MetricsAlertConfig`
export const alertsCreateBodyDetectorConfigOneOneDetectorsItemOneTypeDefault = `zscore`
export const alertsCreateBodyDetectorConfigOneOneDetectorsItemTwoTypeDefault = `mad`
export const alertsCreateBodyDetectorConfigOneOneDetectorsItemThreeTypeDefault = `iqr`
@@ -178,6 +179,15 @@ export const AlertsCreateBody = /* @__PURE__ */ zod.object({
metric: zod.enum(['conversion_from_start', 'conversion_from_previous']),
type: zod.enum(['FunnelsAlertConfig']).default(alertsCreateBodyConfigOneThreeTypeDefault),
}),
+ zod.object({
+ check_ongoing_interval: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'When true, anchor on the trailing (possibly still accumulating) bucket instead of the last complete one.'
+ ),
+ type: zod.enum(['MetricsAlertConfig']).default(alertsCreateBodyConfigOneFourTypeDefault),
+ }),
])
.describe(
'Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support.'
@@ -1343,6 +1353,7 @@ export const alertsPartialUpdateBodyThresholdOneNameMax = 255
export const alertsPartialUpdateBodyConfigOneOneTypeDefault = `TrendsAlertConfig`
export const alertsPartialUpdateBodyConfigOneTwoTypeDefault = `HogQLAlertConfig`
export const alertsPartialUpdateBodyConfigOneThreeTypeDefault = `FunnelsAlertConfig`
+export const alertsPartialUpdateBodyConfigOneFourTypeDefault = `MetricsAlertConfig`
export const alertsPartialUpdateBodyDetectorConfigOneOneDetectorsItemOneTypeDefault = `zscore`
export const alertsPartialUpdateBodyDetectorConfigOneOneDetectorsItemTwoTypeDefault = `mad`
export const alertsPartialUpdateBodyDetectorConfigOneOneDetectorsItemThreeTypeDefault = `iqr`
@@ -1479,6 +1490,15 @@ export const AlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
.enum(['FunnelsAlertConfig'])
.default(alertsPartialUpdateBodyConfigOneThreeTypeDefault),
}),
+ zod.object({
+ check_ongoing_interval: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'When true, anchor on the trailing (possibly still accumulating) bucket instead of the last complete one.'
+ ),
+ type: zod.enum(['MetricsAlertConfig']).default(alertsPartialUpdateBodyConfigOneFourTypeDefault),
+ }),
])
.describe(
'Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support.'
@@ -2663,6 +2683,7 @@ export const alertsSimulateCreateBodySeriesIndexDefault = 0
export const alertsSimulateCreateBodyConfigOneOneTypeDefault = `TrendsAlertConfig`
export const alertsSimulateCreateBodyConfigOneTwoTypeDefault = `HogQLAlertConfig`
export const alertsSimulateCreateBodyConfigOneThreeTypeDefault = `FunnelsAlertConfig`
+export const alertsSimulateCreateBodyConfigOneFourTypeDefault = `MetricsAlertConfig`
export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({
insight: zod.number().describe('Insight ID to simulate the detector on.'),
@@ -3732,6 +3753,17 @@ export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({
.enum(['FunnelsAlertConfig'])
.default(alertsSimulateCreateBodyConfigOneThreeTypeDefault),
}),
+ zod.object({
+ check_ongoing_interval: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'When true, anchor on the trailing (possibly still accumulating) bucket instead of the last complete one.'
+ ),
+ type: zod
+ .enum(['MetricsAlertConfig'])
+ .default(alertsSimulateCreateBodyConfigOneFourTypeDefault),
+ }),
])
.describe(
'Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support.'
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json
index d02d42ee554f..3487e5d8d00e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json
@@ -128,6 +128,27 @@
},
"required": ["metric"],
"type": "object"
+ },
+ {
+ "properties": {
+ "check_ongoing_interval": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "When true, anchor on the trailing (possibly still accumulating) bucket instead of the last complete one."
+ },
+ "type": {
+ "default": "MetricsAlertConfig",
+ "enum": ["MetricsAlertConfig"],
+ "type": "string"
+ }
+ },
+ "type": "object"
}
],
"description": "Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support."
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json
index 0c4ee54fa1db..3a8019006519 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json
@@ -105,6 +105,27 @@
},
"required": ["metric"],
"type": "object"
+ },
+ {
+ "properties": {
+ "check_ongoing_interval": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "When true, anchor on the trailing (possibly still accumulating) bucket instead of the last complete one."
+ },
+ "type": {
+ "default": "MetricsAlertConfig",
+ "enum": ["MetricsAlertConfig"],
+ "type": "string"
+ }
+ },
+ "type": "object"
}
],
"description": "Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support."
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json
index 2f496873be04..51061213d28c 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json
@@ -128,6 +128,27 @@
},
"required": ["metric"],
"type": "object"
+ },
+ {
+ "properties": {
+ "check_ongoing_interval": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "When true, anchor on the trailing (possibly still accumulating) bucket instead of the last complete one."
+ },
+ "type": {
+ "default": "MetricsAlertConfig",
+ "enum": ["MetricsAlertConfig"],
+ "type": "string"
+ }
+ },
+ "type": "object"
}
],
"description": "Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support."