:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(alerts): fail loud on incomplete SQL detector history and disable capped alerts (#103016)
Vasco de Krijgerd144cfdfd038
diff --git a/posthog/caching/calculate_results.py b/posthog/caching/calculate_results.pyindex 7f12b21be336..d278a53754a8 100644--- a/posthog/caching/calculate_results.py+++ b/posthog/caching/calculate_results.py@@ -88,6 +88,7 @@ def calculate_for_query_based_insight(cache_age_seconds: Optional[int] = None,analytics_props: Optional[AnalyticsProps] = None,allow_raw_results: bool = False,+ limit_context: LimitContext = LimitContext.QUERY_ASYNC,) -> "InsightResult":from posthog.caching.insight_result import InsightResult, NothingInCacheResult@@ -121,8 +122,7 @@ def calculate_for_query_based_insight(user_access_control=user_access_control,insight_id=insight.pk,dashboard_id=dashboard.pk if dashboard else None,- # QUERY_ASYNC provides extended max execution time for insight queries- limit_context=LimitContext.QUERY_ASYNC,+ limit_context=limit_context,cache_age_seconds=cache_age_seconds,analytics_props=analytics_props,allow_raw_results=allow_raw_results,diff --git a/posthog/hogql/constants.py b/posthog/hogql/constants.pyindex e91e93d87034..51e999523110 100644--- a/posthog/hogql/constants.py+++ b/posthog/hogql/constants.py@@ -89,6 +89,7 @@ type HogQLParserBackend = Literal["cpp-json", "rust-json", "rust-py"]class LimitContext(StrEnum):QUERY = "query"QUERY_ASYNC = "query_async"+ SQL_ALERT = "sql_alert"EXPORT = "export"COHORT_CALCULATION = "cohort_calculation"HEATMAPS = "heatmaps"@@ -103,6 +104,7 @@ def get_max_limit_for_context(limit_context: LimitContext) -> int:if limit_context in (LimitContext.QUERY,LimitContext.QUERY_ASYNC,+ LimitContext.SQL_ALERT,):return MAX_SELECT_RETURNED_ROWS # 50kelif limit_context == LimitContext.EXPORT:@@ -129,7 +131,7 @@ def get_default_limit_for_context(limit_context: LimitContext) -> int:"""Limit used if no limit is provided"""if limit_context == LimitContext.EXPORT:return CSV_EXPORT_LIMIT- elif limit_context in (LimitContext.QUERY, LimitContext.QUERY_ASYNC):+ elif limit_context in (LimitContext.QUERY, LimitContext.QUERY_ASYNC, LimitContext.SQL_ALERT):return DEFAULT_RETURNED_ROWS # 100elif limit_context == LimitContext.POSTHOG_AI:return DEFAULT_POSTHOG_AI_RETURNED_ROWS # 100diff --git a/posthog/hogql/query.py b/posthog/hogql/query.pyindex 1a83a937f11a..873c70f537cb 100644--- a/posthog/hogql/query.py+++ b/posthog/hogql/query.py@@ -358,6 +358,7 @@ class HogQLQueryExecutor:LimitContext.COHORT_CALCULATION,LimitContext.NOTEBOOK_MATERIALIZE,LimitContext.QUERY_ASYNC,+ LimitContext.SQL_ALERT,LimitContext.SAVED_QUERY,LimitContext.RETENTION,LimitContext.POSTHOG_AI,@@ -634,6 +635,7 @@ class HogQLQueryExecutor:LimitContext.COHORT_CALCULATION,LimitContext.NOTEBOOK_MATERIALIZE,LimitContext.QUERY_ASYNC,+ LimitContext.SQL_ALERT,LimitContext.SAVED_QUERY,LimitContext.RETENTION,LimitContext.POSTHOG_AI,diff --git a/posthog/hogql_queries/hogql_query_runner.py b/posthog/hogql_queries/hogql_query_runner.pyindex 6245593265a3..6225db4901ca 100644--- a/posthog/hogql_queries/hogql_query_runner.py+++ b/posthog/hogql_queries/hogql_query_runner.py@@ -16,7 +16,7 @@ from posthog.schema import ()from posthog.hogql import ast-from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.constants import HogQLGlobalSettings, LimitContextfrom posthog.hogql.database.schema.activity_log_visibility import activity_log_visibility_policy_versionfrom posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERROR, get_direct_connection_sourcefrom posthog.hogql.errors import ExposedHogQLError@@ -275,7 +275,9 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):validate_user_query(query, team=self.team)paginator = None- if isinstance(query, ast.SelectQuery) and not query.limit:+ if self.limit_context == LimitContext.SQL_ALERT:+ paginator = HogQLHasMorePaginator.from_alert_query(query, limit_context=self.limit_context)+ elif isinstance(query, ast.SelectQuery) and not query.limit:paginator = HogQLHasMorePaginator.from_limit_context(limit_context=self.limit_context)func = cast(Callable[..., HogQLQueryResponse],diff --git a/posthog/hogql_queries/paginators.py b/posthog/hogql_queries/paginators.pyindex 2d5b9a68d7a6..69d0161fdff6 100644--- a/posthog/hogql_queries/paginators.py+++ b/posthog/hogql_queries/paginators.py@@ -15,6 +15,21 @@ from posthog.hogql.constants import (from posthog.hogql.query import execute_hogql_query+def get_query_limit(query: ast.SelectQuery | ast.SelectSetQuery) -> int | None:+ """Return a constant row limit, or None when the query has no usable one.++ A percentage limit resolves to a row count only after the result size is known, and WITH TIES+ can return more rows than the stated limit, so neither gives a hard cap a caller could pad or+ compare row counts against.+ """+ if query.limit_percent or query.limit_with_ties:+ return None+ limit = query.limit+ if isinstance(limit, ast.Constant) and type(limit.value) is int and limit.value >= 0:+ return limit.value+ return None++class HogQLHasMorePaginator:"""Paginator that fetches one more result than requested to determine if there are more results.@@ -39,6 +54,25 @@ class HogQLHasMorePaginator:limit = min(max_rows, default_rows if (limit is None or limit <= 0) else limit)return cls(limit=limit, offset=offset, limit_context=limit_context)+ @classmethod+ def from_alert_query(+ cls, query: ast.SelectQuery | ast.SelectSetQuery, *, limit_context: LimitContext+ ) -> "HogQLHasMorePaginator | None":+ if not isinstance(query, ast.SelectQuery) or query.limit_percent or query.limit_with_ties:+ return None+ limit = get_query_limit(query) if query.limit is not None else get_default_limit_for_context(limit_context)+ if limit is None or limit <= 0:+ return None+ # The extra probe row must fit under the execution cap to prove completeness.+ if limit >= get_max_limit_for_context(limit_context):+ return None+ offset = query.offset+ if offset is None:+ return cls(limit=limit, offset=None, limit_context=limit_context)+ if not isinstance(offset, ast.Constant) or type(offset.value) is not int or offset.value < 0:+ return None+ return cls(limit=limit, offset=offset.value, limit_context=limit_context)+def paginate(self, query: Union[ast.SelectQuery, ast.SelectSetQuery]) -> Union[ast.SelectQuery, ast.SelectSetQuery]:if isinstance(query, ast.SelectQuery):query.limit = ast.Constant(value=self.limit + 1)diff --git a/posthog/hogql_queries/test/test_hogql_query_runner.py b/posthog/hogql_queries/test/test_hogql_query_runner.pyindex 417afa8b2e23..4fced43acdf7 100644--- a/posthog/hogql_queries/test/test_hogql_query_runner.py+++ b/posthog/hogql_queries/test/test_hogql_query_runner.py@@ -19,6 +19,7 @@ from posthog.schema import ()from posthog.hogql import ast+from posthog.hogql.constants import LimitContextfrom posthog.hogql.errors import ExposedHogQLError, QueryErrorfrom posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.user_query_validator import HOGQL_PERSONAL_API_KEY_OFFSET_ALLOWED_FLAG, OFFSET_NOT_ALLOWED_MESSAGE@@ -123,6 +124,20 @@ class TestHogQLQueryRunner(ClickhouseTestMixin, APIBaseTest):self.assertEqual(len(response.results), 5)self.assertNotIn("hasMore", response)+ @parameterized.expand([(3, False), (4, True)])+ def test_alert_explicit_limit_probes_one_extra_row(self, row_count, has_more):+ query = HogQLQuery(query=f"SELECT arrayJoin(range({row_count + 2})) AS value ORDER BY value LIMIT 3 OFFSET 2")+ runner = HogQLQueryRunner(query=query, team=self.team, limit_context=LimitContext.SQL_ALERT)+ normal = HogQLQueryRunner(query=query, team=self.team, limit_context=LimitContext.QUERY_ASYNC)+ assert runner.get_cache_key() != normal.get_cache_key()+ response = runner.calculate()+ assert response.results == [(2,), (3,), (4,)]+ assert response.hasMore is has_more+ normal_response = normal.calculate()+ assert normal_response.results == response.results+ assert normal_response.hasMore is None+ assert query.query.endswith("LIMIT 3 OFFSET 2")+def test_hogql_query_filters(self):runner = self._create_runner(HogQLQuery(diff --git a/posthog/hogql_queries/test/test_paginators.py b/posthog/hogql_queries/test/test_paginators.pyindex 55173e357a16..1eaeb29a7327 100644--- a/posthog/hogql_queries/test/test_paginators.py+++ b/posthog/hogql_queries/test/test_paginators.py@@ -5,6 +5,10 @@ from typing import castfrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_eventsfrom unittest.mock import MagicMock, patch+from django.test import SimpleTestCase++from parameterized import parameterized+from posthog.schema import ActorsQuery, PersonPropertyFilter, PropertyOperatorfrom posthog.hogql.ast import And, CompareOperation, Constant, SelectQuery@@ -547,3 +551,38 @@ class TestHogQLCursorPaginator(ClickhouseTestMixin, APIBaseTest):self.assertEqual(paginator.secondary_sort_field, "uuid")self.assertEqual(paginator.order_field, "timestamp")+++class TestAlertPaginator(SimpleTestCase):+ @parameterized.expand(+ [+ ("SELECT 1 LIMIT {n}",),+ ("SELECT 1 LIMIT 0",),+ ("SELECT 1 LIMIT 50000",),+ ("SELECT 1 LIMIT 3 OFFSET {n}",),+ ("SELECT 1 UNION ALL SELECT 2",),+ ("SELECT 1 ORDER BY 1 LIMIT 3 WITH TIES",),+ ]+ )+ def test_unsupported_limits_do_not_claim_completeness(self, sql):+ # None means the runner attaches no paginator, has_more stays unset, and the alert path+ # raises its retryable "could not confirm the query returned every row" error with the+ # fix in the message. The alert stays enabled.+ assert HogQLHasMorePaginator.from_alert_query(parse_select(sql), limit_context=LimitContext.SQL_ALERT) is None++ def test_only_the_outer_limit_is_changed(self):+ query = cast(+ SelectQuery, parse_select("SELECT value FROM (SELECT 1 AS value LIMIT 2) ORDER BY value LIMIT 3 OFFSET 1")+ )+ paginator = HogQLHasMorePaginator.from_alert_query(query, limit_context=LimitContext.SQL_ALERT)+ assert paginator is not None+ paginated = cast(SelectQuery, paginator.paginate(query))+ outer_limit = paginated.limit+ assert outer_limit == Constant(value=4), "outer LIMIT 3 gains the +1 probe row"+ assert paginated.offset == Constant(value=1), "outer OFFSET is preserved"+ assert paginated.select_from is not None+ subquery = paginated.select_from.table+ assert isinstance(subquery, SelectQuery)+ inner_limit = subquery.limit+ assert isinstance(inner_limit, Constant)+ assert inner_limit.value == 2, "the subquery's own LIMIT is left untouched"diff --git a/posthog/tasks/alerts/test/test_detector_breakdowns.py b/posthog/tasks/alerts/test/test_detector_breakdowns.pyindex a64d61e2b3c1..80793b7d06e9 100644--- a/posthog/tasks/alerts/test/test_detector_breakdowns.py+++ b/posthog/tasks/alerts/test/test_detector_breakdowns.py@@ -415,7 +415,7 @@ class TestSimulateDetectorBreakdowns:# 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"])+ mock_calc.return_value = MagicMock(result=rows, columns=["value"], has_more=False)insight = MagicMock(spec=Insight)insight.query = {"kind": "HogQLQuery", "query": "SELECT value FROM events"}diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.pyindex 5a040096b9a1..152c5f43519b 100644--- a/posthog/tasks/alerts/utils.py+++ b/posthog/tasks/alerts/utils.py@@ -654,6 +654,16 @@ def disable_invalid_alert(as an exception. Returns the recorded ERRORED AlertCheck so callers can reference it."""logger.warning("check_alert.auto_disabling", alert_id=alert.id, reason=reason)+ ph_background_capture()(+ distinct_id=str(alert.id),+ event="alert auto disabled",+ properties={+ "team_id": alert.team_id,+ "alert_id": str(alert.id),+ "error_code": error_code,+ "reason": reason,+ },+ )state_fields = apply_invalid_configuration(alert)alert.last_checked_at = datetime.now(UTC)alert.save(update_fields=[*state_fields, "last_checked_at"])diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.pyindex d52afa0880a2..132b7f88ed98 100644--- a/posthog/temporal/alerts/activities.py+++ b/posthog/temporal/alerts/activities.py@@ -59,7 +59,7 @@ from posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.metrics import get_metric_meterfrom products.alerts.backend.evaluation import check_alert_for_insight-from products.alerts.backend.evaluation.contract import AlertExtractionError+from products.alerts.backend.evaluation.contract import AlertDataUnavailableError, AlertExtractionErrorfrom products.alerts.backend.evaluation.validation import validate_alert_config, validate_alert_insight_queryfrom products.alerts.backend.facade.api import (LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,@@ -369,6 +369,8 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRerecord_ai_detector_check_outcome("evaluated")except CH_TRANSIENT_ERRORS:raise+ except AlertDataUnavailableError as err:+ error = {"message": str(err)}except LLMDetectorUnavailableError:# An LLM detector that couldn't reach a verdict must not resolve to "not firing":# re-raise so the retry policy gets another attempt. Once the attempts run out thediff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_tools.py b/posthog/temporal/tests/ai/test_anomaly_investigation_tools.pyindex cee9e1ed3507..4ca5178ce695 100644--- a/posthog/temporal/tests/ai/test_anomaly_investigation_tools.py+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_tools.py@@ -213,6 +213,7 @@ def test_run_detector_simulation_scores_the_configured_column_of_a_multi_numericmock_calculate.return_value = InsightResult(result=rows,columns=["day", "failure_rate_pct", "run_count"],+ has_more=False,timezone="UTC",last_refresh=None,cache_key="",diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.pyindex ac351e4bbb92..4dd7c3070abe 100644--- a/posthog/temporal/tests/test_alerts_activities.py+++ b/posthog/temporal/tests/test_alerts_activities.py@@ -6,7 +6,7 @@ from datetime import UTC, datetimeimport pytestimport time_machine-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.db import OperationalError, connection, transaction@@ -59,7 +59,7 @@ from posthog.temporal.alerts.types import (SkipReason,)-from products.alerts.backend.evaluation.contract import AlertExtractionError+from products.alerts.backend.evaluation.contract import AlertDataUnavailableError, AlertExtractionErrorfrom products.alerts.backend.evaluation.validation import THRESHOLD_BOUNDS_REQUIRED_MESSAGEfrom products.alerts.backend.facade.api import (LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,@@ -714,10 +714,92 @@ class TestEvaluateAlert:refreshed = await sync_to_async(AlertConfiguration.objects.get)(pk=alert.pk)assert refreshed.enabled is True+ async def test_unavailable_data_records_error_without_disabling(self, alert_with_user) -> None:+ with (+ patch(+ "posthog.temporal.alerts.activities.check_alert_for_insight",+ side_effect=AlertDataUnavailableError("SQL history is incomplete"),+ ),+ patch("posthog.temporal.alerts.activities.capture_exception") as mock_capture,+ patch("posthog.tasks.alerts.utils.send_notifications_for_disabled") as mock_notify,+ ):+ result = await ActivityEnvironment().run(+ evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert_with_user.id))+ )++ assert result.new_state == AlertState.ERRORED+ check = await sync_to_async(AlertCheck.objects.get)(pk=result.alert_check_id)+ assert check.calculated_value is None+ assert check.error == {"message": "SQL history is incomplete"}+ refreshed = await sync_to_async(AlertConfiguration.objects.get)(pk=alert_with_user.pk)+ assert refreshed.enabled is True+ mock_capture.assert_not_called()+ mock_notify.assert_not_called()++ @pytest.mark.parametrize(+ "rows,has_more,sql_limit,expected_error,expect_disabled",+ [+ ([[f"hour-{i}", float(i)] for i in range(100)], True, "", "newest rows are missing", True),+ ([[f"hour-{i}", float(i)] for i in range(100)], True, " LIMIT 200", "newest rows are missing", True),+ ([[f"hour-{i}", float(i)] for i in range(200)], True, " LIMIT 200", "newest rows are missing", True),+ ([[f"hour-{i}", float(i)] for i in range(50)], False, " LIMIT 100", "at least 169", True),+ ([[f"hour-{i}", float(i)] for i in range(50)], False, "", "at least", False),+ ],+ )+ async def test_detector_unavailable_data_routes_through_evaluate_alert(+ self, ateam, auser, rows, has_more, sql_limit, expected_error, expect_disabled+ ) -> None:+ # Cross-layer guard: the dispatcher must route a detector-configured HogQL alert into the+ # extractor whose AlertDataUnavailableError reaches evaluate_alert's typed handler. Only the+ # query boundary is patched, so a routing or exception-propagation regression fails here.+ alert = await _create_alert(+ ateam,+ query={+ "kind": "HogQLQuery",+ "query": "SELECT toStartOfHour(timestamp) AS bucket, count() AS value FROM events GROUP BY bucket ORDER BY bucket ASC"+ + sql_limit,+ },+ config={"type": "HogQLAlertConfig", "evaluation": "last_row", "column": "value"},+ detector_config={"type": "mad", "window": 168, "threshold": 0.95},+ )+ await sync_to_async(alert.subscribed_users.add)(auser)+ calculation = MagicMock(result=rows, columns=["bucket", "value"], has_more=has_more)+ with (+ patch(+ "products.alerts.backend.evaluation.hogql.calculate_for_query_based_insight",+ return_value=calculation,+ ),+ patch("posthog.temporal.alerts.activities.capture_exception") as mock_capture,+ patch("posthog.tasks.alerts.utils.send_notifications_for_disabled", return_value=[]) as mock_notify,+ ):+ env = ActivityEnvironment()+ result = await env.run(evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id)))+ mock_notify.assert_not_called()+ if expect_disabled:+ assert result.alert_check_id is not None+ await env.run(+ notify_alert,+ NotifyAlertActivityInputs(alert_id=str(alert.id), alert_check_id=result.alert_check_id),+ )++ assert result.new_state == AlertState.ERRORED+ check = await sync_to_async(AlertCheck.objects.get)(pk=result.alert_check_id)+ assert check.error is not None and expected_error in check.error["message"]+ refreshed = await sync_to_async(AlertConfiguration.objects.get)(pk=alert.pk)+ # A capped result is a configuration error that recurs every check, so it disables and+ # notifies; a short-but-uncapped history can be a young project growing into its window.+ assert refreshed.enabled is (not expect_disabled)+ mock_capture.assert_not_called()+ if expect_disabled:+ mock_notify.assert_called_once()+ else:+ mock_notify.assert_not_called()+@pytest.mark.parametrize("error_type", [AlertExtractionError, LLMDetectorMisconfiguredError])async def test_evaluate_auto_disables_and_skips_error_tracking_on_configuration_error(self, alert_with_user, error_type) -> None:+with (patch("posthog.temporal.alerts.activities.check_alert_for_insight",diff --git a/products/alerts/backend/evaluation/contract.py b/products/alerts/backend/evaluation/contract.pyindex 321745ddd5a3..81392e1fca33 100644--- a/products/alerts/backend/evaluation/contract.py+++ b/products/alerts/backend/evaluation/contract.py@@ -78,6 +78,10 @@ class AlertExtractionError(Exception):"""+class AlertDataUnavailableError(AlertExtractionError):+ """This check lacks usable data; keep the alert enabled for future checks."""++def lookback_intervals_for(condition: AlertCondition) -> int:"""How many trailing intervals an extractor must fetch for this condition.diff --git a/products/alerts/backend/evaluation/hogql.py b/products/alerts/backend/evaluation/hogql.pyindex 47538cfadf24..49cc35954bb8 100644--- a/products/alerts/backend/evaluation/hogql.py+++ b/products/alerts/backend/evaluation/hogql.py@@ -5,14 +5,20 @@ from typing import Anyfrom posthog.schema import AlertCondition, AlertConditionType, HogQLAlertConfig, HogQLAlertEvaluation-from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS+from posthog.hogql import ast+from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS, LimitContext+from posthog.hogql.errors import BaseHogQLError+from posthog.hogql.parser import parse_selectfrom posthog.api.services.query import ExecutionModefrom posthog.caching.calculate_results import calculate_for_query_based_insight+from posthog.dataclasses import frozenfrom posthog.event_usage import EventSource+from posthog.hogql_queries.paginators import get_query_limitfrom posthog.tasks.alerts.detector import _compute_min_samples_for_detector, min_points_to_evaluatefrom products.alerts.backend.evaluation.contract import (+ AlertDataUnavailableError,AlertExtractionError,ComparableSeries,ExtractionResult,@@ -57,12 +63,39 @@ def hogql_config_or_default(raw: dict | None) -> HogQLAlertConfig:return HogQLAlertConfig.model_validate(raw or _DEFAULT_HOGQL_CONFIG)+def _explicit_limit(insight: Insight) -> int | None:+ """Read the saved query's constant row limit for detector validation."""+ query = insight.query or {}+ source = query.get("source") if query.get("kind") == "DataVisualizationNode" else query+ if not isinstance(source, dict) or not isinstance(source.get("query"), str):+ return None+ try:+ parsed = parse_select(source["query"])+ except BaseHogQLError:+ return None+ return get_query_limit(parsed) if isinstance(parsed, ast.SelectQuery | ast.SelectSetQuery) else None+++@frozen+class _FetchedRows:+ rows: list+ column_names: list[str] | None+ truncated: bool++def _calculate_rows_and_columns(- insight: Insight, team: Any, *, user: Any, execution_mode: ExecutionMode-) -> 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.+ insight: Insight,+ team: Any,+ *,+ user: Any,+ execution_mode: ExecutionMode,+ evaluation: HogQLAlertEvaluation,+) -> _FetchedRows:+ """Run a SQL insight — 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. Every evaluation except+ first_row needs the complete result, so those get the completeness check; first_row reads+ the head, which truncation can't touch."""calculation_result = calculate_for_query_based_insight(insight,@@ -70,15 +103,37 @@ def _calculate_rows_and_columns(execution_mode=execution_mode,user=user,analytics_props={"source": EventSource.ALERT},+ limit_context=LimitContext.SQL_ALERT,)+ truncated = calculation_result.has_more is Truerows = calculation_result.resultif 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__}).")+ if evaluation != HogQLAlertEvaluation.FIRST_ROW:+ if truncated:+ # Missing tail rows can change last-row and any-row results. The owner must adjust+ # the query before checks can safely resume.+ if evaluation == HogQLAlertEvaluation.LAST_ROW:+ raise AlertExtractionError(+ "The query returns more rows than its row limit, so the newest rows are missing and the "+ "alert would check the wrong row. Raise the SQL LIMIT to cover every row the alert needs, "+ "or order newest first and use first-row evaluation."+ )+ raise AlertExtractionError(+ "The query returns more rows than its row limit, so rows this alert should check are missing "+ "and a breach could go unnoticed. Raise the SQL LIMIT to cover every row the alert needs, or "+ "aggregate the query to return fewer rows."+ )+ if calculation_result.has_more is not False:+ raise AlertDataUnavailableError(+ "The alert could not confirm the query returned every row. Use a plain SELECT with a constant "+ f"LIMIT under {MAX_SELECT_RETURNED_ROWS}, or use first-row evaluation if only the first rows matter."+ )columns = calculation_result.columns if isinstance(calculation_result.columns, list) else Nonecolumn_names = [str(c) for c in columns] if columns else None- return rows, column_names+ return _FetchedRows(rows=rows, column_names=column_names, truncated=truncated)def _check_row_caps(rows: list, evaluation: HogQLAlertEvaluation) -> None:@@ -144,9 +199,15 @@ class HogQLExtractor:config = hogql_config_or_default(alert.config)evaluation = config.evaluation- rows, column_names = _calculate_rows_and_columns(- insight, alert.team, user=alert.created_by, execution_mode=execution_mode+ fetched = _calculate_rows_and_columns(+ insight,+ alert.team,+ user=alert.created_by,+ execution_mode=execution_mode,+ evaluation=evaluation,)+ rows = fetched.rows+ column_names = fetched.column_namesif len(rows) == 0:# No rows means the metric is genuinely 0 this check (matching trends), so a lower# bound can still breach.@@ -219,14 +280,8 @@ def extract_hogql_detector_series(execution_mode: ExecutionMode,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).+ """Extract SQL history for checks and simulation. Invalid limits disable checks; short uncapped+ histories remain retryable. Empty results retain the zero-result semantics."""if config.evaluation == HogQLAlertEvaluation.ANY_ROW:raise AlertExtractionError(@@ -234,7 +289,24 @@ def extract_hogql_detector_series("entities, not a time series. Use last-row or first-row evaluation.")- rows, column_names = _calculate_rows_and_columns(insight, team, user=user, execution_mode=execution_mode)+ min_samples = _compute_min_samples_for_detector(detector_config)+ required_samples = min_points_to_evaluate(detector_config)+ explicit_limit = _explicit_limit(insight)+ if explicit_limit is not None and explicit_limit < required_samples:+ raise AlertExtractionError(+ f"The query's LIMIT of {explicit_limit} rows is below the {required_samples} rows the detector "+ f"needs. Raise the LIMIT to at least {required_samples}, or reduce the detector window."+ )++ fetched = _calculate_rows_and_columns(+ insight,+ team,+ user=user,+ execution_mode=execution_mode,+ evaluation=config.evaluation,+ )+ rows = fetched.rows+ column_names = fetched.column_namesif len(rows) == 0:return ExtractionResult(series=[], is_breakdown=False, subject=_HOGQL_SUBJECT, framed=False, empty_query_result=True@@ -255,13 +327,22 @@ def extract_hogql_detector_series(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_points_to_evaluate(detector_config):- return ExtractionResult(series=[], is_breakdown=False, subject=_HOGQL_SUBJECT, framed=False)+ # SQL rows are the series verbatim, so the detector's minimum is the exact cutoff.+ # A short series cannot establish that the alert is not firing.+ if len(values) < required_samples:+ if fetched.truncated:+ # The history is short because the row limit provably cut it, not because the data+ # is young, so waiting never heals it — same configuration-error routing as the+ # last-row guard.+ raise AlertExtractionError(+ f"The detector needs at least {required_samples} rows, but the row limit cut the result to "+ f"{len(values)}. Raise the SQL LIMIT to cover the full history, or reduce the detector window."+ )+ raise AlertDataUnavailableError(+ f"The anomaly alert needs at least {required_samples} rows, but the query returned {len(values)}. "+ "The alert retries as more data arrives. To evaluate sooner, expand the query history or reduce "+ "the detector window."+ )# 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 — sodiff --git a/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py b/products/alerts/backend/evaluation/test/test_high_frequency_freshness.pyindex b7199b9a8b1e..bd57677fa96e 100644--- a/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py+++ b/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py@@ -155,7 +155,7 @@ EXTRACTOR_FORWARDING_CASES = [),pytest.param("products.alerts.backend.evaluation.hogql.calculate_for_query_based_insight",- MagicMock(result=[[5.0], [6.0]], columns=["value"]),+ MagicMock(result=[[5.0], [6.0]], columns=["value"], has_more=False),_hogql_forward,id="hogql",),diff --git a/products/alerts/backend/evaluation/test/test_hogql_detector.py b/products/alerts/backend/evaluation/test/test_hogql_detector.pyindex 7379a5f5ac80..df1f9378db43 100644--- a/products/alerts/backend/evaluation/test/test_hogql_detector.py+++ b/products/alerts/backend/evaluation/test/test_hogql_detector.py@@ -8,11 +8,12 @@ from posthog.schema import HogQLAlertConfigfrom posthog.api.services.query import ExecutionModefrom posthog.tasks.alerts.detector import _compute_min_samples_for_detector-from products.alerts.backend.evaluation.contract import AlertExtractionError+from products.alerts.backend.evaluation.contract import AlertDataUnavailableError, AlertExtractionErrorfrom products.alerts.backend.evaluation.detector import evaluate_with_detectorfrom products.alerts.backend.evaluation.hogql import (LAST_ROW_MAX_ROWS,HogQLDetectorExtractor,+ _explicit_limit,extract_hogql_detector_series,)@@ -33,12 +34,12 @@ def _alert(rows_config: dict | None = None, detector_config: dict | None = ZSCORreturn alert-def _extract(values, *, columns=None, rows_config=None, detector_config=ZSCORE):+def _extract(values, *, columns=None, rows_config=None, detector_config=ZSCORE, query=None):rows = [[v] for v in values] if columns is None else valueswith patch(CALC_PATH) as calc:- calc.return_value = MagicMock(result=rows, columns=columns)+ calc.return_value = MagicMock(result=rows, columns=columns, has_more=False)return HogQLDetectorExtractor().extract(- _alert(rows_config, detector_config), MagicMock(), MagicMock(), EXEC_MODE+ _alert(rows_config, detector_config), MagicMock(query=query), MagicMock(), EXEC_MODE)@@ -92,12 +93,15 @@ def test_large_result_is_bounded_to_the_detector_window(evaluation, label_type):assert [point.date for point in result.series[0].points] == expected_dates-def test_a_short_sql_series_still_reaches_the_ai_judge():[email protected]("sql", ["SELECT value FROM events", "SELECT value FROM events LIMIT 6"])+def test_a_short_sql_series_still_reaches_the_ai_judge(sql):llm = {"type": "llm", "threshold": 0.7, "window": 90}- result = _extract([1.0, 2.0, 1.0, 2.0, 1.0, 9.0], detector_config=llm)+ result = _extract([1.0, 2.0, 1.0, 2.0, 1.0, 9.0], detector_config=llm, query={"kind": "HogQLQuery", "query": sql})assert len(result.series[0].points) == 6- assert _extract([1.0, 2.0, 1.0, 9.0], detector_config=llm).series == []- assert _extract([1.0, 2.0, 1.0, 2.0, 1.0, 9.0], detector_config=ZSCORE).series == []+ with pytest.raises(AlertDataUnavailableError, match="at least 5 rows"):+ _extract([1.0, 2.0, 1.0, 9.0], detector_config=llm)+ with pytest.raises(AlertDataUnavailableError, match="at least 31 rows"):+ _extract([1.0, 2.0, 1.0, 2.0, 1.0, 9.0], detector_config=ZSCORE)def test_last_row_truncation_guard_rejects_a_capped_result():@@ -126,13 +130,10 @@ def test_exactly_the_detector_minimum_is_scored():assert evaluation.breaches and "Anomaly detected" in evaluation.breaches[0]-def test_one_row_below_the_detector_minimum_is_uncomputed():+def test_one_row_below_the_detector_minimum_reports_insufficient_history():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 == []+ with pytest.raises(AlertDataUnavailableError, match=f"at least {minimum} rows"):+ _extract(STABLE_HISTORY[: minimum - 1])def test_threshold_detector_scores_a_single_row():@@ -178,9 +179,37 @@ 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)+ calc.return_value = MagicMock(result=[[v] for v in [*STABLE_HISTORY, 100.0]], columns=None, has_more=False)result = extract_hogql_detector_series(MagicMock(), MagicMock(), config, ZSCORE, user=None, execution_mode=EXEC_MODE)assert len(result.series[0].points) == _compute_min_samples_for_detector(ZSCORE) # bounded to the minimumassert evaluate_with_detector(result, ZSCORE).value == 100.0++[email protected]("evaluation", ["last_row", "first_row"])[email protected]("row_count", [0, 5, 25])+def test_explicit_limit_below_detector_minimum_is_a_configuration_error(evaluation, row_count):+ insight = MagicMock(query={"kind": "HogQLQuery", "query": "SELECT 1 AS value LIMIT 25"})+ with patch(CALC_PATH, return_value=MagicMock(result=[[1.0]] * row_count, columns=["value"], has_more=False)):+ with pytest.raises(AlertExtractionError, match="LIMIT.*25.*at least 31") as exc:+ HogQLDetectorExtractor().extract(_alert({"evaluation": evaluation}), insight, insight.query, EXEC_MODE)+ assert type(exc.value) is AlertExtractionError+++ "sql,expected",+ [+ ("SELECT 1 LIMIT 25", 25),+ ("SELECT 1", None),+ ("SELECT 1 LIMIT {n}", None),+ ("not valid sql", None),+ ("SELECT 1 LIMIT 0", 0),+ ],+)[email protected]("wrapped", [False, True])+def test_saved_query_explicit_limit(sql, expected, wrapped):+ query = {"kind": "HogQLQuery", "query": sql}+ if wrapped:+ query = {"kind": "DataVisualizationNode", "source": query}+ assert _explicit_limit(MagicMock(query=query)) == expecteddiff --git a/products/alerts/backend/evaluation/test/test_hogql_extractor.py b/products/alerts/backend/evaluation/test/test_hogql_extractor.pyindex d7dc60ec96de..7a222c4fe2f4 100644--- a/products/alerts/backend/evaluation/test/test_hogql_extractor.py+++ b/products/alerts/backend/evaluation/test/test_hogql_extractor.py@@ -14,7 +14,7 @@ from posthog.schema import (from posthog.api.services.query import ExecutionModefrom products.alerts.backend.evaluation.comparator import MAX_BREACH_MESSAGES, evaluate_threshold-from products.alerts.backend.evaluation.contract import AlertExtractionError+from products.alerts.backend.evaluation.contract import AlertDataUnavailableError, AlertExtractionErrorfrom products.alerts.backend.evaluation.hogql import (ANY_ROW_MAX_ROWS,LAST_ROW_MAX_ROWS,@@ -43,7 +43,7 @@ def _threshold(type_=InsightThresholdType.ABSOLUTE, lower=None, upper=None):def _extract(rows, *, columns=None, condition_type=AlertConditionType.ABSOLUTE_VALUE, config: dict | None = None):with patch(CALC_PATH) as calc:- calc.return_value = MagicMock(result=rows, columns=columns)+ calc.return_value = MagicMock(result=rows, columns=columns, has_more=False)return HogQLExtractor().extract(_alert(condition_type, config), MagicMock(), MagicMock(), _IF_STALE)@@ -109,7 +109,7 @@ def test_evaluation_uses_saved_variable_values_not_session_overrides():# never reach evaluation. This is why the configure-time preview (which reads the user's# possibly-overridden cached result) can disagree with what the alert actually evaluates.with patch(CALC_PATH) as calc:- calc.return_value = MagicMock(result=[[5]], columns=["count"])+ calc.return_value = MagicMock(result=[[5]], columns=["count"], has_more=False)HogQLExtractor().extract(_alert(), MagicMock(), MagicMock(), _IF_STALE)assert "variables_override" not in calc.call_args.kwargs@@ -366,3 +366,34 @@ def test_any_row_rejects_relative_conditions():condition_type=AlertConditionType.RELATIVE_INCREASE,config={"type": "HogQLAlertConfig", "evaluation": "any_row"},)+++ "evaluation,has_more,raises",+ [+ ("last_row", True, True),+ ("any_row", True, True),+ ("first_row", True, False),+ ("last_row", False, False),+ ("any_row", False, False),+ ("first_row", False, False),+ ],+)+def test_completeness_uses_the_extra_row_evidence(evaluation, has_more, raises):+ insight = MagicMock(query={"kind": "HogQLQuery", "query": "SELECT 1 AS value LIMIT 3"})+ with patch(CALC_PATH, return_value=MagicMock(result=[[1.0], [2.0], [3.0]], columns=["value"], has_more=has_more)):+ alert = _alert(config={"evaluation": evaluation, "column": "value"})+ if raises:+ with pytest.raises(AlertExtractionError, match="more rows than its row limit") as exc:+ HogQLExtractor().extract(alert, insight, insight.query, _IF_STALE)+ assert type(exc.value) is AlertExtractionError+ else:+ result = HogQLExtractor().extract(alert, insight, insight.query, _IF_STALE)+ assert result.series+++def test_unproven_completeness_stays_retryable():+ insight = MagicMock(query={"kind": "HogQLQuery", "query": "SELECT 1 AS value LIMIT {n}"})+ with patch(CALC_PATH, return_value=MagicMock(result=[[1.0]], columns=["value"], has_more=None)):+ with pytest.raises(AlertDataUnavailableError, match="could not confirm the query returned every row"):+ HogQLExtractor().extract(_alert(), insight, insight.query, _IF_STALE)diff --git a/products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.py b/products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.pyindex 5011f045a255..7c20abddb97d 100644--- a/products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.py+++ b/products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.py@@ -1,9 +1,16 @@import time_machinefrom posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events+from parameterized import parameterized++from posthog.schema import HogQLAlertConfig+from posthog.api.services.query import ExecutionMode+from posthog.caching.calculate_results import calculate_for_query_based_insight-from products.alerts.backend.evaluation.hogql import HogQLExtractor+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 HogQLExtractor, extract_hogql_detector_seriesfrom products.alerts.backend.models.alert import AlertConfigurationfrom products.product_analytics.backend.facade.models import Insight@@ -65,3 +72,98 @@ class TestHogQLExtractorFiltersPlaceholder(APIBaseTest, ClickhouseDestroyTablesM)== 5.0)+++class TestHogQLThresholdTruncation(APIBaseTest):+ @parameterized.expand(+ [+ ("last_row", "", AlertExtractionError, "newest rows are missing and the alert would check the wrong row"),+ ("any_row", "", AlertExtractionError, "a breach could go unnoticed"),+ ("last_row", " LIMIT 100", AlertExtractionError, "newest rows are missing"),+ ("any_row", " LIMIT 3", AlertExtractionError, "a breach could go unnoticed"),+ ]+ )+ def test_a_capped_threshold_result_fails_loud(self, evaluation, sql_limit, expected_exception, expected_error):+ insight = Insight.objects.create(+ team=self.team,+ query={+ "kind": "HogQLQuery",+ "query": f"SELECT arrayJoin(range(150)) AS value ORDER BY value ASC{sql_limit}",+ },+ )+ alert = AlertConfiguration.objects.create(+ team=self.team,+ insight=insight,+ name="threshold truncation",+ condition={"type": "absolute_value"},+ config={"type": "HogQLAlertConfig", "evaluation": evaluation, "column": "value"},+ calculation_interval="daily",+ )+ with self.assertRaisesRegex(expected_exception, expected_error):+ HogQLExtractor().extract(alert, insight, insight.query, ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+++class TestHogQLDetectorPagination(APIBaseTest):+ @parameterized.expand(+ [+ # last_row: scores the newest row, so a cut tail is a configuration error, and the+ # detector's requirement is window + 1 (the history plus the point it scores).+ ("last_row", 99, 30, None, None, None),+ (+ "last_row",+ 169,+ 168,+ None,+ AlertExtractionError,+ "newest rows are missing and the alert would check the wrong row",+ ),+ ("last_row", 169, 168, 100, AlertExtractionError, "Raise the LIMIT to at least 169"),+ ("last_row", 150, 30, 100, AlertExtractionError, "newest rows are missing"),+ ("last_row", 501, 168, 501, None, None),+ ("last_row", 501, 168, 502, None, None),+ # first_row: reads the head, immune to a cut tail, but still needs enough history.+ ("first_row", 501, 30, None, None, None),+ ("first_row", 501, 30, 100, None, None),+ ("first_row", 501, 168, None, AlertExtractionError, "row limit cut the result"),+ ("first_row", 10, 168, 100, AlertExtractionError, "Raise the LIMIT to at least 169"),+ # any_row: rows are unrelated entities, not a time series, so detectors refuse it.+ ("any_row", 99, 30, None, AlertExtractionError, "isn't supported for any-row"),+ ]+ )+ def test_detector_checks_paginated_history(+ self, evaluation, row_count, window, explicit_limit, expected_exception, expected_error+ ):+ direction = "DESC" if evaluation == "first_row" else "ASC"+ sql_limit = f" LIMIT {explicit_limit}" if explicit_limit else ""+ insight = Insight.objects.create(+ team=self.team,+ query={+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": f"SELECT arrayJoin(range({row_count})) AS value ORDER BY value {direction}{sql_limit}",+ },+ },+ )+ saved_query = insight.query+ calculation = calculate_for_query_based_insight(+ insight, team=self.team, user=self.user, execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS+ )+ assert isinstance(calculation.result, list)+ assert len(calculation.result) == min(row_count, explicit_limit or 100)+ assert calculation.has_more is (None if explicit_limit else row_count > 100)+ config = HogQLAlertConfig(type="HogQLAlertConfig", evaluation=evaluation, column="value")+ detector = {"type": "mad", "threshold": 0.95, "window": window}+ mode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE+ if expected_error:+ with self.assertRaisesRegex(expected_exception, expected_error):+ extract_hogql_detector_series(insight, self.team, config, detector, user=self.user, execution_mode=mode)+ else:+ result = extract_hogql_detector_series(+ insight, self.team, config, detector, user=self.user, execution_mode=mode+ )+ assert evaluate_with_detector(result, detector).value == row_count - 1 # newest point survives+ normal = calculate_for_query_based_insight(insight, team=self.team, user=self.user, execution_mode=mode)+ assert isinstance(normal.result, list)+ assert [list(row) for row in normal.result] == [list(row) for row in calculation.result]+ assert insight.query == saved_querydiff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.pyindex 83a126dfe58c..751360bb7deb 100644--- a/products/alerts/backend/tests/api/test_alert.py+++ b/products/alerts/backend/tests/api/test_alert.py@@ -1756,6 +1756,23 @@ class TestAlertSimulate(TrendsInsightAPITest):assert isinstance(data["scores"], list)assert len(data["scores"]) == 34+ @mock.patch("products.alerts.backend.evaluation.hogql.calculate_for_query_based_insight")+ def test_simulate_short_sql_history_returns_validation_error(self, mock_calculate) -> None:+ insight = Insight.objects.create(team=self.team, query={"kind": "HogQLQuery", "query": "SELECT 1 AS value"})+ mock_calculate.return_value = mock.MagicMock(result=[[1.0]], columns=["value"], has_more=False)+ response = self.client.post(+ f"/api/projects/{self.team.id}/alerts/simulate",+ {+ "insight": insight.id,+ "detector_config": {"type": "zscore", "threshold": 0.9, "window": 30},+ "config": {"type": "HogQLAlertConfig", "evaluation": "last_row", "column": "value"},+ },+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "needs at least" in response.json()["detail"]+ assert not AlertCheck.objects.filter(alert_configuration__insight=insight).exists()+@mock.patch("products.alerts.backend.presentation.views.alert.simulate_detector_on_insight")def test_simulate_uses_default_detector_config(self, mock_simulate) -> None:mock_simulate.return_value = {