:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(alerts): keep the platform's schedule when a backfill reruns (#113668)
Jimmy Zhuadb01f6475cd
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.mdindex 9895e9abb9f1..ced9ee39876e 100644--- a/docs/internal/alerts-platform-temporal.md+++ b/docs/internal/alerts-platform-temporal.md@@ -459,6 +459,7 @@ python manage.py backfill_platform_alert_configurationsPass `--team-id` to copy one team's configurations only.It is a seed, not a sync: the logs product keeps the control plane, and a later change to a logs alert reaches these tables only on the next run.A second run updates rather than duplicates, because `legacy_configuration_id` carries the row each copy came from.+A second run of either backfill, logs or insight, leaves an enabled copy's `next_check_at` alone unless it has none yet or its cadence changed, because the platform owns its schedule once the row exists. The logs product parks its own next check at the end of quiet hours, while the platform checks through them and only mutes. A new or re-enabled copy still takes the source's due time, which spreads a large copy's first checks the way the source spreads them.Each run also copies the logs alert's snooze onto its platform alert row, so a snoozed alert stays silent, and an alert unsnoozed since the last run is unsnoozed here too.Insight alerts are copied the same way:diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.pyindex cd495650a32b..47e629aaf172 100644--- a/products/alerts_platform/backend/logic/platform_lifecycle.py+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py@@ -6,6 +6,7 @@ and every write to these rows, stays here. A source never holds one of these modfrom collections.abc import Collection, Sequencefrom datetime import datetime+from typing import Finalfrom django.db import transactionfrom django.db.models import Exists, OuterRef, Q@@ -283,11 +284,19 @@ def record_outcomes(team_id: int, outcomes: Sequence[PlatformAlertOutcome], now:return len(configurations)+_CADENCE_FIELDS: Final = ("check_interval_minutes", "recurrence_unit", "anchor_time")++def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:"""Copies one source configuration in. Returns True when it created a row.Keyed on the row it came from, so a second run updates rather than duplicates.+ `next_check_at` is copied into a new row, into a disabled copy, into a copy with no schedule+ yet, and into a copy whose cadence this run changes. Otherwise the platform owns its schedule: a source can park its own next+ check, for example at the end of quiet hours, and copying that would skip checks the platform+ still runs.+The recurrence is checked here rather than where the schedule advances, because anunparseable unit or anchor raised there would fail a whole batch of unrelated checks."""@@ -296,23 +305,36 @@ def upsert_configuration(upsert: PlatformAlertUpsert) -> bool:anchor_time = validate_and_normalize_schedule_start_time(upsert.anchor_time)with transaction.atomic():+ existing = (+ PlatformAlertConfiguration.objects.unscoped()+ .select_for_update()+ .filter(legacy_configuration_id=upsert.legacy_configuration_id)+ .values("enabled", "next_check_at", *_CADENCE_FIELDS)+ .first()+ )+ defaults = {+ "team_id": upsert.team_id,+ "name": upsert.name,+ "enabled": upsert.enabled,+ "source_kind": upsert.source_kind.value,+ "source_config": upsert.source_config,+ "check_interval_minutes": upsert.check_interval_minutes,+ "recurrence_unit": upsert.recurrence_unit,+ "anchor_time": anchor_time,+ "evaluation_periods": upsert.evaluation_periods,+ "datapoints_to_alarm": upsert.datapoints_to_alarm,+ "cooldown_minutes": upsert.cooldown_minutes,+ "schedule_restriction": upsert.schedule_restriction,+ }+ if (+ existing is None+ or not existing["enabled"]+ or existing["next_check_at"] is None+ or any(existing[key] != defaults[key] for key in _CADENCE_FIELDS)+ ):+ defaults["next_check_at"] = upsert.next_check_atconfiguration, created = PlatformAlertConfiguration.objects.unscoped().update_or_create(- legacy_configuration_id=upsert.legacy_configuration_id,- defaults={- "team_id": upsert.team_id,- "name": upsert.name,- "enabled": upsert.enabled,- "source_kind": upsert.source_kind.value,- "source_config": upsert.source_config,- "check_interval_minutes": upsert.check_interval_minutes,- "recurrence_unit": upsert.recurrence_unit,- "anchor_time": anchor_time,- "evaluation_periods": upsert.evaluation_periods,- "datapoints_to_alarm": upsert.datapoints_to_alarm,- "cooldown_minutes": upsert.cooldown_minutes,- "schedule_restriction": upsert.schedule_restriction,- "next_check_at": upsert.next_check_at,- },+ legacy_configuration_id=upsert.legacy_configuration_id, defaults=defaults)alert = _alerts_for_write(upsert.team_id, [configuration])[str(configuration.id)]# State is left alone because a muted alert keeps tracking reality.diff --git a/products/alerts_platform/backend/tests/test_platform_lifecycle.py b/products/alerts_platform/backend/tests/test_platform_lifecycle.pyindex d5b5073d91d7..78ba56f58e5e 100644--- a/products/alerts_platform/backend/tests/test_platform_lifecycle.py+++ b/products/alerts_platform/backend/tests/test_platform_lifecycle.py@@ -1,13 +1,21 @@from datetime import UTC, datetime, timedelta-from uuid import uuid4+from typing import Any+from uuid import UUID, uuid4import time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin+from parameterized import parameterized+from posthog.clickhouse.client import sync_executefrom posthog.models.scoping import team_scope-from products.alerts_platform.backend.facade.api import due_checks, record_outcomes, upsert_configuration+from products.alerts_platform.backend.facade.api import (+ disable_configurations,+ due_checks,+ record_outcomes,+ upsert_configuration,+)from products.alerts_platform.backend.facade.contracts import (AlertEventKind,FiringEpisode,@@ -135,30 +143,73 @@ class TestPlatformAlertLifecycle(ClickhouseTestMixin, APIBaseTest):assert rows == [("not_firing", self.cutoff)]assert self._alert().firing_started_at is None+ def _copy(self, legacy_id: UUID, **overrides: Any) -> None:+ fields: dict[str, Any] = {+ "legacy_configuration_id": legacy_id,+ "team_id": self.team.id,+ "name": "Copied alert",+ "enabled": True,+ "source_kind": SourceKind.LOGS,+ "source_config": {"condition": {"threshold_count": 1, "threshold_operator": "above", "window_minutes": 5}},+ "check_interval_minutes": 5,+ "evaluation_periods": 1,+ "datapoints_to_alarm": 1,+ "cooldown_minutes": 0,+ "schedule_restriction": None,+ "next_check_at": self.cutoff - timedelta(minutes=1),+ "snooze_until": None,+ }+ fields.update(overrides)+ upsert_configuration(PlatformAlertUpsert(**fields))++ @parameterized.expand(+ [+ # The source parks its own next check at the end of quiet hours. The platform still+ # checks through them and only mutes, so taking that time would skip the muted checks.+ ("an_enabled_copy_keeps_its_own_schedule", False, 5, timedelta(minutes=-1), timedelta(minutes=-1)),+ # A copy that has never had a schedule takes the first one the source offers.+ ("an_unscheduled_copy_takes_the_source_schedule", False, 5, None, timedelta(minutes=34)),+ # A copy switched off with --disable comes back at the source's next due time.+ ("a_disabled_copy_takes_the_source_schedule", True, 5, timedelta(minutes=-1), timedelta(minutes=34)),+ # A new cadence makes the old due time wrong, so the source's own one is the better guess.+ ("a_new_cadence_takes_the_source_schedule", False, 60, timedelta(minutes=-1), timedelta(minutes=34)),+ ]+ )+ def test_a_second_copy_keeps_the_schedule_the_platform_owns(+ self,+ _name: str,+ disabled_between: bool,+ interval_on_rerun: int,+ first_offset: timedelta | None,+ expected_offset: timedelta,+ ) -> None:+ legacy_id = uuid4()+ quiet_hours = {"blocked_windows": [{"start": "15:00", "end": "15:34"}]}++ self._copy(+ legacy_id,+ schedule_restriction=quiet_hours,+ next_check_at=None if first_offset is None else self.cutoff + first_offset,+ )+ if disabled_between:+ disable_configurations(SourceKind.LOGS, team_id=self.team.id)+ self._copy(+ legacy_id,+ schedule_restriction=quiet_hours,+ next_check_at=self.cutoff + timedelta(minutes=34),+ check_interval_minutes=interval_on_rerun,+ )++ with team_scope(self.team.id):+ copied = PlatformAlertConfiguration.objects.get(legacy_configuration_id=legacy_id)+ assert copied.next_check_at == self.cutoff + expected_offset+def test_a_copied_snooze_mutes_without_holding_back_the_check(self) -> None:legacy_id = uuid4()snoozed_until = self.cutoff + timedelta(hours=2)def copy(snooze_until: datetime | None) -> None:- upsert_configuration(- PlatformAlertUpsert(- legacy_configuration_id=legacy_id,- team_id=self.team.id,- name="Snoozed alert",- enabled=True,- source_kind=SourceKind.LOGS,- source_config={- "condition": {"threshold_count": 1, "threshold_operator": "above", "window_minutes": 5}- },- check_interval_minutes=5,- evaluation_periods=1,- datapoints_to_alarm=1,- cooldown_minutes=0,- schedule_restriction=None,- next_check_at=self.cutoff - timedelta(minutes=1),- snooze_until=snooze_until,- )- )+ self._copy(legacy_id, snooze_until=snooze_until)def snooze_seen_by_check() -> tuple[str, datetime | None]:(check,) = [