Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(alerts): always recompute fresh for every-15-minutes alerts (#62988)

Vasco de Krijgereb7dd8c1edbe
diff --git a/posthog/tasks/alerts/test/test_detector_breakdowns.py b/posthog/tasks/alerts/test/test_detector_breakdowns.py
index 6cb10ac24c84..ae4b6c26dbcb 100644
--- a/posthog/tasks/alerts/test/test_detector_breakdowns.py
+++ b/posthog/tasks/alerts/test/test_detector_breakdowns.py
@@ -18,6 +18,7 @@ from posthog.schema import (
TrendsQuery,
)
+from posthog.api.services.query import ExecutionMode
from posthog.caching.fetch_from_cache import InsightResult
from posthog.tasks.alerts.detector import MAX_DETECTOR_BREAKDOWN_VALUES
@@ -255,7 +256,11 @@ class TestCheckTrendsAlertWithDetectorBreakdowns:
alert = _make_alert(MagicMock(), ZSCORE_DETECTOR_CONFIG)
extraction = extract_detector_series(
- MagicMock(spec=Insight), alert.team, _make_query_without_breakdown(), ZSCORE_DETECTOR_CONFIG
+ MagicMock(spec=Insight),
+ alert.team,
+ _make_query_without_breakdown(),
+ ZSCORE_DETECTOR_CONFIG,
+ ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
)
assert extraction.series == []
assert extraction.empty_query_result is True
@@ -284,7 +289,13 @@ class TestCheckTrendsAlertWithDetectorBreakdowns:
)
alert = _make_alert(MagicMock(), ZSCORE_DETECTOR_CONFIG)
- extraction = extract_detector_series(MagicMock(spec=Insight), alert.team, query, ZSCORE_DETECTOR_CONFIG)
+ extraction = extract_detector_series(
+ MagicMock(spec=Insight),
+ alert.team,
+ query,
+ ZSCORE_DETECTOR_CONFIG,
+ ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
+ )
assert extraction.series == []
assert extraction.empty_query_result is False
diff --git a/products/alerts/backend/evaluation/contract.py b/products/alerts/backend/evaluation/contract.py
index c1d722e61c8c..3cab467337d8 100644
--- a/products/alerts/backend/evaluation/contract.py
+++ b/products/alerts/backend/evaluation/contract.py
@@ -3,6 +3,7 @@ from typing import Any, Protocol
from posthog.schema import AlertCondition, AlertConditionType, IntervalType
+from posthog.api.services.query import ExecutionMode
from posthog.models.team import Team
from posthog.models.user import User
@@ -88,6 +89,13 @@ def lookback_intervals_for(condition: AlertCondition) -> int:
raise AlertExtractionError(f"Unsupported alert condition type: {condition.type}")
+def execution_mode_for_alert(interval: IntervalType | None, *, high_frequency: bool) -> ExecutionMode:
+ """Pick the query execution mode for an alert check, shared by every extractor."""
+ if interval == IntervalType.HOUR or high_frequency:
+ return ExecutionMode.CALCULATE_BLOCKING_ALWAYS
+ return ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
+
+
@dataclass
class SimulationContext:
"""Alert-less inputs for a read-only detector simulation. Each extractor reads only the fields its
@@ -103,7 +111,11 @@ class SimulationContext:
class Extractor(Protocol):
- def extract(self, alert: AlertConfiguration, insight: Insight, query: object) -> ExtractionResult: ...
+ # The dispatcher resolves execution_mode once (via execution_mode_for_alert) and passes it in, so
+ # the cache/recompute decision lives at one site instead of being re-derived in each extractor.
+ def extract(
+ self, alert: AlertConfiguration, insight: Insight, query: object, execution_mode: ExecutionMode
+ ) -> ExtractionResult: ...
class DetectorExtractor(Extractor, Protocol):
diff --git a/products/alerts/backend/evaluation/detector.py b/products/alerts/backend/evaluation/detector.py
index c857cdbe4948..49021d9d91db 100644
--- a/products/alerts/backend/evaluation/detector.py
+++ b/products/alerts/backend/evaluation/detector.py
@@ -3,7 +3,7 @@ from zoneinfo import ZoneInfo
import numpy as np
-from posthog.schema import IntervalType, TrendsAlertConfig, TrendsQuery
+from posthog.schema import TrendsAlertConfig, TrendsQuery
from posthog.api.services.query import ExecutionMode
from posthog.caching.calculate_results import calculate_for_query_based_insight
@@ -30,6 +30,7 @@ from products.alerts.backend.evaluation.contract import (
ExtractionResult,
SeriesPoint,
SimulationContext,
+ execution_mode_for_alert,
)
from products.alerts.backend.models.alert import AlertConfiguration
from products.product_analytics.backend.models.insight import Insight
@@ -40,6 +41,7 @@ def extract_detector_series(
team: Any,
query: TrendsQuery,
detector_config: dict[str, Any],
+ execution_mode: ExecutionMode,
*,
series_index: int = 0,
date_from: str | None = None,
@@ -69,10 +71,6 @@ def extract_detector_series(
else:
filters_override = _date_range_override_for_detector(query, min_samples)
- execution_mode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
- if query.interval == IntervalType.HOUR:
- execution_mode = ExecutionMode.CALCULATE_BLOCKING_ALWAYS
-
calculation_result = calculate_for_query_based_insight(
insight, team=team, execution_mode=execution_mode, user=user, filters_override=filters_override
)
@@ -190,23 +188,34 @@ class TrendsDetectorExtractor:
fetching the detector's wider lookback window (the whole series is scored, not a single anchor).
"""
- def extract(self, alert: AlertConfiguration, insight: Insight, query: Any) -> ExtractionResult:
+ def extract(
+ self, alert: AlertConfiguration, insight: Insight, query: Any, execution_mode: ExecutionMode
+ ) -> ExtractionResult:
detector_config = alert.detector_config
if not detector_config:
raise ValueError("TrendsDetectorExtractor requires detector_config — dispatcher invariant violated")
trends_query = TrendsQuery.model_validate(query)
series_index = (alert.config or {}).get("series_index", 0)
return extract_detector_series(
- insight, alert.team, trends_query, detector_config, series_index=series_index, user=alert.created_by
+ insight,
+ alert.team,
+ trends_query,
+ detector_config,
+ execution_mode,
+ 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)
+ # Simulation isn't cadence-bound, so high_frequency=False; the interval still forces fresh on HOUR.
+ execution_mode = execution_mode_for_alert(trends_query.interval, high_frequency=False)
result = extract_detector_series(
insight,
ctx.team,
trends_query,
ctx.detector_config,
+ execution_mode,
series_index=ctx.series_index,
date_from=ctx.date_from,
user=ctx.user,
diff --git a/products/alerts/backend/evaluation/dispatcher.py b/products/alerts/backend/evaluation/dispatcher.py
index 49542a08eb00..5cf0f196bf1f 100644
--- a/products/alerts/backend/evaluation/dispatcher.py
+++ b/products/alerts/backend/evaluation/dispatcher.py
@@ -1,11 +1,12 @@
-from posthog.schema import AlertCondition, InsightThreshold, NodeKind
+from posthog.schema import AlertCondition, InsightThreshold, IntervalType, NodeKind
+from posthog.api.services.query import ExecutionMode
from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResult
from posthog.utils import get_from_dict_or_attr
from products.alerts.backend.evaluation.comparator import evaluate_threshold
-from products.alerts.backend.evaluation.contract import DetectorExtractor, Extractor
+from products.alerts.backend.evaluation.contract import DetectorExtractor, Extractor, execution_mode_for_alert
from products.alerts.backend.evaluation.detector import TrendsDetectorExtractor, evaluate_with_detector
from products.alerts.backend.evaluation.funnels import FunnelsExtractor
from products.alerts.backend.evaluation.hogql import HogQLDetectorExtractor, HogQLExtractor
@@ -30,6 +31,15 @@ DETECTOR_EXTRACTORS: dict[NodeKind, DetectorExtractor] = {
}
+def _resolve_execution_mode(alert: AlertConfiguration, kind: NodeKind, query: object) -> ExecutionMode:
+ # Compute the cache/recompute decision once for every kind. Only time-axis kinds (trends/detector)
+ # escalate to a fresh recompute on hourly buckets; SQL/funnels have no hourly axis, so for them
+ # only the alert cadence (every-15-minutes) forces fresh.
+ raw_interval = get_from_dict_or_attr(query, "interval") if kind == NodeKind.TRENDS_QUERY else None
+ interval = IntervalType(raw_interval) if raw_interval is not None else None
+ return execution_mode_for_alert(interval, high_frequency=alert.is_high_frequency_interval)
+
+
def check_detector_alert(alert: AlertConfiguration, insight: Insight, query: object) -> AlertEvaluationResult:
"""Route a detector (anomaly) alert to its kind's detector extractor, then score the series.
@@ -43,7 +53,7 @@ def check_detector_alert(alert: AlertConfiguration, insight: Insight, query: obj
detector_extractor = DETECTOR_EXTRACTORS.get(kind)
if detector_extractor is None:
raise NotImplementedError(f"AlertCheckError: Detector alerts for {kind} are not supported yet")
- result = detector_extractor.extract(alert, insight, query)
+ result = detector_extractor.extract(alert, insight, query, _resolve_execution_mode(alert, kind, query))
return evaluate_with_detector(result, detector_config)
@@ -78,5 +88,5 @@ def check_alert_for_insight(alert: AlertConfiguration) -> AlertEvaluationResult:
return AlertEvaluationResult(value=0, breaches=[])
condition = AlertCondition.model_validate(alert.condition)
- result = extractor.extract(alert, insight, query)
+ result = extractor.extract(alert, insight, query, _resolve_execution_mode(alert, kind, query))
return evaluate_threshold(result, condition, threshold)
diff --git a/products/alerts/backend/evaluation/funnels.py b/products/alerts/backend/evaluation/funnels.py
index 60208ec8b9ae..c85c2213e37f 100644
--- a/products/alerts/backend/evaluation/funnels.py
+++ b/products/alerts/backend/evaluation/funnels.py
@@ -31,7 +31,9 @@ class FunnelsExtractor:
A breakdown funnel yields one series per breakdown value and fires if ANY breaches (matching trends).
"""
- def extract(self, alert: AlertConfiguration, insight: Insight, query: Any) -> ExtractionResult:
+ def extract(
+ self, alert: AlertConfiguration, insight: Insight, query: Any, execution_mode: ExecutionMode
+ ) -> ExtractionResult:
funnels_query = FunnelsQuery.model_validate(query)
viz = funnels_query.funnelsFilter.funnelVizType if funnels_query.funnelsFilter else None
if viz not in (None, FunnelVizType.STEPS):
@@ -51,7 +53,7 @@ class FunnelsExtractor:
calculation_result = calculate_for_query_based_insight(
insight,
team=alert.team,
- execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
+ execution_mode=execution_mode,
user=alert.created_by,
analytics_props={"source": EventSource.ALERT},
)
diff --git a/products/alerts/backend/evaluation/hogql.py b/products/alerts/backend/evaluation/hogql.py
index 5db8db63d4d5..4bb2a0b288e5 100644
--- a/products/alerts/backend/evaluation/hogql.py
+++ b/products/alerts/backend/evaluation/hogql.py
@@ -17,6 +17,7 @@ from products.alerts.backend.evaluation.contract import (
ExtractionResult,
SeriesPoint,
SimulationContext,
+ execution_mode_for_alert,
zero_sentinel_series,
)
from products.alerts.backend.models.alert import AlertConfiguration
@@ -42,7 +43,9 @@ def hogql_config_or_default(raw: dict | None) -> HogQLAlertConfig:
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]:
+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.
@@ -50,7 +53,7 @@ def _calculate_rows_and_columns(insight: Insight, team: Any, *, user: Any) -> tu
calculation_result = calculate_for_query_based_insight(
insight,
team=team,
- execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
+ execution_mode=execution_mode,
user=user,
analytics_props={"source": EventSource.ALERT},
)
@@ -119,13 +122,17 @@ class HogQLExtractor:
7. anchor row: ``last_row`` reads the tail, ``first_row`` the head; both yield (previous, current)
"""
- def extract(self, alert: AlertConfiguration, insight: Insight, query: Any) -> ExtractionResult:
+ def extract(
+ self, alert: AlertConfiguration, insight: Insight, query: Any, execution_mode: ExecutionMode
+ ) -> ExtractionResult:
# ``query`` is unused (Protocol signature): the extractor recomputes via the insight.
condition = AlertCondition.model_validate(alert.condition)
config = hogql_config_or_default(alert.config)
evaluation = config.evaluation
- rows, column_names = _calculate_rows_and_columns(insight, alert.team, user=alert.created_by)
+ rows, column_names = _calculate_rows_and_columns(
+ insight, alert.team, user=alert.created_by, execution_mode=execution_mode
+ )
if len(rows) == 0:
# No rows means the metric is genuinely 0 this check (matching trends), so a lower
# bound can still breach.
@@ -195,6 +202,7 @@ def extract_hogql_detector_series(
config: HogQLAlertConfig,
detector_config: dict[str, Any],
*,
+ execution_mode: ExecutionMode,
user: Any = None,
) -> ExtractionResult:
"""Build the full ordered value series an anomaly detector scores from a SQL/HogQL insight.
@@ -212,7 +220,7 @@ 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)
+ rows, column_names = _calculate_rows_and_columns(insight, team, user=user, execution_mode=execution_mode)
if len(rows) == 0:
return ExtractionResult(
series=[], is_breakdown=False, subject=_HOGQL_SUBJECT, framed=False, empty_query_result=True
@@ -266,17 +274,27 @@ class HogQLDetectorExtractor:
``TrendsDetectorExtractor`` wraps ``extract_detector_series``.
"""
- def extract(self, alert: AlertConfiguration, insight: Insight, query: Any) -> ExtractionResult:
+ def extract(
+ self, alert: AlertConfiguration, insight: Insight, query: Any, execution_mode: ExecutionMode
+ ) -> 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)
+ return extract_hogql_detector_series(
+ insight, alert.team, config, detector_config, execution_mode=execution_mode, 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.
+ # SQL rows are their own series, so there's no chart interval — return None alongside. SQL has
+ # no time axis to force fresh on, so the read-only simulation uses the cache-friendly mode.
result = extract_hogql_detector_series(
- insight, ctx.team, hogql_config_or_default(ctx.config), ctx.detector_config, user=ctx.user
+ insight,
+ ctx.team,
+ hogql_config_or_default(ctx.config),
+ ctx.detector_config,
+ execution_mode=execution_mode_for_alert(None, high_frequency=False),
+ user=ctx.user,
)
return result, None
diff --git a/products/alerts/backend/evaluation/test/test_funnels_extractor.py b/products/alerts/backend/evaluation/test/test_funnels_extractor.py
index f3b8a1a32b15..3ca70e5fc5dc 100644
--- a/products/alerts/backend/evaluation/test/test_funnels_extractor.py
+++ b/products/alerts/backend/evaluation/test/test_funnels_extractor.py
@@ -3,10 +3,13 @@ from unittest.mock import MagicMock, patch
from posthog.schema import AlertConditionType
+from posthog.api.services.query import ExecutionMode
+
from products.alerts.backend.evaluation.contract import AlertExtractionError
from products.alerts.backend.evaluation.funnels import FunnelsExtractor
CALC_PATH = "products.alerts.backend.evaluation.funnels.calculate_for_query_based_insight"
+IF_STALE = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
def _steps(*counts: int) -> list[dict]:
@@ -35,7 +38,7 @@ def _extract(
):
with patch(CALC_PATH) as calc:
calc.return_value = MagicMock(result=result)
- return FunnelsExtractor().extract(_alert(config, condition_type), MagicMock(), _query(viz))
+ return FunnelsExtractor().extract(_alert(config, condition_type), MagicMock(), _query(viz), IF_STALE)
def _config(metric: str = "conversion_from_start", funnel_step: int | None = None) -> dict:
diff --git a/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py b/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py
new file mode 100644
index 000000000000..2f99dd1e1f87
--- /dev/null
+++ b/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py
@@ -0,0 +1,172 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import (
+ AlertCalculationInterval,
+ AlertCondition,
+ AlertConditionType,
+ BaseMathType,
+ ChartDisplayType,
+ EventsNode,
+ InsightsThresholdBounds,
+ InsightThreshold,
+ InsightThresholdType,
+ IntervalType,
+ NodeKind,
+ TrendsFilter,
+ TrendsQuery,
+)
+
+from posthog.api.services.query import ExecutionMode
+from posthog.caching.fetch_from_cache import InsightResult
+
+from products.alerts.backend.evaluation.contract import execution_mode_for_alert
+from products.alerts.backend.evaluation.detector import extract_detector_series
+from products.alerts.backend.evaluation.dispatcher import _resolve_execution_mode
+from products.alerts.backend.evaluation.funnels import FunnelsExtractor
+from products.alerts.backend.evaluation.hogql import HogQLExtractor
+from products.alerts.backend.evaluation.trends import TrendsExtractor
+from products.alerts.backend.models.alert import AlertConfiguration
+from products.product_analytics.backend.models.insight import Insight
+
+ALWAYS = ExecutionMode.CALCULATE_BLOCKING_ALWAYS
+IF_STALE = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
+ZSCORE_DETECTOR_CONFIG = {"type": "zscore", "threshold": 0.9, "window": 10}
+EMPTY_RESULT = InsightResult(result=[], columns=[], timezone="UTC", last_refresh=None, cache_key="", is_cached=False)
+
+
+def _day_query() -> TrendsQuery:
+ # Daily bucketing: without the high-frequency cadence this would reuse the recent-results cache.
+ return TrendsQuery(
+ series=[EventsNode(event="signed_up", math=BaseMathType.TOTAL)],
+ trendsFilter=TrendsFilter(display=ChartDisplayType.ACTIONS_LINE_GRAPH),
+ interval=IntervalType.DAY,
+ )
+
+
+def _trends_alert(*, high_frequency: bool) -> MagicMock:
+ alert = MagicMock(spec=AlertConfiguration)
+ alert.team = MagicMock()
+ alert.config = {"type": "TrendsAlertConfig", "series_index": 0}
+ alert.condition = AlertCondition(type=AlertConditionType.ABSOLUTE_VALUE).model_dump()
+ threshold = MagicMock()
+ threshold.configuration = InsightThreshold(
+ type=InsightThresholdType.ABSOLUTE, bounds=InsightsThresholdBounds(lower=1)
+ ).model_dump()
+ alert.threshold = threshold
+ alert.is_high_frequency_interval = high_frequency
+ return alert
+
+
+ "interval,high_frequency,expected",
+ [
+ (IntervalType.HOUR, False, ALWAYS), # hourly insight → always fresh (relative-time cache key)
+ (IntervalType.HOUR, True, ALWAYS),
+ (IntervalType.DAY, False, IF_STALE), # daily insight, normal cadence → cache is fine
+ (IntervalType.DAY, True, ALWAYS), # high-frequency cadence forces fresh regardless of bucketing
+ (None, False, IF_STALE), # no time axis (funnels/hogql), normal cadence → cache
+ (None, True, ALWAYS), # no time axis but high-frequency → fresh
+ ],
+)
+def test_execution_mode_for_alert(interval, high_frequency, expected):
+ assert execution_mode_for_alert(interval, high_frequency=high_frequency) == expected
+
+
+ "interval,expected",
+ [
+ (AlertCalculationInterval.EVERY_15_MINUTES, True),
+ (AlertCalculationInterval.HOURLY, False),
+ (AlertCalculationInterval.DAILY, False),
+ (None, False),
+ ],
+)
+def test_is_high_frequency_interval_property(interval, expected):
+ assert AlertConfiguration(calculation_interval=interval).is_high_frequency_interval is expected
+
+
+# The freshness decision lives in the dispatcher's _resolve_execution_mode — one site for every kind.
+# Only trends/detector escalate on hourly buckets (real time axis); funnels/hogql have none, so for
+# them the every-15-minutes cadence is the only fresh-recompute trigger.
+ "kind,interval,high_frequency,expected",
+ [
+ (NodeKind.TRENDS_QUERY, "hour", False, ALWAYS),
+ (NodeKind.TRENDS_QUERY, "day", False, IF_STALE),
+ (NodeKind.TRENDS_QUERY, "day", True, ALWAYS),
+ (NodeKind.TRENDS_QUERY, None, False, IF_STALE), # missing interval reads as None → same as the DAY default
+ (NodeKind.TRENDS_QUERY, None, True, ALWAYS),
+ (NodeKind.FUNNELS_QUERY, None, False, IF_STALE),
+ (NodeKind.FUNNELS_QUERY, None, True, ALWAYS),
+ (NodeKind.HOG_QL_QUERY, None, False, IF_STALE),
+ (NodeKind.HOG_QL_QUERY, None, True, ALWAYS),
+ ],
+)
+def test_resolve_execution_mode(kind, interval, high_frequency, expected):
+ alert = MagicMock()
+ alert.is_high_frequency_interval = high_frequency
+ query = {"kind": kind, "interval": interval} if interval is not None else {"kind": kind}
+ assert _resolve_execution_mode(alert, kind, query) == expected
+
+
+def _trends_forward(mode):
+ TrendsExtractor().extract(_trends_alert(high_frequency=False), MagicMock(spec=Insight), _day_query(), mode)
+
+
+def _detector_forward(mode):
+ extract_detector_series(MagicMock(spec=Insight), MagicMock(), _day_query(), ZSCORE_DETECTOR_CONFIG, mode)
+
+
+def _funnels_forward(mode):
+ alert = MagicMock()
+ alert.config = {"type": "FunnelsAlertConfig", "metric": "conversion_from_start", "funnel_step": None}
+ alert.condition = {"type": AlertConditionType.ABSOLUTE_VALUE}
+ query = {"kind": "FunnelsQuery", "series": [{"kind": "EventsNode", "event": "step_a"}]}
+ FunnelsExtractor().extract(alert, MagicMock(), query, mode)
+
+
+def _hogql_forward(mode):
+ alert = MagicMock()
+ alert.condition = {"type": AlertConditionType.ABSOLUTE_VALUE}
+ alert.config = {"type": "HogQLAlertConfig", "evaluation": "last_row"}
+ HogQLExtractor().extract(alert, MagicMock(), MagicMock(), mode)
+
+
+# (calc-path to patch, the result that path returns, a thunk that drives the extractor for one kind).
+EXTRACTOR_FORWARDING_CASES = [
+ pytest.param(
+ "products.alerts.backend.evaluation.trends.calculate_for_query_based_insight",
+ EMPTY_RESULT,
+ _trends_forward,
+ id="trends",
+ ),
+ pytest.param(
+ "products.alerts.backend.evaluation.detector.calculate_for_query_based_insight",
+ EMPTY_RESULT,
+ _detector_forward,
+ id="detector",
+ ),
+ pytest.param(
+ "products.alerts.backend.evaluation.funnels.calculate_for_query_based_insight",
+ MagicMock(result=[{"order": 0, "count": 100, "breakdown_value": None}]),
+ _funnels_forward,
+ id="funnels",
+ ),
+ pytest.param(
+ "products.alerts.backend.evaluation.hogql.calculate_for_query_based_insight",
+ MagicMock(result=[[5.0], [6.0]], columns=["value"]),
+ _hogql_forward,
+ id="hogql",
+ ),
+]
+
+
+# Every extractor forwards the mode it's handed (the dispatcher decides it) straight to the query layer.
[email protected]("mode", [ALWAYS, IF_STALE])
[email protected]("calc_path,calc_result,forward", EXTRACTOR_FORWARDING_CASES)
+def test_extractor_forwards_execution_mode(calc_path, calc_result, forward, mode):
+ with patch(calc_path) as mock_calc:
+ mock_calc.return_value = calc_result
+ forward(mode)
+ assert mock_calc.call_args.kwargs["execution_mode"] == mode
diff --git a/products/alerts/backend/evaluation/test/test_hogql_detector.py b/products/alerts/backend/evaluation/test/test_hogql_detector.py
index 9d52bddfec31..7721c01016fc 100644
--- a/products/alerts/backend/evaluation/test/test_hogql_detector.py
+++ b/products/alerts/backend/evaluation/test/test_hogql_detector.py
@@ -3,6 +3,7 @@ from unittest.mock import MagicMock, patch
from posthog.schema import HogQLAlertConfig
+from posthog.api.services.query import ExecutionMode
from posthog.tasks.alerts.detector import _compute_min_samples_for_detector
from products.alerts.backend.evaluation.contract import AlertExtractionError
@@ -15,6 +16,7 @@ from products.alerts.backend.evaluation.hogql import (
CALC_PATH = "products.alerts.backend.evaluation.hogql.calculate_for_query_based_insight"
ZSCORE = {"type": "zscore", "threshold": 0.9, "window": 5}
+EXEC_MODE = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
# 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.
@@ -33,7 +35,9 @@ 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())
+ return HogQLDetectorExtractor().extract(
+ _alert(rows_config, detector_config), MagicMock(), MagicMock(), EXEC_MODE
+ )
@pytest.mark.parametrize(
@@ -142,6 +146,8 @@ def test_extract_hogql_detector_series_is_alert_less():
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)
+ 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 minimum
assert evaluate_with_detector(result, ZSCORE).value == 100.0
diff --git a/products/alerts/backend/evaluation/test/test_hogql_extractor.py b/products/alerts/backend/evaluation/test/test_hogql_extractor.py
index 0ba50983d152..d7dc60ec96de 100644
--- a/products/alerts/backend/evaluation/test/test_hogql_extractor.py
+++ b/products/alerts/backend/evaluation/test/test_hogql_extractor.py
@@ -11,6 +11,8 @@ from posthog.schema import (
InsightThresholdType,
)
+from posthog.api.services.query import ExecutionMode
+
from products.alerts.backend.evaluation.comparator import MAX_BREACH_MESSAGES, evaluate_threshold
from products.alerts.backend.evaluation.contract import AlertExtractionError
from products.alerts.backend.evaluation.hogql import (
@@ -21,6 +23,7 @@ from products.alerts.backend.evaluation.hogql import (
)
CALC_PATH = "products.alerts.backend.evaluation.hogql.calculate_for_query_based_insight"
+_IF_STALE = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
ABSOLUTE = AlertCondition(type=AlertConditionType.ABSOLUTE_VALUE)
@@ -41,7 +44,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)
- return HogQLExtractor().extract(_alert(condition_type, config), MagicMock(), MagicMock())
+ return HogQLExtractor().extract(_alert(condition_type, config), MagicMock(), MagicMock(), _IF_STALE)
@pytest.mark.parametrize(
@@ -107,7 +110,7 @@ def test_evaluation_uses_saved_variable_values_not_session_overrides():
# 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"])
- HogQLExtractor().extract(_alert(), MagicMock(), MagicMock())
+ HogQLExtractor().extract(_alert(), MagicMock(), MagicMock(), _IF_STALE)
assert "variables_override" not in calc.call_args.kwargs
diff --git a/products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.py b/products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.py
index 81b95290d15f..16558e869217 100644
--- a/products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.py
+++ b/products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.py
@@ -1,6 +1,8 @@
from freezegun import freeze_time
from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events
+from posthog.api.services.query import ExecutionMode
+
from products.alerts.backend.evaluation.hogql import HogQLExtractor
from products.alerts.backend.models.alert import AlertConfiguration
from products.product_analytics.backend.models.insight import Insight
@@ -25,7 +27,9 @@ class TestHogQLExtractorFiltersPlaceholder(APIBaseTest, ClickhouseDestroyTablesM
config={"type": "HogQLAlertConfig", "evaluation": "last_row"},
calculation_interval="daily",
)
- result = HogQLExtractor().extract(alert, insight, hogql_source)
+ result = HogQLExtractor().extract(
+ alert, insight, hogql_source, ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
+ )
assert len(result.series) == 1
return result.series[0].points[result.series[0].current_index].value
diff --git a/products/alerts/backend/evaluation/trends.py b/products/alerts/backend/evaluation/trends.py
index 76e842b4101f..d10d928cad86 100644
--- a/products/alerts/backend/evaluation/trends.py
+++ b/products/alerts/backend/evaluation/trends.py
@@ -47,7 +47,9 @@ class TrendsExtractor:
normalize. Relative conditions are invalid for non-time-series insights and raise.
"""
- def extract(self, alert: AlertConfiguration, insight: Insight, query: Any) -> ExtractionResult:
+ def extract(
+ self, alert: AlertConfiguration, insight: Insight, query: Any, execution_mode: ExecutionMode
+ ) -> ExtractionResult:
query = TrendsQuery.model_validate(query)
if not (alert.config and "type" in alert.config and alert.config["type"] == "TrendsAlertConfig"):
raise ValueError(f"Unsupported alert config type: {alert.config}")
@@ -66,10 +68,6 @@ class TrendsExtractor:
lookback_intervals = lookback_intervals_for(condition)
interval_type = None if is_non_time_series else query.interval
- execution_mode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
- if query.interval == IntervalType.HOUR:
- execution_mode = ExecutionMode.CALCULATE_BLOCKING_ALWAYS
-
match condition.type:
case AlertConditionType.ABSOLUTE_VALUE:
if threshold.type != InsightThresholdType.ABSOLUTE:
diff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.py
index ba4bc373bc37..e99249a86038 100644
--- a/products/alerts/backend/models/alert.py
+++ b/products/alerts/backend/models/alert.py
@@ -194,6 +194,10 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
def __str__(self) -> str:
return f"{self.name} (Team: {self.team})"
+ @property
+ def is_high_frequency_interval(self) -> bool:
+ return self.calculation_interval == AlertCalculationInterval.EVERY_15_MINUTES
+
def get_subscribed_users_emails(self) -> list[str]:
return list(
self.subscribed_users.filter(organization_membership__organization=self.team.organization).values_list(
@@ -264,7 +268,7 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
"alert_name": self.name,
"condition_type": self.condition.get("type") if self.condition else None,
"calculation_interval": self.calculation_interval,
- "is_high_frequency_interval": self.calculation_interval == AlertCalculationInterval.EVERY_15_MINUTES,
+ "is_high_frequency_interval": self.is_high_frequency_interval,
"enabled": self.enabled,
"skip_weekend": bool(self.skip_weekend),
"has_schedule_restriction": has_schedule_restriction,