: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
feat(alerts): shadow a new team's insight alerts when they're created (#129812)
Jimmy Zhu3db75e29e52f
diff --git a/products/alerts/backend/platform_alert_backfill.py b/products/alerts/backend/platform_alert_backfill.pyindex 40101547d5ed..22bec8846964 100644--- a/products/alerts/backend/platform_alert_backfill.py+++ b/products/alerts/backend/platform_alert_backfill.py@@ -109,10 +109,11 @@ def disable_platform_insight_alert_configurations(def follow_insight_alert(alert: AlertConfiguration) -> None:- """Copies an insight alert that was just created or turned back on, if its team runs insight on the platform.+ """Copies an insight alert that was just created or turned back on, while insight runs on the platform.Checks only read enabled copies, so no check would ever see this alert otherwise, and it would- stay off the platform until the next backfill.+ stay off the platform until the next backfill. The insight parallel run covers every team, so a+ team with no enabled copy yet, such as one creating its first alert, is admitted too.An AI detector alert is never followed. The backfill copies those only when an operator asks,and a copy's stored detector is what records that request, so following would overwrite it.@@ -121,4 +122,4 @@ def follow_insight_alert(alert: AlertConfiguration) -> None:returnupsert = platform_upsert_of(alert)if upsert is not None:- upsert_if_running(upsert, revive=True)+ upsert_if_running(upsert, revive=True, admit_new_teams=True)diff --git a/products/alerts/backend/test/test_platform_alert_backfill.py b/products/alerts/backend/test/test_platform_alert_backfill.pyindex b03aabe3e274..e7d98379f5f3 100644--- a/products/alerts/backend/test/test_platform_alert_backfill.py+++ b/products/alerts/backend/test/test_platform_alert_backfill.py@@ -11,6 +11,7 @@ from parameterized import parameterizedfrom posthog.schema import ChartDisplayType, EventsNode, IntervalType, TrendsFilter, TrendsQuery+from posthog.models import Teamfrom posthog.models.scoping import team_scopefrom posthog.schema_enums import AlertCalculationInterval@@ -29,9 +30,10 @@ THRESHOLD = {"type": "absolute", "bounds": {"upper": 100.0}}class TestPlatformInsightAlertBackfill(APIBaseTest):- def _alert(self, **overrides: Any) -> AlertConfiguration:+ def _alert(self, team: Team | None = None, **overrides: Any) -> AlertConfiguration:+ team = team or self.teaminsight = Insight.objects.create(- team=self.team,+ team=team,name="insight",query=TrendsQuery(series=[EventsNode(event="$pageview")],@@ -39,9 +41,9 @@ class TestPlatformInsightAlertBackfill(APIBaseTest):trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),).model_dump(),)- threshold = Threshold.objects.create(team=self.team, insight=insight, configuration=THRESHOLD)+ threshold = Threshold.objects.create(team=team, insight=insight, configuration=THRESHOLD)fields: dict[str, Any] = {- "team": self.team,+ "team": team,"insight": insight,"name": "alert","calculation_interval": AlertCalculationInterval.DAILY.value,@@ -129,23 +131,38 @@ class TestPlatformInsightAlertBackfill(APIBaseTest):@parameterized.expand([- ("a_team_on_the_platform", True, False, None, "renamed"),- ("a_team_off_the_platform", False, False, None, None),- ("an_ai_alert", True, False, {"type": "llm"}, None),- ("an_alert_switched_to_ai_after_its_copy", True, True, {"type": "llm"}, "alert"),+ ("a_team_on_the_platform", "running", False, None, "renamed"),+ ("insight_off_the_platform", "nowhere", False, None, None),+ ("a_team_new_to_the_platform", "elsewhere", False, None, "renamed"),+ ("a_team_with_only_disabled_copies", "disabled_copies", False, None, "renamed"),+ ("a_team_an_operator_switched_off", "switched_off", False, None, None),+ ("a_team_switched_off_with_only_disabled_copies", "switched_off_disabled_copies", False, None, None),+ ("an_ai_alert", "running", False, {"type": "llm"}, None),+ ("an_alert_switched_to_ai_after_its_copy", "running", True, {"type": "llm"}, "alert"),])def test_a_created_or_reenabled_alert_follows_its_team_onto_the_platform(self,_name: str,- running: bool,+ team_state: str,copied_before: bool,detector: dict[str, str] | None,copy_name: str | None,) -> None:- if running:+ if team_state != "nowhere":+ other_team = Team.objects.create(organization=self.organization, name="other")+ self._alert(team=other_team)+ backfill_platform_insight_alert_configurations(team_id=other_team.id)+ if team_state in ("running", "switched_off"):self._alert()backfill_platform_insight_alert_configurations(team_id=self.team.id)+ if team_state == "switched_off":+ disable_platform_insight_alert_configurations(team_id=self.team.id)+ if team_state in ("disabled_copies", "switched_off_disabled_copies"):+ self._alert(enabled=False)+ backfill_platform_insight_alert_configurations(team_id=self.team.id)+ if team_state == "switched_off_disabled_copies":+ disable_platform_insight_alert_configurations(team_id=self.team.id)created = self._alert()if copied_before:backfill_platform_insight_alert_configurations(alert_ids=[created.id])diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.pyindex ae05609cac6e..9989e6930574 100644--- a/products/alerts_platform/backend/facade/api.py+++ b/products/alerts_platform/backend/facade/api.py@@ -138,12 +138,14 @@ def upsert_configuration(upsert: PlatformAlertUpsert, *, revive: bool = False) -return platform_lifecycle.upsert_configuration(upsert, revive=revive)-def upsert_if_running(upsert: PlatformAlertUpsert, *, revive: bool = False) -> None:+def upsert_if_running(upsert: PlatformAlertUpsert, *, revive: bool = False, admit_new_teams: bool = False) -> None:"""Copy one configuration in only when its team already runs that source here.`revive` says the source alert was just created or turned back on, so the copy starts clean.+ `admit_new_teams` also admits a team with no enabled copy while the source runs elsewhere and+ no operator switched that team off."""- platform_lifecycle.upsert_if_running(upsert, revive=revive)+ platform_lifecycle.upsert_if_running(upsert, revive=revive, admit_new_teams=admit_new_teams)def refresh_settings(team_id: int, configuration_id: UUID, upsert: PlatformAlertUpsert) -> None:diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.pyindex 6663df7b0ff1..0dedbf6ecf5e 100644--- a/products/alerts_platform/backend/logic/platform_lifecycle.py+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py@@ -897,7 +897,7 @@ def write_snooze(configuration: PlatformAlertConfiguration, snooze_until: dateticonfiguration.save(update_fields=["snooze_until", "next_check_at", "updated_at"])-def upsert_if_running(upsert: PlatformAlertUpsert, *, revive: bool = False) -> None:+def upsert_if_running(upsert: PlatformAlertUpsert, *, revive: bool = False, admit_new_teams: bool = False) -> None:"""Copies one configuration in when its team already runs that source here.A copy the platform owns gets nothing, because every edit already writes both of its rows.@@ -905,6 +905,10 @@ def upsert_if_running(upsert: PlatformAlertUpsert, *, revive: bool = False) -> Nenabled. A team the backfill left out of its sample, or one`disable_configurations` switched off, gets nothing, and neither does a copy an operator switchedoff by name, so a write in the source never widens a sample or undoes an operator's switch-off.++ `admit_new_teams` is for a source whose parallel run covers every team. It also admits a team with+ no enabled copy, such as one whose first alert this is, while the source runs for another team and+ no operator switched this team off."""with transaction.atomic():_hold_admission(upsert.source_kind.value, exclusive=False)@@ -914,12 +918,25 @@ def upsert_if_running(upsert: PlatformAlertUpsert, *, revive: bool = False) -> Nexisting = team_copies.filter(legacy_configuration_id=upsert.legacy_configuration_id).first()if existing is not None and existing.owner == PlatformAlertOwner.PLATFORM:return- running = team_copies.filter(owner=PlatformAlertOwner.SOURCE, enabled=True).exists()+ running = team_copies.filter(owner=PlatformAlertOwner.SOURCE, enabled=True).exists() or (+ admit_new_teams and _admits_new_team(team_copies, upsert.source_kind.value)+ )switched_off = existing is not None and existing.switched_off_at is not Noneif running and not switched_off:upsert_configuration(upsert, revive=revive)+def _admits_new_team(team_copies: QuerySet[PlatformAlertConfiguration], source_kind: str) -> bool:+ if team_copies.filter(switched_off_at__isnull=False).exists():+ return False+ # A switch-off of the whole source leaves no enabled copy anywhere, so this admits nothing then.+ return (+ PlatformAlertConfiguration.objects.unscoped()+ .filter(source_kind=source_kind, owner=PlatformAlertOwner.SOURCE, enabled=True)+ .exists()+ )++def _hold_admission(source_kind: str, *, exclusive: bool) -> None:"""Orders admitting a copy against an operator's switch-off, so neither reads the other half done.@@ -1184,10 +1201,14 @@ def disable_configurations(# source still owns: once the platform owns an alert, its copy is the production alert, and# switching it off would silence real notifications rather than stop a parallel check.rows = PlatformAlertConfiguration.objects.unscoped().filter(- source_kind=source_kind, enabled=True, owner=PlatformAlertOwner.SOURCE+ source_kind=source_kind, owner=PlatformAlertOwner.SOURCE)if team_id is not None:rows = rows.filter(team_id=team_id)if legacy_configuration_ids is not None:rows = rows.filter(legacy_configuration_id__in=legacy_configuration_ids)- return rows.update(enabled=False, switched_off_at=django_timezone.now())+ at = django_timezone.now()+ # A copy that is already disabled carries the switch-off too, so `upsert_if_running` cannot+ # admit a switched-off team again through a new alert.+ rows.filter(enabled=False, switched_off_at__isnull=True).update(switched_off_at=at)+ return rows.filter(enabled=True).update(enabled=False, switched_off_at=at)