: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): handle empty funnel query results in alert evaluation (#67406)
Vasco de Krijger63feb33ff460
diff --git a/products/alerts/backend/evaluation/funnel_strategies.py b/products/alerts/backend/evaluation/funnel_strategies.pyindex 9bd3e72a7b8c..ed4afcd87465 100644--- a/products/alerts/backend/evaluation/funnel_strategies.py+++ b/products/alerts/backend/evaluation/funnel_strategies.py@@ -57,14 +57,16 @@ class StepsFunnelStrategy(FunnelVizStrategy):def to_series(self, result: Any, config: FunnelsAlertConfig) -> list[ComparableSeries]:# A steps funnel is a single snapshot: the condition is always absolute (enforced upstream) and# check_ongoing_interval has no meaning (there are no periods), so neither is read here.- breakdowns = _steps_per_breakdown(_current_period_only(result))+ rows = _require_list(_current_period_only(result), "steps")+ if not rows:+ return _no_data_series()return [ComparableSeries(label=_label_for_breakdown(steps[0].get("breakdown_value") if steps else None),points=[SeriesPoint(date=None, value=_conversion_rate(steps, config))],current_index=0,)- for steps in breakdowns+ for steps in _steps_per_breakdown(rows)]@@ -78,7 +80,10 @@ class HistoricalTrendsFunnelStrategy(FunnelVizStrategy):supports_relative_conditions = Truedef to_series(self, result: Any, config: FunnelsAlertConfig) -> list[ComparableSeries]:- series_dicts = _require_series_list(_current_period_only(result), "trends")+ series_dicts = _require_list(_current_period_only(result), "trends")+ # Empty = no one entered the funnel: benign, not a misconfig.+ if not series_dicts:+ return _no_data_series()# By default evaluate the last *complete* period — the latest one is still in progress, so# anchoring there would read a partial rate (and, for relative, diff a partial against a complete# one). check_ongoing_interval opts into that in-progress period. The anchor is the same for@@ -140,21 +145,27 @@ def _current_period_only(result: Any) -> Any:return [row for row in result if _is_current_period_row(row)]-def _require_series_list(result: Any, viz_label: str) -> list[Any]:- if not result or not isinstance(result, list):- raise AlertExtractionError(f"Funnel {viz_label} alert query returned no data.")- return result+def _no_data_series() -> list[ComparableSeries]:+ # A missing anchor value the comparator skips (NOT_FIRING, no error), so a benign empty funnel+ # isn't reported to error tracking as a crash.+ return [ComparableSeries(label="conversion", points=[SeriesPoint(date=None, value=None)], current_index=0)]-def _steps_per_breakdown(result: Any) -> list[list[dict[str, Any]]]:- """Normalize a steps funnel result into a list of step-lists (one per breakdown value).+def _require_list(result: Any, viz_label: str) -> list[Any]:+ # A non-list (e.g. None from a swallowed query error) is a real failure, not "no data" — raise so+ # the alert auto-disables. An empty list is left for the caller to treat as benign no-data.+ if not isinstance(result, list):+ raise AlertExtractionError(+ f"Funnel {viz_label} alert query returned an unexpected result shape ({type(result).__name__})."+ )+ return result- A non-breakdown funnel returns ``list[step]``; a breakdown funnel returns ``list[list[step]]``.- """- series = _require_series_list(result, "steps")- if isinstance(series[0], list):- return cast(list[list[dict[str, Any]]], series)- return [cast(list[dict[str, Any]], series)]++def _steps_per_breakdown(result: list[Any]) -> list[list[dict[str, Any]]]:+ # The runner returns ``list[step]`` without a breakdown and ``list[list[step]]`` with one; unify.+ if isinstance(result[0], list):+ return cast(list[list[dict[str, Any]]], result)+ return [cast(list[dict[str, Any]], result)]def _label_for_breakdown(breakdown: Any) -> str:diff --git a/products/alerts/backend/evaluation/test/test_funnels_extractor.py b/products/alerts/backend/evaluation/test/test_funnels_extractor.pyindex baa73e9c82cb..c14559d6f1a0 100644--- a/products/alerts/backend/evaluation/test/test_funnels_extractor.py+++ b/products/alerts/backend/evaluation/test/test_funnels_extractor.py@@ -84,9 +84,11 @@ def test_result_is_unframed_single_series():),(_steps(100, 40), None, None, AlertConditionType.RELATIVE_INCREASE, "absolute value conditions"),(_steps(100, 40), None, None, AlertConditionType.RELATIVE_DECREASE, "absolute value conditions"),- ([], None, None, AlertConditionType.ABSOLUTE_VALUE, "no data"),([{"order": 0}, {"order": 1}], None, None, AlertConditionType.ABSOLUTE_VALUE, "non-numeric count"),([{"order": 0, "count": 100}, "broken"], None, None, AlertConditionType.ABSOLUTE_VALUE, "malformed"),+ # A falsy non-list ({}) must raise, not be swallowed as benign empty ([]).+ ({}, None, None, AlertConditionType.ABSOLUTE_VALUE, "unexpected result shape"),+ ({}, None, "trends", AlertConditionType.ABSOLUTE_VALUE, "unexpected result shape"),],)def test_extract_raises_extraction_error(result, config, viz, condition_type, match):@@ -158,9 +160,14 @@ def test_trends_funnel_compare_evaluates_current_period_only():assert result.series[0].points[result.series[0].current_index].value == 40.0-def test_trends_funnel_empty_result_raises_extraction_error():- with pytest.raises(AlertExtractionError, match="no data"):- _extract([], viz="trends")[email protected]("viz", [None, "trends"])+def test_empty_result_is_benign_no_data(viz):+ # An empty funnel result (no users in the window) is benign "no data this interval", not a+ # misconfiguration — it must NOT raise (which would surface a benign empty funnel to error+ # tracking as a crash). It yields a single missing point so the comparator skips it.+ result = _extract([], viz=viz)+ assert len(result.series) == 1+ assert result.series[0].points[result.series[0].current_index].value is Nonedef test_unsupported_viz_raises():