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): add 15-minute scheduling and billing validation (#59103)

Matt Pua509a1551ca8f
diff --git a/ee/models/license.py b/ee/models/license.py
index 75f7b70e409c..9799559b3c11 100644
--- a/ee/models/license.py
+++ b/ee/models/license.py
@@ -68,6 +68,7 @@ class License(models.Model):
AvailableFeature.RECORDINGS_PLAYLISTS,
AvailableFeature.RECORDINGS_FILE_EXPORT,
AvailableFeature.RECORDINGS_PERFORMANCE,
+ AvailableFeature.HIGH_FREQUENCY_ALERTS,
]
ENTERPRISE_PLAN = "enterprise"
diff --git a/frontend/src/mocks/fixtures/_billing_platform_addons.tsx b/frontend/src/mocks/fixtures/_billing_platform_addons.tsx
index e72a52937995..9a58930ade68 100644
--- a/frontend/src/mocks/fixtures/_billing_platform_addons.tsx
+++ b/frontend/src/mocks/fixtures/_billing_platform_addons.tsx
@@ -109,6 +109,12 @@ const auditLogs = (months: number): AddonPlanFeature =>
'See who in your organization has accessed or modified entities within PostHog.',
{ limit: months, unit: 'months' }
)
+const highFrequencyAlerts = feature(
+ 'high_frequency_alerts',
+ 'High frequency alerts',
+ 'Run insight alerts as frequently as every 15 minutes.',
+ { entitlement_only: true }
+)
const prioritySupport = (note: string = 'Target response time 24 hours'): AddonPlanFeature =>
feature(
'priority_support',
@@ -172,6 +178,7 @@ const TEAMS_FEATURES: AddonPlanFeature[] = [
organizationInviteSettings,
organizationSecuritySettings,
sessionReplayDataRetention(12),
+ highFrequencyAlerts,
]
const BOOST_FEATURES: AddonPlanFeature[] = [
@@ -188,6 +195,7 @@ const BOOST_FEATURES: AddonPlanFeature[] = [
organizationInviteSettings,
organizationSecuritySettings,
sessionReplayDataRetention(12),
+ highFrequencyAlerts,
]
const SCALE_FEATURES: AddonPlanFeature[] = [
@@ -208,6 +216,7 @@ const SCALE_FEATURES: AddonPlanFeature[] = [
organizationInviteSettings,
organizationSecuritySettings,
sessionReplayDataRetention(12),
+ highFrequencyAlerts,
]
const ENTERPRISE_FEATURES: AddonPlanFeature[] = [
@@ -235,6 +244,7 @@ const ENTERPRISE_FEATURES: AddonPlanFeature[] = [
prioritySupport('Target response time 8 hours'),
saml,
approvals,
+ highFrequencyAlerts,
]
type AddonSpec = {
diff --git a/posthog/api/test/test_alert_15_minute_interval.py b/posthog/api/test/test_alert_15_minute_interval.py
new file mode 100644
index 000000000000..39a94e31704f
--- /dev/null
+++ b/posthog/api/test/test_alert_15_minute_interval.py
@@ -0,0 +1,154 @@
+from datetime import UTC, datetime
+from typing import Any, cast
+
+import pytest
+from freezegun import freeze_time
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from rest_framework import status
+
+from posthog.schema import AlertCalculationInterval, AlertConditionType, InsightThresholdType
+
+from posthog.constants import AvailableFeature
+from posthog.tasks.alerts.utils import (
+ alert_calculation_interval_to_relativedelta,
+ calculation_interval_to_order,
+ next_check_time,
+)
+
+from products.alerts.backend.models.alert import AlertConfiguration
+
+
+@patch("products.alerts.backend.models.alert.posthoganalytics.feature_enabled")
+class TestAlert15MinuteInterval(APIBaseTest):
+ def _enable_feature_flag(self, mock_feature_enabled: MagicMock) -> None:
+ mock_feature_enabled.return_value = True
+
+ def _disable_feature_flag(self, mock_feature_enabled: MagicMock) -> None:
+ mock_feature_enabled.return_value = False
+
+ def setUp(self):
+ super().setUp()
+ self.default_insight_data: dict[str, Any] = {
+ "query": {
+ "kind": "TrendsQuery",
+ "series": [
+ {
+ "kind": "EventsNode",
+ "event": "$pageview",
+ }
+ ],
+ "trendsFilter": {"display": "BoldNumber"},
+ },
+ }
+ self.insight = self.client.post(f"/api/projects/{self.team.id}/insights", data=self.default_insight_data).json()
+
+ def _creation_request(self, **overrides: Any) -> dict[str, Any]:
+ payload = {
+ "insight": self.insight["id"],
+ "subscribed_users": [self.user.id],
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "name": "15 min alert",
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},
+ "calculation_interval": AlertCalculationInterval.EVERY_15_MINUTES,
+ }
+ payload.update(overrides)
+ return payload
+
+ def _enable_high_frequency_alerts(self) -> None:
+ self.organization.available_product_features = [
+ *(self.organization.available_product_features or []),
+ {"key": AvailableFeature.HIGH_FREQUENCY_ALERTS, "name": "High frequency alerts"},
+ ]
+ self.organization.save()
+
+ def test_create_every_15_minutes_rejected_without_billing_entitlement(
+ self, mock_feature_enabled: MagicMock
+ ) -> None:
+ self._enable_feature_flag(mock_feature_enabled)
+ response = self.client.post(f"/api/projects/{self.team.id}/alerts", self._creation_request())
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "Boost, Scale, or Enterprise" in str(response.json())
+
+ def test_create_every_15_minutes_rejected_when_feature_flag_disabled(self, mock_feature_enabled: MagicMock) -> None:
+ self._disable_feature_flag(mock_feature_enabled)
+ self._enable_high_frequency_alerts()
+ response = self.client.post(f"/api/projects/{self.team.id}/alerts", self._creation_request())
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "not available for your organization yet" in str(response.json())
+
+ def test_create_every_15_minutes_succeeds_with_entitlement(self, mock_feature_enabled: MagicMock) -> None:
+ self._enable_feature_flag(mock_feature_enabled)
+ self._enable_high_frequency_alerts()
+ response = self.client.post(f"/api/projects/{self.team.id}/alerts", self._creation_request())
+ assert response.status_code == status.HTTP_201_CREATED, response.content
+ assert response.json()["calculation_interval"] == AlertCalculationInterval.EVERY_15_MINUTES
+
+ def test_patch_every_15_minutes_succeeds_with_entitlement(self, mock_feature_enabled: MagicMock) -> None:
+ self._enable_feature_flag(mock_feature_enabled)
+ self._enable_high_frequency_alerts()
+ create_response = self.client.post(f"/api/projects/{self.team.id}/alerts", self._creation_request())
+ alert_id = create_response.json()["id"]
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/alerts/{alert_id}",
+ {"name": "updated 15 min alert"},
+ )
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json()["name"] == "updated 15 min alert"
+ assert response.json()["calculation_interval"] == AlertCalculationInterval.EVERY_15_MINUTES
+
+ def test_patch_existing_every_15_minutes_rejected_after_entitlement_removed(
+ self, mock_feature_enabled: MagicMock
+ ) -> None:
+ self._enable_feature_flag(mock_feature_enabled)
+ self._enable_high_frequency_alerts()
+ create_response = self.client.post(f"/api/projects/{self.team.id}/alerts", self._creation_request())
+ alert_id = create_response.json()["id"]
+
+ self.organization.available_product_features = []
+ self.organization.save()
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/alerts/{alert_id}",
+ {"name": "still 15 min"},
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "Boost, Scale, or Enterprise" in str(response.json())
+
+
+class TestAlert15MinuteScheduling:
+ def test_calculation_interval_to_order_ranks_every_15_minutes_before_hourly(self) -> None:
+ assert calculation_interval_to_order(AlertCalculationInterval.EVERY_15_MINUTES) < calculation_interval_to_order(
+ AlertCalculationInterval.HOURLY
+ )
+
+ def test_alert_calculation_interval_to_relativedelta_every_15_minutes(self) -> None:
+ delta = alert_calculation_interval_to_relativedelta(AlertCalculationInterval.EVERY_15_MINUTES)
+ assert delta.minutes == 15
+
+ def test_next_check_time_advances_by_15_minutes(self) -> None:
+ alert = MagicMock(spec=AlertConfiguration)
+ alert.calculation_interval = AlertCalculationInterval.EVERY_15_MINUTES
+ alert.next_check_at = datetime(2026, 4, 6, 14, 0, 0, tzinfo=UTC)
+ alert.team = MagicMock()
+ alert.team.timezone = "UTC"
+ alert.schedule_restriction = None
+ alert.skip_weekend = False
+
+ with freeze_time("2026-04-06T14:00:00Z"):
+ assert next_check_time(alert) == datetime(2026, 4, 6, 14, 15, 0, tzinfo=UTC)
+
+ def test_calculation_interval_to_order_raises_for_none(self) -> None:
+ with pytest.raises(ValueError, match="Invalid alert calculation interval: None"):
+ calculation_interval_to_order(None)
+
+ def test_calculation_interval_to_order_raises_for_unknown_interval(self) -> None:
+ with pytest.raises(ValueError, match="Unhandled alert calculation interval"):
+ calculation_interval_to_order(cast(AlertCalculationInterval, "every_5_minutes"))
+
+ def test_alert_calculation_interval_to_relativedelta_raises_for_unknown_interval(self) -> None:
+ with pytest.raises(ValueError, match="Unhandled alert calculation interval"):
+ alert_calculation_interval_to_relativedelta(cast(AlertCalculationInterval, "every_5_minutes"))
diff --git a/posthog/tasks/alerts/test/test_schedule_restriction.py b/posthog/tasks/alerts/test/test_schedule_restriction.py
index 9a1dba413c44..63643ebfb198 100644
--- a/posthog/tasks/alerts/test/test_schedule_restriction.py
+++ b/posthog/tasks/alerts/test/test_schedule_restriction.py
@@ -190,6 +190,11 @@ class TestNextCheckAtAfterScheduleRestrictionChange:
setattr(alert, k, v)
return alert
+ def _every_15_minutes_alert(self, **kwargs: Any) -> MagicMock:
+ alert = self._hourly_alert(**kwargs)
+ alert.calculation_interval = "every_15_minutes"
+ return alert
+
def test_cleared_restriction_delegates_to_next_check_time(self) -> None:
with freeze_time("2026-04-06T14:00:00Z"):
alert = self._hourly_alert(schedule_restriction=None, next_check_at=None)
@@ -224,3 +229,33 @@ class TestNextCheckAtAfterScheduleRestrictionChange:
)
out = next_check_at_after_schedule_restriction_change(alert)
assert out == datetime(2026, 4, 6, 16, 0, 0, tzinfo=UTC)
+
+ def test_every_15_minutes_future_next_check_inside_blocked_window_snaps_to_first_unblocked_minute(
+ self,
+ ) -> None:
+ with freeze_time("2026-04-06T14:00:00Z"):
+ alert = self._every_15_minutes_alert(
+ schedule_restriction={"blocked_windows": [{"start": "11:00", "end": "16:00"}]},
+ next_check_at=datetime(2026, 4, 6, 15, 30, tzinfo=UTC),
+ )
+ out = next_check_at_after_schedule_restriction_change(alert)
+ assert out == datetime(2026, 4, 6, 16, 0, 0, tzinfo=UTC)
+
+ def test_every_15_minutes_does_not_keep_stale_snap_when_earlier_runs_are_allowed(self) -> None:
+ with freeze_time("2026-04-06T16:44:00Z"):
+ alert = self._every_15_minutes_alert(
+ team=MagicMock(timezone="America/Toronto"),
+ schedule_restriction={"blocked_windows": [{"start": "14:00", "end": "16:00"}]},
+ next_check_at=datetime(2026, 4, 6, 20, 0, 0, tzinfo=UTC),
+ )
+ out = next_check_at_after_schedule_restriction_change(alert)
+ assert out == datetime(2026, 4, 6, 16, 59, 0, tzinfo=UTC)
+
+ def test_every_15_minutes_null_next_check_at_with_restriction_uses_interval_then_snap(self) -> None:
+ with freeze_time("2026-04-06T14:00:00Z"):
+ alert = self._every_15_minutes_alert(
+ schedule_restriction={"blocked_windows": [{"start": "11:00", "end": "16:00"}]},
+ next_check_at=None,
+ )
+ out = next_check_at_after_schedule_restriction_change(alert)
+ assert out == datetime(2026, 4, 6, 16, 0, 0, tzinfo=UTC)
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.py
index 44d9aa8dee38..f61f8a33f29b 100644
--- a/posthog/tasks/alerts/utils.py
+++ b/posthog/tasks/alerts/utils.py
@@ -138,16 +138,26 @@ def validate_alert_config(
def calculation_interval_to_order(interval: AlertCalculationInterval | None) -> int:
match interval:
- case AlertCalculationInterval.HOURLY:
+ case AlertCalculationInterval.EVERY_15_MINUTES:
return 0
- case AlertCalculationInterval.DAILY:
+ case AlertCalculationInterval.HOURLY:
return 1
- case _:
+ case AlertCalculationInterval.DAILY:
return 2
+ case AlertCalculationInterval.WEEKLY:
+ return 3
+ case AlertCalculationInterval.MONTHLY:
+ return 3
+ case None:
+ raise ValueError("Invalid alert calculation interval: None")
+ case _ as unreachable:
+ raise ValueError(f"Unhandled alert calculation interval: {unreachable!r}")
def alert_calculation_interval_to_relativedelta(alert_calculation_interval: AlertCalculationInterval) -> relativedelta:
match alert_calculation_interval:
+ case AlertCalculationInterval.EVERY_15_MINUTES:
+ return relativedelta(minutes=15)
case AlertCalculationInterval.HOURLY:
return relativedelta(hours=1)
case AlertCalculationInterval.DAILY:
@@ -156,8 +166,8 @@ def alert_calculation_interval_to_relativedelta(alert_calculation_interval: Aler
return relativedelta(weeks=1)
case AlertCalculationInterval.MONTHLY:
return relativedelta(months=1)
- case _:
- raise ValueError(f"Invalid alert calculation interval: {alert_calculation_interval}")
+ case _ as unreachable:
+ raise ValueError(f"Unhandled alert calculation interval: {unreachable!r}")
def skip_because_of_weekend(alert: AlertConfiguration) -> bool:
@@ -177,6 +187,8 @@ def _next_check_time_core(alert: AlertConfiguration) -> datetime:
team_timezone = pytz.timezone(alert.team.timezone)
match alert.calculation_interval:
+ case AlertCalculationInterval.EVERY_15_MINUTES:
+ return (alert.next_check_at or now) + relativedelta(minutes=15)
case AlertCalculationInterval.HOURLY:
return (alert.next_check_at or now) + relativedelta(hours=1)
case AlertCalculationInterval.DAILY:
@@ -199,8 +211,8 @@ def _next_check_time_core(alert: AlertConfiguration) -> datetime:
next_month_1am_local = next_month_local.replace(day=1, hour=4)
# Convert to UTC
return next_month_1am_local.astimezone(pytz.utc)
- case _:
- raise ValueError(f"Invalid alert calculation interval: {alert.calculation_interval}")
+ case _ as unreachable:
+ raise ValueError(f"Unhandled alert calculation interval: {unreachable!r}")
def next_check_time(alert: AlertConfiguration) -> datetime:
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index f5326fde250a..9dd34aa3da87 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -61,10 +61,12 @@ async def retrieve_due_alerts() -> list[AlertInfo]:
# 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.HOURLY.value, then=Value(0)),
- When(calculation_interval=AlertCalculationInterval.DAILY.value, then=Value(1)),
- default=Value(2),
+ When(calculation_interval=AlertCalculationInterval.EVERY_15_MINUTES.value, then=Value(0)),
+ When(calculation_interval=AlertCalculationInterval.HOURLY.value, then=Value(1)),
+ When(calculation_interval=AlertCalculationInterval.DAILY.value, then=Value(2)),
+ default=Value(3),
output_field=IntegerField(),
)
diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.py
index fbba6020fc11..c42a06fc7b50 100644
--- a/products/alerts/backend/api/alert.py
+++ b/products/alerts/backend/api/alert.py
@@ -41,6 +41,20 @@ from products.alerts.backend.api.alert_schedule_restriction import AlertSchedule
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold
+def _validate_every_15_minutes_interval(
+ *,
+ calculation_interval: str | AlertCalculationInterval | None,
+ request,
+ organization,
+) -> None:
+ if error := AlertConfiguration.every_15_minutes_interval_validation_error(
+ calculation_interval=calculation_interval,
+ user_distinct_id=str(request.user.distinct_id),
+ organization=organization,
+ ):
+ raise ValidationError({"calculation_interval": [error]})
+
+
@extend_schema_field(InsightThreshold) # type: ignore[arg-type]
class ThresholdConfigurationField(serializers.JSONField):
pass
@@ -211,7 +225,7 @@ class AlertSerializer(serializers.ModelSerializer):
calculation_interval = serializers.ChoiceField(
choices=AlertConfiguration.CALCULATION_INTERVAL_CHOICES,
required=False,
- help_text="How often the alert is checked: hourly, daily, weekly, or monthly.",
+ help_text="How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.",
)
snoozed_until = RelativeDateTimeField(
allow_null=True,
@@ -525,6 +539,13 @@ class AlertSerializer(serializers.ModelSerializer):
except ValueError as e:
raise ValidationError(str(e))
+ organization = self.context["get_organization"]()
+ _validate_every_15_minutes_interval(
+ calculation_interval=calculation_interval,
+ request=self.context["request"],
+ organization=organization,
+ )
+
# Investigation agent is only supported for detector-based alerts.
investigation_enabled = attrs.get(
"investigation_agent_enabled",
diff --git a/products/alerts/backend/api/test/test_alert.py b/products/alerts/backend/api/test/test_alert.py
index d68572660d9b..9c691b3d0a0c 100644
--- a/products/alerts/backend/api/test/test_alert.py
+++ b/products/alerts/backend/api/test/test_alert.py
@@ -9,7 +9,7 @@ from unittest import mock
from parameterized import parameterized
from rest_framework import status
-from posthog.schema import AlertConditionType, AlertState, InsightThresholdType
+from posthog.schema import AlertCalculationInterval, AlertConditionType, AlertState, InsightThresholdType
from posthog.models.hog_functions.hog_function import HogFunction
from posthog.models.personal_api_key import PersonalAPIKey
@@ -1059,6 +1059,7 @@ class TestAlertEventProperties(APIBaseTest):
"threshold_absolute",
{"type": "absolute_value"},
None,
+ "daily",
{
"alert_mode": "threshold",
"detector_type": None,
@@ -1071,6 +1072,7 @@ class TestAlertEventProperties(APIBaseTest):
"single_detector_no_preprocessing",
{"type": "absolute_value"},
{"type": "zscore", "threshold": 0.95, "window": 30},
+ "daily",
{
"alert_mode": "detector",
"detector_type": "zscore",
@@ -1083,6 +1085,7 @@ class TestAlertEventProperties(APIBaseTest):
"single_detector_with_preprocessing",
{"type": "absolute_value"},
{"type": "zscore", "threshold": 0.95, "window": 30, "preprocessing": {"diffs_n": 1}},
+ "daily",
{
"alert_mode": "detector",
"detector_type": "zscore",
@@ -1102,6 +1105,7 @@ class TestAlertEventProperties(APIBaseTest):
{"type": "mad", "threshold": 0.95, "window": 30},
],
},
+ "daily",
{
"alert_mode": "detector",
"detector_type": "ensemble",
@@ -1121,6 +1125,7 @@ class TestAlertEventProperties(APIBaseTest):
{"type": "threshold"},
],
},
+ "daily",
{
"alert_mode": "detector",
"detector_type": "ensemble",
@@ -1129,6 +1134,20 @@ class TestAlertEventProperties(APIBaseTest):
"has_preprocessing": False,
},
),
+ (
+ "every_15_minutes_high_frequency",
+ {"type": "absolute_value"},
+ None,
+ "every_15_minutes",
+ {
+ "alert_mode": "threshold",
+ "detector_type": None,
+ "ensemble_operator": None,
+ "ensemble_detector_types": None,
+ "has_preprocessing": False,
+ "is_high_frequency_interval": True,
+ },
+ ),
]
)
def test_event_properties(
@@ -1136,18 +1155,22 @@ class TestAlertEventProperties(APIBaseTest):
_name: str,
condition: dict,
detector_config: dict | None,
+ calculation_interval: str,
expected_detector_fields: dict,
) -> None:
alert = AlertConfiguration(
name="test alert",
condition=condition,
detector_config=detector_config,
- calculation_interval="daily",
+ calculation_interval=calculation_interval,
)
props = alert._get_event_properties()
assert props["alert_name"] == "test alert"
assert props["condition_type"] == condition["type"]
- assert props["calculation_interval"] == "daily"
+ assert props["calculation_interval"] == calculation_interval
+ assert props["is_high_frequency_interval"] == (
+ calculation_interval == AlertCalculationInterval.EVERY_15_MINUTES
+ )
for key, value in expected_detector_fields.items():
assert props[key] == value, f"{key} expected {value}, got {props[key]}"
diff --git a/products/alerts/backend/max_tools.py b/products/alerts/backend/max_tools.py
index 8db46cf9846d..bcabe3909a1d 100644
--- a/products/alerts/backend/max_tools.py
+++ b/products/alerts/backend/max_tools.py
@@ -74,6 +74,7 @@ UPSERT_ALERT_TOOL_DESCRIPTION = dedent("""
- For percentage-based thresholds, set threshold_type to "percentage" and use decimal values (e.g., 0.5 for 50%)
# Calculation intervals
+ - **every_15_minutes**: Check every 15 minutes (Boost+ and feature flag required)
- **hourly**: Check every hour
- **daily**: Check once per day (default for create)
- **weekly**: Check once per week
@@ -112,7 +113,7 @@ class CreateAlertAction(BaseModel):
)
calculation_interval: AlertCalculationInterval = Field(
default=AlertCalculationInterval.DAILY,
- description="How often to check: hourly, daily, weekly, or monthly",
+ description="How often to check: every_15_minutes (Boost+), hourly, daily, weekly, or monthly",
)
upper_threshold: float | None = Field(
default=None,
@@ -145,7 +146,10 @@ class UpdateAlertAction(BaseModel):
alert_id: str = Field(description="The ID of the alert to update (find via list_data with kind='alerts')")
name: str | None = Field(default=None, description="New alert name")
condition_type: AlertConditionType | None = Field(default=None, description="New condition type")
- calculation_interval: AlertCalculationInterval | None = Field(default=None, description="New calculation interval")
+ calculation_interval: AlertCalculationInterval | None = Field(
+ default=None,
+ description="New calculation interval (every_15_minutes requires Boost+ and feature flag)",
+ )
upper_threshold: float | None = Field(default=None, description="New upper threshold bound")
lower_threshold: float | None = Field(default=None, description="New lower threshold bound")
threshold_type: InsightThresholdType | None = Field(default=None, description="New threshold type")
@@ -192,6 +196,21 @@ class UpsertAlertTool(MaxTool):
else:
return await self._handle_update(action)
+ async def _validate_every_15_minutes_interval(
+ self,
+ calculation_interval: str | AlertCalculationInterval | None,
+ *,
+ existing_interval: str | AlertCalculationInterval | None = None,
+ ) -> str | None:
+ team = self._team
+ user = self._user
+ org = await sync_to_async(lambda: team.organization)()
+ return await sync_to_async(AlertConfiguration.every_15_minutes_interval_validation_error)(
+ calculation_interval=calculation_interval or existing_interval,
+ user_distinct_id=str(user.distinct_id),
+ organization=org,
+ )
+
async def _handle_create(self, action: CreateAlertAction) -> tuple[str, dict[str, Any]]:
try:
team = self._team
@@ -205,6 +224,9 @@ class UpsertAlertTool(MaxTool):
if limit_msg := await self._check_alert_limit():
return limit_msg, {"error": "plan_limit_reached"}
+ if interval_msg := await self._validate_every_15_minutes_interval(action.calculation_interval):
+ return interval_msg, {"error": "validation_failed"}
+
try:
insight, was_auto_saved = await self._resolve_and_validate_insight(
action.insight_id, action_description="create alert for"
@@ -283,6 +305,12 @@ class UpsertAlertTool(MaxTool):
await self.check_object_access(alert, "editor", resource="alert", action="edit")
+ if interval_msg := await self._validate_every_15_minutes_interval(
+ action.calculation_interval,
+ existing_interval=alert.calculation_interval,
+ ):
+ return interval_msg, {"error": "validation_failed"}
+
update_fields: list[str] = []
conditions_or_threshold_changed = False
diff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.py
index aeda3d4c1328..624928da211a 100644
--- a/products/alerts/backend/models/alert.py
+++ b/products/alerts/backend/models/alert.py
@@ -12,10 +12,11 @@ if TYPE_CHECKING:
from posthog.models.user import User
import pydantic
+import posthoganalytics
from posthog.schema import AlertCalculationInterval, AlertState, InsightThreshold
-from posthog.constants import AvailableFeature
+from posthog.constants import ALERTS_15_MINUTE_INTERVAL_FEATURE_FLAG_KEY, AvailableFeature
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.utils import CreatedMetaFields, UUIDTModel
@@ -308,6 +309,28 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
def supports_high_frequency_intervals(cls, organization: Organization) -> bool:
return organization.is_feature_available(AvailableFeature.HIGH_FREQUENCY_ALERTS)
+ @classmethod
+ def every_15_minutes_interval_validation_error(
+ cls,
+ *,
+ calculation_interval: str | AlertCalculationInterval | None,
+ user_distinct_id: str,
+ organization: Organization,
+ ) -> str | None:
+ if calculation_interval != AlertCalculationInterval.EVERY_15_MINUTES:
+ return None
+ if not posthoganalytics.feature_enabled(
+ ALERTS_15_MINUTE_INTERVAL_FEATURE_FLAG_KEY,
+ user_distinct_id,
+ groups={"organization": str(organization.id)},
+ group_properties={"organization": {"id": str(organization.id)}},
+ only_evaluate_locally=False,
+ ):
+ return "15-minute alert intervals are not available for your organization yet."
+ if not cls.supports_high_frequency_intervals(organization):
+ return "15-minute alert intervals require a Boost, Scale, or Enterprise platform add-on."
+ return None
+
class AlertSubscription(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
user = models.ForeignKey(
diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.ts
index 84d9c19bd0bf..0698e30da7ed 100644
--- a/products/alerts/frontend/generated/api.schemas.ts
+++ b/products/alerts/frontend/generated/api.schemas.ts
@@ -455,7 +455,7 @@ export interface AlertApi {
/** Trends-specific alert configuration. Includes series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). */
config?: TrendsAlertConfigApi | null
detector_config?: DetectorConfigApi | null
- /** How often the alert is checked: hourly, daily, weekly, or monthly.
+ /** How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.
* `every_15_minutes` - every_15_minutes
* `hourly` - hourly
@@ -534,7 +534,7 @@ export interface PatchedAlertApi {
/** Trends-specific alert configuration. Includes series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). */
config?: TrendsAlertConfigApi | null
detector_config?: DetectorConfigApi | null
- /** How often the alert is checked: hourly, daily, weekly, or monthly.
+ /** How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.
* `every_15_minutes` - every_15_minutes
* `hourly` - hourly
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e786a1a3810b..a925a12692ae 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -4042,7 +4042,7 @@ export namespace Schemas {
/** Trends-specific alert configuration. Includes series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). */
config?: TrendsAlertConfig | null;
detector_config?: DetectorConfig | null;
- /** How often the alert is checked: hourly, daily, weekly, or monthly.
+ /** How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.
* `every_15_minutes` - every_15_minutes
* `hourly` - hourly
@@ -25744,7 +25744,7 @@ export namespace Schemas {
/** Trends-specific alert configuration. Includes series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). */
config?: TrendsAlertConfig | null;
detector_config?: DetectorConfig | null;
- /** How often the alert is checked: hourly, daily, weekly, or monthly.
+ /** How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.
* `every_15_minutes` - every_15_minutes
* `hourly` - hourly
diff --git a/services/mcp/src/generated/alerts/api.ts b/services/mcp/src/generated/alerts/api.ts
index a7905d9c0e5d..0cad13610559 100644
--- a/services/mcp/src/generated/alerts/api.ts
+++ b/services/mcp/src/generated/alerts/api.ts
@@ -1483,7 +1483,7 @@ export const AlertsCreateBody = /* @__PURE__ */ zod.object({
)
.optional()
.describe(
- 'How often the alert is checked: hourly, daily, weekly, or monthly.\n\n* `every_15_minutes` - every_15_minutes\n* `hourly` - hourly\n* `daily` - daily\n* `weekly` - weekly\n* `monthly` - monthly'
+ 'How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.\n\n* `every_15_minutes` - every_15_minutes\n* `hourly` - hourly\n* `daily` - daily\n* `weekly` - weekly\n* `monthly` - monthly'
),
snoozed_until: zod
.string()
@@ -3144,7 +3144,7 @@ export const AlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
)
.optional()
.describe(
- 'How often the alert is checked: hourly, daily, weekly, or monthly.\n\n* `every_15_minutes` - every_15_minutes\n* `hourly` - hourly\n* `daily` - daily\n* `weekly` - weekly\n* `monthly` - monthly'
+ 'How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.\n\n* `every_15_minutes` - every_15_minutes\n* `hourly` - hourly\n* `daily` - daily\n* `weekly` - weekly\n* `monthly` - monthly'
),
snoozed_until: zod
.string()
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/alert-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/alert-create.json
index 9252474f8078..5166262410e9 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/alert-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/alert-create.json
@@ -2,7 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"calculation_interval": {
- "description": "How often the alert is checked: hourly, daily, weekly, or monthly.\n\n* `every_15_minutes` - every_15_minutes\n* `hourly` - hourly\n* `daily` - daily\n* `weekly` - weekly\n* `monthly` - monthly",
+ "description": "How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.\n\n* `every_15_minutes` - every_15_minutes\n* `hourly` - hourly\n* `daily` - daily\n* `weekly` - weekly\n* `monthly` - monthly",
"enum": ["every_15_minutes", "hourly", "daily", "weekly", "monthly"],
"type": "string"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/alert-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/alert-update.json
index 4685a5be9d32..695871cd9761 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/alert-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/alert-update.json
@@ -2,7 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"calculation_interval": {
- "description": "How often the alert is checked: hourly, daily, weekly, or monthly.\n\n* `every_15_minutes` - every_15_minutes\n* `hourly` - hourly\n* `daily` - daily\n* `weekly` - weekly\n* `monthly` - monthly",
+ "description": "How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.\n\n* `every_15_minutes` - every_15_minutes\n* `hourly` - hourly\n* `daily` - daily\n* `weekly` - weekly\n* `monthly` - monthly",
"enum": ["every_15_minutes", "hourly", "daily", "weekly", "monthly"],
"type": "string"
},
diff --git a/services/mcp/tests/workers/fixtures/api_organizations_id.json b/services/mcp/tests/workers/fixtures/api_organizations_id.json
index a1fbf2ee371a..02a3972c6fab 100644
--- a/services/mcp/tests/workers/fixtures/api_organizations_id.json
+++ b/services/mcp/tests/workers/fixtures/api_organizations_id.json
@@ -87,6 +87,10 @@
"key": "recordings_performance",
"name": "Recordings_performance"
},
+ {
+ "key": "high_frequency_alerts",
+ "name": "High_frequency_alerts"
+ },
{
"key": "advanced_permissions",
"name": "Advanced_permissions"
diff --git a/services/mcp/tests/workers/fixtures/api_users__me.json b/services/mcp/tests/workers/fixtures/api_users__me.json
index 4fff9b80ed80..b04e60ad71a9 100644
--- a/services/mcp/tests/workers/fixtures/api_users__me.json
+++ b/services/mcp/tests/workers/fixtures/api_users__me.json
@@ -133,6 +133,10 @@
"key": "recordings_performance",
"name": "Recordings_performance"
},
+ {
+ "key": "high_frequency_alerts",
+ "name": "High_frequency_alerts"
+ },
{
"key": "advanced_permissions",
"name": "Advanced_permissions"