:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(alerts): anomaly detection for SQL (HogQL) alerts (#65187)
Vasco de Krijgerfade99eaddac
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 328d0155fe37..15e40d2a3b1e 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -266,7 +266,7 @@ import type {import { AgentMode } from '../queries/schema'import type { AttachedContext, MaxUIContext } from '../scenes/max/maxTypes'-import { AlertSimulationResult, AlertType, AlertTypeWrite } from './components/Alerts/types'+import { AlertConfig, AlertSimulationResult, AlertType, AlertTypeWrite } from './components/Alerts/types'import {ErrorTrackingFingerprint,ErrorTrackingRelease,@@ -6425,6 +6425,7 @@ const api = {detector_config: Record<string, any>series_index?: numberdate_from?: string+ config?: AlertConfig | null}): Promise<AlertSimulationResult> {return await new ApiRequest().alerts().withAction('simulate').create({ data })},diff --git a/frontend/src/lib/components/Alerts/alertFormLogic.ts b/frontend/src/lib/components/Alerts/alertFormLogic.tsindex dd3057856248..7263d3bad8ca 100644--- a/frontend/src/lib/components/Alerts/alertFormLogic.ts+++ b/frontend/src/lib/components/Alerts/alertFormLogic.ts@@ -236,6 +236,9 @@ export const alertFormLogic = kea<alertFormLogicType>([date_from:values.simulationDateFrom ??getDefaultSimulationRange(values.alertForm.calculation_interval),+ // SQL insights have no series_index; the config carries the evaluated column+ // and read direction so the preview matches what the alert will score.+ config: formConfig,})},clearSimulation: () => null,diff --git a/frontend/src/lib/components/Alerts/types.test.ts b/frontend/src/lib/components/Alerts/types.test.tsnew file mode 100644index 000000000000..ed41320db445--- /dev/null+++ b/frontend/src/lib/components/Alerts/types.test.ts@@ -0,0 +1,13 @@+import { AlertConfig, supportsAnomalyDetection } from './types'++describe('supportsAnomalyDetection', () => {+ it.each([+ ['trends', { type: 'TrendsAlertConfig', series_index: 0 } as AlertConfig, true],+ ['SQL last_row', { type: 'HogQLAlertConfig', evaluation: 'last_row' } as AlertConfig, true],+ ['SQL first_row', { type: 'HogQLAlertConfig', evaluation: 'first_row' } as AlertConfig, true],+ ['SQL any_row', { type: 'HogQLAlertConfig', evaluation: 'any_row' } as AlertConfig, false],+ ['null', null, false],+ ])('%s -> %s', (_name, config, expected) => {+ expect(supportsAnomalyDetection(config)).toBe(expected)+ })+})diff --git a/frontend/src/lib/components/Alerts/types.ts b/frontend/src/lib/components/Alerts/types.tsindex df1ac8bdb026..d2b4aa606ce9 100644--- a/frontend/src/lib/components/Alerts/types.ts+++ b/frontend/src/lib/components/Alerts/types.ts@@ -38,9 +38,10 @@ export const supportsOngoingInterval = (config: AlertConfig | null | undefined):* own window inside the query, so there's no interval to echo in the UI. */export const supportsTimeWindow = (config: AlertConfig | null | undefined): boolean => !isHogQLAlertConfig(config)-/** Anomaly detection currently only has a trends detector extractor. */-export const supportsAnomalyDetection = (config: AlertConfig | null | undefined): config is TrendsAlertConfig =>- isTrendsAlertConfig(config)+/** Anomaly detection needs a time series to score: trends, or SQL in last/first-row mode (an+ * any-row SQL alert's rows are unrelated entities, not a time axis, so there's nothing to score). */+export const supportsAnomalyDetection = (config: AlertConfig | null | undefined): boolean =>+ isTrendsAlertConfig(config) || (isHogQLAlertConfig(config) && !isAnyRowHogQLConfig(config))export type BlockedWindow = AlertScheduleRestrictionWindowdiff --git a/frontend/src/lib/components/Alerts/views/SimulationSummary.tsx b/frontend/src/lib/components/Alerts/views/SimulationSummary.tsxindex 9476b2786a84..8ba426693b73 100644--- a/frontend/src/lib/components/Alerts/views/SimulationSummary.tsx+++ b/frontend/src/lib/components/Alerts/views/SimulationSummary.tsx@@ -90,7 +90,8 @@ function SimulationChart({getConfig: () => ({type: 'line' as const,data: {- labels: result.dates,+ // SQL insights carry no dates (their rows aren't a time axis) — label by row position.+ labels: result.dates.length > 0 ? result.dates : result.data.map((_, i) => `Row ${i + 1}`),datasets: [// Data series (left y-axis){diff --git a/posthog/tasks/alerts/test/test_detector_breakdowns.py b/posthog/tasks/alerts/test/test_detector_breakdowns.pyindex 86661ef79224..6cb10ac24c84 100644--- a/posthog/tasks/alerts/test/test_detector_breakdowns.py+++ b/posthog/tasks/alerts/test/test_detector_breakdowns.py@@ -294,13 +294,12 @@ class TestCheckTrendsAlertWithDetectorBreakdowns:@parameterized.expand([- ("hogql", NodeKind.HOG_QL_QUERY),("funnels", NodeKind.FUNNELS_QUERY),])def test_detector_alert_on_unsupported_kind_raises(self, _name: str, kind: NodeKind) -> None:- # Detector alerts are trends-only: a detector_config on any other insight kind is rejected- # loudly via the DETECTOR_EXTRACTORS miss, not silently routed to the threshold path.+ # A detector_config on a kind without a detector extractor (here, funnels) is rejected loudly+ # via the DETECTOR_EXTRACTORS miss, not silently routed to the threshold path.alert = _make_alert(MagicMock(), ZSCORE_DETECTOR_CONFIG)with pytest.raises(NotImplementedError):check_detector_alert(alert, MagicMock(spec=Insight), {"kind": kind})@@ -393,3 +392,28 @@ class TestSimulateDetectorBreakdowns:)assert len(result["breakdown_results"]) == MAX_DETECTOR_BREAKDOWN_VALUES++ @patch("products.alerts.backend.evaluation.detector.upgrade_query")+ @patch("products.alerts.backend.evaluation.hogql.calculate_for_query_based_insight")+ def test_simulates_a_hogql_insight_through_the_registry(+ self, mock_calc: MagicMock, _mock_upgrade: MagicMock+ ) -> None:+ # Exercises the HogQLDetectorExtractor.simulate() dispatch route end-to-end: a HOG_QL_QUERY+ # insight resolves to the SQL extractor via DETECTOR_EXTRACTORS and scores its own rows.+ rows = [[v] for v in [*([10.0, 11.0, 10.0, 9.0] * 10), 500.0]] # 41 single-column rows, spike last+ mock_calc.return_value = MagicMock(result=rows, columns=["value"])++ insight = MagicMock(spec=Insight)+ insight.query = {"kind": "HogQLQuery", "query": "SELECT value FROM events"}+ team = MagicMock()++ result = simulate_detector_on_insight(+ insight=insight,+ team=team,+ detector_config=ZSCORE_DETECTOR_CONFIG,+ )++ assert "breakdown_results" not in result # SQL rows are a single series, not a breakdown+ assert result["interval"] is None # SQL insights have no chart interval+ assert result["anomaly_count"] >= 1 # the trailing spike is flagged — the full path scored+ assert len(result["scores"]) == result["total_points"]diff --git a/posthog/tasks/alerts/test/test_validate_alert_config.py b/posthog/tasks/alerts/test/test_validate_alert_config.pyindex 8768892cd777..f6a31fce1343 100644--- a/posthog/tasks/alerts/test/test_validate_alert_config.py+++ b/posthog/tasks/alerts/test/test_validate_alert_config.py@@ -365,12 +365,38 @@ class TestValidateAlertConfig:"daily",)- def test_detector_config_rejected_for_non_trends_insight(self) -> None:- with pytest.raises(ValueError, match="Anomaly detection alerts are only supported for trends insights"):+ def test_detector_config_accepted_for_hogql_insight(self) -> None:+ # SQL/HogQL insights support anomaly detection (last/first-row series), so a detector_config+ # is accepted — not rejected like genuinely-unsupported kinds.+ validate_alert_config(+ _hogql_query(),+ _base_condition(),+ _hogql_config(),+ _base_threshold(),+ "daily",+ detector_config={"type": "zscore", "threshold": 0.95, "window": 30},+ )++ def test_detector_config_rejected_for_any_row_hogql_alert(self) -> None:+ # any_row rows are entities, not a time series — reject anomaly detection at config time+ # so the alert can't be saved only to fail every check.+ with pytest.raises(ValueError, match="Anomaly detection isn't supported for any-row SQL alerts"):validate_alert_config(_hogql_query(),_base_condition(),- _hogql_config(),+ {"type": "HogQLAlertConfig", "evaluation": "any_row"},+ _base_threshold(),+ "daily",+ detector_config={"type": "zscore", "threshold": 0.95, "window": 30},+ )++ def test_detector_config_rejected_for_unsupported_insight(self) -> None:+ # Funnels have no detector extractor, so a detector_config is rejected at config time.+ with pytest.raises(ValueError, match="Anomaly detection alerts aren't supported"):+ validate_alert_config(+ {"kind": "FunnelsQuery", "series": [{"kind": "EventsNode", "event": "a"}]},+ _base_condition(),+ {"type": "FunnelsAlertConfig", "metric": "conversion_from_start", "funnel_step": None},_base_threshold(),"daily",detector_config={"type": "zscore", "threshold": 0.95, "window": 30},diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.pyindex 530497f77b7d..e16c827cbe9d 100644--- a/products/alerts/backend/api/alert.py+++ b/products/alerts/backend/api/alert.py@@ -41,6 +41,7 @@ from posthog.tasks.alerts.utils import next_check_at_after_schedule_restriction_from posthog.utils import relative_date_parsefrom products.alerts.backend.api.alert_schedule_restriction import AlertScheduleRestriction+from products.alerts.backend.evaluation.contract import AlertExtractionErrorfrom products.alerts.backend.evaluation.detector import simulate_detector_on_insightfrom products.alerts.backend.evaluation.validation import THRESHOLD_BOUNDS_REQUIRED_MESSAGE, validate_alert_configfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold@@ -684,16 +685,28 @@ class AlertSimulateSerializer(serializers.Serializer):detector_config = DetectorConfigField(help_text="Detector configuration to simulate.",)+ # TODO: fold series_index and date_from into a per-kind range on `config` once a second insight+ # kind needs a range knob. They stay flat today because date_from is a preview-only range with+ # no home in the persisted alert config, and trends is the only kind with a range knob — but the+ # duplication (series_index already lives in TrendsAlertConfig) should be removed at that point.series_index = serializers.IntegerField(default=0,- help_text="Zero-based index of the series to analyze.",+ help_text="Zero-based index of the series to analyze (trends insights only).",)date_from = serializers.CharField(required=False,allow_null=True,default=None,help_text="Relative date string for how far back to simulate (e.g. '-24h', '-30d', '-4w'). "- "If not provided, uses the detector's minimum required samples.",+ "If not provided, uses the detector's minimum required samples. Trends insights only — a SQL "+ "query's own rows are the series.",+ )+ config = AlertConfigField(+ required=False,+ allow_null=True,+ default=None,+ help_text="Per-insight-kind alert config. For SQL insights, selects the evaluated column and "+ "read direction (last_row/first_row) so the preview matches the alert; ignored for trends.",)def validate_insight(self, value):@@ -974,7 +987,10 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):responses={200: AlertSimulateResponseSerializer},description="Simulate a detector on an insight's historical data. Read-only — no AlertCheck records are created.",)- @action(detail=False, methods=["POST"], url_path="simulate", required_scopes=["alert:read"])+ # Returns an insight's computed result series, so it requires insight read in addition to+ # alert read — an alert-scoped token must not read insight/query data it isn't scoped for.+ # (Object-level insight viewer access is enforced separately in AlertSimulateSerializer.)+ @action(detail=False, methods=["POST"], url_path="simulate", required_scopes=["alert:read", "insight:read"])def simulate(self, request, *args, **kwargs):serializer = AlertSimulateSerializer(data=request.data, context=self.get_serializer_context())serializer.is_valid(raise_exception=True)@@ -983,6 +999,7 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):detector_config = serializer.validated_data["detector_config"]series_index = serializer.validated_data["series_index"]date_from = serializer.validated_data.get("date_from")+ config = serializer.validated_data.get("config")try:result = simulate_detector_on_insight(@@ -992,8 +1009,9 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):series_index=series_index,date_from=date_from,user=cast(User, request.user),+ config=config,)- except (ValueError, IndexError) as e:+ except (ValueError, IndexError, AlertExtractionError) as e:raise ValidationError(str(e))except RuntimeError:raise ValidationError("Simulation failed: unable to compute results for this insight.")diff --git a/products/alerts/backend/api/test/test_alert.py b/products/alerts/backend/api/test/test_alert.pyindex 7d61b1570451..cd82fffae1b0 100644--- a/products/alerts/backend/api/test/test_alert.py+++ b/products/alerts/backend/api/test/test_alert.py@@ -1715,3 +1715,56 @@ class TestAlertAPIKeyAccess(APIBaseTest):assert response.status_code == expected_statusif error_scope:assert error_scope in response.json()["detail"]++ @parameterized.expand(+ [+ # simulate returns an insight's result series, so alert:read alone isn't enough.+ (["feature_flag:read"], "alert:read"),+ (["alert:read"], "insight:read"),+ ]+ )+ def test_simulate_requires_insight_read_scope(self, scopes, missing_scope):+ api_key = self._create_api_key(scopes)+ self.client.logout()++ response = self.client.post(+ f"/api/projects/{self.team.id}/alerts/simulate/",+ data={"insight": self.insight["id"], "detector_config": {"type": "zscore", "threshold": 0.9}},+ HTTP_AUTHORIZATION=f"Bearer {api_key}",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert missing_scope in response.json()["detail"]++ @parameterized.expand(+ [+ (["alert:read", "insight:read"],),+ (["alert:write", "insight:write"],), # write grants read for both+ ]+ )+ @mock.patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")+ def test_simulate_with_both_scopes_passes_the_gate(self, scopes, mock_calculate) -> None:+ mock_calculate.return_value = mock.MagicMock(+ result=[+ {+ "data": [10.0, 12.0, 11.0, 50.0, 13.0, 12.0, 11.0] * 5,+ "days": [f"2024-01-{i:02d}" for i in range(1, 36)],+ "labels": [f"2024-01-{i:02d}" for i in range(1, 36)],+ "label": "pageview",+ }+ ]+ )+ api_key = self._create_api_key(scopes)+ self.client.logout()++ response = self.client.post(+ f"/api/projects/{self.team.id}/alerts/simulate/",+ data={+ "insight": self.insight["id"],+ "detector_config": {"type": "zscore", "threshold": 0.9, "window": 30},+ "series_index": 0,+ },+ HTTP_AUTHORIZATION=f"Bearer {api_key}",+ )++ assert response.status_code == status.HTTP_200_OK, response.contentdiff --git a/products/alerts/backend/evaluation/contract.py b/products/alerts/backend/evaluation/contract.pyindex 1fb6cdab32b5..65524a3121e5 100644--- a/products/alerts/backend/evaluation/contract.py+++ b/products/alerts/backend/evaluation/contract.py@@ -1,8 +1,11 @@from dataclasses import dataclass-from typing import Protocol+from typing import Any, Protocolfrom posthog.schema import AlertCondition, AlertConditionType, IntervalType+from posthog.models.team import Team+from posthog.models.user import User+from products.alerts.backend.models.alert import AlertConfigurationfrom products.product_analytics.backend.models.insight import Insight@@ -84,5 +87,30 @@ def lookback_intervals_for(condition: AlertCondition) -> int:raise AlertExtractionError(f"Unsupported alert condition type: {condition.type}")+@dataclass+class SimulationContext:+ """Alert-less inputs for a read-only detector simulation. Each extractor reads only the fields its+ kind needs: trends uses ``series_index``/``date_from``, SQL uses ``config``; both use ``team``,+ ``user``, and ``detector_config`` (the latter sizes the lookback window)."""++ team: Team+ detector_config: dict[str, Any]+ user: User | None = None+ series_index: int = 0+ date_from: str | None = None+ config: dict[str, Any] | None = None++class Extractor(Protocol):def extract(self, alert: AlertConfiguration, insight: Insight, query: object) -> ExtractionResult: ...+++class DetectorExtractor(Extractor, Protocol):+ """An ``Extractor`` that can also build its series for a read-only simulation (no+ ``AlertConfiguration``). One implementation per detector-supported kind, registered in+ ``dispatcher.DETECTOR_EXTRACTORS`` — the single source of truth for both the alert-check path+ (``extract``) and the simulation path (``simulate``)."""++ def simulate(self, insight: Insight, query: object, ctx: SimulationContext) -> tuple[ExtractionResult, str | None]:+ """Return the extracted series plus the chart interval (None for kinds with no time interval)."""+ ...diff --git a/products/alerts/backend/evaluation/detector.py b/products/alerts/backend/evaluation/detector.pyindex f9fba5fad584..c857cdbe4948 100644--- a/products/alerts/backend/evaluation/detector.py+++ b/products/alerts/backend/evaluation/detector.py@@ -3,11 +3,12 @@ from zoneinfo import ZoneInfoimport numpy as np-from posthog.schema import IntervalType, NodeKind, TrendsAlertConfig, TrendsQuery+from posthog.schema import IntervalType, TrendsAlertConfig, TrendsQueryfrom posthog.api.services.query import ExecutionModefrom posthog.caching.calculate_results import calculate_for_query_based_insightfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.schema_migrations.upgrade_manager import upgrade_query@@ -24,7 +25,12 @@ from posthog.tasks.alerts.trends import TrendResult, _has_breakdown, _is_non_timfrom posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResultfrom posthog.utils import get_from_dict_or_attr, relative_date_parse-from products.alerts.backend.evaluation.contract import ComparableSeries, ExtractionResult, SeriesPoint+from products.alerts.backend.evaluation.contract import (+ ComparableSeries,+ ExtractionResult,+ SeriesPoint,+ SimulationContext,+)from products.alerts.backend.models.alert import AlertConfigurationfrom products.product_analytics.backend.models.insight import Insight@@ -194,14 +200,29 @@ class TrendsDetectorExtractor:insight, alert.team, trends_query, detector_config, series_index=series_index, user=alert.created_by)+ def simulate(self, insight: Insight, query: object, ctx: SimulationContext) -> tuple[ExtractionResult, str | None]:+ trends_query = TrendsQuery.model_validate(query)+ result = extract_detector_series(+ insight,+ ctx.team,+ trends_query,+ ctx.detector_config,+ series_index=ctx.series_index,+ date_from=ctx.date_from,+ user=ctx.user,+ )+ interval_value = trends_query.interval.value if trends_query.interval else None+ return result, interval_value+def simulate_detector_on_insight(insight: Insight,- team: Any,+ team: Team,detector_config: dict[str, Any],series_index: int = 0,date_from: str | None = None,user: Optional[User] = None,+ config: dict[str, Any] | None = None,) -> dict[str, Any]:"""Run a detector over historical insight data for chart visualization. Read-only (no AlertCheck)."""if insight.query is None:@@ -214,17 +235,32 @@ def simulate_detector_on_insight(if kind in WRAPPER_NODE_KINDS:query = get_from_dict_or_attr(query, "source")kind = get_from_dict_or_attr(query, "kind")- if kind != NodeKind.TRENDS_QUERY:- raise ValueError("Only TrendsQuery insights are supported for simulation.")- trends_query = TrendsQuery.model_validate(query)# Read-only simulation runs outside the alert-check activity, so tag its query directly.tag_queries(product=Product.PRODUCT_ANALYTICS, feature=Feature.ALERTING)detector_type_str = detector_config.get("type", "zscore")- result = extract_detector_series(- insight, team, trends_query, detector_config, series_index=series_index, date_from=date_from, user=user++ # Route through the same kind→extractor registry as the alert path (check_detector_alert), so+ # simulation and evaluation can't drift: a kind added to DETECTOR_EXTRACTORS is automatically+ # simulatable via its extractor's simulate(). The import is lazy because dispatcher imports this+ # module's extractor classes — importing the registry at module load would cycle.+ from products.alerts.backend.evaluation.dispatcher import ( # noqa: PLC0415 — breaks dispatcher↔detector import cycle+ DETECTOR_EXTRACTORS,+ )++ extractor = DETECTOR_EXTRACTORS.get(kind)+ if extractor is None:+ raise ValueError(f"Anomaly detection simulation isn't supported for {kind} insights")++ ctx = SimulationContext(+ team=team,+ detector_config=detector_config,+ user=user,+ series_index=series_index,+ date_from=date_from,+ config=config,)- interval_value = trends_query.interval.value if trends_query.interval else None+ result, interval_value = extractor.simulate(insight, query, ctx)if not result.series:# Preserve the original, more specific diagnostics: a genuinely empty query vs rows that@@ -233,7 +269,12 @@ def simulate_detector_on_insight(raise ValueError("No results found for insight.")if result.is_breakdown:raise ValueError("No breakdown values had enough data points for simulation.")- raise ValueError("No data points found for the selected series.")+ # Rows exist but the series is shorter than the detector's window — say so, rather than the+ # misleading "no data" (e.g. a 40-row SQL query against the default 90-point window).+ raise ValueError(+ "Not enough data points to score: the series is shorter than the detector's window size. "+ "Return more rows or reduce the window size."+ )if result.is_breakdown:breakdown_sims = [_sim_from_series(s, detector_config, detector_type_str) for s in result.series]diff --git a/products/alerts/backend/evaluation/dispatcher.py b/products/alerts/backend/evaluation/dispatcher.pyindex 19e6c14671a3..6ffec43c82d3 100644--- a/products/alerts/backend/evaluation/dispatcher.py+++ b/products/alerts/backend/evaluation/dispatcher.py@@ -5,9 +5,9 @@ from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResultfrom posthog.utils import get_from_dict_or_attrfrom products.alerts.backend.evaluation.comparator import evaluate_threshold-from products.alerts.backend.evaluation.contract import Extractor+from products.alerts.backend.evaluation.contract import DetectorExtractor, Extractorfrom products.alerts.backend.evaluation.detector import TrendsDetectorExtractor, evaluate_with_detector-from products.alerts.backend.evaluation.hogql import HogQLExtractor+from products.alerts.backend.evaluation.hogql import HogQLDetectorExtractor, HogQLExtractorfrom products.alerts.backend.evaluation.trends import TrendsExtractorfrom products.alerts.backend.models.alert import AlertConfigurationfrom products.product_analytics.backend.models.insight import Insight@@ -19,9 +19,12 @@ EXTRACTORS: dict[NodeKind, Extractor] = {}# The anomaly-detector path mirrors EXTRACTORS: one detector extractor per kind, scored by the shared-# evaluate_with_detector. Trends-only in v1, but the dispatch no longer hardcodes the kind.-DETECTOR_EXTRACTORS: dict[NodeKind, Extractor] = {+# evaluate_with_detector. Funnels stay threshold-only (no native time series to score). This is the+# single source of truth for both detector paths — alert checks call extract(), read-only simulation+# (simulate_detector_on_insight) calls simulate() — so adding a kind here makes it work in both.+DETECTOR_EXTRACTORS: dict[NodeKind, DetectorExtractor] = {NodeKind.TRENDS_QUERY: TrendsDetectorExtractor(),+ NodeKind.HOG_QL_QUERY: HogQLDetectorExtractor(),}@@ -45,9 +48,9 @@ def check_detector_alert(alert: AlertConfiguration, insight: Insight, query: objdef check_alert_for_insight(alert: AlertConfiguration) -> AlertEvaluationResult:"""Dispatch an alert to its insight-kind extractor, then run the shared comparator.- If ``detector_config`` is set, routes through the anomaly-detector registry (trends-only in v1);- each detector extractor shares the ``ComparableSeries`` contract, so the dispatch shape mirrors- the threshold path. Otherwise the extractor normalizes the query result into an+ If ``detector_config`` is set, routes through the anomaly-detector registry (one extractor per+ supported insight kind); each detector extractor shares the ``ComparableSeries`` contract, so the+ dispatch shape mirrors the threshold path. Otherwise the extractor normalizes the query result into an``ExtractionResult`` and the comparator evaluates it against the threshold."""insight = alert.insightdiff --git a/products/alerts/backend/evaluation/hogql.py b/products/alerts/backend/evaluation/hogql.pyindex 7ba9564b17d4..5db8db63d4d5 100644--- a/products/alerts/backend/evaluation/hogql.py+++ b/products/alerts/backend/evaluation/hogql.py@@ -9,12 +9,14 @@ from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWSfrom posthog.api.services.query import ExecutionModefrom posthog.caching.calculate_results import calculate_for_query_based_insightfrom posthog.event_usage import EventSource+from posthog.tasks.alerts.detector import _compute_min_samples_for_detectorfrom products.alerts.backend.evaluation.contract import (AlertExtractionError,ComparableSeries,ExtractionResult,SeriesPoint,+ SimulationContext,zero_sentinel_series,)from products.alerts.backend.models.alert import AlertConfiguration@@ -32,6 +34,58 @@ ANY_ROW_MAX_ROWS = 50# the head, which truncation never touches, so it has no such limit — use it (with a DESC ORDER BY)# for queries that would otherwise return too many rows.LAST_ROW_MAX_ROWS = MAX_SELECT_RETURNED_ROWS+_DEFAULT_HOGQL_CONFIG = {"type": "HogQLAlertConfig", "evaluation": "last_row"}+++def hogql_config_or_default(raw: dict | None) -> HogQLAlertConfig:+ """Validate a stored SQL alert config, defaulting an absent one to last-row evaluation."""+ return HogQLAlertConfig.model_validate(raw or _DEFAULT_HOGQL_CONFIG)+++def _calculate_rows_and_columns(insight: Insight, team: Any, *, user: Any) -> tuple[list, list[str] | None]:+ """Run a SQL insight and return (rows, column_names) — the fetch-and-validate prologue shared by+ the threshold and detector extractors. A ``None`` result means the query layer swallowed an error+ (raise to avoid a misfire, matching trends); a non-list result is a malformed shape.+ """+ calculation_result = calculate_for_query_based_insight(+ insight,+ team=team,+ execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,+ user=user,+ analytics_props={"source": EventSource.ALERT},+ )+ rows = calculation_result.result+ if rows is None:+ raise RuntimeError(f"No results found for insight with id = {insight.id}")+ if not isinstance(rows, list):+ raise AlertExtractionError(f"SQL alert query returned an unexpected result shape ({type(rows).__name__}).")+ columns = calculation_result.columns if isinstance(calculation_result.columns, list) else None+ column_names = [str(c) for c in columns] if columns else None+ return rows, column_names+++def _check_row_caps(rows: list, evaluation: HogQLAlertEvaluation) -> None:+ """Fail loud on a result the evaluation mode can't trust. last_row reads the tail, which HogQL's+ hard cap can silently truncate (so the last row might not be the real one); any_row would skip a+ breaching row past its cap. first_row reads the head (truncation-immune), so it has no cap. Shared+ by the threshold and detector extractors so the guard can't drift between them.+ """+ if evaluation == HogQLAlertEvaluation.ANY_ROW and len(rows) > ANY_ROW_MAX_ROWS:+ raise AlertExtractionError(+ f"Any-row SQL alerts evaluate at most {ANY_ROW_MAX_ROWS} rows, but the query returned "+ f"{len(rows)} — add a LIMIT or aggregate the query."+ )+ if evaluation == HogQLAlertEvaluation.LAST_ROW and len(rows) >= LAST_ROW_MAX_ROWS:+ raise AlertExtractionError(+ f"Last-row SQL alerts can't trust a result of {len(rows)}+ rows — it may be truncated, so "+ "the last row might not be the real one. Add ORDER BY ... LIMIT, aggregate, or use first-row "+ "evaluation with a newest-first ordering."+ )+++def _value_column_label(column_names: list[str] | None, value_index: int) -> str:+ """Name the evaluated value column, falling back to 'result' when there's no column metadata."""+ return column_names[value_index] if column_names and value_index < len(column_names) else "result"class HogQLExtractor:@@ -68,23 +122,10 @@ class HogQLExtractor:def extract(self, alert: AlertConfiguration, insight: Insight, query: Any) -> ExtractionResult:# ``query`` is unused (Protocol signature): the extractor recomputes via the insight.condition = AlertCondition.model_validate(alert.condition)- config = HogQLAlertConfig.model_validate(alert.config or {"type": "HogQLAlertConfig", "evaluation": "last_row"})+ config = hogql_config_or_default(alert.config)evaluation = config.evaluation- calculation_result = calculate_for_query_based_insight(- insight,- team=alert.team,- execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,- user=None,- analytics_props={"source": EventSource.ALERT},- )- rows = calculation_result.result- # ``None`` (vs an empty list) means the query layer swallowed an error — raise to avoid a- # misfire, matching the trends extractor's handling of a None result.- if rows is None:- raise RuntimeError(f"No results found for insight with alert id = {alert.id}")- if not isinstance(rows, list):- raise AlertExtractionError(f"SQL alert query returned an unexpected result shape ({type(rows).__name__}).")+ rows, column_names = _calculate_rows_and_columns(insight, alert.team, user=alert.created_by)if len(rows) == 0:# No rows means the metric is genuinely 0 this check (matching trends), so a lower# bound can still breach.@@ -96,24 +137,10 @@ class HogQLExtractor:empty_query_result=True,)- # Row caps are checked before column resolution so an oversized result gets the clearer- # "too many rows" error rather than a column-resolution one. last_row reads the tail, which- # a truncated result destroys, so fail loud at the hard cap; first_row reads the head and is- # unaffected, so it has no cap.- if evaluation == HogQLAlertEvaluation.ANY_ROW and len(rows) > ANY_ROW_MAX_ROWS:- raise AlertExtractionError(- f"Any-row SQL alerts evaluate at most {ANY_ROW_MAX_ROWS} rows, but the query returned "- f"{len(rows)} — add a LIMIT or aggregate the query."- )- if evaluation == HogQLAlertEvaluation.LAST_ROW and len(rows) >= LAST_ROW_MAX_ROWS:- raise AlertExtractionError(- f"Last-row SQL alerts can't trust a result of {len(rows)}+ rows — it may be truncated, so "- "the last row might not be the real one. Add ORDER BY ... LIMIT, aggregate, or use first-row "- "evaluation with a newest-first ordering."- )+ # Checked before column resolution so an oversized result gets the clearer "too many rows"+ # error rather than a column-resolution one.+ _check_row_caps(rows, evaluation)- columns = calculation_result.columns if isinstance(calculation_result.columns, list) else None- column_names = [str(c) for c in columns] if columns else Nonevalue_index = _resolve_value_column_index(config.column, column_names, rows)if evaluation == HogQLAlertEvaluation.ANY_ROW:@@ -144,13 +171,12 @@ class HogQLExtractor:raise AlertExtractionError("Relative alerts on SQL insights need at least two rows (current and previous).")points = [SeriesPoint(date=None, value=v) for v in values]- value_column_name = column_names[value_index] if column_names and value_index < len(column_names) else "result"# Label the evaluated row by its label column (the METRIC column shown in the preview),# falling back to the value column name when the result has no distinct label column.label_index = _resolve_label_column_index(config.label_column, column_names, value_index, rows)anchor_row = rows[0] if evaluation == HogQLAlertEvaluation.FIRST_ROW else rows[-1]label_cell = _label_cell(anchor_row, label_index)- series_label = label_cell if label_cell is not None else value_column_name+ series_label = label_cell if label_cell is not None else _value_column_label(column_names, value_index)single = ComparableSeries(label=series_label, points=points, current_index=len(points) - 1)# Surface the label in the breach message only when it's a real label cell — the value-column# fallback would just read "The SQL insight value (value) (...)", which adds nothing.@@ -163,6 +189,98 @@ class HogQLExtractor:)+def extract_hogql_detector_series(+ insight: Insight,+ team: Any,+ config: HogQLAlertConfig,+ detector_config: dict[str, Any],+ *,+ user: Any = None,+) -> ExtractionResult:+ """Build the full ordered value series an anomaly detector scores from a SQL/HogQL insight.++ Shared by the alert-check extractor and the read-only simulation. Unlike trends, a SQL query is+ self-contained — its rows *are* the history, so there's no wider lookback window to refetch; the+ query must return enough rows for the detector's window. Only ``last_row``/``first_row`` apply:+ ``any_row`` rows are unrelated entities, not a time axis, so scoring change across them is+ meaningless. Too few rows to fill the window yields an empty series (uncomputed); an empty result+ yields an empty series flagged ``empty_query_result`` (the metric is genuinely 0).+ """+ if config.evaluation == HogQLAlertEvaluation.ANY_ROW:+ raise AlertExtractionError(+ "Anomaly detection isn't supported for any-row SQL alerts — its rows are unrelated "+ "entities, not a time series. Use last-row or first-row evaluation."+ )++ rows, column_names = _calculate_rows_and_columns(insight, team, user=user)+ if len(rows) == 0:+ return ExtractionResult(+ series=[], is_breakdown=False, subject=_HOGQL_SUBJECT, framed=False, empty_query_result=True+ )+ # last_row scores the tail as the current value, so the same truncation guard the threshold path+ # enforces applies here — a tail truncated at HogQL's hard cap would score the wrong "current" row.+ _check_row_caps(rows, config.evaluation)++ value_index = _resolve_value_column_index(config.column, column_names, rows)+ # The series is the value column across every row, oldest->newest so the detector scores the+ # latest point against its history. first_row results are newest-first, so reverse them.+ from_head = config.evaluation == HogQLAlertEvaluation.FIRST_ROW+ ordered = list(reversed(rows)) if from_head else rows+ # position reports the original result-row number (not the reversed index) for clear error text.+ n = len(rows)+ values = [+ _numeric_cell(row, value_index, position=f"row {n - i if from_head else i + 1}")+ for i, row in enumerate(ordered)+ ]++ # Too few points to score → report uncomputed (None). SQL rows are the series verbatim — unlike+ # trends, there's no incomplete-interval drop to offset — so the detector's own minimum is the+ # exact cutoff. (Trends adds +1 to compensate for the dropped interval; SQL must not, or a query+ # returning exactly the detector's minimum would be wrongly rejected as "not enough data".)+ min_samples = _compute_min_samples_for_detector(detector_config)+ if len(values) < min_samples:+ return ExtractionResult(series=[], is_breakdown=False, subject=_HOGQL_SUBJECT, framed=False)++ # Score only the most recent window the detector needs (current stays last). A SQL query can+ # return a large result, and detectors like KNN/LOF/OCSVM train on every point handed in — so+ # without this bound a big result set would make alert workers train on tens of thousands of+ # points each check. The trends path bounds the same way via its date-range fetch.+ values = values[-min_samples:]++ # Label the evaluated (current) row by its label column — same as the threshold path — so an+ # anomaly breach names e.g. "Burn rate 24h" rather than the bare value-column name. The current+ # row is the original latest row (head for first_row, tail otherwise), regardless of the slice.+ label_index = _resolve_label_column_index(config.label_column, column_names, value_index, rows)+ anchor_row = rows[0] if from_head else rows[-1]+ label_cell = _label_cell(anchor_row, label_index)+ series_label = label_cell if label_cell is not None else _value_column_label(column_names, value_index)++ points = [SeriesPoint(date=None, value=v) for v in values]+ single = ComparableSeries(label=series_label, points=points, current_index=len(points) - 1)+ return ExtractionResult(series=[single], is_breakdown=False, subject=_HOGQL_SUBJECT, framed=False)+++class HogQLDetectorExtractor:+ """Detector-path extractor for SQL/HogQL insights — thin alert adapter over+ ``extract_hogql_detector_series`` (which the read-only simulation also uses), mirroring how+ ``TrendsDetectorExtractor`` wraps ``extract_detector_series``.+ """++ def extract(self, alert: AlertConfiguration, insight: Insight, query: Any) -> ExtractionResult:+ detector_config = alert.detector_config+ if not detector_config:+ raise ValueError("HogQLDetectorExtractor requires detector_config — dispatcher invariant violated")+ config = hogql_config_or_default(alert.config)+ return extract_hogql_detector_series(insight, alert.team, config, detector_config, user=alert.created_by)++ def simulate(self, insight: Insight, query: object, ctx: SimulationContext) -> tuple[ExtractionResult, str | None]:+ # SQL rows are their own series, so there's no chart interval — return None alongside.+ result = extract_hogql_detector_series(+ insight, ctx.team, hogql_config_or_default(ctx.config), ctx.detector_config, user=ctx.user+ )+ return result, None++def _resolve_value_column_index(configured: str | None, column_names: list[str] | None, rows: list) -> int:"""Pick the result column the alert evaluates.diff --git a/products/alerts/backend/evaluation/test/test_hogql_detector.py b/products/alerts/backend/evaluation/test/test_hogql_detector.pynew file mode 100644index 000000000000..9d52bddfec31--- /dev/null+++ b/products/alerts/backend/evaluation/test/test_hogql_detector.py@@ -0,0 +1,147 @@+import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import HogQLAlertConfig++from posthog.tasks.alerts.detector import _compute_min_samples_for_detector++from products.alerts.backend.evaluation.contract import AlertExtractionError+from products.alerts.backend.evaluation.detector import evaluate_with_detector+from products.alerts.backend.evaluation.hogql import (+ LAST_ROW_MAX_ROWS,+ HogQLDetectorExtractor,+ extract_hogql_detector_series,+)++CALC_PATH = "products.alerts.backend.evaluation.hogql.calculate_for_query_based_insight"+ZSCORE = {"type": "zscore", "threshold": 0.9, "window": 5}++# zscore floors min-samples at 31, so STABLE_HISTORY is exactly the detector minimum. Non-zero+# variance gives the detector a baseline to flag a spike against.+STABLE_HISTORY = [round(1.0 + (i % 3) * 0.1, 2) for i in range(31)]+_LATEST = len(STABLE_HISTORY) # index of the appended (evaluated) row in [*STABLE_HISTORY, latest]+++def _alert(rows_config: dict | None = None, detector_config: dict | None = ZSCORE) -> MagicMock:+ alert = MagicMock()+ alert.config = {"type": "HogQLAlertConfig", "evaluation": "last_row", **(rows_config or {})}+ alert.detector_config = detector_config+ return alert+++def _extract(values, *, columns=None, rows_config=None, detector_config=ZSCORE):+ rows = [[v] for v in values] if columns is None else values+ with patch(CALC_PATH) as calc:+ calc.return_value = MagicMock(result=rows, columns=columns)+ return HogQLDetectorExtractor().extract(_alert(rows_config, detector_config), MagicMock(), MagicMock())+++ "latest,expect_anomaly",+ [+ (100.0, True), # a spike far outside the stable baseline fires+ (1.1, False), # a value within the baseline range does not+ ],+)+def test_scores_the_latest_value(latest, expect_anomaly):+ evaluation = evaluate_with_detector(_extract([*STABLE_HISTORY, latest]), ZSCORE)+ assert evaluation.value == latest+ assert bool(evaluation.breaches) is expect_anomaly+ if expect_anomaly:+ assert evaluation.breaches and "Anomaly detected" in evaluation.breaches[0]+++def test_large_result_is_bounded_to_the_detector_window():+ # A big SQL result must not train the detector on every point — only the most recent window+ # it needs (the latest point is preserved as "current"), so workers can't be made to score+ # tens of thousands of points each check.+ expected = _compute_min_samples_for_detector(ZSCORE)+ row_count = 501+ assert expected < row_count # guard: the fixture must exceed the window or this test is moot+ result = _extract([float(i % 5) for i in range(row_count - 1)] + [999.0])+ assert len(result.series[0].points) == expected # bounded to the window, not the full result+ assert result.series[0].points[-1].value == 999.0 # latest row preserved as current+++def test_last_row_truncation_guard_rejects_a_capped_result():+ # last_row scores the tail; a result at HogQL's hard cap may be truncated, so the detector path+ # must fail loud just like the threshold extractor rather than score a wrong "current" row.+ with pytest.raises(AlertExtractionError, match="may be truncated"):+ _extract([[1.0]] * LAST_ROW_MAX_ROWS, columns=["value"])+++def test_first_row_reverses_so_the_head_is_current():+ # first_row results are newest-first; the spike at the head must be scored as the current value.+ result = _extract([100.0, *STABLE_HISTORY], rows_config={"evaluation": "first_row"})+ evaluation = evaluate_with_detector(result, ZSCORE)+ assert evaluation.value == 100.0+ assert evaluation.breaches and "Anomaly detected" in evaluation.breaches[0]+++def test_exactly_the_detector_minimum_is_scored():+ # A result with exactly the detector's minimum row count must be scored, not rejected as "not+ # enough data". Regression: the cutoff previously required one row more than the detector needs.+ minimum = _compute_min_samples_for_detector(ZSCORE)+ rows = [*STABLE_HISTORY[: minimum - 1], 100.0] # exactly `minimum` rows, spike last+ assert len(rows) == minimum+ evaluation = evaluate_with_detector(_extract(rows), ZSCORE)+ assert evaluation.value == 100.0+ assert evaluation.breaches and "Anomaly detected" in evaluation.breaches[0]+++def test_one_row_below_the_detector_minimum_is_uncomputed():+ minimum = _compute_min_samples_for_detector(ZSCORE)+ result = _extract(STABLE_HISTORY[: minimum - 1]) # one short of the minimum → uncomputed+ assert result.series == []+ evaluation = evaluate_with_detector(result, ZSCORE)+ assert evaluation.value is None+ assert evaluation.breaches == []+++def test_threshold_detector_scores_a_single_row():+ # The threshold detector needs only one point, so a one-row SQL result must score and can fire —+ # not be silently rejected. Regression for the same off-by-one at the minimum=1 extreme.+ config = {"type": "threshold", "upper_bound": 10.0}+ result = _extract([[500.0]], columns=["value"], detector_config=config)+ assert len(result.series[0].points) == 1+ evaluation = evaluate_with_detector(result, config)+ assert evaluation.value == 500.0+ assert evaluation.breaches and "Anomaly detected" in evaluation.breaches[0]+++def test_empty_result_is_zero():+ result = _extract([])+ assert result.empty_query_result is True+ evaluation = evaluate_with_detector(result, ZSCORE)+ assert evaluation.value == 0+++def test_any_row_not_supported():+ with pytest.raises(AlertExtractionError, match="any-row"):+ _extract([*STABLE_HISTORY, 100.0], rows_config={"evaluation": "any_row"})+++# The evaluated (latest) row's label, like the threshold path: explicit label_column, else the first+# non-evaluated column, else the value-column name (never "row N").+ "columns,rows_config,row_fn,expected_label",+ [+ (["metric", "value"], None, lambda i, v: [f"m{i}", v], f"m{_LATEST}"), # first non-evaluated column+ (["id", "note", "value"], {"label_column": "id"}, lambda i, v: [f"r{i}", "x", v], f"r{_LATEST}"), # explicit+ (["value"], None, lambda i, v: [v], "value"), # single column → value-column name+ ],+)+def test_labels_evaluated_row(columns, rows_config, row_fn, expected_label):+ rows = [row_fn(i, v) for i, v in enumerate([*STABLE_HISTORY, 100.0])]+ result = _extract(rows, columns=columns, rows_config=rows_config)+ assert result.series[0].label == expected_label+++def test_extract_hogql_detector_series_is_alert_less():+ # The simulation reuses the alert-less builder directly (no AlertConfiguration).+ config = HogQLAlertConfig(type="HogQLAlertConfig", evaluation="last_row")+ with patch(CALC_PATH) as calc:+ calc.return_value = MagicMock(result=[[v] for v in [*STABLE_HISTORY, 100.0]], columns=None)+ result = extract_hogql_detector_series(MagicMock(), MagicMock(), config, ZSCORE, user=None)+ assert len(result.series[0].points) == _compute_min_samples_for_detector(ZSCORE) # bounded to the minimum+ assert evaluate_with_detector(result, ZSCORE).value == 100.0diff --git a/products/alerts/backend/evaluation/validation.py b/products/alerts/backend/evaluation/validation.pyindex 52407cedec5d..8618961c6f6c 100644--- a/products/alerts/backend/evaluation/validation.py+++ b/products/alerts/backend/evaluation/validation.py@@ -86,6 +86,10 @@ def _validate_hogql_alert_config(ctx: _AlertConfigValidationContext) -> None:):# Rows are entities in any_row mode, not a time axis — relative change is meaningless.raise ValueError("Any-row SQL alerts only support absolute value conditions")+ if ctx.detector_config is not None and parsed.evaluation == HogQLAlertEvaluation.ANY_ROW:+ # Same reason anomaly detection rejects any_row at evaluation time: its rows aren't a time+ # series. Reject at config time so the alert can't be saved only to fail every check.+ raise ValueError("Anomaly detection isn't supported for any-row SQL alerts — use last-row or first-row")_validate_condition_threshold_compatibility(ctx.parsed_condition, ctx.threshold_config)if ctx.require_threshold_bounds and ctx.detector_config is None:validate_threshold_bounds_required(ctx.threshold_config)@@ -181,7 +185,7 @@ def validate_alert_config(# alert would raise at evaluation time, so reject it here at configuration time. Reading the# dispatcher's registry directly keeps the config-time and evaluation-time views from drifting.if detector_config is not None and kind not in DETECTOR_EXTRACTORS:- raise ValueError("Anomaly detection alerts are only supported for trends insights")+ raise ValueError(f"Anomaly detection alerts aren't supported for {kind} insights")validator = _ALERT_CONFIG_VALIDATORS.get(config_type) if isinstance(config_type, str) else Noneif validator is None:diff --git a/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx b/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsxindex f8b9b3ce1594..3f8eeba01351 100644--- a/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx+++ b/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx@@ -89,9 +89,13 @@ export function HogQLDefinitionFields({value={value ?? 'last_row'}onChange={(newValue) => {onChange(newValue)- // Any-row mode checks unrelated rows — a relative condition is meaningless.+ // Any-row rows are unrelated entities, not a time series: a relative+ // condition has no prior value, and anomaly detection has nothing to+ // score. Reset both so we can't land in an unsupported any-row+detector+ // (or any-row+relative) state.if (newValue === 'any_row') {onSetAlertFormValue('condition', { type: AlertConditionType.ABSOLUTE_VALUE })+ onSetAlertFormValue('detector_config', null)}}}options={[diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.tsindex 08fee0eb14ab..f2c5bd845bb0 100644--- a/products/alerts/frontend/generated/api.schemas.ts+++ b/products/alerts/frontend/generated/api.schemas.ts@@ -622,13 +622,15 @@ export interface AlertSimulateApi {insight: number/** Detector configuration to simulate. */detector_config: DetectorConfigApi- /** Zero-based index of the series to analyze. */+ /** Zero-based index of the series to analyze (trends insights only). */series_index?: number/**- * Relative date string for how far back to simulate (e.g. '-24h', '-30d', '-4w'). If not provided, uses the detector's minimum required samples.+ * Relative date string for how far back to simulate (e.g. '-24h', '-30d', '-4w'). If not provided, uses the detector's minimum required samples. Trends insights only — a SQL query's own rows are the series.* @nullable*/date_from?: string | null+ /** Per-insight-kind alert config. For SQL insights, selects the evaluated column and read direction (last_row/first_row) so the preview matches the alert; ignored for trends. */+ config?: AlertConfigUnionApi | null}export type AlertSimulateResponseApiSubDetectorScoresItem = { [key: string]: unknown }diff --git a/products/alerts/frontend/generated/api.zod.ts b/products/alerts/frontend/generated/api.zod.tsindex d3581bd8f80d..58951ac5cc52 100644--- a/products/alerts/frontend/generated/api.zod.ts+++ b/products/alerts/frontend/generated/api.zod.ts@@ -50,6 +50,8 @@ export const alertsSimulateCreateBodyDetectorConfigOneOneoneTypeDefault = `lof`export const alertsSimulateCreateBodyDetectorConfigOneOnetwoTypeDefault = `ocsvm`export const alertsSimulateCreateBodyDetectorConfigOneOnethreeTypeDefault = `pca`export const alertsSimulateCreateBodySeriesIndexDefault = 0+export const alertsSimulateCreateBodyConfigOneOneTypeDefault = `TrendsAlertConfig`+export const alertsSimulateCreateBodyConfigOneTwoTypeDefault = `HogQLAlertConfig`export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({insight: zod.number().describe('Insight ID to simulate the detector on.'),@@ -1062,11 +1064,55 @@ export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({series_index: zod.number().default(alertsSimulateCreateBodySeriesIndexDefault)- .describe('Zero-based index of the series to analyze.'),+ .describe('Zero-based index of the series to analyze (trends insights only).'),date_from: zod.string().nullish().describe(- "Relative date string for how far back to simulate (e.g. '-24h', '-30d', '-4w'). If not provided, uses the detector's minimum required samples."+ "Relative date string for how far back to simulate (e.g. '-24h', '-30d', '-4w'). If not provided, uses the detector's minimum required samples. Trends insights only — a SQL query's own rows are the series."+ ),+ config: zod+ .union([+ zod+ .union([+ zod.object({+ check_ongoing_interval: zod+ .union([zod.boolean(), zod.null()])+ .optional()+ .describe(+ 'When true, evaluate the current (still incomplete) time interval in addition to completed ones.'+ ),+ series_index: zod+ .number()+ .describe("Zero-based index of the series in the insight's query to monitor."),+ type: zod.enum(['TrendsAlertConfig']).default(alertsSimulateCreateBodyConfigOneOneTypeDefault),+ }),+ zod.object({+ column: zod+ .union([zod.string(), zod.null()])+ .optional()+ .describe(+ 'Name of the result column to evaluate. When unset, the single numeric column is used (an error if the result has more than one numeric column).'+ ),+ evaluation: zod+ .enum(['last_row', 'first_row', 'any_row'])+ .describe('How to read the result rows — an explicit choice, no implicit default.'),+ label_column: zod+ .union([zod.string(), zod.null()])+ .optional()+ .describe(+ 'Column whose value labels the evaluated row(s) in breach messages: every row in `any_row` mode, or the single evaluated row in `last_row`\/`first_row`. When unset, the first non-evaluated column is used, falling back to the row number (any_row) or the value column name (last_row\/first_row).'+ ),+ type: zod.enum(['HogQLAlertConfig']).default(alertsSimulateCreateBodyConfigOneTwoTypeDefault),+ }),+ ])+ .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.'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Per-insight-kind alert config. For SQL insights, selects the evaluated column and read direction (last_row\/first_row) so the preview matches the alert; ignored for trends.'),})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 19fff8f64148..175394a7f926 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -9078,13 +9078,15 @@ export namespace Schemas {insight: number;/** Detector configuration to simulate. */detector_config: DetectorConfig;- /** Zero-based index of the series to analyze. */+ /** Zero-based index of the series to analyze (trends insights only). */series_index?: number;/**- * Relative date string for how far back to simulate (e.g. '-24h', '-30d', '-4w'). If not provided, uses the detector's minimum required samples.+ * Relative date string for how far back to simulate (e.g. '-24h', '-30d', '-4w'). If not provided, uses the detector's minimum required samples. Trends insights only — a SQL query's own rows are the series.* @nullable*/date_from?: string | null;+ /** Per-insight-kind alert config. For SQL insights, selects the evaluated column and read direction (last_row/first_row) so the preview matches the alert; ignored for trends. */+ config?: AlertConfigUnion | null;}export type AlertSimulateResponseSubDetectorScoresItem = { [key: string]: unknown };diff --git a/services/mcp/src/generated/alerts/api.ts b/services/mcp/src/generated/alerts/api.tsindex 93b4532f051f..7b22479234dc 100644--- a/services/mcp/src/generated/alerts/api.ts+++ b/services/mcp/src/generated/alerts/api.ts@@ -2612,6 +2612,8 @@ export const alertsSimulateCreateBodyDetectorConfigOneOneoneTypeDefault = `lof`export const alertsSimulateCreateBodyDetectorConfigOneOnetwoTypeDefault = `ocsvm`export const alertsSimulateCreateBodyDetectorConfigOneOnethreeTypeDefault = `pca`export const alertsSimulateCreateBodySeriesIndexDefault = 0+export const alertsSimulateCreateBodyConfigOneOneTypeDefault = `TrendsAlertConfig`+export const alertsSimulateCreateBodyConfigOneTwoTypeDefault = `HogQLAlertConfig`export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({insight: zod.number().describe('Insight ID to simulate the detector on.'),@@ -3624,11 +3626,55 @@ export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({series_index: zod.number().default(alertsSimulateCreateBodySeriesIndexDefault)- .describe('Zero-based index of the series to analyze.'),+ .describe('Zero-based index of the series to analyze (trends insights only).'),date_from: zod.string().nullish().describe(- "Relative date string for how far back to simulate (e.g. '-24h', '-30d', '-4w'). If not provided, uses the detector's minimum required samples."+ "Relative date string for how far back to simulate (e.g. '-24h', '-30d', '-4w'). If not provided, uses the detector's minimum required samples. Trends insights only — a SQL query's own rows are the series."+ ),+ config: zod+ .union([+ zod+ .union([+ zod.object({+ check_ongoing_interval: zod+ .union([zod.boolean(), zod.null()])+ .optional()+ .describe(+ 'When true, evaluate the current (still incomplete) time interval in addition to completed ones.'+ ),+ series_index: zod+ .number()+ .describe("Zero-based index of the series in the insight's query to monitor."),+ type: zod.enum(['TrendsAlertConfig']).default(alertsSimulateCreateBodyConfigOneOneTypeDefault),+ }),+ zod.object({+ column: zod+ .union([zod.string(), zod.null()])+ .optional()+ .describe(+ 'Name of the result column to evaluate. When unset, the single numeric column is used (an error if the result has more than one numeric column).'+ ),+ evaluation: zod+ .enum(['last_row', 'first_row', 'any_row'])+ .describe('How to read the result rows — an explicit choice, no implicit default.'),+ label_column: zod+ .union([zod.string(), zod.null()])+ .optional()+ .describe(+ 'Column whose value labels the evaluated row(s) in breach messages: every row in `any_row` mode, or the single evaluated row in `last_row`/`first_row`. When unset, the first non-evaluated column is used, falling back to the row number (any_row) or the value column name (last_row/first_row).'+ ),+ type: zod.enum(['HogQLAlertConfig']).default(alertsSimulateCreateBodyConfigOneTwoTypeDefault),+ }),+ ])+ .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.'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Per-insight-kind alert config. For SQL insights, selects the evaluated column and read direction (last_row/first_row) so the preview matches the alert; ignored for trends.'),})diff --git a/services/mcp/src/tools/generated/alerts.ts b/services/mcp/src/tools/generated/alerts.tsindex 8808e002985c..70a6efbe5ab4 100644--- a/services/mcp/src/tools/generated/alerts.ts+++ b/services/mcp/src/tools/generated/alerts.ts@@ -133,6 +133,9 @@ const alertSimulate = (): ToolBase<typeof AlertSimulateSchema, Schemas.AlertSimuif (params.date_from !== undefined) {body['date_from'] = params.date_from}+ if (params.config !== undefined) {+ body['config'] = params.config+ }const result = await context.api.request<Schemas.AlertSimulateResponse>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/alerts/simulate/`,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.jsonindex 489641a9d1f8..5a432feca0b0 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json@@ -1,6 +1,83 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {+ "config": {+ "anyOf": [+ {+ "anyOf": [+ {+ "properties": {+ "check_ongoing_interval": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "description": "When true, evaluate the current (still incomplete) time interval in addition to completed ones."+ },+ "series_index": {+ "description": "Zero-based index of the series in the insight's query to monitor.",+ "type": "number"+ },+ "type": {+ "default": "TrendsAlertConfig",+ "enum": ["TrendsAlertConfig"],+ "type": "string"+ }+ },+ "required": ["series_index"],+ "type": "object"+ },+ {+ "properties": {+ "column": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Name of the result column to evaluate. When unset, the single numeric column is used (an error if the result has more than one numeric column)."+ },+ "evaluation": {+ "description": "How to read the result rows — an explicit choice, no implicit default.",+ "enum": ["last_row", "first_row", "any_row"],+ "type": "string"+ },+ "label_column": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Column whose value labels the evaluated row(s) in breach messages: every row in `any_row` mode, or the single evaluated row in `last_row`/`first_row`. When unset, the first non-evaluated column is used, falling back to the row number (any_row) or the value column name (last_row/first_row)."+ },+ "type": {+ "default": "HogQLAlertConfig",+ "enum": ["HogQLAlertConfig"],+ "type": "string"+ }+ },+ "required": ["evaluation"],+ "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."+ },+ {+ "type": "null"+ }+ ],+ "description": "Per-insight-kind alert config. For SQL insights, selects the evaluated column and read direction (last_row/first_row) so the preview matches the alert; ignored for trends."+ },"date_from": {"anyOf": [{@@ -10,7 +87,7 @@"type": "null"}],- "description": "Relative date string for how far back to simulate (e.g. '-24h', '-30d', '-4w'). If not provided, uses the detector's minimum required samples."+ "description": "Relative date string for how far back to simulate (e.g. '-24h', '-30d', '-4w'). If not provided, uses the detector's minimum required samples. Trends insights only — a SQL query's own rows are the series."},"detector_config": {"anyOf": [@@ -2075,7 +2152,7 @@},"series_index": {"default": 0,- "description": "Zero-based index of the series to analyze.",+ "description": "Zero-based index of the series to analyze (trends insights only).","type": "number"}},