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 real-time interval option to alert UI (#67936)

Matt Puab27ef5c71309
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e302630fd7a0..48451e45322c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6767,7 +6767,7 @@ snapshots:
scenes-app-settings-organization--settings-organization-details--dark:
hash: v1.k794b7964.42bb07ba29e5727f687fd3792eff1df7c8cb4b536343c95d9e51658a89677e3e.cGfJpWmm01Oxd5JLWEfkzexgdZI7AGiVVPdWvziNzPI
scenes-app-settings-organization--settings-organization-details--light:
- hash: v1.k794b7964.29b8ac9b106df49b30d8acd6aeca3b24ff6f5754066f4f97d1e7b7ae5f6a0354.XR0nCLUHueSiJ3lsue0N67EIY-inQ5eoldh5MqE_iTg
+ hash: v1.k794b7964.5832cdd23724d21e797adaeb677a0ee983e7e61bd3ec7095aff87966b99a3f3b.hqLxN9o3Ki2bs4ZUCNCgCF07IvOl6mm-DzG0H3ku2S8
scenes-app-settings-organization--settings-organization-members--dark:
hash: v1.k794b7964.9b7c856187e6b01c2abe4dfcfcba4593258de828b3a289d2924cfcf1fb5497dc.n-Z_pbWeZvSzYjKOkvb-ajQi97HcZHzhXCPKhN6M1g0
scenes-app-settings-organization--settings-organization-members--light:
diff --git a/frontend/src/lib/components/Alerts/alertFormLogic.ts b/frontend/src/lib/components/Alerts/alertFormLogic.ts
index 75e561f0b103..31d5f7ba16e3 100644
--- a/frontend/src/lib/components/Alerts/alertFormLogic.ts
+++ b/frontend/src/lib/components/Alerts/alertFormLogic.ts
@@ -22,10 +22,9 @@ import {
import { AvailableFeature, InsightLogicProps, IntervalType, QueryBasedInsightModel } from '~/types'
import {
- blockSubmitWithoutHighFrequencyAlertsEntitlement,
+ blockSubmitWithoutEntitlement,
getDefaultSimulationRange,
- HIGH_FREQUENCY_ALERTS_REQUIRED_MESSAGE,
- isHighFrequencyAlertInterval,
+ isSubDailyAlertInterval,
} from 'products/alerts/frontend/logic/alertIntervalHelpers'
import type { alertFormLogicType } from './alertFormLogicType'
@@ -290,7 +289,7 @@ export const alertFormLogic = kea<alertFormLogicType>([
],
})),
- forms(({ props, values }) => ({
+ forms(({ props, values, actions }) => ({
alertForm: {
defaults: props.alert
? alertToFormType(props.alert, props.insightId)
@@ -324,14 +323,18 @@ export const alertFormLogic = kea<alertFormLogicType>([
} as AlertFormType),
errors: (alert: AlertFormType) => getAlertFormValidationErrors(alert),
submit: async (alert) => {
- if (
- blockSubmitWithoutHighFrequencyAlertsEntitlement(
- alert.calculation_interval,
- userLogic.values.hasAvailableFeature(AvailableFeature.HIGH_FREQUENCY_ALERTS)
- )
- ) {
- lemonToast.error(HIGH_FREQUENCY_ALERTS_REQUIRED_MESSAGE)
- throw new Error(HIGH_FREQUENCY_ALERTS_REQUIRED_MESSAGE)
+ const entitlementCheck = blockSubmitWithoutEntitlement(alert.calculation_interval, {
+ hasHighFrequencyAlertsEntitlement: userLogic.values.hasAvailableFeature(
+ AvailableFeature.HIGH_FREQUENCY_ALERTS
+ ),
+ hasRealTimeAlertsEntitlement: userLogic.values.hasAvailableFeature(
+ AvailableFeature.REAL_TIME_ALERTS
+ ),
+ })
+ if (entitlementCheck.blocked) {
+ lemonToast.error(entitlementCheck.message)
+ actions.setAlertFormManualErrors({ calculation_interval: entitlementCheck.message })
+ throw new Error(entitlementCheck.message)
}
const payload: AlertTypeWrite = {
@@ -341,7 +344,7 @@ export const alertFormLogic = kea<alertFormLogicType>([
// can only skip weekends for sub-daily alerts
skip_weekend:
(alert.calculation_interval === AlertCalculationInterval.DAILY ||
- isHighFrequencyAlertInterval(alert.calculation_interval)) &&
+ isSubDailyAlertInterval(alert.calculation_interval)) &&
alert.skip_weekend,
// can only check ongoing interval for absolute value/increase alerts with upper threshold
config: isTrendsAlertConfig(alert.config)
diff --git a/frontend/src/lib/components/Alerts/views/Alerts.tsx b/frontend/src/lib/components/Alerts/views/Alerts.tsx
index 06f2bf88d8ff..6602093d8917 100644
--- a/frontend/src/lib/components/Alerts/views/Alerts.tsx
+++ b/frontend/src/lib/components/Alerts/views/Alerts.tsx
@@ -13,6 +13,8 @@ import { urls } from 'scenes/urls'
import { ProductKey } from '~/queries/schema/schema-general'
+import { alertIntervalDisplayLabel } from 'products/alerts/frontend/logic/alertIntervalHelpers'
+
import { AlertState } from '../../../../queries/schema/schema-general'
import { alertLogic } from '../alertLogic'
import { AlertsFiltersBar } from '../AlertsFiltersBar'
@@ -65,6 +67,14 @@ export function Alerts({ alertId }: AlertsProps): JSX.Element {
return alert.enabled ? <AlertStateIndicator alert={alert} /> : null
},
},
+ {
+ title: 'Interval',
+ dataIndex: 'calculation_interval',
+ key: 'calculation_interval',
+ render: function renderInterval(_, alert: AlertType) {
+ return <div className="whitespace-nowrap">{alertIntervalDisplayLabel(alert.calculation_interval)}</div>
+ },
+ },
{
title: 'Last checked',
sorter: true,
diff --git a/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx b/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx
index 98cddd15c88c..2bbb157ba802 100644
--- a/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx
+++ b/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx
@@ -5,7 +5,6 @@ import { useCallback, useMemo } from 'react'
import { IconCalendar, IconChevronLeft } from '@posthog/icons'
import { LemonCheckbox, LemonInput, Link, SpinnerOverlay } from '@posthog/lemon-ui'
-import { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'
import { UserActivityIndicator } from 'lib/components/UserActivityIndicator/UserActivityIndicator'
import { dayjs } from 'lib/dayjs'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
@@ -18,17 +17,16 @@ import { getDisplayNameFromEntityNode } from 'scenes/insights/utils'
import { teamLogic } from 'scenes/teamLogic'
import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
import { urls } from 'scenes/urls'
-import { userLogic } from 'scenes/userLogic'
import { AlertCalculationInterval, AlertState } from '~/queries/schema/schema-general'
import { containsHogQLQuery, isFunnelsQuery, isInsightVizNode } from '~/queries/utils'
-import { AvailableFeature, FunnelVizType, InsightLogicProps, InsightShortId, QueryBasedInsightModel } from '~/types'
+import { FunnelVizType, InsightLogicProps, InsightShortId, QueryBasedInsightModel } from '~/types'
import { AlertAdvancedOptionsSection } from 'products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection'
import { AlertDefinitionSection } from 'products/alerts/frontend/components/editAlertModal/AlertDefinitionSection'
import { AlertIntervalRow } from 'products/alerts/frontend/components/editAlertModal/AlertIntervalRow'
import { AlertNotificationSection } from 'products/alerts/frontend/components/editAlertModal/AlertNotificationSection'
-import { isHighFrequencyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'
+import { isSubDailyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'
import { alertFormLogic, canCheckOngoingInterval } from '../alertFormLogic'
import { alertLogic } from '../alertLogic'
@@ -137,10 +135,6 @@ export function EditAlertModal({
const inlineNotificationsEnabled = useFeatureFlag('ALERTS_INLINE_NOTIFICATIONS')
const investigationAgentEnabled = useFeatureFlag('ALERTS_INVESTIGATION_AGENT')
- const { hasAvailableFeature } = useValues(userLogic)
- const { guardAvailableFeature } = useValues(upgradeModalLogic)
- const hasHighFrequencyAlertsEntitlement = hasAvailableFeature(AvailableFeature.HIGH_FREQUENCY_ALERTS)
-
const { pendingNotifications } = useValues(alertNotificationLogic({ alertId: alertId }))
const hasPendingNotifications = inlineNotificationsEnabled && pendingNotifications.length > 0
@@ -205,7 +199,7 @@ export function EditAlertModal({
}
if (
(alertForm.calculation_interval === AlertCalculationInterval.DAILY ||
- isHighFrequencyAlertInterval(alertForm.calculation_interval)) &&
+ isSubDailyAlertInterval(alertForm.calculation_interval)) &&
alertForm.skip_weekend
) {
n += 1
@@ -305,9 +299,9 @@ export function EditAlertModal({
creatingNewAlert={creatingNewAlert}
alert={alert}
trendInterval={trendInterval}
- hasHighFrequencyAlertsEntitlement={hasHighFrequencyAlertsEntitlement}
- guardAvailableFeature={guardAvailableFeature}
nextPlannedEvaluationStale={nextPlannedEvaluationStale}
+ canCheckOngoingInterval={can_check_ongoing_interval}
+ onSetAlertFormValue={setAlertFormValue}
/>
</div>
</div>
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 20a67c081cda..82f7ee418b9e 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -252,6 +252,7 @@ export const FEATURE_FLAGS = {
ALERTS_ANOMALY_DETECTION: 'alerts-anomaly-detection', // owner: @andrewm4894
ALERTS_INLINE_NOTIFICATIONS: 'alerts-inline-notifications', // owner: @vdekrijger
ALERTS_INVESTIGATION_AGENT: 'alerts-investigation-agent', // owner: @andrewm4894, anomaly alerts — investigation agent on firing
+ ALERTS_REAL_TIME_INTERVAL: 'alerts-real-time-interval', // owner: #team-analytics-platform, gates real-time (2-minute) insight alert interval
AMPLITUDE_BATCH_IMPORT_OPTIONS: 'amplitude-batch-import-options', // owner: #team-ingestion
APPROVALS: 'approvals', // owner: @yasen-posthog #team-platform-features
AVERAGE_PAGE_VIEW_COLUMN: 'average-page-view-column', // owner: @jordanm-posthog #team-web-analytics
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index cba26a7d3a6f..3303ed69e746 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -209,6 +209,7 @@ export enum AvailableFeature {
MANAGED_REVERSE_PROXY = 'managed_reverse_proxy',
ALERTS = 'alerts',
HIGH_FREQUENCY_ALERTS = 'high_frequency_alerts',
+ REAL_TIME_ALERTS = 'real_time_alerts',
DATA_COLOR_THEMES = 'data_color_themes',
ORGANIZATION_INVITE_SETTINGS = 'organization_invite_settings',
ORGANIZATION_SECURITY_SETTINGS = 'organization_security_settings',
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1162b22a3017..583691678899 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2672,6 +2672,9 @@ importers:
'@types/react':
specifier: 18.3.27
version: 18.3.27
+ kea:
+ specifier: 'catalog:'
+ version: 4.0.0-pre.5([email protected])
kea-forms:
specifier: '*'
diff --git a/posthog/tasks/alerts/test/test_utils.py b/posthog/tasks/alerts/test/test_utils.py
new file mode 100644
index 000000000000..846abab5434e
--- /dev/null
+++ b/posthog/tasks/alerts/test/test_utils.py
@@ -0,0 +1,37 @@
+from datetime import UTC, datetime
+
+from freezegun import freeze_time
+from unittest.mock import MagicMock
+
+from posthog.schema import AlertCalculationInterval
+
+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
+
+
+class TestAlertUtils:
+ def test_calculation_interval_to_order_ranks_real_time_first(self) -> None:
+ assert calculation_interval_to_order(AlertCalculationInterval.REAL_TIME) < calculation_interval_to_order(
+ AlertCalculationInterval.EVERY_15_MINUTES
+ )
+
+ def test_alert_calculation_interval_to_relativedelta_real_time(self) -> None:
+ delta = alert_calculation_interval_to_relativedelta(AlertCalculationInterval.REAL_TIME)
+ assert delta.minutes == 2
+
+ def test_next_check_time_advances_by_2_minutes(self) -> None:
+ alert = MagicMock(spec=AlertConfiguration)
+ alert.calculation_interval = AlertCalculationInterval.REAL_TIME
+ 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, 2, 0, tzinfo=UTC)
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.py
index d913dc2fd851..3d87e1114884 100644
--- a/posthog/tasks/alerts/utils.py
+++ b/posthog/tasks/alerts/utils.py
@@ -46,32 +46,37 @@ def is_non_time_series_trend(query: TrendsQuery) -> bool:
return display in NON_TIME_SERIES_DISPLAY_TYPES
+REAL_TIME_CADENCE_MINUTES = 2
+EVERY_15_MINUTES_CADENCE_MINUTES = 15
+
+# Cheaper, more time-sensitive checks get workers first when the due batch is large.
+# Single source for both the Python ordering and the ORM Case in
+# posthog/temporal/alerts/activities.py retrieve_due_alerts.
+CALCULATION_INTERVAL_ORDER: dict[AlertCalculationInterval, int] = {
+ AlertCalculationInterval.REAL_TIME: 0,
+ AlertCalculationInterval.EVERY_15_MINUTES: 1,
+ AlertCalculationInterval.HOURLY: 2,
+ AlertCalculationInterval.DAILY: 3,
+ AlertCalculationInterval.WEEKLY: 4,
+ AlertCalculationInterval.MONTHLY: 4,
+}
+
+
def calculation_interval_to_order(interval: AlertCalculationInterval | None) -> int:
- match interval:
- case AlertCalculationInterval.REAL_TIME:
- return 0
- case AlertCalculationInterval.EVERY_15_MINUTES:
- return 1
- case AlertCalculationInterval.HOURLY:
- return 2
- case AlertCalculationInterval.DAILY:
- return 3
- case AlertCalculationInterval.WEEKLY:
- return 4
- case AlertCalculationInterval.MONTHLY:
- return 4
- case None:
- raise ValueError("Invalid alert calculation interval: None")
- case _ as unreachable:
- raise ValueError(f"Unhandled alert calculation interval: {unreachable!r}")
+ if interval is None:
+ raise ValueError("Invalid alert calculation interval: None")
+ try:
+ return CALCULATION_INTERVAL_ORDER[interval]
+ except KeyError:
+ raise ValueError(f"Unhandled alert calculation interval: {interval!r}")
def alert_calculation_interval_to_relativedelta(alert_calculation_interval: AlertCalculationInterval) -> relativedelta:
match alert_calculation_interval:
case AlertCalculationInterval.REAL_TIME:
- return relativedelta(minutes=2)
+ return relativedelta(minutes=REAL_TIME_CADENCE_MINUTES)
case AlertCalculationInterval.EVERY_15_MINUTES:
- return relativedelta(minutes=15)
+ return relativedelta(minutes=EVERY_15_MINUTES_CADENCE_MINUTES)
case AlertCalculationInterval.HOURLY:
return relativedelta(hours=1)
case AlertCalculationInterval.DAILY:
@@ -102,7 +107,7 @@ def _next_check_time_core(alert: AlertConfiguration) -> datetime:
match alert.calculation_interval:
case AlertCalculationInterval.REAL_TIME:
- return (alert.next_check_at or now) + relativedelta(minutes=2)
+ return (alert.next_check_at or now) + relativedelta(minutes=REAL_TIME_CADENCE_MINUTES)
case AlertCalculationInterval.EVERY_15_MINUTES:
return (alert.next_check_at or now) + relativedelta(minutes=15)
case AlertCalculationInterval.HOURLY:
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index 87f95134e57f..b4a5afaefbc5 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -8,7 +8,7 @@ import structlog
import temporalio.activity
from temporalio.exceptions import ApplicationError
-from posthog.schema import AlertCalculationInterval, AlertState
+from posthog.schema import AlertState
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.errors import CH_TRANSIENT_ERRORS
@@ -18,6 +18,7 @@ from posthog.sync import database_sync_to_async
from posthog.tasks.alerts.investigation_notifications import run_investigation_notification_safety_net
from posthog.tasks.alerts.schedule_restriction import is_utc_datetime_blocked, next_unblocked_utc
from posthog.tasks.alerts.utils import (
+ CALCULATION_INTERVAL_ORDER,
add_alert_check,
disable_invalid_alert,
dispatch_alert_notification,
@@ -60,13 +61,12 @@ async def retrieve_due_alerts() -> list[AlertInfo]:
def get_alerts() -> list[AlertInfo]:
now = datetime.now(UTC)
- # 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)),
- When(calculation_interval=AlertCalculationInterval.EVERY_15_MINUTES.value, then=Value(1)),
- When(calculation_interval=AlertCalculationInterval.HOURLY.value, then=Value(2)),
- When(calculation_interval=AlertCalculationInterval.DAILY.value, then=Value(3)),
- default=Value(4),
+ *(
+ When(calculation_interval=interval.value, then=Value(order))
+ for interval, order in CALCULATION_INTERVAL_ORDER.items()
+ ),
+ default=Value(max(CALCULATION_INTERVAL_ORDER.values())),
output_field=IntegerField(),
)
@@ -124,12 +124,7 @@ async def prepare_alert(inputs: PrepareAlertActivityInputs) -> PrepareAlertResul
# 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(
+ entitlement_error = AlertConfiguration.interval_entitlement_error(
calculation_interval=alert.calculation_interval,
organization=alert.team.organization,
)
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index 0b4eb79b58da..93de2221fd7e 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -332,7 +332,6 @@ class TestPrepareAlert:
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}]
diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.py
index 2189150fd7ef..21527aed8f5b 100644
--- a/products/alerts/backend/api/alert.py
+++ b/products/alerts/backend/api/alert.py
@@ -44,29 +44,21 @@ from posthog.utils import relative_date_parse
from products.alerts.backend.api.alert_schedule_restriction import AlertScheduleRestriction
from products.alerts.backend.evaluation.contract import AlertExtractionError
from products.alerts.backend.evaluation.detector import simulate_detector_on_insight
-from products.alerts.backend.evaluation.validation import THRESHOLD_BOUNDS_REQUIRED_MESSAGE, validate_alert_config
+from products.alerts.backend.evaluation.validation import (
+ THRESHOLD_BOUNDS_REQUIRED_MESSAGE,
+ should_default_check_ongoing_interval,
+ validate_alert_config,
+)
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold
from products.product_analytics.backend.models.insight import Insight
-def _validate_every_15_minutes_interval(
- *,
- calculation_interval: str | AlertCalculationInterval | None,
- organization,
-) -> None:
- if error := AlertConfiguration.every_15_minutes_interval_validation_error(
- calculation_interval=calculation_interval,
- organization=organization,
- ):
- raise ValidationError({"calculation_interval": [error]})
-
-
-def _validate_real_time_interval(
+def _validate_interval_entitlement(
*,
calculation_interval: str | AlertCalculationInterval | None,
organization,
) -> None:
- if error := AlertConfiguration.real_time_interval_validation_error(
+ if error := AlertConfiguration.interval_entitlement_error(
calculation_interval=calculation_interval,
organization=organization,
):
@@ -634,6 +626,19 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
self.instance is None or "threshold" in attrs or "detector_config" in attrs
)
+ # Mirror the UI's default for cadences finer than the insight interval. Applied before
+ # validate_alert_config so the validated config is the persisted config.
+ if isinstance(config, dict) and config.get("check_ongoing_interval") is None:
+ if should_default_check_ongoing_interval(
+ query=query,
+ config=config,
+ condition=condition,
+ threshold_config=threshold_config,
+ calculation_interval=calculation_interval,
+ ):
+ config = {**config, "check_ongoing_interval": True}
+ attrs["config"] = config
+
try:
validate_alert_config(
query,
@@ -650,11 +655,7 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
raise ValidationError(str(e))
organization = self.context["get_organization"]()
- _validate_every_15_minutes_interval(
- calculation_interval=calculation_interval,
- organization=organization,
- )
- _validate_real_time_interval(
+ _validate_interval_entitlement(
calculation_interval=calculation_interval,
organization=organization,
)
@@ -694,7 +695,6 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
}
)
- # Total alert count only checked on create.
if self.context["request"].method == "POST":
if msg := AlertConfiguration.check_alert_limit(self.context["team_id"], self.context["get_organization"]()):
raise ValidationError({"alert": [msg]})
diff --git a/products/alerts/backend/api/test/test_alert.py b/products/alerts/backend/api/test/test_alert.py
index 89eb347809de..7f84e5aaf882 100644
--- a/products/alerts/backend/api/test/test_alert.py
+++ b/products/alerts/backend/api/test/test_alert.py
@@ -11,6 +11,7 @@ from rest_framework import status
from posthog.schema import AlertCalculationInterval, AlertConditionType, AlertState, InsightThresholdType
+from posthog.constants import AvailableFeature
from posthog.models import User
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team import Team
@@ -1890,3 +1891,152 @@ class TestAlertAPIKeyAccess(APIBaseTest):
)
assert response.status_code == status.HTTP_200_OK, response.content
+
+
+class TestAlertRealTimeInterval(APIBaseTest):
+ 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": "real time alert",
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"lower": 0}}},
+ "calculation_interval": AlertCalculationInterval.REAL_TIME,
+ }
+ payload.update(overrides)
+ return payload
+
+ def _enable_real_time_alerts(self, limit: int | None = None) -> None:
+ feature: dict[str, Any] = {"key": AvailableFeature.REAL_TIME_ALERTS, "name": "Real-time alerts"}
+ if limit is not None:
+ feature["limit"] = limit
+ self.organization.available_product_features = [
+ *(self.organization.available_product_features or []),
+ feature,
+ ]
+ self.organization.save()
+
+ def test_create_real_time_rejected_without_billing_entitlement(self) -> None:
+ response = self.client.post(f"/api/projects/{self.team.id}/alerts", self._creation_request())
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "Scale or Enterprise" in str(response.json())
+
+ def test_create_real_time_succeeds_with_entitlement(self) -> None:
+ self._enable_real_time_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.REAL_TIME
+
+ def test_patch_real_time_succeeds_with_entitlement(self) -> None:
+ self._enable_real_time_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 real time alert"},
+ )
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json()["name"] == "updated real time alert"
+ assert response.json()["calculation_interval"] == AlertCalculationInterval.REAL_TIME
+
+ def test_patch_existing_real_time_rejected_after_entitlement_removed(self) -> None:
+ self._enable_real_time_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 real time"},
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "Scale or Enterprise" in str(response.json())
+
+ def test_create_real_time_rejected_when_limit_reached(self) -> None:
+ self._enable_real_time_alerts(limit=1)
+ first = self.client.post(f"/api/projects/{self.team.id}/alerts", self._creation_request())
+ assert first.status_code == status.HTTP_201_CREATED, first.content
+
+ second = self.client.post(f"/api/projects/{self.team.id}/alerts", self._creation_request(name="second"))
+ assert second.status_code == status.HTTP_400_BAD_REQUEST
+ assert "limit of 1 real-time alerts" in str(second.json())
+
+ def test_real_time_limit_ignores_disabled_alerts(self) -> None:
+ self._enable_real_time_alerts(limit=1)
+ first = self.client.post(f"/api/projects/{self.team.id}/alerts", self._creation_request())
+ assert first.status_code == status.HTTP_201_CREATED, first.content
+
+ self.client.patch(
+ f"/api/projects/{self.team.id}/alerts/{first.json()['id']}",
+ {"enabled": False},
+ )
+
+ second = self.client.post(f"/api/projects/{self.team.id}/alerts", self._creation_request(name="second"))
+ assert second.status_code == status.HTTP_201_CREATED, second.content
+
+ def test_real_time_limit_ignores_other_intervals(self) -> None:
+ self._enable_real_time_alerts(limit=1)
+ daily = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ self._creation_request(name="daily", calculation_interval=AlertCalculationInterval.DAILY),
+ )
+ assert daily.status_code == status.HTTP_201_CREATED, daily.content
+
+ response = self.client.post(f"/api/projects/{self.team.id}/alerts", self._creation_request())
+ assert response.status_code == status.HTTP_201_CREATED, response.content
+
+ def test_patch_to_real_time_rejected_when_limit_reached(self) -> None:
+ self._enable_real_time_alerts(limit=1)
+ real_time = self.client.post(f"/api/projects/{self.team.id}/alerts", self._creation_request())
+ assert real_time.status_code == status.HTTP_201_CREATED, real_time.content
+
+ daily = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ self._creation_request(name="daily", calculation_interval=AlertCalculationInterval.DAILY),
+ )
+ assert daily.status_code == status.HTTP_201_CREATED, daily.content
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/alerts/{daily.json()['id']}",
+ {"calculation_interval": AlertCalculationInterval.REAL_TIME},
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "limit of 1 real-time alerts" in str(response.json())
+
+ def test_enable_real_time_rejected_when_limit_reached(self) -> None:
+ self._enable_real_time_alerts(limit=1)
+ first = self.client.post(f"/api/projects/{self.team.id}/alerts", self._creation_request())
+ assert first.status_code == status.HTTP_201_CREATED, first.content
+
+ disabled = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ self._creation_request(name="disabled", enabled=False),
+ )
+ assert disabled.status_code == status.HTTP_201_CREATED, disabled.content
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/alerts/{disabled.json()['id']}",
+ {"enabled": True},
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "limit of 1 real-time alerts" in str(response.json())
diff --git a/products/alerts/backend/evaluation/test/test_check_ongoing_default.py b/products/alerts/backend/evaluation/test/test_check_ongoing_default.py
new file mode 100644
index 000000000000..7a8ba6556716
--- /dev/null
+++ b/products/alerts/backend/evaluation/test/test_check_ongoing_default.py
@@ -0,0 +1,101 @@
+from parameterized import parameterized
+
+from posthog.schema import AlertCalculationInterval
+
+from products.alerts.backend.evaluation.validation import should_default_check_ongoing_interval
+
+TRENDS = "TrendsAlertConfig"
+FUNNELS = "FunnelsAlertConfig"
+
+
+def _trends_query(interval="day", non_time_series=False):
+ query = {"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}], "interval": interval}
+ if non_time_series:
+ query["trendsFilter"] = {"display": "BoldNumber"}
+ return query
+
+
+def _funnels_query(interval="day", viz="trends"):
+ return {
+ "kind": "FunnelsQuery",
+ "series": [{"kind": "EventsNode", "event": "a"}, {"kind": "EventsNode", "event": "b"}],
+ "interval": interval,
+ "funnelsFilter": {"funnelVizType": viz},
+ }
+
+
+def _threshold(upper=100, lower=None):
+ bounds = {}
+ if upper is not None:
+ bounds["upper"] = upper
+ if lower is not None:
+ bounds["lower"] = lower
+ return {"type": "absolute", "bounds": bounds}
+
+
+ABSOLUTE = {"type": "absolute_value"}
+INCREASE = {"type": "relative_increase"}
+DECREASE = {"type": "relative_decrease"}
+
+
+class TestShouldDefaultCheckOngoingInterval:
+ @parameterized.expand(
+ [
+ ("trends day + 15min", _trends_query(), TRENDS, ABSOLUTE, _threshold(), "every_15_minutes", True),
+ ("trends day + hourly", _trends_query(), TRENDS, ABSOLUTE, _threshold(), "hourly", True),
+ ("trends day + real_time increase", _trends_query(), TRENDS, INCREASE, _threshold(), "real_time", True),
+ ("trends day + daily", _trends_query(), TRENDS, ABSOLUTE, _threshold(), "daily", False),
+ ("trends hour + hourly", _trends_query("hour"), TRENDS, ABSOLUTE, _threshold(), "hourly", False),
+ ("trends hour + 15min", _trends_query("hour"), TRENDS, ABSOLUTE, _threshold(), "every_15_minutes", True),
+ (
+ "trends no upper bound",
+ _trends_query(),
+ TRENDS,
+ ABSOLUTE,
+ _threshold(upper=None, lower=5),
+ "hourly",
+ False,
+ ),
+ ("trends decrease condition", _trends_query(), TRENDS, DECREASE, _threshold(), "hourly", False),
+ (
+ "trends non-time-series",
+ _trends_query(non_time_series=True),
+ TRENDS,
+ ABSOLUTE,
+ _threshold(),
+ "hourly",
+ False,
+ ),
+ ("trends funnel day + 15min", _funnels_query(), FUNNELS, ABSOLUTE, _threshold(), "every_15_minutes", True),
+ (
+ "steps funnel day + 15min",
+ _funnels_query(viz="steps"),
+ FUNNELS,
+ ABSOLUTE,
+ _threshold(),
+ "every_15_minutes",
+ False,
+ ),
+ ("trends funnel day + daily", _funnels_query(), FUNNELS, ABSOLUTE, _threshold(), "daily", False),
+ ]
+ )
+ def test_should_default(self, _name, query, config_type, condition, threshold, cadence, expected):
+ result = should_default_check_ongoing_interval(
+ query=query,
+ config={"type": config_type},
+ condition=condition,
+ threshold_config=threshold,
+ calculation_interval=AlertCalculationInterval(cadence),
+ )
+ assert result is expected
+
+ @parameterized.expand([("hogql config", {"type": "HogQLAlertConfig"}), ("not a dict", None)])
+ def test_non_ongoing_config_never_defaults(self, _name, config):
+ result = should_default_check_ongoing_interval(
+ query=_trends_query(),
+ config=config,
+ condition=ABSOLUTE,
+ threshold_config=_threshold(),
+ calculation_interval=AlertCalculationInterval.HOURLY,
+ )
+ assert result is False
diff --git a/products/alerts/backend/evaluation/validation.py b/products/alerts/backend/evaluation/validation.py
index e12dd6a3f3c5..dbba238733e3 100644
--- a/products/alerts/backend/evaluation/validation.py
+++ b/products/alerts/backend/evaluation/validation.py
@@ -13,12 +13,13 @@ from posthog.schema import (
HogQLAlertEvaluation,
InsightThreshold,
InsightThresholdType,
+ IntervalType,
NodeKind,
TrendsAlertConfig,
TrendsQuery,
)
-from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, is_non_time_series_trend
+from posthog.tasks.alerts.utils import REAL_TIME_CADENCE_MINUTES, WRAPPER_NODE_KINDS, is_non_time_series_trend
from posthog.utils import get_from_dict_or_attr
from products.alerts.backend.evaluation.dispatcher import DETECTOR_EXTRACTORS
@@ -177,6 +178,101 @@ _ALERT_CONFIG_VALIDATORS: dict[str, Callable[[_AlertConfigValidationContext], No
}
+# Twin of CADENCE_DURATION_MINUTES / INSIGHT_INTERVAL_DURATION_MINUTES in
+# products/alerts/frontend/logic/alertIntervalHelpers.ts — keep the two in sync.
+_CADENCE_DURATION_MINUTES: dict[AlertCalculationInterval, float] = {
+ AlertCalculationInterval.REAL_TIME: REAL_TIME_CADENCE_MINUTES,
+ AlertCalculationInterval.EVERY_15_MINUTES: 15,
+ AlertCalculationInterval.HOURLY: 60,
+ AlertCalculationInterval.DAILY: 60 * 24,
+ AlertCalculationInterval.WEEKLY: 60 * 24 * 7,
+ AlertCalculationInterval.MONTHLY: 60 * 24 * 30,
+}
+
+_INTERVAL_DURATION_MINUTES: dict[IntervalType, float] = {
+ IntervalType.SECOND: 1 / 60,
+ IntervalType.MINUTE: 1,
+ IntervalType.HOUR: 60,
+ IntervalType.DAY: 60 * 24,
+ IntervalType.WEEK: 60 * 24 * 7,
+ IntervalType.MONTH: 60 * 24 * 30,
+}
+
+
+def _cadence_finer_than_interval(cadence: AlertCalculationInterval, insight_interval: IntervalType | None) -> bool:
+ interval_minutes = _INTERVAL_DURATION_MINUTES.get(
+ insight_interval or IntervalType.DAY, _INTERVAL_DURATION_MINUTES[IntervalType.DAY]
+ )
+ return _CADENCE_DURATION_MINUTES[cadence] < interval_minutes
+
+
+def _threshold_has_upper_bound(threshold_config: dict | None) -> bool:
+ if threshold_config is None:
+ return False
+ try:
+ threshold = InsightThreshold.model_validate(threshold_config)
+ except PydanticValidationError:
+ return False
+ return threshold.bounds is not None and threshold.bounds.upper is not None
+
+
+def should_default_check_ongoing_interval(
+ *,
+ query: dict,
+ config: dict | None,
+ condition: dict | None,
+ threshold_config: dict | None,
+ calculation_interval: str | None,
+) -> bool:
+ """Whether an alert left with ``check_ongoing_interval`` unset should default it on.
+
+ A cadence finer than the insight's grouping interval re-checks a frozen completed bucket until it
+ closes, so evaluating the ongoing (incomplete) bucket is what makes the faster cadence meaningful.
+ Only applies where the toggle is valid — mirrors the UI's ``canCheckOngoingInterval``: a trends
+ absolute/increase alert above an upper bound, or a time-series (historical-trend) funnel.
+ """
+ if not isinstance(config, dict) or calculation_interval is None:
+ return False
+ try:
+ cadence = AlertCalculationInterval(calculation_interval)
+ except ValueError:
+ return False
+
+ kind = get_from_dict_or_attr(query, "kind")
+ if kind in WRAPPER_NODE_KINDS:
+ query = get_from_dict_or_attr(query, "source")
+
+ config_type = config.get("type")
+ if config_type == "TrendsAlertConfig":
+ try:
+ trends_query = TrendsQuery.model_validate(query)
+ parsed_condition = AlertCondition.model_validate(condition)
+ except PydanticValidationError:
+ return False
+ if is_non_time_series_trend(trends_query):
+ return False
+ if parsed_condition.type not in (AlertConditionType.ABSOLUTE_VALUE, AlertConditionType.RELATIVE_INCREASE):
+ return False
+ return _cadence_finer_than_interval(cadence, trends_query.interval) and _threshold_has_upper_bound(
+ threshold_config
+ )
+
+ if config_type == "FunnelsAlertConfig":
+ try:
+ funnels_query = FunnelsQuery.model_validate(query)
+ except PydanticValidationError:
+ return False
+ viz = funnels_query.funnelsFilter.funnelVizType if funnels_query.funnelsFilter else None
+ try:
+ strategy = strategy_for_viz(viz)
+ except ValueError:
+ return False
+ # Time-series funnels only (steps funnels have no periods) — the same gate as isTrendsFunnel.
+ return strategy.supports_relative_conditions and _cadence_finer_than_interval(cadence, funnels_query.interval)
+
+ return False
+
+
def validate_alert_config(
query: dict,
condition: dict | None,
diff --git a/products/alerts/backend/max_tools.py b/products/alerts/backend/max_tools.py
index 5cc0b9845cc4..85b6052fbe89 100644
--- a/products/alerts/backend/max_tools.py
+++ b/products/alerts/backend/max_tools.py
@@ -76,6 +76,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
+ - **real_time**: Check in real time (Scale+ required)
- **every_15_minutes**: Check every 15 minutes (Boost+ required)
- **hourly**: Check every hour
- **daily**: Check once per day (default for create)
@@ -115,7 +116,7 @@ class CreateAlertAction(BaseModel):
)
calculation_interval: AlertCalculationInterval = Field(
default=AlertCalculationInterval.DAILY,
- description="How often to check: every_15_minutes (Boost+), hourly, daily, weekly, or monthly",
+ description="How often to check: real_time (Scale+), every_15_minutes (Boost+), hourly, daily, weekly, or monthly",
)
upper_threshold: float | None = Field(
default=None,
@@ -150,7 +151,7 @@ class UpdateAlertAction(BaseModel):
condition_type: AlertConditionType | None = Field(default=None, description="New condition type")
calculation_interval: AlertCalculationInterval | None = Field(
default=None,
- description="New calculation interval (every_15_minutes requires Boost+)",
+ description="New calculation interval (real_time requires Scale+, every_15_minutes requires Boost+)",
)
upper_threshold: float | None = Field(default=None, description="New upper threshold bound")
lower_threshold: float | None = Field(default=None, description="New lower threshold bound")
@@ -198,7 +199,7 @@ class UpsertAlertTool(MaxTool):
else:
return await self._handle_update(action)
- async def _validate_every_15_minutes_interval(
+ async def _validate_interval_entitlement(
self,
calculation_interval: str | AlertCalculationInterval | None,
*,
@@ -206,7 +207,7 @@ class UpsertAlertTool(MaxTool):
) -> str | None:
team = self._team
org = await sync_to_async(lambda: team.organization)()
- return await sync_to_async(AlertConfiguration.every_15_minutes_interval_validation_error)(
+ return await sync_to_async(AlertConfiguration.interval_entitlement_error)(
calculation_interval=calculation_interval or existing_interval,
organization=org,
)
@@ -241,7 +242,7 @@ 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):
+ if interval_msg := await self._validate_interval_entitlement(action.calculation_interval):
return interval_msg, {"error": "validation_failed"}
if real_time_msg := await self._validate_real_time_alert(
@@ -327,7 +328,7 @@ class UpsertAlertTool(MaxTool):
await self.check_object_access(alert, "editor", resource="alert", action="edit")
- if interval_msg := await self._validate_every_15_minutes_interval(
+ if interval_msg := await self._validate_interval_entitlement(
action.calculation_interval,
existing_interval=alert.calculation_interval,
):
diff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.py
index 6b08fc26ee8a..5460555de631 100644
--- a/products/alerts/backend/models/alert.py
+++ b/products/alerts/backend/models/alert.py
@@ -196,6 +196,8 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
@property
def is_high_frequency_interval(self) -> bool:
+ # Real-time counts as high frequency so its checks always run fresh ClickHouse
+ # queries (CALCULATE_BLOCKING_ALWAYS) instead of reading a possibly stale cache.
return self.calculation_interval in (
AlertCalculationInterval.EVERY_15_MINUTES,
AlertCalculationInterval.REAL_TIME,
@@ -350,6 +352,22 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
return "Real-time alert intervals require a Scale or Enterprise plan."
return None
+ @classmethod
+ def interval_entitlement_error(
+ cls,
+ *,
+ calculation_interval: str | AlertCalculationInterval | None,
+ organization: Organization,
+ ) -> str | None:
+ """Entitlement gate for any plan-restricted interval — the single entry point for
+ write paths and evaluation-time downgrade checks. Each underlying check returns None
+ unless the interval matches, so at most one can produce an error."""
+ return cls.real_time_interval_validation_error(
+ calculation_interval=calculation_interval, organization=organization
+ ) or cls.every_15_minutes_interval_validation_error(
+ calculation_interval=calculation_interval, organization=organization
+ )
+
@classmethod
def check_real_time_alert_limit(
cls, team_id: int, organization: Organization, *, exclude_id: str | None = None
@@ -365,7 +383,6 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
return None
allowed = feature.get("limit")
- # If allowed is None then the org is allowed unlimited real-time alerts
if allowed is None:
return None
@@ -387,19 +404,16 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
enabled: bool,
existing: AlertConfiguration | None = None,
) -> str | None:
- """Validate a create/update that would leave an alert in the given real-time state.
+ """Validate the active real-time limit for 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.
+ Purely the limit check — callers gate the entitlement first via
+ interval_entitlement_error. 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 = (
diff --git a/products/alerts/frontend/components/QuietHoursFields.tsx b/products/alerts/frontend/components/QuietHoursFields.tsx
index f8871f057f30..741de4d89a63 100644
--- a/products/alerts/frontend/components/QuietHoursFields.tsx
+++ b/products/alerts/frontend/components/QuietHoursFields.tsx
@@ -8,7 +8,7 @@ import type { BlockedWindow, ScheduleRestriction } from 'lib/components/Alerts/t
import { AlertCalculationInterval } from '~/queries/schema/schema-general'
-import { isHighFrequencyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'
+import { isSubDailyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'
import { estimateCheckSlotsNext24h } from 'products/alerts/frontend/logic/scheduleRestrictionPreview'
import { QuietHoursDayTimeline } from './QuietHoursDayTimeline'
@@ -107,7 +107,7 @@ export function QuietHoursFields({
[enabled, windows]
)
- const nonHighFrequencyInterval = !isHighFrequencyAlertInterval(calculationInterval)
+ const coarseInterval = !isSubDailyAlertInterval(calculationInterval)
? calculationInterval === AlertCalculationInterval.DAILY
? 'day'
: calculationInterval === AlertCalculationInterval.WEEKLY
@@ -130,10 +130,10 @@ export function QuietHoursFields({
/>
{enabled ? (
<>
- {nonHighFrequencyInterval ? (
+ {coarseInterval ? (
<LemonBanner type="info">
If a scheduled run would fall during quiet hours, it runs at the next allowed time in that
- same day or cycle instead of waiting until the next {nonHighFrequencyInterval}.
+ same day or cycle instead of waiting until the next {coarseInterval}.
</LemonBanner>
) : null}
<div className="flex flex-wrap gap-2">
diff --git a/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx b/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx
index 620fcf9bfa6d..2518c9e1cf6d 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx
+++ b/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx
@@ -8,7 +8,7 @@ import { LemonField } from 'lib/lemon-ui/LemonField'
import { AlertCalculationInterval } from '~/queries/schema/schema-general'
-import { isHighFrequencyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'
+import { isSubDailyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'
import { QuietHoursFields } from '../QuietHoursFields'
@@ -76,7 +76,7 @@ export function AlertAdvancedOptionsSection({
<LemonCheckbox
checked={
(alertForm?.calculation_interval === AlertCalculationInterval.DAILY ||
- isHighFrequencyAlertInterval(
+ isSubDailyAlertInterval(
alertForm?.calculation_interval ?? AlertCalculationInterval.DAILY
)) &&
alertForm?.skip_weekend
@@ -86,7 +86,7 @@ export function AlertAdvancedOptionsSection({
label="Skip checking on weekends"
disabledReason={
alertForm?.calculation_interval !== AlertCalculationInterval.DAILY &&
- !isHighFrequencyAlertInterval(
+ !isSubDailyAlertInterval(
alertForm?.calculation_interval ?? AlertCalculationInterval.DAILY
) &&
'Can only skip weekend checking for 15-minute, hourly, or daily alerts'
diff --git a/products/alerts/frontend/components/editAlertModal/AlertIntervalRow.tsx b/products/alerts/frontend/components/editAlertModal/AlertIntervalRow.tsx
index d41c9c25d22c..f486d9623873 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertIntervalRow.tsx
+++ b/products/alerts/frontend/components/editAlertModal/AlertIntervalRow.tsx
@@ -1,13 +1,29 @@
+import { useValues } from 'kea'
+
import { IconClock } from '@posthog/icons'
-import { LemonSelect } from '@posthog/lemon-ui'
+import { LemonSelect, Tooltip } from '@posthog/lemon-ui'
import { AlertFormType } from 'lib/components/Alerts/alertFormLogic'
-import { AlertType, isHogQLAlertConfig, isTrendsAlertConfig, supportsTimeWindow } from 'lib/components/Alerts/types'
+import {
+ AlertType,
+ isHogQLAlertConfig,
+ isTrendsAlertConfig,
+ supportsOngoingInterval,
+ supportsTimeWindow,
+} from 'lib/components/Alerts/types'
import { TZLabel } from 'lib/components/TZLabel'
-import type { GuardAvailableFeatureFn } from 'lib/components/UpgradeModal/upgradeModalLogic'
+import { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonField } from 'lib/lemon-ui/LemonField'
+import { userLogic } from 'scenes/userLogic'
+
+import { AlertCalculationInterval } from '~/queries/schema/schema-general'
+import { AvailableFeature } from '~/types'
-import { selectAlertCalculationInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'
+import {
+ cadenceFinerThanInsightInterval,
+ selectAlertCalculationInterval,
+} from 'products/alerts/frontend/logic/alertIntervalHelpers'
import { getAlertIntervalOptions } from './editAlertModalUtils'
@@ -16,9 +32,9 @@ export interface AlertIntervalRowProps {
creatingNewAlert: boolean
alert: AlertType | null | undefined
trendInterval: string | null | undefined
- hasHighFrequencyAlertsEntitlement: boolean
- guardAvailableFeature: GuardAvailableFeatureFn
nextPlannedEvaluationStale: boolean
+ canCheckOngoingInterval: boolean
+ onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
}
export function AlertIntervalRow({
@@ -26,10 +42,15 @@ export function AlertIntervalRow({
creatingNewAlert,
alert,
trendInterval,
- hasHighFrequencyAlertsEntitlement,
- guardAvailableFeature,
nextPlannedEvaluationStale,
+ canCheckOngoingInterval,
+ onSetAlertFormValue,
}: AlertIntervalRowProps): JSX.Element {
+ const { hasAvailableFeature } = useValues(userLogic)
+ const { guardAvailableFeature } = useValues(upgradeModalLogic)
+ const hasHighFrequencyAlertsEntitlement = hasAvailableFeature(AvailableFeature.HIGH_FREQUENCY_ALERTS)
+ const hasRealTimeAlertsEntitlement = hasAvailableFeature(AvailableFeature.REAL_TIME_ALERTS)
+ const realTimeAlertsEnabled = useFeatureFlag('ALERTS_REAL_TIME_INTERVAL')
const hogqlEvaluation = isHogQLAlertConfig(alertForm.config) ? alertForm.config.evaluation : null
const hogqlEvaluatedText =
hogqlEvaluation === 'any_row'
@@ -40,7 +61,11 @@ export function AlertIntervalRow({
return (
<>
<div className="flex flex-wrap gap-x-3 gap-y-2 items-center">
- <div>Run alert every</div>
+ <div>
+ {alertForm.calculation_interval === AlertCalculationInterval.REAL_TIME
+ ? 'Run alert'
+ : 'Run alert every'}
+ </div>
<LemonField name="calculation_interval">
{({ value, onChange }) => (
<LemonSelect
@@ -48,12 +73,31 @@ export function AlertIntervalRow({
className="w-36 shrink-0 whitespace-nowrap"
data-attr="alertForm-calculation-interval"
value={value}
- options={getAlertIntervalOptions(hasHighFrequencyAlertsEntitlement)}
+ options={getAlertIntervalOptions(
+ hasHighFrequencyAlertsEntitlement,
+ hasRealTimeAlertsEntitlement,
+ // Keep the option visible for alerts that already use it, even if the rollout flag is off
+ realTimeAlertsEnabled || value === AlertCalculationInterval.REAL_TIME
+ )}
onChange={(interval) => {
selectAlertCalculationInterval(interval, {
guardAvailableFeature,
- onSelect: onChange,
+ onSelect: (selected) => {
+ onChange(selected)
+ if (
+ cadenceFinerThanInsightInterval(selected, trendInterval) &&
+ canCheckOngoingInterval &&
+ supportsOngoingInterval(alertForm.config) &&
+ alertForm.config.check_ongoing_interval === undefined
+ ) {
+ onSetAlertFormValue('config', {
+ ...alertForm.config,
+ check_ongoing_interval: true,
+ })
+ }
+ },
hasHighFrequencyAlertsEntitlement,
+ hasRealTimeAlertsEntitlement,
})
}}
/>
@@ -64,32 +108,23 @@ export function AlertIntervalRow({
// so state what is actually evaluated instead of a trends-style "check last day".
<div>{hogqlEvaluatedText}</div>
) : (
- <>
- <div>
- and check{' '}
- {isTrendsAlertConfig(alertForm?.config) && alertForm.config.check_ongoing_interval
- ? 'current'
- : 'last'}
- </div>
- <LemonSelect
- fullWidth
- className="w-28"
- data-attr="alertForm-trend-interval"
- disabledReason={
+ <div data-attr="alertForm-trend-interval">
+ and check{' '}
+ {isTrendsAlertConfig(alertForm?.config) && alertForm.config.check_ongoing_interval
+ ? 'current'
+ : 'last'}{' '}
+ <Tooltip
+ title={
<>
- To change the interval being checked, edit and <b>save</b> the interval which the
- insight is 'grouped by'
+ Set by the insight's <b>grouped by</b> interval. Edit the insight to change it.
</>
}
- value={trendInterval ?? 'day'}
- options={[
- {
- label: trendInterval ?? 'day',
- value: trendInterval ?? 'day',
- },
- ]}
- />
- </>
+ >
+ <span className="font-semibold underline decoration-dotted cursor-help">
+ {trendInterval ?? 'day'}
+ </span>
+ </Tooltip>
+ </div>
)}
</div>
{!creatingNewAlert && alert ? (
diff --git a/products/alerts/frontend/components/editAlertModal/editAlertModalUtils.tsx b/products/alerts/frontend/components/editAlertModal/editAlertModalUtils.tsx
index 1f9cd9229b28..0c529b3451c3 100644
--- a/products/alerts/frontend/components/editAlertModal/editAlertModalUtils.tsx
+++ b/products/alerts/frontend/components/editAlertModal/editAlertModalUtils.tsx
@@ -48,10 +48,10 @@ export function getSimulationRangeOptions(interval: AlertCalculationInterval): {
}
}
-export function alertCalculationIntervalToLabel(interval: AlertCalculationInterval): string {
+export function intervalDropdownPhrase(interval: AlertCalculationInterval): string {
switch (interval) {
case AlertCalculationInterval.REAL_TIME:
- return 'Real time'
+ return 'in real time'
case AlertCalculationInterval.EVERY_15_MINUTES:
return '15 minutes'
case AlertCalculationInterval.HOURLY:
@@ -73,12 +73,20 @@ export const ALERT_INTERVAL_OPTIONS: AlertCalculationInterval[] = [
]
export function getAlertIntervalOptions(
- hasHighFrequencyAlertsEntitlement: boolean
+ hasHighFrequencyAlertsEntitlement: boolean,
+ hasRealTimeAlertsEntitlement: boolean,
+ showRealTimeOption: boolean
): Array<{ label: string | JSX.Element; value: AlertCalculationInterval }> {
- const intervals = [AlertCalculationInterval.EVERY_15_MINUTES, ...ALERT_INTERVAL_OPTIONS]
+ const intervals = [
+ ...(showRealTimeOption ? [AlertCalculationInterval.REAL_TIME] : []),
+ AlertCalculationInterval.EVERY_15_MINUTES,
+ ...ALERT_INTERVAL_OPTIONS,
+ ]
return intervals.map((interval) => {
- const labelText = alertCalculationIntervalToLabel(interval)
- const showLock = interval === AlertCalculationInterval.EVERY_15_MINUTES && !hasHighFrequencyAlertsEntitlement
+ const labelText = intervalDropdownPhrase(interval)
+ const showLock =
+ (interval === AlertCalculationInterval.EVERY_15_MINUTES && !hasHighFrequencyAlertsEntitlement) ||
+ (interval === AlertCalculationInterval.REAL_TIME && !hasRealTimeAlertsEntitlement)
return {
label: showLock ? (
<span className="flex items-center gap-1.5">
diff --git a/products/alerts/frontend/logic/alertIntervalHelpers.test.ts b/products/alerts/frontend/logic/alertIntervalHelpers.test.ts
index e71468373fac..ad34a96c0209 100644
--- a/products/alerts/frontend/logic/alertIntervalHelpers.test.ts
+++ b/products/alerts/frontend/logic/alertIntervalHelpers.test.ts
@@ -8,7 +8,7 @@ import { AvailableFeature } from '~/types'
import {
getDefaultSimulationRange,
- isHighFrequencyAlertInterval,
+ isSubDailyAlertInterval,
selectAlertCalculationInterval,
} from './alertIntervalHelpers'
@@ -19,6 +19,7 @@ describe('alertIntervalHelpers', () => {
describe('getDefaultSimulationRange', () => {
it.each([
+ [AlertCalculationInterval.REAL_TIME, '-1h'],
[AlertCalculationInterval.EVERY_15_MINUTES, '-12h'],
[AlertCalculationInterval.HOURLY, '-48h'],
[AlertCalculationInterval.DAILY, '-30d'],
@@ -42,6 +43,7 @@ describe('alertIntervalHelpers', () => {
guardAvailableFeature: upgradeModalLogic.values.guardAvailableFeature,
onSelect,
hasHighFrequencyAlertsEntitlement: false,
+ hasRealTimeAlertsEntitlement: false,
})
expect(applied).toBe(false)
@@ -49,6 +51,21 @@ describe('alertIntervalHelpers', () => {
expect(upgradeModalLogic.values.upgradeModalFeatureKey).toBe(AvailableFeature.HIGH_FREQUENCY_ALERTS)
})
+ it('opens upgrade modal and does not update interval when real time is selected without entitlement', () => {
+ const onSelect = jest.fn()
+
+ const applied = selectAlertCalculationInterval(AlertCalculationInterval.REAL_TIME, {
+ guardAvailableFeature: upgradeModalLogic.values.guardAvailableFeature,
+ onSelect,
+ hasHighFrequencyAlertsEntitlement: false,
+ hasRealTimeAlertsEntitlement: false,
+ })
+
+ expect(applied).toBe(false)
+ expect(onSelect).not.toHaveBeenCalled()
+ expect(upgradeModalLogic.values.upgradeModalFeatureKey).toBe(AvailableFeature.REAL_TIME_ALERTS)
+ })
+
it('updates interval when 15-minute is selected with entitlement', () => {
const onSelect = jest.fn()
const guardAvailableFeature: GuardAvailableFeatureFn = (_feature, callback) => {
@@ -60,12 +77,31 @@ describe('alertIntervalHelpers', () => {
guardAvailableFeature,
onSelect,
hasHighFrequencyAlertsEntitlement: true,
+ hasRealTimeAlertsEntitlement: false,
})
expect(applied).toBe(true)
expect(onSelect).toHaveBeenCalledWith(AlertCalculationInterval.EVERY_15_MINUTES)
})
+ it('updates interval when real time is selected with entitlement', () => {
+ const onSelect = jest.fn()
+ const guardAvailableFeature: GuardAvailableFeatureFn = (_feature, callback) => {
+ callback?.()
+ return true
+ }
+
+ const applied = selectAlertCalculationInterval(AlertCalculationInterval.REAL_TIME, {
+ guardAvailableFeature,
+ onSelect,
+ hasHighFrequencyAlertsEntitlement: false,
+ hasRealTimeAlertsEntitlement: true,
+ })
+
+ expect(applied).toBe(true)
+ expect(onSelect).toHaveBeenCalledWith(AlertCalculationInterval.REAL_TIME)
+ })
+
it('updates interval for non-15-minute options without calling the guard', () => {
const onSelect = jest.fn()
const guardAvailableFeature = jest.fn<
@@ -77,6 +113,7 @@ describe('alertIntervalHelpers', () => {
guardAvailableFeature,
onSelect,
hasHighFrequencyAlertsEntitlement: false,
+ hasRealTimeAlertsEntitlement: false,
})
expect(onSelect).toHaveBeenCalledWith(AlertCalculationInterval.HOURLY)
@@ -84,15 +121,16 @@ describe('alertIntervalHelpers', () => {
})
})
- describe('isHighFrequencyAlertInterval', () => {
+ describe('isSubDailyAlertInterval', () => {
it.each([
+ [AlertCalculationInterval.REAL_TIME, true],
[AlertCalculationInterval.EVERY_15_MINUTES, true],
[AlertCalculationInterval.HOURLY, true],
[AlertCalculationInterval.DAILY, false],
[AlertCalculationInterval.WEEKLY, false],
[AlertCalculationInterval.MONTHLY, false],
])('%s → %s', (interval, expected) => {
- expect(isHighFrequencyAlertInterval(interval)).toBe(expected)
+ expect(isSubDailyAlertInterval(interval)).toBe(expected)
})
})
})
diff --git a/products/alerts/frontend/logic/alertIntervalHelpers.ts b/products/alerts/frontend/logic/alertIntervalHelpers.ts
index 8674ab1007ed..52515ea89779 100644
--- a/products/alerts/frontend/logic/alertIntervalHelpers.ts
+++ b/products/alerts/frontend/logic/alertIntervalHelpers.ts
@@ -3,7 +3,7 @@ import posthog from 'posthog-js'
import type { GuardAvailableFeatureFn } from 'lib/components/UpgradeModal/upgradeModalLogic'
import { AlertCalculationInterval } from '~/queries/schema/schema-general'
-import { AvailableFeature } from '~/types'
+import { AvailableFeature, IntervalType } from '~/types'
export function getDefaultSimulationRange(interval: AlertCalculationInterval): string {
switch (interval) {
@@ -22,18 +22,91 @@ export function getDefaultSimulationRange(interval: AlertCalculationInterval): s
}
}
-export function isHighFrequencyAlertInterval(interval: AlertCalculationInterval): boolean {
- return interval === AlertCalculationInterval.HOURLY || interval === AlertCalculationInterval.EVERY_15_MINUTES
-}
-
export const HIGH_FREQUENCY_ALERTS_REQUIRED_MESSAGE =
'15-minute alert intervals require a Boost, Scale, or Enterprise platform add-on.'
-export function blockSubmitWithoutHighFrequencyAlertsEntitlement(
- interval: AlertCalculationInterval,
- hasHighFrequencyAlertsEntitlement: boolean
+const SUB_DAILY_INTERVALS = [
+ AlertCalculationInterval.HOURLY,
+ AlertCalculationInterval.EVERY_15_MINUTES,
+ AlertCalculationInterval.REAL_TIME,
+]
+
+export function isSubDailyAlertInterval(interval: AlertCalculationInterval): boolean {
+ return SUB_DAILY_INTERVALS.includes(interval)
+}
+
+const INTERVAL_DISPLAY_LABELS: Record<AlertCalculationInterval, string> = {
+ [AlertCalculationInterval.REAL_TIME]: 'Real time',
+ [AlertCalculationInterval.EVERY_15_MINUTES]: 'Every 15 minutes',
+ [AlertCalculationInterval.HOURLY]: 'Hourly',
+ [AlertCalculationInterval.DAILY]: 'Daily',
+ [AlertCalculationInterval.WEEKLY]: 'Weekly',
+ [AlertCalculationInterval.MONTHLY]: 'Monthly',
+}
+
+export function alertIntervalDisplayLabel(interval: AlertCalculationInterval): string {
+ return INTERVAL_DISPLAY_LABELS[interval]
+}
+
+// Twin of _CADENCE_DURATION_MINUTES / _INTERVAL_DURATION_MINUTES in
+// products/alerts/backend/evaluation/validation.py — keep the two in sync.
+const CADENCE_DURATION_MINUTES: Record<AlertCalculationInterval, number> = {
+ [AlertCalculationInterval.REAL_TIME]: 2,
+ [AlertCalculationInterval.EVERY_15_MINUTES]: 15,
+ [AlertCalculationInterval.HOURLY]: 60,
+ [AlertCalculationInterval.DAILY]: 60 * 24,
+ [AlertCalculationInterval.WEEKLY]: 60 * 24 * 7,
+ [AlertCalculationInterval.MONTHLY]: 60 * 24 * 30,
+}
+
+const INSIGHT_INTERVAL_DURATION_MINUTES: Record<IntervalType, number> = {
+ second: 1 / 60,
+ minute: 1,
+ hour: 60,
+ day: 60 * 24,
+ week: 60 * 24 * 7,
+ month: 60 * 24 * 30,
+}
+
+/** An alert re-checks the insight's last completed bucket, whose size is the insight's grouping
+ * interval. A cadence finer than that bucket re-reads the same frozen value until the bucket closes,
+ * so evaluating the ongoing (incomplete) bucket is what makes the faster cadence meaningful. */
+export function cadenceFinerThanInsightInterval(
+ cadence: AlertCalculationInterval,
+ insightInterval: string | null | undefined
): boolean {
- return interval === AlertCalculationInterval.EVERY_15_MINUTES && !hasHighFrequencyAlertsEntitlement
+ const insightMinutes =
+ INSIGHT_INTERVAL_DURATION_MINUTES[(insightInterval as IntervalType | null) ?? 'day'] ??
+ INSIGHT_INTERVAL_DURATION_MINUTES.day
+ return CADENCE_DURATION_MINUTES[cadence] < insightMinutes
+}
+
+type EntitlementResult =
+ | { blocked: true; message: string; feature: AvailableFeature }
+ | { blocked: false; message: null; feature: null }
+
+export function blockSubmitWithoutEntitlement(
+ interval: AlertCalculationInterval,
+ {
+ hasHighFrequencyAlertsEntitlement,
+ hasRealTimeAlertsEntitlement,
+ }: { hasHighFrequencyAlertsEntitlement: boolean; hasRealTimeAlertsEntitlement: boolean }
+): EntitlementResult {
+ if (interval === AlertCalculationInterval.EVERY_15_MINUTES && !hasHighFrequencyAlertsEntitlement) {
+ return {
+ blocked: true,
+ message: HIGH_FREQUENCY_ALERTS_REQUIRED_MESSAGE,
+ feature: AvailableFeature.HIGH_FREQUENCY_ALERTS,
+ }
+ }
+ if (interval === AlertCalculationInterval.REAL_TIME && !hasRealTimeAlertsEntitlement) {
+ return {
+ blocked: true,
+ message: 'Real-time alert intervals require a Scale or Enterprise plan.',
+ feature: AvailableFeature.REAL_TIME_ALERTS,
+ }
+ }
+ return { blocked: false, message: null, feature: null }
}
export function selectAlertCalculationInterval(
@@ -42,12 +115,22 @@ export function selectAlertCalculationInterval(
guardAvailableFeature,
onSelect,
hasHighFrequencyAlertsEntitlement,
+ hasRealTimeAlertsEntitlement,
}: {
guardAvailableFeature: GuardAvailableFeatureFn
onSelect: (interval: AlertCalculationInterval) => void
hasHighFrequencyAlertsEntitlement: boolean
+ hasRealTimeAlertsEntitlement: boolean
}
): boolean {
+ if (value === AlertCalculationInterval.REAL_TIME) {
+ posthog.capture('alert real time interval selected', {
+ has_entitlement: hasRealTimeAlertsEntitlement,
+ })
+ return guardAvailableFeature(AvailableFeature.REAL_TIME_ALERTS, () => {
+ onSelect(value)
+ })
+ }
if (value === AlertCalculationInterval.EVERY_15_MINUTES) {
posthog.capture('alert 15 min interval selected', {
has_entitlement: hasHighFrequencyAlertsEntitlement,
diff --git a/products/alerts/package.json b/products/alerts/package.json
index f1aee994a865..d005c8c1ff7d 100644
--- a/products/alerts/package.json
+++ b/products/alerts/package.json
@@ -4,6 +4,7 @@
"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"
},
"dependencies": {
+ "kea": "catalog:",
"posthog-js": "catalog:"
},
"devDependencies": {