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.

fix(alerts): age an alert's cache from the interval bucket (#125655)

Matt Puab27f85929ad1
diff --git a/products/alerts/backend/evaluation/contract.py b/products/alerts/backend/evaluation/contract.py
index 2da532f7e79c..58911d597fa3 100644
--- a/products/alerts/backend/evaluation/contract.py
+++ b/products/alerts/backend/evaluation/contract.py
@@ -1,11 +1,14 @@
from collections.abc import Callable
from dataclasses import dataclass
+from datetime import datetime
from typing import Any, Protocol
+from zoneinfo import ZoneInfo
from posthog.schema import AlertCondition, AlertConditionType, IntervalType
from posthog.api.services.query import ExecutionMode
from posthog.dataclasses import frozen
+from posthog.interval_specs import interval_spec
from posthog.models.team import Team
from posthog.models.user import User
@@ -122,6 +125,25 @@ def execution_mode_for_alert(interval: IntervalType | None, *, high_frequency: b
return ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
+def cache_age_seconds_for_alert(interval: IntervalType | None, *, now: datetime, team: Team) -> int | None:
+ """Max cache age for this check, counted from the start of the bucket ``now`` falls in.
+ None leaves the shared staleness rule in place.
+
+ The cache key holds the relative date range (``-1h``), so consecutive checks share a key while
+ scoring different buckets. Ageing from the bucket start rejects a result from the previous bucket.
+ """
+ if interval is None:
+ return None
+ spec = interval_spec(interval)
+ local_now = now.astimezone(ZoneInfo(team.timezone))
+ # A DST transition can put the aligned bucket start after local_now.
+ elapsed = max(int((local_now - spec.align(local_now, team.week_start_day)).total_seconds()), 0)
+ if spec.staleness_default is None:
+ return None
+ # The override replaces the shared threshold, so cap it there to only ever tighten it.
+ return min(elapsed, int(spec.staleness_default.total_seconds()))
+
+
@dataclass(frozen=False)
class SimulationContext:
"""Alert-less inputs for a read-only detector simulation. Each extractor reads only the fields its
@@ -138,10 +160,15 @@ class SimulationContext:
class Extractor(Protocol):
- # 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.
+ # The dispatcher resolves execution_mode and cache_age_seconds once and passes them 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
+ self,
+ alert: AlertConfiguration,
+ insight: Insight,
+ query: object,
+ execution_mode: ExecutionMode,
+ cache_age_seconds: int | None = None,
) -> ExtractionResult: ...
diff --git a/products/alerts/backend/evaluation/detector.py b/products/alerts/backend/evaluation/detector.py
index 9e85b859179c..4e6b4505e351 100644
--- a/products/alerts/backend/evaluation/detector.py
+++ b/products/alerts/backend/evaluation/detector.py
@@ -71,6 +71,7 @@ def extract_detector_series(
detector_config: dict[str, Any],
execution_mode: ExecutionMode,
*,
+ cache_age_seconds: int | None = None,
series_index: int = 0,
date_from: str | None = None,
user: Optional[User] = None,
@@ -103,7 +104,12 @@ def extract_detector_series(
filters_override = _date_range_override_for_detector(query, min_samples)
calculation_result = calculate_for_query_based_insight(
- insight, team=team, execution_mode=execution_mode, user=user, filters_override=filters_override
+ insight,
+ team=team,
+ execution_mode=execution_mode,
+ cache_age_seconds=cache_age_seconds,
+ user=user,
+ filters_override=filters_override,
)
if calculation_result.result is None:
@@ -508,7 +514,12 @@ class TrendsDetectorExtractor:
"""
def extract(
- self, alert: AlertConfiguration, insight: Insight, query: Any, execution_mode: ExecutionMode
+ self,
+ alert: AlertConfiguration,
+ insight: Insight,
+ query: Any,
+ execution_mode: ExecutionMode,
+ cache_age_seconds: int | None = None,
) -> ExtractionResult:
detector_config = alert.detector_config
if not detector_config:
@@ -521,6 +532,7 @@ class TrendsDetectorExtractor:
trends_query,
detector_config,
execution_mode,
+ cache_age_seconds=cache_age_seconds,
series_index=series_index,
user=alert.created_by,
evaluation_delay_intervals=alert.evaluation_delay_intervals,
diff --git a/products/alerts/backend/evaluation/dispatcher.py b/products/alerts/backend/evaluation/dispatcher.py
index e56a7b9abf3a..7a853baf0313 100644
--- a/products/alerts/backend/evaluation/dispatcher.py
+++ b/products/alerts/backend/evaluation/dispatcher.py
@@ -1,7 +1,9 @@
from collections.abc import Callable, Iterator
from contextlib import AbstractContextManager, contextmanager, nullcontext
from dataclasses import replace
+from datetime import UTC, datetime
from typing import Any
+from zoneinfo import ZoneInfo
from rest_framework.exceptions import ValidationError as DRFValidationError
@@ -13,9 +15,10 @@ from posthog.api.services.query import ExecutionMode
from posthog.dataclasses import frozen
from posthog.errors import CH_TRANSIENT_ERRORS, ExposedCHQueryError
from posthog.hogql_queries.validation.validate_query import rule_violation_message
+from posthog.models.team import Team
from posthog.schema_migrations.upgrade_manager import upgrade_insight
from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResult
-from posthog.utils import get_from_dict_or_attr
+from posthog.utils import get_from_dict_or_attr, relative_date_parse_with_delta_mapping
from products.alerts.backend.evaluation.comparator import evaluate_threshold
from products.alerts.backend.evaluation.contract import (
@@ -24,6 +27,7 @@ from products.alerts.backend.evaluation.contract import (
DetectorExtractor,
ExtractionResult,
Extractor,
+ cache_age_seconds_for_alert,
execution_mode_for_alert,
)
from products.alerts.backend.evaluation.delay import (
@@ -68,6 +72,51 @@ def _resolve_execution_mode(alert: AlertConfiguration, kind: NodeKind, query: ob
return execution_mode_for_alert(interval, high_frequency=alert.is_high_frequency_interval)
+def _query_interval(query: object) -> IntervalType | None:
+ # Metrics insights use interval strings outside the enum (``minute_5``, ``$window``).
+ try:
+ raw_interval = get_from_dict_or_attr(query, "interval")
+ except AttributeError:
+ return None
+ if raw_interval is None:
+ return None
+ try:
+ return IntervalType(raw_interval)
+ except ValueError:
+ return None
+
+
+def _ends_in_the_past(query: object, *, now: datetime, team: Team) -> bool:
+ # The shared rule caches a closed range forever, and the override would replace that rule.
+ try:
+ date_range = get_from_dict_or_attr(query, "dateRange")
+ except AttributeError:
+ return False
+ if date_range is None:
+ return False
+ try:
+ date_to = get_from_dict_or_attr(date_range, "date_to")
+ except AttributeError:
+ return False
+ if not isinstance(date_to, str):
+ return False
+ parsed, delta_mapping, _position = relative_date_parse_with_delta_mapping(date_to, ZoneInfo(team.timezone), now=now)
+ return delta_mapping is None and parsed < now
+
+
+def _resolve_cache_age_seconds(alert: AlertConfiguration, query: object, execution_mode: ExecutionMode) -> int | None:
+ # Read for every kind, unlike _resolve_execution_mode, because funnels also hit the cache.
+ if execution_mode == ExecutionMode.CALCULATE_BLOCKING_ALWAYS:
+ return None
+ if get_from_dict_or_attr(query, "kind") == NodeKind.METRICS_QUERY:
+ # Metrics already age on a minute threshold, so a bucket limit would loosen it.
+ return None
+ now = datetime.now(UTC)
+ if _ends_in_the_past(query, now=now, team=alert.team):
+ return None
+ return cache_age_seconds_for_alert(_query_interval(query), now=now, team=alert.team)
+
+
@contextmanager
def owner_sql_errors(query: object) -> Iterator[None]:
"""Raise a user-safe failure of a SQL insight's own query as an ``AlertExtractionError``.
@@ -116,7 +165,9 @@ def run_extractor(
"""
try:
with query_slot(), owner_sql_errors(query):
- return extractor.extract(alert, insight, query, execution_mode)
+ # Resolve inside the slot so a slot wait cannot push the window past a bucket boundary.
+ cache_age_seconds = _resolve_cache_age_seconds(alert, query, execution_mode)
+ return extractor.extract(alert, insight, query, execution_mode, cache_age_seconds)
except DRFValidationError as err:
if getattr(err, "served_from_query_failure_cache", False):
raise
diff --git a/products/alerts/backend/evaluation/funnels.py b/products/alerts/backend/evaluation/funnels.py
index 5ebcadc2b607..2d75d504bc15 100644
--- a/products/alerts/backend/evaluation/funnels.py
+++ b/products/alerts/backend/evaluation/funnels.py
@@ -43,7 +43,12 @@ class FunnelsExtractor:
"""
def extract(
- self, alert: AlertConfiguration, insight: Insight, query: Any, execution_mode: ExecutionMode
+ self,
+ alert: AlertConfiguration,
+ insight: Insight,
+ query: Any,
+ execution_mode: ExecutionMode,
+ cache_age_seconds: int | None = None,
) -> ExtractionResult:
funnels_query = FunnelsQuery.model_validate(query)
viz = funnels_query.funnelsFilter.funnelVizType if funnels_query.funnelsFilter else None
@@ -76,6 +81,7 @@ class FunnelsExtractor:
insight,
team=alert.team,
execution_mode=execution_mode,
+ cache_age_seconds=cache_age_seconds,
user=alert.created_by,
filters_override=filters_override,
analytics_props={"source": EventSource.ALERT},
diff --git a/products/alerts/backend/evaluation/hogql.py b/products/alerts/backend/evaluation/hogql.py
index a3ed678985d2..adf7ec31ed4d 100644
--- a/products/alerts/backend/evaluation/hogql.py
+++ b/products/alerts/backend/evaluation/hogql.py
@@ -89,6 +89,7 @@ def _calculate_rows_and_columns(
*,
user: Any,
execution_mode: ExecutionMode,
+ cache_age_seconds: int | None = None,
evaluation: HogQLAlertEvaluation,
) -> _FetchedRows:
"""Run a SQL insight — the fetch-and-validate prologue shared by the threshold and detector
@@ -101,6 +102,7 @@ def _calculate_rows_and_columns(
insight,
team=team,
execution_mode=execution_mode,
+ cache_age_seconds=cache_age_seconds,
user=user,
analytics_props={"source": EventSource.ALERT},
limit_context=LimitContext.SQL_ALERT,
@@ -192,7 +194,12 @@ class HogQLExtractor:
"""
def extract(
- self, alert: AlertConfiguration, insight: Insight, query: Any, execution_mode: ExecutionMode
+ self,
+ alert: AlertConfiguration,
+ insight: Insight,
+ query: Any,
+ execution_mode: ExecutionMode,
+ cache_age_seconds: int | None = None,
) -> ExtractionResult:
# ``query`` is unused (Protocol signature): the extractor recomputes via the insight.
condition = AlertCondition.model_validate(alert.condition)
@@ -204,6 +211,7 @@ class HogQLExtractor:
alert.team,
user=alert.created_by,
execution_mode=execution_mode,
+ cache_age_seconds=cache_age_seconds,
evaluation=evaluation,
)
rows = fetched.rows
@@ -278,6 +286,7 @@ def extract_hogql_detector_series(
detector_config: dict[str, Any],
*,
execution_mode: ExecutionMode,
+ cache_age_seconds: int | None = None,
user: Any = None,
) -> ExtractionResult:
"""Extract SQL history for checks and simulation. Invalid limits disable checks; short uncapped
@@ -303,6 +312,7 @@ def extract_hogql_detector_series(
team,
user=user,
execution_mode=execution_mode,
+ cache_age_seconds=cache_age_seconds,
evaluation=config.evaluation,
)
rows = fetched.rows
@@ -373,14 +383,25 @@ class HogQLDetectorExtractor:
"""
def extract(
- self, alert: AlertConfiguration, insight: Insight, query: Any, execution_mode: ExecutionMode
+ self,
+ alert: AlertConfiguration,
+ insight: Insight,
+ query: Any,
+ execution_mode: ExecutionMode,
+ cache_age_seconds: int | None = None,
) -> 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, execution_mode=execution_mode, user=alert.created_by
+ insight,
+ alert.team,
+ config,
+ detector_config,
+ execution_mode=execution_mode,
+ cache_age_seconds=cache_age_seconds,
+ user=alert.created_by,
)
def simulate(self, insight: Insight, query: object, ctx: SimulationContext) -> tuple[ExtractionResult, str | None]:
diff --git a/products/alerts/backend/evaluation/metrics.py b/products/alerts/backend/evaluation/metrics.py
index c34ec4c855ed..b0f98e002511 100644
--- a/products/alerts/backend/evaluation/metrics.py
+++ b/products/alerts/backend/evaluation/metrics.py
@@ -38,7 +38,12 @@ class MetricsExtractor:
"""
def extract(
- self, alert: AlertConfiguration, insight: Insight, query: Any, execution_mode: ExecutionMode
+ self,
+ alert: AlertConfiguration,
+ insight: Insight,
+ query: Any,
+ execution_mode: ExecutionMode,
+ cache_age_seconds: int | None = None,
) -> ExtractionResult:
metrics_query = MetricsQuery.model_validate(query)
if not (alert.config and alert.config.get("type") == "MetricsAlertConfig"):
@@ -60,6 +65,7 @@ class MetricsExtractor:
insight,
team=alert.team,
execution_mode=execution_mode,
+ cache_age_seconds=cache_age_seconds,
# Scheduled alert check (no request user); attribute the read to the alert owner.
user=alert.created_by,
analytics_props={"source": EventSource.ALERT},
diff --git a/products/alerts/backend/evaluation/test/test_bucket_freshness_clickhouse.py b/products/alerts/backend/evaluation/test/test_bucket_freshness_clickhouse.py
new file mode 100644
index 000000000000..fd158f54dc5f
--- /dev/null
+++ b/products/alerts/backend/evaluation/test/test_bucket_freshness_clickhouse.py
@@ -0,0 +1,57 @@
+import time_machine
+from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events
+
+from posthog.test.persons import create_person
+
+from products.alerts.backend.evaluation.dispatcher import check_alert_for_insight
+from products.alerts.backend.models.alert import AlertConfiguration, Threshold
+from products.product_analytics.backend.facade.models import Insight
+
+
+class TestHourlyAlertScoresItsOwnWindow(APIBaseTest, ClickhouseDestroyTablesMixin):
+ def _hour_of_events(self, hour: str, starts: int, finishes: int) -> None:
+ for i in range(starts):
+ create_person(team_id=self.team.pk, distinct_ids=[f"{hour}_{i}"])
+ _create_event(team=self.team, event="step_a", distinct_id=f"{hour}_{i}", timestamp=f"{hour}:10:00Z")
+ for i in range(finishes):
+ _create_event(team=self.team, event="step_b", distinct_id=f"{hour}_{i}", timestamp=f"{hour}:20:00Z")
+
+ def test_consecutive_hourly_checks_do_not_reuse_the_previous_window(self) -> None:
+ self.team.timezone = "UTC"
+ self.team.save()
+
+ self._hour_of_events("2026-10-28T20", starts=10, finishes=6)
+ self._hour_of_events("2026-10-28T21", starts=10, finishes=9)
+ flush_persons_and_events()
+
+ insight = Insight.objects.create(
+ team=self.team,
+ query={
+ "kind": "FunnelsQuery",
+ "interval": "hour",
+ "dateRange": {"date_from": "-1h"},
+ "series": [
+ {"kind": "EventsNode", "event": "step_a"},
+ {"kind": "EventsNode", "event": "step_b"},
+ ],
+ },
+ )
+ alert = AlertConfiguration.objects.create(
+ team=self.team,
+ insight=insight,
+ name="hourly funnel",
+ condition={"type": "absolute_value"},
+ config={"type": "FunnelsAlertConfig", "metric": "conversion_from_start", "funnel_step": None},
+ calculation_interval="hourly",
+ threshold=Threshold.objects.create(
+ team=self.team, insight=insight, name="t", configuration={"type": "absolute", "bounds": {"lower": 0}}
+ ),
+ )
+
+ with time_machine.travel("2026-10-28T21:01:20Z", tick=False):
+ first = check_alert_for_insight(alert)
+ with time_machine.travel("2026-10-28T22:01:13Z", tick=False):
+ second = check_alert_for_insight(alert)
+
+ assert first.value == 75.0
+ assert second.value == 90.0
diff --git a/products/alerts/backend/evaluation/test/test_dispatcher.py b/products/alerts/backend/evaluation/test/test_dispatcher.py
index e108591532a0..1a2b51cc28f8 100644
--- a/products/alerts/backend/evaluation/test/test_dispatcher.py
+++ b/products/alerts/backend/evaluation/test/test_dispatcher.py
@@ -37,7 +37,14 @@ class _Extractor:
def __init__(self, outcome: Exception | ExtractionResult) -> None:
self._outcome = outcome
- def extract(self, alert: Any, insight: Any, query: Any, execution_mode: ExecutionMode) -> ExtractionResult:
+ def extract(
+ self,
+ alert: Any,
+ insight: Any,
+ query: Any,
+ execution_mode: ExecutionMode,
+ cache_age_seconds: int | None = None,
+ ) -> ExtractionResult:
if isinstance(self._outcome, Exception):
raise self._outcome
return self._outcome
diff --git a/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py b/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py
index 750145bc1f8c..8d047ebc2a93 100644
--- a/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py
+++ b/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py
@@ -1,3 +1,5 @@
+from datetime import UTC, datetime, timedelta
+
import pytest
from unittest.mock import MagicMock, patch
@@ -19,10 +21,11 @@ from posthog.schema import (
from posthog.api.services.query import ExecutionMode
from posthog.caching.insight_result import InsightResult
+from posthog.interval_specs import interval_spec
-from products.alerts.backend.evaluation.contract import execution_mode_for_alert
+from products.alerts.backend.evaluation.contract import cache_age_seconds_for_alert, 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.dispatcher import _resolve_cache_age_seconds, _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
@@ -111,27 +114,36 @@ def test_resolve_execution_mode(kind, interval, high_frequency, expected):
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 _trends_forward(mode, cache_age_seconds):
+ TrendsExtractor().extract(
+ _trends_alert(high_frequency=False), MagicMock(spec=Insight), _day_query(), mode, cache_age_seconds
+ )
-def _detector_forward(mode):
- extract_detector_series(MagicMock(spec=Insight), MagicMock(), _day_query(), ZSCORE_DETECTOR_CONFIG, mode)
+def _detector_forward(mode, cache_age_seconds):
+ extract_detector_series(
+ MagicMock(spec=Insight),
+ MagicMock(),
+ _day_query(),
+ ZSCORE_DETECTOR_CONFIG,
+ mode,
+ cache_age_seconds=cache_age_seconds,
+ )
-def _funnels_forward(mode):
+def _funnels_forward(mode, cache_age_seconds):
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)
+ FunnelsExtractor().extract(alert, MagicMock(), query, mode, cache_age_seconds)
-def _hogql_forward(mode):
+def _hogql_forward(mode, cache_age_seconds):
alert = MagicMock()
alert.condition = {"type": AlertConditionType.ABSOLUTE_VALUE}
alert.config = {"type": "HogQLAlertConfig", "evaluation": "last_row"}
- HogQLExtractor().extract(alert, MagicMock(), MagicMock(), mode)
+ HogQLExtractor().extract(alert, MagicMock(), MagicMock(), mode, cache_age_seconds)
# (calc-path to patch, the result that path returns, a thunk that drives the extractor for one kind).
@@ -163,11 +175,101 @@ EXTRACTOR_FORWARDING_CASES = [
]
-# Every extractor forwards the mode it's handed (the dispatcher decides it) straight to the query layer.
+# Every extractor forwards the mode and cache age it's handed straight to the query layer.
@pytest.mark.parametrize("mode", [ALWAYS, IF_STALE])
@pytest.mark.parametrize("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)
+ forward(mode, 73)
assert mock_calc.call_args.kwargs["execution_mode"] == mode
+ assert mock_calc.call_args.kwargs["cache_age_seconds"] == 73
+
+
+def _team(timezone: str) -> MagicMock:
+ team = MagicMock()
+ team.timezone = timezone
+ team.week_start_day = None
+ return team
+
+
+ "previous_check,current_check,reusable",
+ [
+ pytest.param(
+ datetime(2026, 10, 28, 21, 1, 20, tzinfo=UTC),
+ datetime(2026, 10, 28, 22, 1, 13, tzinfo=UTC),
+ False,
+ id="gap-just-under-an-hour",
+ ),
+ pytest.param(
+ datetime(2026, 10, 28, 4, 50, 5, tzinfo=UTC),
+ datetime(2026, 10, 28, 5, 0, 30, tzinfo=UTC),
+ False,
+ id="gap-compressed-by-a-quiet-window",
+ ),
+ pytest.param(
+ datetime(2026, 10, 28, 22, 1, 13, tzinfo=UTC),
+ datetime(2026, 10, 28, 22, 1, 40, tzinfo=UTC),
+ True,
+ id="retry-inside-the-same-bucket",
+ ),
+ ],
+)
+def test_hourly_cache_age_tracks_the_bucket_not_the_gap(previous_check, current_check, reusable):
+ limit = cache_age_seconds_for_alert(IntervalType.HOUR, now=current_check, team=_team("UTC"))
+ assert limit is not None
+ assert ((current_check - previous_check).total_seconds() <= limit) is reusable
+
+
+ "interval,timezone,now,expected",
+ [
+ (IntervalType.HOUR, "UTC", datetime(2026, 10, 28, 22, 1, 13, tzinfo=UTC), 73),
+ # Half-hour offset: hour buckets open at :30 past the UTC hour.
+ (IntervalType.HOUR, "Asia/Kolkata", datetime(2026, 10, 28, 22, 1, 13, tzinfo=UTC), 1873),
+ (IntervalType.HOUR, "Asia/Kolkata", datetime(2026, 10, 28, 22, 31, 13, tzinfo=UTC), 73),
+ (IntervalType.DAY, "Asia/Bangkok", datetime(2026, 10, 28, 22, 1, 13, tzinfo=UTC), 18073),
+ (None, "UTC", datetime(2026, 10, 28, 22, 1, 13, tzinfo=UTC), None),
+ (IntervalType.SECOND, "UTC", datetime(2026, 10, 28, 22, 1, 13, tzinfo=UTC), None),
+ ],
+)
+def test_cache_age_seconds_for_alert(interval, timezone, now, expected):
+ assert cache_age_seconds_for_alert(interval, now=now, team=_team(timezone)) == expected
+
+
[email protected]("interval", [i for i in IntervalType if interval_spec(i).staleness_default is not None])
[email protected]("hours_into_bucket", [0, 5, 23, 24 * 20])
+def test_cache_age_never_exceeds_the_shared_threshold(interval, hours_into_bucket):
+ shared_threshold = interval_spec(interval).staleness_default
+ assert shared_threshold is not None
+ now = datetime(2026, 3, 1, tzinfo=UTC) + timedelta(hours=hours_into_bucket)
+ limit = cache_age_seconds_for_alert(interval, now=now, team=_team("UTC"))
+ assert limit is not None
+ assert limit <= shared_threshold.total_seconds()
+
+
+ "kind,interval,execution_mode,expects_limit,date_to",
+ [
+ (NodeKind.FUNNELS_QUERY, "hour", IF_STALE, True, None),
+ (NodeKind.TRENDS_QUERY, "day", IF_STALE, True, None),
+ (NodeKind.FUNNELS_QUERY, "hour", IF_STALE, True, "-1d"),
+ (NodeKind.FUNNELS_QUERY, "hour", IF_STALE, False, "2020-01-01"),
+ (NodeKind.METRICS_QUERY, "hour", IF_STALE, False, None),
+ (NodeKind.METRICS_QUERY, "day", IF_STALE, False, None),
+ (NodeKind.METRICS_QUERY, "minute_5", IF_STALE, False, None),
+ (NodeKind.METRICS_QUERY, "$window", IF_STALE, False, None),
+ (NodeKind.HOG_QL_QUERY, None, IF_STALE, False, None),
+ (NodeKind.FUNNELS_QUERY, "hour", ALWAYS, False, None),
+ ],
+)
+def test_resolve_cache_age_seconds(kind, interval, execution_mode, expects_limit, date_to):
+ alert = MagicMock()
+ alert.team = _team("UTC")
+ query: dict = {"kind": kind}
+ if interval is not None:
+ query["interval"] = interval
+ if date_to is not None:
+ query["dateRange"] = {"date_to": date_to}
+ assert (_resolve_cache_age_seconds(alert, query, execution_mode) is not None) is expects_limit
diff --git a/products/alerts/backend/evaluation/trends.py b/products/alerts/backend/evaluation/trends.py
index 8878c3296e24..ead895d7f6de 100644
--- a/products/alerts/backend/evaluation/trends.py
+++ b/products/alerts/backend/evaluation/trends.py
@@ -54,7 +54,12 @@ class TrendsExtractor:
"""
def extract(
- self, alert: AlertConfiguration, insight: Insight, query: Any, execution_mode: ExecutionMode
+ self,
+ alert: AlertConfiguration,
+ insight: Insight,
+ query: Any,
+ execution_mode: ExecutionMode,
+ cache_age_seconds: int | None = None,
) -> ExtractionResult:
query = TrendsQuery.model_validate(query)
if not (alert.config and "type" in alert.config and alert.config["type"] == "TrendsAlertConfig"):
@@ -95,7 +100,9 @@ class TrendsExtractor:
if is_non_time_series
else _date_range_override_for_intervals(query, last_x_intervals=lookback_intervals)
)
- calculation_result = self._calculate(alert, insight, execution_mode, filters_override)
+ calculation_result = self._calculate(
+ alert, insight, execution_mode, cache_age_seconds, filters_override
+ )
if (
empty := self._empty_result(
calculation_result, alert, has_breakdown, interval_type, value_formatter
@@ -114,7 +121,9 @@ class TrendsExtractor:
# When the current interval is incomplete we compare the previous interval
# against the one before it, so we need the extra lookback interval.
filters_override = _date_range_override_for_intervals(query, last_x_intervals=lookback_intervals)
- calculation_result = self._calculate(alert, insight, execution_mode, filters_override)
+ calculation_result = self._calculate(
+ alert, insight, execution_mode, cache_age_seconds, filters_override
+ )
if (
empty := self._empty_result(
calculation_result, alert, has_breakdown, interval_type, value_formatter
@@ -131,7 +140,9 @@ class TrendsExtractor:
if is_non_time_series:
raise ValueError("Relative alerts not supported for non time series trends")
filters_override = _date_range_override_for_intervals(query, last_x_intervals=lookback_intervals)
- calculation_result = self._calculate(alert, insight, execution_mode, filters_override)
+ calculation_result = self._calculate(
+ alert, insight, execution_mode, cache_age_seconds, filters_override
+ )
if (
empty := self._empty_result(
calculation_result, alert, has_breakdown, interval_type, value_formatter
@@ -172,12 +183,14 @@ class TrendsExtractor:
alert: AlertConfiguration,
insight: Insight,
execution_mode: ExecutionMode,
+ cache_age_seconds: int | None,
filters_override: dict | None,
) -> InsightResult:
return calculate_for_query_based_insight(
insight,
team=alert.team,
execution_mode=execution_mode,
+ cache_age_seconds=cache_age_seconds,
# Scheduled alert check (no request user); attribute the read to the alert owner so
# warehouse HogQL access control resolves against their access.
user=alert.created_by,