: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): auto-disable entitlement-gated alerts on plan downgrade (#67935)
Matt Pua9ec082647ca1
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.pyindex 5bbfb96dcc4f..160a67ebfc78 100644--- a/posthog/temporal/alerts/activities.py+++ b/posthog/temporal/alerts/activities.py@@ -60,8 +60,6 @@ async def retrieve_due_alerts() -> list[AlertInfo]:def get_alerts() -> list[AlertInfo]:now = datetime.now(UTC)- # Hourly before daily before weekly/monthly so the cheaper, more- # time-sensitive checks get workers first when the due batch is large.# Keep ordering in sync with calculation_interval_to_order in posthog/tasks/alerts/utils.py.calculation_interval_order = Case(When(calculation_interval=AlertCalculationInterval.REAL_TIME.value, then=Value(0)),@@ -105,7 +103,9 @@ async def prepare_alert(inputs: PrepareAlertActivityInputs) -> PrepareAlertResul@database_sync_to_async(thread_sensitive=False)def _prepare() -> PrepareAlertResult:try:- alert = AlertConfiguration.objects.select_related("insight", "team", "threshold").get(id=inputs.alert_id)+ alert = AlertConfiguration.objects.select_related("insight", "team", "team__organization", "threshold").get(+ id=inputs.alert_id+ )except AlertConfiguration.DoesNotExist:logger.warning("Alert not found", alert_id=inputs.alert_id)return PrepareAlertResult(action=PrepareAction.SKIP, reason=SkipReason.NOT_FOUND)@@ -122,6 +122,21 @@ async def prepare_alert(inputs: PrepareAlertActivityInputs) -> PrepareAlertResul)return PrepareAlertResult(action=PrepareAction.SKIP, reason=SkipReason.INSIGHT_DELETED)+ # Plan downgrade protection: entitlement-gated intervals must stop evaluating when the+ # org loses the feature (e.g. billing downgrade), since API validation only runs on writes.+ # Only one of these will be non-None for any given interval — each returns None when+ # the interval doesn't match, so this is an exclusive check, not a combination.+ entitlement_error = AlertConfiguration.real_time_interval_validation_error(+ calculation_interval=alert.calculation_interval,+ organization=alert.team.organization,+ ) or AlertConfiguration.every_15_minutes_interval_validation_error(+ calculation_interval=alert.calculation_interval,+ organization=alert.team.organization,+ )+ if entitlement_error:+ disable_invalid_alert(alert, entitlement_error)+ return PrepareAlertResult(action=PrepareAction.AUTO_DISABLE, reason=entitlement_error)+now = datetime.now(UTC)if alert.next_check_at and alert.next_check_at > now:diff --git a/posthog/temporal/alerts/retry_policy.py b/posthog/temporal/alerts/retry_policy.pyindex 5106130a7ea7..60696fc7a751 100644--- a/posthog/temporal/alerts/retry_policy.py+++ b/posthog/temporal/alerts/retry_policy.py@@ -1,7 +1,10 @@import datetime as dt+import dataclassesfrom temporalio.common import RetryPolicy+from posthog.schema_enums import AlertCalculationInterval+from products.exports.backend.tasks.failure_handler import USER_QUERY_ERROR_NAMESALERT_PREPARE_RETRY_POLICY = RetryPolicy(@@ -25,3 +28,48 @@ ALERT_NOTIFY_RETRY_POLICY = RetryPolicy(backoff_coefficient=2.0,maximum_attempts=5,)++[email protected](frozen=True)+class AlertTimeouts:+ workflow_execution: dt.timedelta+ activity_schedule_to_close: dt.timedelta+ evaluate_start_to_close: dt.timedelta+ evaluate_retry_policy: RetryPolicy+ heartbeat_timeout: dt.timedelta+ notify_start_to_close: dt.timedelta+++_DEFAULT_TIMEOUTS = AlertTimeouts(+ workflow_execution=dt.timedelta(minutes=15),+ activity_schedule_to_close=dt.timedelta(minutes=12),+ evaluate_start_to_close=dt.timedelta(minutes=10),+ evaluate_retry_policy=ALERT_EVALUATE_RETRY_POLICY,+ heartbeat_timeout=dt.timedelta(minutes=2),+ notify_start_to_close=dt.timedelta(minutes=5),+)++_REAL_TIME_EVALUATE_RETRY_POLICY = RetryPolicy(+ initial_interval=dt.timedelta(seconds=1),+ maximum_interval=dt.timedelta(seconds=10),+ backoff_coefficient=2.0,+ maximum_attempts=2,+ non_retryable_error_types=list(USER_QUERY_ERROR_NAMES),+)++# workflow_execution covers prepare (2 min) + evaluate at its schedule_to_close cap+# (7 min) + notify (1 min), so one activity exhausting its budget can't kill the run.+_REAL_TIME_TIMEOUTS = AlertTimeouts(+ workflow_execution=dt.timedelta(minutes=10),+ activity_schedule_to_close=dt.timedelta(minutes=7),+ evaluate_start_to_close=dt.timedelta(minutes=3),+ evaluate_retry_policy=_REAL_TIME_EVALUATE_RETRY_POLICY,+ heartbeat_timeout=dt.timedelta(seconds=90),+ notify_start_to_close=dt.timedelta(seconds=60),+)+++def alert_timeouts(calculation_interval: str | AlertCalculationInterval | None) -> AlertTimeouts:+ if calculation_interval == AlertCalculationInterval.REAL_TIME:+ return _REAL_TIME_TIMEOUTS+ return _DEFAULT_TIMEOUTSdiff --git a/posthog/temporal/alerts/workflows.py b/posthog/temporal/alerts/workflows.pyindex 3b0039a0e11b..8719a650d99f 100644--- a/posthog/temporal/alerts/workflows.py+++ b/posthog/temporal/alerts/workflows.py@@ -18,11 +18,7 @@ from posthog.temporal.alerts.activities import (retrieve_due_alerts,run_investigation_safety_net,)-from posthog.temporal.alerts.retry_policy import (- ALERT_EVALUATE_RETRY_POLICY,- ALERT_NOTIFY_RETRY_POLICY,- ALERT_PREPARE_RETRY_POLICY,-)+from posthog.temporal.alerts.retry_policy import ALERT_NOTIFY_RETRY_POLICY, ALERT_PREPARE_RETRY_POLICY, alert_timeoutsfrom posthog.temporal.alerts.types import (CheckAlertWorkflowInputs,EvaluateAlertActivityInputs,@@ -37,14 +33,6 @@ with temporalio.workflow.unsafe.imports_passed_through():from posthog.temporal.ai.anomaly_investigation import AnomalyInvestigationWorkflowInputs-# Each activity's retry budget must exhaust inside the child workflow's execution-# timeout: a server-side workflow timeout skips workflow code entirely, so the SLO-# completion would never be emitted and the alert's next_check_at would never advance.-# Compound worst cases (e.g. a slow prepare pushing evaluate past the envelope) can-# still hit the server-side timeout; the cap guarantees no single activity does.-CHECK_ALERT_EXECUTION_TIMEOUT = dt.timedelta(minutes=15)-ALERT_ACTIVITY_SCHEDULE_TO_CLOSE_TIMEOUT = dt.timedelta(minutes=12)-@temporalio.workflow.defn(name="schedule-due-alert-checks")class ScheduleDueAlertChecksWorkflow(PostHogWorkflow):@@ -96,7 +84,7 @@ class ScheduleDueAlertChecksWorkflow(PostHogWorkflow):),id=f"check-alert-{alert.alert_id}",parent_close_policy=temporalio.workflow.ParentClosePolicy.ABANDON,- execution_timeout=CHECK_ALERT_EXECUTION_TIMEOUT,+ execution_timeout=alert_timeouts(alert.calculation_interval).workflow_execution,)tasks.append(task)@@ -138,6 +126,7 @@ class CheckAlertWorkflow(PostHogWorkflow):new_state: AlertState | None = Noneskip_reason: str | None = Nonecaught_error: BaseException | None = None+ timeouts = alert_timeouts(inputs.calculation_interval)try:# Phase 1 — prepare: load alert, validate config, check should-skip@@ -145,7 +134,7 @@ class CheckAlertWorkflow(PostHogWorkflow):prepare_alert,PrepareAlertActivityInputs(alert_id=inputs.alert_id),start_to_close_timeout=dt.timedelta(minutes=2),- schedule_to_close_timeout=ALERT_ACTIVITY_SCHEDULE_TO_CLOSE_TIMEOUT,+ schedule_to_close_timeout=timeouts.activity_schedule_to_close,retry_policy=ALERT_PREPARE_RETRY_POLICY,)@@ -157,10 +146,10 @@ class CheckAlertWorkflow(PostHogWorkflow):evaluation = await temporalio.workflow.execute_activity(evaluate_alert,EvaluateAlertActivityInputs(alert_id=inputs.alert_id),- start_to_close_timeout=dt.timedelta(minutes=10),- schedule_to_close_timeout=ALERT_ACTIVITY_SCHEDULE_TO_CLOSE_TIMEOUT,- heartbeat_timeout=dt.timedelta(minutes=2),- retry_policy=ALERT_EVALUATE_RETRY_POLICY,+ start_to_close_timeout=timeouts.evaluate_start_to_close,+ schedule_to_close_timeout=timeouts.activity_schedule_to_close,+ heartbeat_timeout=timeouts.heartbeat_timeout,+ retry_policy=timeouts.evaluate_retry_policy,)new_state = evaluation.new_state@@ -176,8 +165,8 @@ class CheckAlertWorkflow(PostHogWorkflow):alert_check_id=evaluation.alert_check_id,breaches=evaluation.breaches,),- start_to_close_timeout=dt.timedelta(minutes=5),- schedule_to_close_timeout=ALERT_ACTIVITY_SCHEDULE_TO_CLOSE_TIMEOUT,+ start_to_close_timeout=timeouts.notify_start_to_close,+ schedule_to_close_timeout=timeouts.activity_schedule_to_close,retry_policy=ALERT_NOTIFY_RETRY_POLICY,)diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.pyindex e1b2667c3c25..0b4eb79b58da 100644--- a/posthog/temporal/tests/test_alerts_activities.py+++ b/posthog/temporal/tests/test_alerts_activities.py@@ -21,6 +21,7 @@ from posthog.schema import (TrendsQuery,)+from posthog.constants import AvailableFeaturefrom posthog.errors import CHQueryErrorTooManySimultaneousQueriesfrom posthog.models import Userfrom posthog.tasks.alerts.utils import AlertEvaluationResult@@ -299,6 +300,49 @@ class TestPrepareAlert:assert result.action == PrepareAction.EVALUATEassert result.reason is None+ @pytest.mark.parametrize(+ "calculation_interval,required_feature",+ [+ pytest.param(+ AlertCalculationInterval.REAL_TIME.value,+ AvailableFeature.REAL_TIME_ALERTS,+ id="real_time",+ ),+ pytest.param(+ AlertCalculationInterval.EVERY_15_MINUTES.value,+ AvailableFeature.HIGH_FREQUENCY_ALERTS,+ id="every_15_minutes",+ ),+ ],+ )+ async def test_entitlement_gated_interval_auto_disabled_without_feature(+ self, ateam, aorganization, calculation_interval: str, required_feature: AvailableFeature+ ) -> None:+ a = await _create_alert(ateam, calculation_interval=calculation_interval)++ env = ActivityEnvironment()+ result = await env.run(prepare_alert, PrepareAlertActivityInputs(alert_id=str(a.id)))++ assert result.action == PrepareAction.AUTO_DISABLE+ refreshed = await sync_to_async(AlertConfiguration.objects.get)(pk=a.pk)+ assert refreshed.enabled is False+ assert refreshed.state == AlertState.ERRORED++ check = await sync_to_async(AlertCheck.objects.get)(alert_configuration=refreshed)+ assert check.state == AlertState.ERRORED+ assert check.error is not None++ # With the feature restored, an identical alert evaluates normally.+ @sync_to_async+ def _grant_feature() -> None:+ aorganization.available_product_features = [{"key": required_feature, "name": required_feature}]+ aorganization.save()++ await _grant_feature()+ entitled = await _create_alert(ateam, calculation_interval=calculation_interval)+ result = await env.run(prepare_alert, PrepareAlertActivityInputs(alert_id=str(entitled.id)))+ assert result.action == PrepareAction.EVALUATE+@pytest.mark.asyncio@pytest.mark.django_dbdiff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.pyindex 9bf3e15b9848..2189150fd7ef 100644--- a/products/alerts/backend/api/alert.py+++ b/products/alerts/backend/api/alert.py@@ -699,42 +699,24 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializeif msg := AlertConfiguration.check_alert_limit(self.context["team_id"], self.context["get_organization"]()):raise ValidationError({"alert": [msg]})- # Real-time limit applies on create and on any update that would increase the active count:- # switching an alert to real_time, or enabling an already-real_time alert.- is_create = self.context["request"].method == "POST"- existing_interval = self.instance.calculation_interval if self.instance else Noneexisting_enabled = self.instance.enabled if self.instance else True- becoming_real_time = (- is_create- and calculation_interval == AlertCalculationInterval.REAL_TIME- and attrs.get("enabled", True) is True- )- switching_to_real_time = (- not is_create- and calculation_interval == AlertCalculationInterval.REAL_TIME- and existing_interval != AlertCalculationInterval.REAL_TIME- )- enabling_real_time = (- not is_create- and calculation_interval == AlertCalculationInterval.REAL_TIME- and attrs.get("enabled", existing_enabled) is True- and not existing_enabled- )- if becoming_real_time or switching_to_real_time or enabling_real_time:- exclude_id = str(self.instance.pk) if self.instance else None- if msg := AlertConfiguration.check_real_time_alert_limit(- self.context["team_id"], organization, exclude_id=exclude_id- ):- posthoganalytics.capture(- distinct_id=str(self.context["request"].user.distinct_id),- event="real time alert limit reached",- properties={- "team_id": self.context["team_id"],- "organization_id": str(organization.id),- },- groups={"organization": str(organization.id)},- )- raise ValidationError({"calculation_interval": [msg]})+ if msg := AlertConfiguration.real_time_alert_validation_error(+ team_id=self.context["team_id"],+ organization=organization,+ calculation_interval=calculation_interval,+ enabled=attrs.get("enabled", existing_enabled) is True,+ existing=self.instance,+ ):+ posthoganalytics.capture(+ distinct_id=str(self.context["request"].user.distinct_id),+ event="real time alert limit reached",+ properties={+ "team_id": self.context["team_id"],+ "organization_id": str(organization.id),+ },+ groups={"organization": str(organization.id)},+ )+ raise ValidationError({"calculation_interval": [msg]})return attrsdiff --git a/products/alerts/backend/max_tools.py b/products/alerts/backend/max_tools.pyindex bba07e264a3d..5cc0b9845cc4 100644--- a/products/alerts/backend/max_tools.py+++ b/products/alerts/backend/max_tools.py@@ -211,6 +211,23 @@ class UpsertAlertTool(MaxTool):organization=org,)+ async def _validate_real_time_alert(+ self,+ calculation_interval: str | AlertCalculationInterval | None,+ *,+ enabled: bool,+ existing: AlertConfiguration | None = None,+ ) -> str | None:+ team = self._team+ org = await sync_to_async(lambda: team.organization)()+ return await sync_to_async(AlertConfiguration.real_time_alert_validation_error)(+ team_id=team.id,+ organization=org,+ calculation_interval=calculation_interval,+ enabled=enabled,+ existing=existing,+ )+async def _handle_create(self, action: CreateAlertAction) -> tuple[str, dict[str, Any]]:try:team = self._team@@ -227,6 +244,11 @@ class UpsertAlertTool(MaxTool):if interval_msg := await self._validate_every_15_minutes_interval(action.calculation_interval):return interval_msg, {"error": "validation_failed"}+ if real_time_msg := await self._validate_real_time_alert(+ action.calculation_interval, enabled=action.enabled+ ):+ return real_time_msg, {"error": "plan_limit_reached"}+try:insight, was_auto_saved = await self._resolve_and_validate_insight(action.insight_id, action_description="create alert for"@@ -311,6 +333,13 @@ class UpsertAlertTool(MaxTool):):return interval_msg, {"error": "validation_failed"}+ new_interval = (+ action.calculation_interval if action.calculation_interval is not None else alert.calculation_interval+ )+ new_enabled = action.enabled if action.enabled is not None else alert.enabled+ if real_time_msg := await self._validate_real_time_alert(new_interval, enabled=new_enabled, existing=alert):+ return real_time_msg, {"error": "plan_limit_reached"}+update_fields: list[str] = []conditions_or_threshold_changed = Falsediff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.pyindex 1b930f25d0a4..6b08fc26ee8a 100644--- a/products/alerts/backend/models/alert.py+++ b/products/alerts/backend/models/alert.py@@ -377,6 +377,40 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):return f"Your team has reached the limit of {allowed} real-time alerts on your plan."return None+ @classmethod+ def real_time_alert_validation_error(+ cls,+ *,+ team_id: int,+ organization: Organization,+ calculation_interval: str | AlertCalculationInterval | None,+ enabled: bool,+ existing: AlertConfiguration | None = None,+ ) -> str | None:+ """Validate a create/update that would leave an alert in the given real-time state.++ Shared by every write path (REST serializer, AI tool) so the entitlement and the+ active real-time limit can't be bypassed. The limit only applies when the change+ increases the active real-time count — an alert that already was an enabled+ real_time alert doesn't re-count against it.+ """+ if calculation_interval != AlertCalculationInterval.REAL_TIME:+ return None+ if error := cls.real_time_interval_validation_error(+ calculation_interval=calculation_interval, organization=organization+ ):+ return error+ if not enabled:+ return None+ already_active_real_time = (+ existing is not None+ and existing.calculation_interval == AlertCalculationInterval.REAL_TIME+ and existing.enabled+ )+ if already_active_real_time:+ return None+ return cls.check_real_time_alert_limit(team_id, organization, exclude_id=str(existing.pk) if existing else None)+class AlertSubscription(ModelActivityMixin, CreatedMetaFields, UUIDTModel):user = models.ForeignKey(diff --git a/products/alerts/backend/test_max_tools.py b/products/alerts/backend/test_max_tools.pyindex 7d88fc15213c..c60110ac81a2 100644--- a/products/alerts/backend/test_max_tools.py+++ b/products/alerts/backend/test_max_tools.py@@ -9,6 +9,7 @@ from parameterized import parameterizedfrom posthog.schema import AlertCalculationInterval, AlertConditionType, AlertState, InsightThresholdType+from posthog.constants import AvailableFeaturefrom posthog.models import Organization, Teamfrom products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold@@ -356,6 +357,53 @@ class TestUpsertAlertTool(BaseTest):assert "limited to 1 alerts" in content.lower()assert artifact["error"] == "plan_limit_reached"+ async def _enable_real_time_alerts(self, limit: int) -> None:+ def _set():+ self.organization.available_product_features = [+ *(self.organization.available_product_features or []),+ {"key": AvailableFeature.REAL_TIME_ALERTS, "name": "Real-time alerts", "limit": limit},+ ]+ self.organization.save()++ await sync_to_async(_set)()++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_create_rejects_when_real_time_limit_reached(self):+ await self._enable_real_time_alerts(limit=1)+ insight = await self._create_insight()+ await self._create_alert(insight, calculation_interval=AlertCalculationInterval.REAL_TIME)+ tool = self._setup_tool()++ content, artifact = await tool._arun_impl(+ action=CreateAlertAction(+ name="Over real-time limit",+ condition_type=AlertConditionType.ABSOLUTE_VALUE,+ insight_id=insight.id,+ lower_threshold=100.0,+ calculation_interval=AlertCalculationInterval.REAL_TIME,+ )+ )++ assert "limit of 1 real-time alerts" in content.lower()+ assert artifact["error"] == "plan_limit_reached"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_update_rejects_enabling_real_time_over_limit(self):+ await self._enable_real_time_alerts(limit=1)+ insight = await self._create_insight()+ await self._create_alert(insight, name="Active", calculation_interval=AlertCalculationInterval.REAL_TIME)+ disabled = await self._create_alert(+ insight, name="Disabled", calculation_interval=AlertCalculationInterval.REAL_TIME, enabled=False+ )+ tool = self._setup_tool()++ content, artifact = await tool._arun_impl(action=UpdateAlertAction(alert_id=str(disabled.id), enabled=True))++ assert "limit of 1 real-time alerts" in content.lower()+ assert artifact["error"] == "plan_limit_reached"+@pytest.mark.django_db@pytest.mark.asyncioasync def test_rejects_insight_from_other_team(self):