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): compare insight platform checks against production checks (#113680)

Jimmy Zhu9a60cc153772
diff --git a/products/alerts/backend/alert_comparison.py b/products/alerts/backend/alert_comparison.py
new file mode 100644
index 000000000000..1076ec0f6659
--- /dev/null
+++ b/products/alerts/backend/alert_comparison.py
@@ -0,0 +1,375 @@
+"""The insight side of the alerts platform comparison contract.
+
+Production insight writes an `AlertCheck` row for every check, carrying the state that check left
+the alert in. So, unlike logs, nothing is reconstructed: production's verdict is a row.
+
+A platform check names its due slot, and the two stacks do not check at the same minute. Each
+spreads its alerts over an offset within the period, keyed on its own id for the alert, so
+production's check of a period can come before the platform's slot or after it. A platform check
+pairs with production's first check in the same local calendar period: the quarter hour, hour,
+day, ISO week or month the slot falls in. A production stack that made no check in that period is
+behind.
+
+`AlertCheck` rows are deleted after `AlertCheck.RETENTION`, so an older slot cannot be answered.
+"""
+
+from __future__ import annotations
+
+from bisect import bisect_left, bisect_right
+from collections import defaultdict
+from collections.abc import Mapping, Sequence
+from datetime import UTC, datetime, timedelta
+from uuid import UUID
+
+from django.db.models import Q
+
+import pytz
+import structlog
+from dateutil.relativedelta import relativedelta
+
+from posthog.dataclasses import frozen
+from posthog.schema_enums import (
+ AlertCalculationInterval,
+ AlertState as InsightAlertState,
+)
+from posthog.tasks.alerts.schedule_restriction import is_utc_datetime_blocked
+
+from products.alerts.backend.insight_alert_state_machine import INSIGHT_ALERT_POLICY, platform_state_of
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+from products.alerts.backend.platform_source_cycle import CAPACITY_REJECTED, slot_of_evaluation_key
+from products.alerts_platform.backend.facade.contracts import (
+ CheckRef,
+ IntentionalDivergence,
+ PlatformCheck,
+ SourceCorrespondence,
+ SourceCoverage,
+ SourceKind,
+ SourceVerdict,
+ SuppressionReason,
+)
+from products.alerts_platform.backend.facade.lifecycle import AlertState
+from products.alerts_platform.backend.facade.scheduling import is_weekend, local_period_start, next_local_period_start
+
+logger = structlog.get_logger(__name__)
+
+# The bound the retention does not give: an hourly alert holds 336 rows, and alerts add up.
+MAX_CHECKS_PER_BATCH = 100_000
+# Alerts per history query, so one statement never carries a condition per alert of a large team.
+ALERTS_PER_QUERY = 500
+
+# Sub-day periods take their boundaries from the scheduler production uses, which finds them on the
+# local wall clock and so follows a 30-minute daylight-saving change.
+_SUB_DAY_PERIOD_MINUTES: dict[str, int] = {
+ AlertCalculationInterval.EVERY_15_MINUTES: 15,
+ AlertCalculationInterval.HOURLY: 60,
+}
+# Calendar periods follow the team's local calendar: a day across a daylight-saving change is 23 or
+# 25 hours, and a month is as long as it is.
+_CALENDAR_PERIOD: dict[str, relativedelta] = {
+ AlertCalculationInterval.DAILY: relativedelta(days=1),
+ AlertCalculationInterval.WEEKLY: relativedelta(weeks=1),
+ AlertCalculationInterval.MONTHLY: relativedelta(months=1),
+}
+
+# How far past a check's period the read reaches for when production next moved state. A catch-up
+# later than this reads as never, which the comparison's lag buckets already treat as the long tail.
+CATCH_UP_HORIZON = timedelta(days=1)
+
+
+def _refused_for_capacity(check: PlatformCheck, verdict: SourceVerdict) -> bool:
+ return check.error_message == CAPACITY_REJECTED
+
+
+INSIGHT_INTENTIONAL_DIVERGENCES: tuple[IntentionalDivergence, ...] = (
+ IntentionalDivergence(
+ cause="platform_refused_for_capacity",
+ recognizes=_refused_for_capacity,
+ why=(
+ "The parallel run queries as its own ClickHouse user, under a cap of its own, so "
+ "ClickHouse can refuse its query for load where production's ran. The platform then "
+ "keeps its state and production holds a verdict. Every other platform error is left "
+ "to read as real, so a broken grant or query is not excused."
+ ),
+ ),
+)
+
+
+@frozen
+class _Pairing:
+ check: PlatformCheck
+ alert_id: UUID
+ slot: datetime
+
+
+@frozen
+class _Period:
+ start: datetime
+ end: datetime
+
+
+@frozen
+class _ProductionCheck:
+ id: UUID
+ created_at: datetime
+ # None for a spelling the platform does not have, which is answered as unknown.
+ state: str | None
+ skipped: bool
+
+
+@frozen
+class _History:
+ """One alert's production checks, oldest first, indexed so each pairing is a few lookups."""
+
+ rows: list[_ProductionCheck]
+ times: list[datetime]
+ # For each row, the next row whose state differs, or None.
+ next_change: list[int | None]
+ # When production's evaluated checks held each state. A skipped check confirms nothing.
+ evaluated_times: dict[str, list[datetime]]
+
+ @classmethod
+ def of(cls, rows: list[_ProductionCheck]) -> _History:
+ next_change: list[int | None] = [None] * len(rows)
+ for i in range(len(rows) - 2, -1, -1):
+ next_change[i] = i + 1 if rows[i + 1].state != rows[i].state else next_change[i + 1]
+ evaluated_times: dict[str, list[datetime]] = defaultdict(list)
+ for row in rows:
+ if row.state is not None and not row.skipped:
+ evaluated_times[row.state].append(row.created_at)
+ return cls(
+ rows=rows,
+ times=[row.created_at for row in rows],
+ next_change=next_change,
+ evaluated_times=dict(evaluated_times),
+ )
+
+
+class InsightCorrespondence(SourceCorrespondence):
+ source = SourceKind.INSIGHT
+ # The platform adapter runs production's own policy, so the comparison stays meaningful.
+ production_policy = INSIGHT_ALERT_POLICY
+ platform_policy = INSIGHT_ALERT_POLICY
+ intentional_divergences = INSIGHT_INTENTIONAL_DIVERGENCES
+
+ def verdicts_for(self, checks: Sequence[PlatformCheck]) -> Mapping[CheckRef, SourceVerdict]:
+ verdicts: dict[CheckRef, SourceVerdict] = {}
+ by_team: dict[int, list[_Pairing]] = defaultdict(list)
+ for check in checks:
+ slot = slot_of_evaluation_key(check.evaluation_key)
+ if check.legacy_configuration_id is None:
+ verdicts[check.ref] = _unknown("the platform configuration names no insight alert")
+ elif slot is None:
+ verdicts[check.ref] = _unknown("the evaluation key names no due slot")
+ else:
+ by_team[check.team_id].append(_Pairing(check=check, alert_id=check.legacy_configuration_id, slot=slot))
+
+ for team_id, pairings in by_team.items():
+ verdicts.update(_team_verdicts(team_id, pairings))
+ return verdicts
+
+
+def _team_verdicts(team_id: int, pairings: list[_Pairing]) -> dict[CheckRef, SourceVerdict]:
+ alerts = {
+ alert.id: alert
+ for alert in AlertConfiguration.objects.filter(
+ team_id=team_id, id__in={pairing.alert_id for pairing in pairings}
+ )
+ .select_related("team")
+ .only(
+ "id",
+ "team_id",
+ "team__timezone",
+ "calculation_interval",
+ "enabled",
+ "skip_weekend",
+ "schedule_restriction",
+ )
+ }
+ periods: dict[CheckRef, _Period | None] = {
+ pairing.check.ref: _period_of(pairing.slot, alerts[pairing.alert_id])
+ for pairing in pairings
+ if pairing.alert_id in alerts
+ }
+ bounds: dict[UUID, _Period] = {}
+ for pairing in pairings:
+ period = periods.get(pairing.check.ref)
+ if period is not None:
+ known = bounds.get(pairing.alert_id, period)
+ bounds[pairing.alert_id] = _Period(start=min(known.start, period.start), end=max(known.end, period.end))
+
+ rows: list[tuple[UUID, UUID, datetime, str, dict | None]] = []
+ alert_bounds = list(bounds.items())
+ for chunk_start in range(0, len(alert_bounds), ALERTS_PER_QUERY):
+ # Each alert over its own periods, so one old slot does not widen every alert's read.
+ # Built in one step, because growing a Q with |= copies its children on every alert.
+ since = Q(
+ *(
+ Q(
+ alert_configuration_id=alert_id,
+ created_at__gte=bound.start,
+ created_at__lt=bound.end + CATCH_UP_HORIZON,
+ )
+ for alert_id, bound in alert_bounds[chunk_start : chunk_start + ALERTS_PER_QUERY]
+ ),
+ _connector=Q.OR,
+ )
+ rows.extend(
+ AlertCheck.objects.filter(since, alert_configuration__team_id=team_id)
+ .order_by("alert_configuration_id", "created_at")
+ .values_list("alert_configuration_id", "id", "created_at", "state", "triggered_metadata")[
+ : MAX_CHECKS_PER_BATCH + 1 - len(rows)
+ ]
+ )
+ if len(rows) > MAX_CHECKS_PER_BATCH:
+ break
+ if len(rows) > MAX_CHECKS_PER_BATCH:
+ logger.warning("Insight alert comparison could not read every check it needs", team_id=team_id)
+ return {
+ pairing.check.ref: _unknown("too many insight checks to pair this check against") for pairing in pairings
+ }
+
+ checks: dict[UUID, list[_ProductionCheck]] = defaultdict(list)
+ for alert_id, check_id, created_at, state, metadata in rows:
+ if state == InsightAlertState.SNOOZED:
+ # Snoozing writes a row carrying the snoozed state, which no evaluation produces. An unsnooze
+ # row looks like a healthy breakdown evaluation (no value, no error), so it stays.
+ continue
+ skipped = bool((metadata or {}).get("skipped_reason"))
+ checks[alert_id].append(
+ _ProductionCheck(
+ id=check_id,
+ created_at=created_at,
+ state=_platform_state(state),
+ skipped=skipped,
+ )
+ )
+
+ history = {alert_id: _History.of(alert_rows) for alert_id, alert_rows in checks.items()}
+ kept_since = datetime.now(UTC) - AlertCheck.RETENTION
+ verdicts: dict[CheckRef, SourceVerdict] = {}
+ for pairing in pairings:
+ alert = alerts.get(pairing.alert_id)
+ if alert is None:
+ verdicts[pairing.check.ref] = _unknown("no insight alert with that id in this project")
+ continue
+ if pairing.check.state == AlertState.SNOOZED:
+ verdicts[pairing.check.ref] = _snoozed(alert)
+ continue
+ period = periods.get(pairing.check.ref)
+ if period is None:
+ verdicts[pairing.check.ref] = _unknown("the insight alert's interval has no period to pair within")
+ continue
+ # The period, not the slot: production's check of the period can come before the slot.
+ if period.start < kept_since:
+ verdicts[pairing.check.ref] = _unknown("production no longer keeps its checks from this period")
+ continue
+ # The platform tests its schedule when it decides, which can be later than the slot.
+ if _skipped_by_schedule(pairing.check.occurred_at, alert):
+ # Both stacks skip the slot by the alert's schedule, so the platform has no verdict to compare.
+ verdicts[pairing.check.ref] = _unknown("the alert's schedule skips this slot")
+ continue
+ verdicts[pairing.check.ref] = _verdict_at(pairing, alert, period, history.get(pairing.alert_id, _EMPTY))
+ return verdicts
+
+
+def _period_of(slot: datetime, alert: AlertConfiguration) -> _Period | None:
+ """The local calendar period the slot falls in: its quarter hour, hour, day, ISO week or month.
+
+ Both schedulers check once per such period, each at an offset of its own, so production's check
+ of the same period can come before the platform's slot as well as after it.
+ """
+ interval = alert.calculation_interval or ""
+ if interval in _SUB_DAY_PERIOD_MINUTES:
+ minutes = _SUB_DAY_PERIOD_MINUTES[interval]
+ team_timezone = pytz.timezone(alert.team.timezone)
+ start = local_period_start(slot, team_timezone, minutes)
+ return _Period(start=start, end=next_local_period_start(start, team_timezone, minutes))
+ if interval not in _CALENDAR_PERIOD:
+ return None
+ local = slot.astimezone(alert.team.timezone_info)
+ midnight = local.replace(hour=0, minute=0, second=0, microsecond=0)
+ if interval == AlertCalculationInterval.WEEKLY:
+ midnight -= relativedelta(days=midnight.weekday())
+ elif interval == AlertCalculationInterval.MONTHLY:
+ midnight = midnight.replace(day=1)
+ return _Period(start=midnight.astimezone(UTC), end=(midnight + _CALENDAR_PERIOD[interval]).astimezone(UTC))
+
+
+def _platform_state(insight_state: str) -> str | None:
+ try:
+ return platform_state_of(insight_state).value
+ except (ValueError, KeyError):
+ return None
+
+
+def _unknown(detail: str) -> SourceVerdict:
+ return SourceVerdict(caught_up_at=None, coverage=SourceCoverage.UNKNOWN, state=None, detail=detail)
+
+
+_EMPTY = _History.of([])
+
+
+def _verdict_at(pairing: _Pairing, alert: AlertConfiguration, period: _Period, history: _History) -> SourceVerdict:
+ """Production's first check of the slot's period, when it left that state, and when an evaluated
+ check of production's reached the platform's state."""
+ index = bisect_left(history.times, period.start)
+ if index == len(history.rows) or history.rows[index].created_at >= period.end:
+ return _no_check_in_period(alert)
+
+ matched = history.rows[index]
+ if matched.skipped:
+ return _unknown("production skipped this check without evaluating it")
+ if matched.state is None:
+ return _unknown("production recorded a state the platform does not spell")
+ left = history.next_change[index]
+ reached = history.evaluated_times.get(pairing.check.state, [])
+ caught_up = bisect_right(reached, pairing.check.occurred_at)
+ return SourceVerdict(
+ coverage=SourceCoverage.EVALUATED,
+ state=matched.state,
+ observed_at=history.times[left] if left is not None else None,
+ caught_up_at=reached[caught_up] if caught_up < len(reached) else None,
+ evidence_id=str(matched.id),
+ )
+
+
+def _skipped_by_schedule(at: datetime, alert: AlertConfiguration) -> bool:
+ """Whether the alert's schedule skips a check at `at`. The alert's current settings stand in for
+ its settings then, because production keeps no history of them."""
+ return (alert.skip_weekend and is_weekend(at, alert.team.timezone)) or is_utc_datetime_blocked(alert, at)
+
+
+def _snoozed(alert: AlertConfiguration) -> SourceVerdict:
+ """A platform check that held the alert snoozed. Both stacks read the same production snooze and
+ evaluate nothing, unless production has since switched the alert off."""
+ if not alert.enabled:
+ return SourceVerdict(
+ caught_up_at=None,
+ coverage=SourceCoverage.SUPPRESSED,
+ state=None,
+ suppressed_by=SuppressionReason.DISABLED,
+ )
+ return SourceVerdict(
+ coverage=SourceCoverage.SUPPRESSED,
+ state=AlertState.SNOOZED.value,
+ suppressed_by=SuppressionReason.MUTED,
+ caught_up_at=None,
+ )
+
+
+def _no_check_in_period(alert: AlertConfiguration) -> SourceVerdict:
+ """Why production made no check of the slot's period."""
+ if not alert.enabled:
+ # The copy kept checking an alert production switched off, so the backfill is out of date.
+ return SourceVerdict(
+ caught_up_at=None,
+ coverage=SourceCoverage.SUPPRESSED,
+ state=None,
+ suppressed_by=SuppressionReason.DISABLED,
+ )
+ return SourceVerdict(
+ caught_up_at=None,
+ coverage=SourceCoverage.BEHIND,
+ state=None,
+ detail="production made no check of this alert in the slot's period",
+ )
diff --git a/products/alerts/backend/insight_alert_state_machine.py b/products/alerts/backend/insight_alert_state_machine.py
index 6ec8b59121bc..00acef4d46c5 100644
--- a/products/alerts/backend/insight_alert_state_machine.py
+++ b/products/alerts/backend/insight_alert_state_machine.py
@@ -55,9 +55,14 @@ def insight_snapshot(
)
+def platform_state_of(insight_state: str) -> AlertState:
+ """Insight stores the `schema_enums` spelling ("Firing"). The machine spells it "firing"."""
+ return AlertState[InsightAlertState(insight_state).name]
+
+
def snapshot_from_alert(alert: AlertConfiguration) -> AlertSnapshot:
return insight_snapshot(
- AlertState[InsightAlertState(alert.state).name],
+ platform_state_of(alert.state),
last_notified_at=alert.last_notified_at,
snooze_until=alert.snoozed_until,
)
diff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.py
index d063dae286b6..ed6ea516975d 100644
--- a/products/alerts/backend/models/alert.py
+++ b/products/alerts/backend/models/alert.py
@@ -494,9 +494,10 @@ class AlertCheck(UUIDTModel):
the "destinations" key); legacy rows only carry configured recipients."""
return "destinations" in (self.targets_notified or {})
+ RETENTION = timedelta(days=14)
+
@classmethod
def clean_up_old_checks(cls) -> int:
- retention_days = 14
- oldest_allowed_date = datetime.now(UTC) - timedelta(days=retention_days)
+ oldest_allowed_date = datetime.now(UTC) - cls.RETENTION
rows_count, _ = cls.objects.filter(created_at__lt=oldest_allowed_date).delete()
return rows_count
diff --git a/products/alerts/backend/platform_source_cycle.py b/products/alerts/backend/platform_source_cycle.py
index 966b8d2b2c54..7e3f4545e83b 100644
--- a/products/alerts/backend/platform_source_cycle.py
+++ b/products/alerts/backend/platform_source_cycle.py
@@ -83,6 +83,8 @@ QUERY_ID_PREFIX = "alerts-platform-insight:"
# matches on it to set those checks aside.
CAPACITY_REJECTED = "ClickHouse refused the query for capacity"
+SLOT_KEY_PREFIX = "slot:"
+
# Real-time is the most expensive cadence and the one production holds to a tighter budget, so the
# parallel run leaves it out until it agrees with production elsewhere.
EVALUATED_INTERVALS = frozenset(
@@ -225,7 +227,22 @@ def _snapshot(check: PlatformAlertCheckInput) -> AlertSnapshot:
def _evaluation_key(check: PlatformAlertCheckInput, cutoff: datetime) -> str:
"""The due slot. An insight check is one scheduled run, not a window, so the slot names it."""
- return f"slot:{slot_of(check.next_check_at, cutoff)}"
+ return evaluation_key_for_slot(slot_of(check.next_check_at, cutoff))
+
+
+def evaluation_key_for_slot(slot: str) -> str:
+ return f"{SLOT_KEY_PREFIX}{slot}"
+
+
+def slot_of_evaluation_key(evaluation_key: str) -> datetime | None:
+ """The due slot a key names, or None for another shape. Kept beside the minter, so a change to
+ one breaks the other's tests rather than the comparison silently."""
+ if not evaluation_key.startswith(SLOT_KEY_PREFIX):
+ return None
+ try:
+ return datetime.fromisoformat(evaluation_key.removeprefix(SLOT_KEY_PREFIX))
+ except ValueError:
+ return None
def _decide(check: PlatformAlertCheckInput, now: datetime, *, evaluation_id: str) -> PlatformAlertOutcome:
diff --git a/products/alerts/backend/test/test_alert_comparison.py b/products/alerts/backend/test/test_alert_comparison.py
new file mode 100644
index 000000000000..43fd6d914526
--- /dev/null
+++ b/products/alerts/backend/test/test_alert_comparison.py
@@ -0,0 +1,365 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+from uuid import UUID, uuid4
+
+import time_machine
+from posthog.test.base import BaseTest
+from unittest import TestCase
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.schema import ChartDisplayType, EventsNode, IntervalType, TrendsFilter, TrendsQuery
+
+from posthog.schema_enums import (
+ AlertCalculationInterval,
+ AlertState as InsightAlertState,
+)
+
+from products.alerts.backend.alert_comparison import INSIGHT_INTENTIONAL_DIVERGENCES, InsightCorrespondence
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Threshold
+from products.alerts.backend.platform_source_cycle import CAPACITY_REJECTED, evaluation_key_for_slot
+from products.alerts_platform.backend.facade.api import slot_of
+from products.alerts_platform.backend.facade.contracts import (
+ PlatformCheck,
+ SourceCoverage,
+ SourceVerdict,
+ SuppressionReason,
+)
+from products.alerts_platform.backend.facade.testing import undeclared_policy_divergences
+from products.product_analytics.backend.facade.models import Insight
+
+SLOT = datetime(2026, 10, 7, 12, 0, tzinfo=UTC)
+KEY = evaluation_key_for_slot(slot_of(SLOT, SLOT))
+CHECKED_AT = SLOT + timedelta(minutes=1)
+
+
+def _platform_check(*, legacy_configuration_id: UUID | None, team_id: int, **overrides: Any) -> PlatformCheck:
+ fields: dict[str, Any] = {
+ "team_id": team_id,
+ "configuration_id": uuid4(),
+ "legacy_configuration_id": legacy_configuration_id,
+ "alert_id": uuid4(),
+ "grouping_key": "",
+ "evaluation_key": KEY,
+ "kind": "check",
+ "previous_state": "not_firing",
+ "state": "firing",
+ "muted_notification": "none",
+ "error_message": "",
+ "occurred_at": CHECKED_AT,
+ }
+ fields.update(overrides)
+ return PlatformCheck(**fields)
+
+
+class TestInsightDivergenceDeclarations(TestCase):
+ def test_every_policy_divergence_is_declared(self) -> None:
+ assert undeclared_policy_divergences(InsightCorrespondence()) == frozenset()
+
+
+@time_machine.travel(SLOT + timedelta(days=1), tick=False)
+class TestInsightCorrespondence(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ insight = Insight.objects.create(
+ team=self.team,
+ name="insight",
+ query=TrendsQuery(
+ series=[EventsNode(event="$pageview")],
+ interval=IntervalType.DAY,
+ trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),
+ ).model_dump(),
+ )
+ threshold = Threshold.objects.create(
+ team=self.team, insight=insight, configuration={"type": "absolute", "bounds": {"upper": 100.0}}
+ )
+ self.alert = AlertConfiguration.objects.create(
+ team=self.team,
+ insight=insight,
+ name="alert",
+ calculation_interval=AlertCalculationInterval.HOURLY.value,
+ config={"type": "TrendsAlertConfig", "series_index": 0},
+ condition={"type": "absolute_value"},
+ threshold=threshold,
+ )
+
+ def _production(self, *checks: tuple[InsightAlertState, timedelta], skipped: bool = False) -> list[AlertCheck]:
+ rows = []
+ for state, offset in checks:
+ metadata = {"skipped_reason": "no data"} if skipped else None
+ row = AlertCheck.objects.create(
+ alert_configuration=self.alert,
+ state=state.value,
+ triggered_metadata=metadata,
+ calculated_value=None if skipped else 42.0,
+ )
+ AlertCheck.objects.filter(id=row.id).update(created_at=SLOT + offset)
+ rows.append(row)
+ return rows
+
+ def _check(self, **overrides: Any) -> PlatformCheck:
+ return _platform_check(**{"legacy_configuration_id": self.alert.id, "team_id": self.team.id, **overrides})
+
+ def _verdict(self, check: PlatformCheck) -> SourceVerdict:
+ return InsightCorrespondence().verdicts_for([check])[check.ref]
+
+ def test_a_check_pairs_with_productions_first_check_of_the_same_period(self) -> None:
+ _, same_period = self._production(
+ (InsightAlertState.NOT_FIRING, -timedelta(minutes=23)),
+ (InsightAlertState.FIRING, timedelta(minutes=37)),
+ )
+
+ verdict = self._verdict(self._check())
+
+ assert (verdict.coverage, verdict.state, verdict.evidence_id) == (
+ SourceCoverage.EVALUATED,
+ "firing",
+ str(same_period.id),
+ )
+
+ def test_production_leaving_and_catching_up_are_dated_separately(self) -> None:
+ self._production(
+ (InsightAlertState.NOT_FIRING, timedelta(minutes=37)),
+ (InsightAlertState.ERRORED, timedelta(minutes=97)),
+ (InsightAlertState.FIRING, timedelta(minutes=157)),
+ )
+
+ verdict = self._verdict(self._check())
+
+ assert (verdict.state, verdict.observed_at, verdict.caught_up_at) == (
+ "not_firing",
+ SLOT + timedelta(minutes=97),
+ SLOT + timedelta(minutes=157),
+ )
+
+ @parameterized.expand(
+ [
+ ("no_check_since_the_slot", -timedelta(minutes=23), {}, SLOT, SourceCoverage.BEHIND),
+ ("its_next_check_is_a_later_period", timedelta(minutes=97), {}, SLOT, SourceCoverage.BEHIND),
+ (
+ "an_alert_production_disabled",
+ -timedelta(minutes=23),
+ {"enabled": False},
+ SLOT,
+ SourceCoverage.SUPPRESSED,
+ ),
+ (
+ "a_weekend_production_skips",
+ -timedelta(minutes=23),
+ {"skip_weekend": True},
+ datetime(2026, 10, 10, 12, 0, tzinfo=UTC),
+ SourceCoverage.UNKNOWN,
+ ),
+ ]
+ )
+ def test_a_period_production_made_no_check_of(
+ self, _name: str, offset: timedelta, alert_fields: dict[str, Any], slot: datetime, coverage: SourceCoverage
+ ) -> None:
+ self._production((InsightAlertState.NOT_FIRING, offset))
+ AlertConfiguration.objects.filter(id=self.alert.id).update(**alert_fields)
+
+ check = self._check(evaluation_key=evaluation_key_for_slot(slot_of(slot, slot)), occurred_at=slot)
+
+ assert self._verdict(check).coverage is coverage
+
+ @parameterized.expand(
+ [
+ # Production checks the same local day earlier than the platform's slot.
+ (
+ "an_earlier_check_of_the_same_day",
+ AlertCalculationInterval.DAILY,
+ "America/Los_Angeles",
+ datetime(2026, 3, 4, 9, 52, tzinfo=UTC),
+ datetime(2026, 3, 4, 9, 37, tzinfo=UTC),
+ SourceCoverage.EVALUATED,
+ ),
+ # A fixed 31 days from February 1 would reach into March.
+ (
+ "february",
+ AlertCalculationInterval.MONTHLY,
+ "UTC",
+ datetime(2026, 2, 1, 4, 30, tzinfo=UTC),
+ datetime(2026, 3, 1, 4, 20, tzinfo=UTC),
+ SourceCoverage.BEHIND,
+ ),
+ # Spring forward makes March 8 a 23-hour day, so a fixed 24 hours would reach into March 9.
+ (
+ "a_daylight_saving_day",
+ AlertCalculationInterval.DAILY,
+ "America/Los_Angeles",
+ datetime(2026, 3, 8, 9, 0, tzinfo=UTC),
+ datetime(2026, 3, 9, 7, 30, tzinfo=UTC),
+ SourceCoverage.BEHIND,
+ ),
+ (
+ "a_daylight_saving_week",
+ AlertCalculationInterval.WEEKLY,
+ "America/Los_Angeles",
+ datetime(2026, 3, 2, 11, 0, tzinfo=UTC),
+ datetime(2026, 3, 9, 7, 30, tzinfo=UTC),
+ SourceCoverage.BEHIND,
+ ),
+ # Lord Howe springs forward 30 minutes, so its local 02:00 hour lasts from 02:30 to 03:00.
+ (
+ "a_half_hour_daylight_saving_hour",
+ AlertCalculationInterval.HOURLY,
+ "Australia/Lord_Howe",
+ datetime(2026, 10, 3, 15, 40, tzinfo=UTC),
+ datetime(2026, 10, 3, 16, 5, tzinfo=UTC),
+ SourceCoverage.BEHIND,
+ ),
+ ]
+ )
+ def test_a_check_pairs_within_the_local_calendar_period_of_its_slot(
+ self,
+ _name: str,
+ interval: AlertCalculationInterval,
+ timezone: str,
+ slot: datetime,
+ production_check: datetime,
+ coverage: SourceCoverage,
+ ) -> None:
+ self.team.timezone = timezone
+ self.team.save()
+ AlertConfiguration.objects.filter(id=self.alert.id).update(calculation_interval=interval.value)
+ row = AlertCheck.objects.create(
+ alert_configuration=self.alert, state=InsightAlertState.FIRING.value, calculated_value=42.0
+ )
+ AlertCheck.objects.filter(id=row.id).update(created_at=production_check)
+ check = self._check(evaluation_key=evaluation_key_for_slot(slot_of(slot, slot)), occurred_at=slot)
+
+ # Inside production's check retention, so the period decides rather than the retention cut.
+ with time_machine.travel(slot + timedelta(days=1), tick=False):
+ verdict = self._verdict(check)
+
+ assert verdict.coverage is coverage
+
+ def test_a_check_the_schedule_blocked_when_the_platform_decided_is_not_compared(self) -> None:
+ self._production((InsightAlertState.FIRING, timedelta(minutes=5)))
+ AlertConfiguration.objects.filter(id=self.alert.id).update(
+ schedule_restriction={"blocked_windows": [{"start": "12:30", "end": "13:30"}]}
+ )
+ slot = SLOT + timedelta(minutes=25)
+ check = self._check(
+ evaluation_key=evaluation_key_for_slot(slot_of(slot, slot)), occurred_at=SLOT + timedelta(minutes=35)
+ )
+
+ assert self._verdict(check).coverage is SourceCoverage.UNKNOWN
+
+ def _row(self, state: InsightAlertState, offset: timedelta, alert: AlertConfiguration | None = None) -> None:
+ """A production row with no value and no error, the shape of both a snooze row and a healthy
+ breakdown evaluation."""
+ row = AlertCheck.objects.create(alert_configuration=alert or self.alert, state=state.value)
+ AlertCheck.objects.filter(id=row.id).update(created_at=SLOT + offset)
+
+ def test_a_snooze_row_is_not_paired_as_an_evaluation(self) -> None:
+ self._row(InsightAlertState.SNOOZED, timedelta(minutes=5))
+ self._production((InsightAlertState.FIRING, timedelta(minutes=37)))
+
+ verdict = self._verdict(self._check())
+
+ assert (verdict.coverage, verdict.state) == (SourceCoverage.EVALUATED, "firing")
+
+ def test_a_healthy_breakdown_evaluation_without_a_value_is_paired(self) -> None:
+ self._row(InsightAlertState.NOT_FIRING, timedelta(minutes=37))
+
+ verdict = self._verdict(self._check(state="not_firing"))
+
+ assert (verdict.coverage, verdict.state) == (SourceCoverage.EVALUATED, "not_firing")
+
+ def test_alerts_read_across_several_history_queries_are_all_paired(self) -> None:
+ other = AlertConfiguration.objects.create(
+ team=self.team,
+ insight=self.alert.insight,
+ name="other",
+ calculation_interval=self.alert.calculation_interval,
+ )
+ self._row(InsightAlertState.FIRING, timedelta(minutes=37))
+ self._row(InsightAlertState.FIRING, timedelta(minutes=37), alert=other)
+ checks = [self._check(), self._check(legacy_configuration_id=other.id)]
+
+ with patch(f"{InsightCorrespondence.__module__}.ALERTS_PER_QUERY", 1):
+ verdicts = InsightCorrespondence().verdicts_for(checks)
+
+ assert [verdicts[check.ref].coverage for check in checks] == [SourceCoverage.EVALUATED] * 2
+
+ def test_a_skipped_production_check_is_not_catching_up(self) -> None:
+ self._production((InsightAlertState.FIRING, timedelta(minutes=37)))
+ self._production((InsightAlertState.NOT_FIRING, timedelta(minutes=97)), skipped=True)
+
+ verdict = self._verdict(self._check(state="not_firing"))
+
+ assert (verdict.state, verdict.caught_up_at) == ("firing", None)
+
+ def test_production_checks_past_the_catch_up_horizon_are_not_read(self) -> None:
+ self._production(
+ (InsightAlertState.FIRING, timedelta(minutes=37)),
+ *[(InsightAlertState.FIRING, timedelta(days=3, minutes=n)) for n in range(5)],
+ )
+
+ with patch(f"{InsightCorrespondence.__module__}.MAX_CHECKS_PER_BATCH", 3):
+ verdict = self._verdict(self._check())
+
+ assert verdict.coverage is SourceCoverage.EVALUATED
+
+ @parameterized.expand(
+ [
+ ("production_still_snoozes_it", True, "snoozed", SuppressionReason.MUTED),
+ ("production_has_switched_it_off", False, None, SuppressionReason.DISABLED),
+ ]
+ )
+ def test_a_snoozed_check_is_suppressed_on_both_stacks(
+ self, _name: str, enabled: bool, state: str | None, reason: SuppressionReason
+ ) -> None:
+ AlertConfiguration.objects.filter(id=self.alert.id).update(enabled=enabled)
+
+ verdict = self._verdict(self._check(state="snoozed"))
+
+ assert (verdict.coverage, verdict.state, verdict.suppressed_by) == (SourceCoverage.SUPPRESSED, state, reason)
+
+ @parameterized.expand(
+ [
+ ("an_unslotted_key", {"evaluation_key": "window:2026-10-07T12:00:00+00:00"}),
+ ("no_insight_alert", {"legacy_configuration_id": None}),
+ ("another_projects_alert", {"team_id": -1}),
+ (
+ "a_slot_past_retention",
+ {"evaluation_key": evaluation_key_for_slot(slot_of(SLOT - timedelta(days=14), SLOT))},
+ ),
+ ]
+ )
+ def test_a_check_that_names_no_production_check_cannot_be_answered(
+ self, _name: str, overrides: dict[str, Any]
+ ) -> None:
+ self._production((InsightAlertState.FIRING, timedelta(minutes=37)))
+ check = self._check(**overrides)
+ # A batch spans teams, so the alert's own team reads it in the same call.
+ owner = self._check()
+
+ verdicts = InsightCorrespondence().verdicts_for([check, owner])
+
+ assert verdicts[check.ref].coverage is SourceCoverage.UNKNOWN
+ assert verdicts[owner.ref].coverage is SourceCoverage.EVALUATED
+
+ def test_a_check_production_skipped_cannot_be_answered(self) -> None:
+ self._production((InsightAlertState.FIRING, timedelta(minutes=37)), skipped=True)
+
+ assert self._verdict(self._check()).coverage is SourceCoverage.UNKNOWN
+
+ def test_only_a_capacity_refusal_is_declared(self) -> None:
+ self._production((InsightAlertState.FIRING, timedelta(minutes=37)))
+ refused = self._check(
+ state="not_firing",
+ error_message=CAPACITY_REJECTED,
+ )
+ failed = self._check(
+ state="not_firing",
+ error_message="query timed out",
+ )
+
+ verdicts = InsightCorrespondence().verdicts_for([refused, failed])
+ (declared,) = INSIGHT_INTENTIONAL_DIVERGENCES
+
+ assert declared.recognizes(refused, verdicts[refused.ref])
+ assert not declared.recognizes(failed, verdicts[failed.ref])
diff --git a/products/alerts_platform/backend/facade/scheduling.py b/products/alerts_platform/backend/facade/scheduling.py
index 544fe23f496b..9050050566a3 100644
--- a/products/alerts_platform/backend/facade/scheduling.py
+++ b/products/alerts_platform/backend/facade/scheduling.py
@@ -201,7 +201,7 @@ def _calendar_anchor_utc(
return _localize_wall_time(team_timezone, naive_local).astimezone(UTC)
-def _local_period_start(timestamp: datetime, team_timezone: BaseTzInfo, period_minutes: int) -> datetime:
+def local_period_start(timestamp: datetime, team_timezone: BaseTzInfo, period_minutes: int) -> datetime:
"""Start of the local-time period of `period_minutes` that contains `timestamp`.
The start is found on the local wall clock. A 30-minute DST change (Australia/Lord_Howe) moves the
@@ -217,7 +217,7 @@ def _local_period_start(timestamp: datetime, team_timezone: BaseTzInfo, period_m
return _localize_wall_time(team_timezone, wall_start, repeated_is_dst=bool(local.dst())).astimezone(UTC)
-def _next_local_period_start(after: datetime, team_timezone: BaseTzInfo, period_minutes: int) -> datetime:
+def next_local_period_start(after: datetime, team_timezone: BaseTzInfo, period_minutes: int) -> datetime:
"""First start of a local-time period of `period_minutes` that is later than `after`.
A DST change can make a local period longer or shorter than `period_minutes`. A 30-minute change
@@ -227,10 +227,10 @@ def _next_local_period_start(after: datetime, team_timezone: BaseTzInfo, period_
"""
step = timedelta(minutes=min(period_minutes, 15))
probe = after + step
- start = _local_period_start(probe, team_timezone, period_minutes)
+ start = local_period_start(probe, team_timezone, period_minutes)
while start <= after:
probe += step
- start = _local_period_start(probe, team_timezone, period_minutes)
+ start = local_period_start(probe, team_timezone, period_minutes)
return start
@@ -365,9 +365,9 @@ def next_calendar_check_time(
cadence_minutes = EVERY_15_MINUTES_CADENCE_MINUTES if interval == CalendarInterval.EVERY_15_MINUTES else 60
# The check runs at this alert's offset into the first local interval after the previous check,
# which also moves an alert off the minute it was created on.
- candidate = _next_local_period_start(next_check_at or now, team_timezone, cadence_minutes) + offset
+ candidate = next_local_period_start(next_check_at or now, team_timezone, cadence_minutes) + offset
if candidate <= now:
- candidate = _next_local_period_start(now - offset, team_timezone, cadence_minutes) + offset
+ candidate = next_local_period_start(now - offset, team_timezone, cadence_minutes) + offset
return candidate
case CalendarInterval.DAILY:
return _calendar_anchor_utc(