:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(alerts): require threshold bounds on create and in form (#61691)
Matt Pua37836f7ef54c
diff --git a/frontend/src/lib/components/Alerts/alertFormLogic.test.ts b/frontend/src/lib/components/Alerts/alertFormLogic.test.tsindex c2d8bd34c85e..9612dfc188b4 100644--- a/frontend/src/lib/components/Alerts/alertFormLogic.test.ts+++ b/frontend/src/lib/components/Alerts/alertFormLogic.test.ts@@ -20,7 +20,7 @@ import {import { initKeaTests } from '~/test/init'import { InsightLogicProps, InsightShortId } from '~/types'-import { alertFormLogic, type AlertFormType } from './alertFormLogic'+import { alertFormLogic, thresholdAlertHasBounds, type AlertFormType } from './alertFormLogic'import { alertNotificationLogic } from './alertNotificationLogic'import { insightAlertsLogic } from './insightAlertsLogic'import type { AlertType } from './types'@@ -231,6 +231,47 @@ describe('alertFormLogic', () => {expect(successToastSpy).toHaveBeenCalledWith('Alert saved.')})+ it('blocks save when threshold alert has no lower or upper bound', async () => {+ const logic = mountForm()+ logic.actions.setAlertFormValues({+ ...makeFormDefaults({+ threshold: {+ configuration: {+ type: InsightThresholdType.ABSOLUTE,+ bounds: {},+ },+ },+ }),+ checks: undefined,+ })++ expect(thresholdAlertHasBounds(logic.values.alertForm)).toBe(false)++ logic.actions.setAlertFormSubmitAttempted()++ await expectLogic(logic, () => {+ logic.actions.submitAlertForm()+ }).toFinishAllListeners()++ expect(createSpy).not.toHaveBeenCalled()+ expect(successToastSpy).not.toHaveBeenCalled()+ expect(logic.values.thresholdBoundsFormError).toBe('Enter at least one threshold (less than or more than)')+ })++ it('treats cleared threshold inputs as missing bounds', () => {+ expect(+ thresholdAlertHasBounds({+ ...makeFormDefaults(),+ threshold: {+ configuration: {+ type: InsightThresholdType.ABSOLUTE,+ bounds: { lower: '' as unknown as number, upper: '' as unknown as number },+ },+ },+ })+ ).toBe(false)+ })+it('blocks save with error toast for 15-minute interval without entitlement', async () => {userLogic.mount()upgradeModalLogic.mount()diff --git a/frontend/src/lib/components/Alerts/alertFormLogic.ts b/frontend/src/lib/components/Alerts/alertFormLogic.tsindex 1b10276ead12..6a6670bc9b8b 100644--- a/frontend/src/lib/components/Alerts/alertFormLogic.ts+++ b/frontend/src/lib/components/Alerts/alertFormLogic.ts@@ -1,5 +1,5 @@-import { actions, connect, kea, key, listeners, path, props, reducers } from 'kea'-import { forms, type DeepPartialMap, type ValidationErrorType } from 'kea-forms'+import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { forms } from 'kea-forms'import { loaders } from 'kea-loaders'import posthog from 'posthog-js'@@ -26,12 +26,14 @@ import {} from 'products/alerts/frontend/logic/alertIntervalHelpers'import type { alertFormLogicType } from './alertFormLogicType'+import { getAlertFormValidationErrors } from './alertFormSchema'import { alertLogic } from './alertLogic'import { alertNotificationLogic } from './alertNotificationLogic'import { insightAlertsLogic } from './insightAlertsLogic'-import { quietHoursFormError } from './scheduleRestrictionValidation'import { AlertSimulationResult, AlertType, AlertTypeWrite, AnomalyPoint } from './types'+export { THRESHOLD_BOUNDS_FORM_ERROR, thresholdAlertHasBounds } from './alertFormSchema'+export type AlertFormType = Pick<AlertType,| 'name'@@ -164,6 +166,7 @@ export const alertFormLogic = kea<alertFormLogicType>([simulateAlert: true,clearSimulation: true,setSimulationDateFrom: (dateFrom: string) => ({ dateFrom }),+ setAlertFormSubmitAttempted: true,}),reducers({@@ -173,6 +176,13 @@ export const alertFormLogic = kea<alertFormLogicType>([setSimulationDateFrom: (_, { dateFrom }) => dateFrom,},],+ alertFormSubmitAttempted: [+ false,+ {+ setAlertFormSubmitAttempted: () => true,+ submitAlertFormSuccess: () => false,+ },+ ],}),loaders(({ props, values }) => ({@@ -234,11 +244,7 @@ export const alertFormLogic = kea<alertFormLogicType>([investigation_inconclusive_action: 'notify',insight: props.insightId,} as AlertFormType),- errors: (alert: AlertFormType) =>- ({- name: !alert.name ? 'You need to give your alert a name' : undefined,- schedule_restriction: quietHoursFormError(alert.schedule_restriction),- }) as DeepPartialMap<AlertFormType, ValidationErrorType>,+ errors: (alert: AlertFormType) => getAlertFormValidationErrors(alert),submit: async (alert) => {if (blockSubmitWithoutHighFrequencyAlertsEntitlement(@@ -343,7 +349,20 @@ export const alertFormLogic = kea<alertFormLogicType>([},})),- listeners(({ props, values }) => {+ selectors({+ thresholdBoundsFormError: [+ (s) => [s.alertFormSubmitAttempted, s.alertFormErrors],+ (submitAttempted, alertFormErrors): string | undefined => {+ if (!submitAttempted) {+ return undefined+ }+ const thresholdError = alertFormErrors.threshold+ return typeof thresholdError === 'string' ? thresholdError : undefined+ },+ ],+ }),++ listeners(({ props, values, actions }) => {const getParentLogic = (): ReturnType<typeof insightAlertsLogic.build> | undefined => {if (props.insightVizDataLogicProps) {return insightAlertsLogic({@@ -398,6 +417,9 @@ export const alertFormLogic = kea<alertFormLogicType>([}props.onEditSuccess(values.alertForm.id)},+ submitAlertForm: () => {+ actions.setAlertFormSubmitAttempted()+ },submitAlertFormSuccess: async () => {// Background sync to pick up any server-side changesgetParentLogic()?.actions.loadAlerts()diff --git a/frontend/src/lib/components/Alerts/alertFormSchema.test.ts b/frontend/src/lib/components/Alerts/alertFormSchema.test.tsnew file mode 100644index 000000000000..6a653559ae1e--- /dev/null+++ b/frontend/src/lib/components/Alerts/alertFormSchema.test.ts@@ -0,0 +1,93 @@+import { AlertCalculationInterval, AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import type { AlertFormType } from './alertFormLogic'+import { getAlertFormValidationErrors, THRESHOLD_BOUNDS_FORM_ERROR, thresholdAlertHasBounds } from './alertFormSchema'++const baseAlert: AlertFormType = {+ name: 'My alert',+ enabled: true,+ created_by: null,+ created_at: '',+ config: {+ type: 'TrendsAlertConfig',+ series_index: 0,+ check_ongoing_interval: false,+ },+ threshold: {+ configuration: {+ type: InsightThresholdType.ABSOLUTE,+ bounds: { upper: 100 },+ },+ },+ condition: { type: AlertConditionType.ABSOLUTE_VALUE },+ subscribed_users: [],+ checks: [],+ calculation_interval: AlertCalculationInterval.DAILY,+ skip_weekend: false,+ schedule_restriction: null,+ detector_config: null,+ insight: 42,+}++describe('alertFormSchema', () => {+ beforeEach(() => {+ initKeaTests()+ })++ it('returns no errors for a valid threshold alert', () => {+ expect(getAlertFormValidationErrors(baseAlert)).toEqual({})+ })++ it('requires a name', () => {+ expect(getAlertFormValidationErrors({ ...baseAlert, name: '' }).name).toBe('You need to give your alert a name')+ })++ it('requires at least one threshold bound for non-detector alerts', () => {+ const errors = getAlertFormValidationErrors({+ ...baseAlert,+ threshold: {+ configuration: {+ type: InsightThresholdType.ABSOLUTE,+ bounds: {},+ },+ },+ })+ expect(errors.threshold).toBe(THRESHOLD_BOUNDS_FORM_ERROR)+ expect(+ thresholdAlertHasBounds({+ ...baseAlert,+ threshold: { configuration: { type: InsightThresholdType.ABSOLUTE, bounds: {} } },+ })+ ).toBe(false)+ })++ it('treats cleared threshold inputs as missing bounds', () => {+ expect(+ thresholdAlertHasBounds({+ ...baseAlert,+ threshold: {+ configuration: {+ type: InsightThresholdType.ABSOLUTE,+ bounds: { lower: '' as unknown as number, upper: '' as unknown as number },+ },+ },+ })+ ).toBe(false)+ })++ it('skips threshold bounds when detector_config is set', () => {+ expect(+ getAlertFormValidationErrors({+ ...baseAlert,+ detector_config: { type: 'zscore', threshold: 3 },+ threshold: {+ configuration: {+ type: InsightThresholdType.ABSOLUTE,+ bounds: {},+ },+ },+ })+ ).toEqual({})+ })+})diff --git a/frontend/src/lib/components/Alerts/alertFormSchema.ts b/frontend/src/lib/components/Alerts/alertFormSchema.tsnew file mode 100644index 000000000000..c23b7d3e5051--- /dev/null+++ b/frontend/src/lib/components/Alerts/alertFormSchema.ts@@ -0,0 +1,89 @@+import type { DeepPartialMap, ValidationErrorType } from 'kea-forms'+import { z } from 'zod'++import type { AlertFormType } from './alertFormLogic'+import { quietHoursFormError } from './scheduleRestrictionValidation'+import type { AlertType } from './types'++export const THRESHOLD_BOUNDS_FORM_ERROR = 'Enter at least one threshold (less than or more than)'++const NAME_REQUIRED_MESSAGE = 'You need to give your alert a name'++function isFiniteThresholdBound(value: number | string | null | undefined): boolean {+ if (value == null || value === '') {+ return false+ }+ return !Number.isNaN(Number(value))+}++export function thresholdAlertHasBounds(alert: AlertFormType | AlertType): boolean {+ if (alert.detector_config) {+ return true+ }+ const bounds = alert.threshold?.configuration?.bounds+ if (!bounds) {+ return false+ }+ const { lower, upper } = bounds+ return isFiniteThresholdBound(lower) || isFiniteThresholdBound(upper)+}++const alertFormSchema = z+ .object({+ name: z.string(),+ detector_config: z.unknown().nullable(),+ threshold: z+ .object({+ configuration: z+ .object({+ bounds: z+ .object({+ lower: z.union([z.number(), z.string()]).nullish(),+ upper: z.union([z.number(), z.string()]).nullish(),+ })+ .optional(),+ })+ .optional(),+ })+ .optional(),+ schedule_restriction: z.custom<AlertFormType['schedule_restriction']>().nullable().optional(),+ })+ .passthrough()+ .superRefine((alert, ctx) => {+ if (!alert.name) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['name'], message: NAME_REQUIRED_MESSAGE })+ }++ const scheduleError = quietHoursFormError(alert.schedule_restriction)+ if (scheduleError) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['schedule_restriction'],+ message: scheduleError,+ })+ }++ if (!thresholdAlertHasBounds(alert as AlertFormType)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['threshold'],+ message: THRESHOLD_BOUNDS_FORM_ERROR,+ })+ }+ })++export function getAlertFormValidationErrors(alert: AlertFormType): DeepPartialMap<AlertFormType, ValidationErrorType> {+ const result = alertFormSchema.safeParse(alert)+ if (result.success) {+ return {}+ }++ const errors: Record<string, ValidationErrorType> = {}+ for (const issue of result.error.issues) {+ const field = issue.path[0]+ if (typeof field === 'string' && errors[field] === undefined) {+ errors[field] = issue.message+ }+ }+ return errors as DeepPartialMap<AlertFormType, ValidationErrorType>+}diff --git a/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx b/frontend/src/lib/components/Alerts/views/EditAlertModal.tsxindex e21b403b301c..8d5869ae97c5 100644--- a/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx+++ b/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx@@ -90,9 +90,17 @@ export function EditAlertModal({simulationResult,simulationResultLoading,simulationDateFrom,+ thresholdBoundsFormError,} = useValues(formLogic)- const { deleteAlert, snoozeAlert, clearSnooze, simulateAlert, clearSimulation, setSimulationDateFrom } =- useActions(formLogic)+ const {+ deleteAlert,+ snoozeAlert,+ clearSnooze,+ simulateAlert,+ clearSimulation,+ setSimulationDateFrom,+ setAlertFormSubmitAttempted,+ } = useActions(formLogic)const { setAlertFormValue } = useActions(formLogic)const { currentTeam } = useValues(teamLogic)@@ -219,6 +227,7 @@ export function EditAlertModal({<AlertDefinitionSectionalertForm={alertForm}alertMode={alertMode}+ thresholdBoundsFormError={thresholdBoundsFormError}isBreakdownValid={isBreakdownValid}isNonTimeSeriesDisplay={isNonTimeSeriesDisplay}alertSeries={alertSeries}@@ -318,6 +327,7 @@ export function EditAlertModal({htmlType="submit"loading={isAlertFormSubmitting}disabledReason={!alertFormChanged && !hasPendingNotifications && 'No changes to save'}+ onClick={() => setAlertFormSubmitAttempted()}>{creatingNewAlert ? 'Create alert' : 'Save'}</LemonButton>diff --git a/posthog/api/test/test_alert_15_minute_interval.py b/posthog/api/test/test_alert_15_minute_interval.pyindex 39a94e31704f..c6c88570c2df 100644--- a/posthog/api/test/test_alert_15_minute_interval.py+++ b/posthog/api/test/test_alert_15_minute_interval.py@@ -51,7 +51,7 @@ class TestAlert15MinuteInterval(APIBaseTest):"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},"name": "15 min alert",- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"lower": 0}}},"calculation_interval": AlertCalculationInterval.EVERY_15_MINUTES,}payload.update(overrides)diff --git a/posthog/tasks/alerts/test/test_alert_evaluation.py b/posthog/tasks/alerts/test/test_alert_evaluation.pyindex f4d1d9a833cc..e5bf1d5d0a43 100644--- a/posthog/tasks/alerts/test/test_alert_evaluation.py+++ b/posthog/tasks/alerts/test/test_alert_evaluation.py@@ -41,7 +41,7 @@ class TestAlertEvaluation(APIBaseTest, ClickhouseDestroyTablesMixin):"calculation_interval": "daily","config": {"type": "TrendsAlertConfig", "series_index": 0},"condition": {"type": "absolute_value"},- "threshold": {"configuration": {"type": "absolute", "bounds": {}}},+ "threshold": {"configuration": {"type": "absolute", "bounds": {"lower": 0}}},},).json()diff --git a/posthog/tasks/alerts/test/test_alert_subscriptions.py b/posthog/tasks/alerts/test/test_alert_subscriptions.pyindex 6b7cabc76349..eee1fffb7a13 100644--- a/posthog/tasks/alerts/test/test_alert_subscriptions.py+++ b/posthog/tasks/alerts/test/test_alert_subscriptions.py@@ -41,7 +41,7 @@ class TestAlertSubscriptionOrgMembership(APIBaseTest):"calculation_interval": "daily","config": {"type": "TrendsAlertConfig", "series_index": 0},"condition": {"type": "absolute_value"},- "threshold": {"configuration": {"type": "absolute", "bounds": {}}},+ "threshold": {"configuration": {"type": "absolute", "bounds": {"lower": 0}}},},).json()@@ -106,7 +106,7 @@ class TestGetSubscribedUsersEmails(APIBaseTest):"calculation_interval": "daily","config": {"type": "TrendsAlertConfig", "series_index": 0},"condition": {"type": "absolute_value"},- "threshold": {"configuration": {"type": "absolute", "bounds": {}}},+ "threshold": {"configuration": {"type": "absolute", "bounds": {"lower": 0}}},},).json()@@ -176,7 +176,7 @@ class TestAlertEmailNotifications(APIBaseTest):"calculation_interval": "daily","config": {"type": "TrendsAlertConfig", "series_index": 0},"condition": {"type": "absolute_value"},- "threshold": {"configuration": {"type": "absolute", "bounds": {}}},+ "threshold": {"configuration": {"type": "absolute", "bounds": {"lower": 0}}},},).json()diff --git a/posthog/tasks/alerts/test/test_validate_alert_config.py b/posthog/tasks/alerts/test/test_validate_alert_config.pyindex 9583db17aea5..6079d47c1355 100644--- a/posthog/tasks/alerts/test/test_validate_alert_config.py+++ b/posthog/tasks/alerts/test/test_validate_alert_config.py@@ -27,8 +27,9 @@ def _base_query(series_count: int = 1, display: str | None = None) -> dict[str,def _base_threshold(type: str = "absolute", bounds: dict[str, Any] | None = None) -> dict[str, Any]:config: dict[str, Any] = {"type": type}- if bounds is not None:- config["bounds"] = bounds+ if bounds is None:+ bounds = {"upper": 1.0}+ config["bounds"] = boundsreturn config@@ -261,3 +262,33 @@ class TestValidateAlertConfig:else:with pytest.raises(ValueError, match=expected_error_fragment):validate_alert_config(query, condition, config, threshold_config, calculation_interval)++ def test_threshold_alert_requires_at_least_one_bound(self) -> None:+ with pytest.raises(ValueError, match="At least one threshold bound"):+ validate_alert_config(+ _base_query(),+ _base_condition(),+ _base_config(),+ _base_threshold(bounds={}),+ "daily",+ )++ def test_detector_alert_allows_empty_threshold_bounds(self) -> None:+ validate_alert_config(+ _base_query(),+ _base_condition(),+ _base_config(),+ _base_threshold(bounds={}),+ "daily",+ detector_config={"type": "zscore", "threshold": 0.95, "window": 30},+ )++ def test_skips_threshold_bounds_when_not_required(self) -> None:+ validate_alert_config(+ _base_query(),+ _base_condition(),+ _base_config(),+ _base_threshold(bounds={}),+ "daily",+ require_threshold_bounds=False,+ )diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.pyindex f61f8a33f29b..9a239a19feae 100644--- a/posthog/tasks/alerts/utils.py+++ b/posthog/tasks/alerts/utils.py@@ -6,6 +6,7 @@ from django.utils import timezoneimport pytzimport structlogfrom dateutil.relativedelta import MO, relativedelta+from pydantic import ValidationError as PydanticValidationErrorfrom posthog.schema import (AlertCalculationInterval,@@ -59,12 +60,35 @@ def is_non_time_series_trend(query: TrendsQuery) -> bool:return display in NON_TIME_SERIES_DISPLAY_TYPES+THRESHOLD_BOUNDS_REQUIRED_MESSAGE = "At least one threshold bound (lower or upper) must be provided."+++def insight_threshold_has_bounds(threshold_config: dict | None) -> bool:+ if threshold_config is None:+ return False+ try:+ threshold = InsightThreshold.model_validate(threshold_config)+ except PydanticValidationError:+ return False+ bounds = threshold.bounds+ if bounds is None:+ return False+ return bounds.lower is not None or bounds.upper is not None+++def validate_threshold_bounds_required(threshold_config: dict | None) -> None:+ if not insight_threshold_has_bounds(threshold_config):+ raise ValueError(THRESHOLD_BOUNDS_REQUIRED_MESSAGE)++def validate_alert_config(query: dict,condition: dict | None,config: dict | None,threshold_config: dict | None = None,calculation_interval: str | None = None,+ detector_config: dict | None = None,+ require_threshold_bounds: bool = True,) -> None:"""Validate alert configuration dicts. Raises ValueError on failure."""if not calculation_interval or not isinstance(calculation_interval, str):@@ -135,6 +159,9 @@ def validate_alert_config(f"check_ongoing_interval is only supported for alert condition {parsed_condition.type} when upper threshold is specified")+ if require_threshold_bounds and detector_config is None:+ validate_threshold_bounds_required(threshold_config)+def calculation_interval_to_order(interval: AlertCalculationInterval | None) -> int:match interval:diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.pyindex 9dd34aa3da87..b3357415ffcf 100644--- a/posthog/temporal/alerts/activities.py+++ b/posthog/temporal/alerts/activities.py@@ -166,6 +166,7 @@ async def prepare_alert(inputs: PrepareAlertActivityInputs) -> PrepareAlertResulalert.config,threshold_config,alert.calculation_interval,+ detector_config=alert.detector_config,)except ValueError as e:disable_invalid_alert(alert, str(e))diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.pyindex 4cc62d4d5cdf..0257ea90a3d1 100644--- a/posthog/temporal/tests/test_alerts_activities.py+++ b/posthog/temporal/tests/test_alerts_activities.py@@ -23,7 +23,7 @@ from posthog.schema import (from posthog.errors import CHQueryErrorTooManySimultaneousQueriesfrom posthog.models import User-from posthog.tasks.alerts.utils import AlertEvaluationResult+from posthog.tasks.alerts.utils import THRESHOLD_BOUNDS_REQUIRED_MESSAGE, AlertEvaluationResultfrom posthog.temporal.alerts.activities import cleanup_alert_checks, evaluate_alert, notify_alert, prepare_alertfrom posthog.temporal.alerts.types import (EvaluateAlertActivityInputs,@@ -33,7 +33,7 @@ from posthog.temporal.alerts.types import (SkipReason,)-from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Thresholdfrom products.product_analytics.backend.models.insight import Insight@@ -45,6 +45,10 @@ def _valid_trends_query() -> dict:).model_dump()+def _default_threshold_configuration() -> dict:+ return {"type": "absolute", "bounds": {"upper": 100.0}}++async def _create_alert(ateam,*,@@ -53,6 +57,7 @@ async def _create_alert(calculation_interval: str = AlertCalculationInterval.DAILY.value,config: dict | None = None,condition: dict | None = None,+ threshold_configuration: dict | None = None,next_check_at: datetime | None = None,snoozed_until: datetime | None = None,skip_weekend: bool = False,@@ -68,6 +73,11 @@ async def _create_alert(query=query if query is not None else _valid_trends_query(),deleted=insight_deleted,)+ threshold = Threshold.objects.create(+ team=ateam,+ insight=insight,+ configuration=threshold_configuration or _default_threshold_configuration(),+ )alert = AlertConfiguration.objects.create(team=ateam,insight=insight,@@ -76,6 +86,7 @@ async def _create_alert(calculation_interval=calculation_interval,config=config if config is not None else {"type": "TrendsAlertConfig", "series_index": 0},condition=condition if condition is not None else {"type": "absolute_value"},+ threshold=threshold,next_check_at=next_check_at,snoozed_until=snoozed_until,skip_weekend=skip_weekend,@@ -100,6 +111,11 @@ async def alert_with_user(ateam, aorganization):organization=aorganization, email=f"alerts-{uuid.uuid4().hex[:6]}@posthog.com", password=None)insight = Insight.objects.create(team=ateam, name="insight", query=_valid_trends_query())+ threshold = Threshold.objects.create(+ team=ateam,+ insight=insight,+ configuration=_default_threshold_configuration(),+ )a = AlertConfiguration.objects.create(team=ateam,insight=insight,@@ -108,6 +124,7 @@ async def alert_with_user(ateam, aorganization):calculation_interval=AlertCalculationInterval.DAILY.value,config={"type": "TrendsAlertConfig", "series_index": 0},condition={"type": "absolute_value"},+ threshold=threshold,)a.subscribed_users.add(user)return a@@ -236,6 +253,22 @@ class TestPrepareAlert:assert result.action == PrepareAction.EVALUATE+ async def test_auto_disable_when_threshold_bounds_empty(self, ateam) -> None:+ a = await _create_alert(+ ateam,+ threshold_configuration={"type": "absolute", "bounds": {}},+ )++ env = ActivityEnvironment()+ result = await env.run(prepare_alert, PrepareAlertActivityInputs(alert_id=str(a.id)))++ assert result.action == PrepareAction.AUTO_DISABLE+ assert result.reason == THRESHOLD_BOUNDS_REQUIRED_MESSAGE++ refreshed = await sync_to_async(AlertConfiguration.objects.get)(pk=a.pk)+ assert refreshed.enabled is False+ assert refreshed.state == AlertState.ERRORED+async def test_auto_disable_when_config_invalid(self, ateam) -> None:# Missing required "type" in config makes validate_alert_config raise ValueError.a = await _create_alert(ateam, config={"series_index": 0})diff --git a/posthog/temporal/tests/test_alerts_workflows.py b/posthog/temporal/tests/test_alerts_workflows.pyindex 8ee869c1f110..c73c6d0cd440 100644--- a/posthog/temporal/tests/test_alerts_workflows.py+++ b/posthog/temporal/tests/test_alerts_workflows.py@@ -31,7 +31,7 @@ from posthog.temporal.alerts.types import CheckAlertWorkflowInputs, SkipReasonfrom posthog.temporal.alerts.workflows import CheckAlertWorkflowfrom posthog.temporal.common.slo_interceptor import SloInterceptor-from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Thresholdfrom products.product_analytics.backend.models.insight import InsightCHECK_ALERT_ACTIVITIES: list[Callable[..., Any]] = [prepare_alert, evaluate_alert, notify_alert]@@ -59,6 +59,11 @@ def _build_alert(config: dict | None = None,) -> AlertConfiguration:insight = Insight.objects.create(team=ateam, name="insight", query=_valid_trends_query(), deleted=insight_deleted)+ threshold = Threshold.objects.create(+ team=ateam,+ insight=insight,+ configuration={"type": "absolute", "bounds": {"upper": 100.0}},+ )return AlertConfiguration.objects.create(team=ateam,insight=insight,@@ -67,6 +72,7 @@ def _build_alert(calculation_interval=AlertCalculationInterval.DAILY.value,config=config if config is not None else {"type": "TrendsAlertConfig", "series_index": 0},condition={"type": "absolute_value"},+ threshold=threshold,)diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.pyindex 48e67dfe2a20..a924db51e907 100644--- a/products/alerts/backend/api/alert.py+++ b/products/alerts/backend/api/alert.py@@ -37,7 +37,11 @@ from posthog.resource_limits import LimitKey, check_count_limitfrom posthog.schema_migrations.upgrade_manager import upgrade_queryfrom posthog.tasks.alerts.detector import MAX_DETECTOR_BREAKDOWN_VALUESfrom posthog.tasks.alerts.schedule_restriction import validate_and_normalize_schedule_restriction-from posthog.tasks.alerts.utils import next_check_at_after_schedule_restriction_change, validate_alert_config+from posthog.tasks.alerts.utils import (+ THRESHOLD_BOUNDS_REQUIRED_MESSAGE,+ next_check_at_after_schedule_restriction_change,+ validate_alert_config,+)from posthog.utils import relative_date_parsefrom products.alerts.backend.api.alert_schedule_restriction import AlertScheduleRestriction@@ -87,7 +91,8 @@ class ScheduleRestrictionField(serializers.JSONField):class ThresholdSerializer(serializers.ModelSerializer):configuration = ThresholdConfigurationField(- help_text="Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage).",+ help_text="Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). "+ "For threshold-based alerts (no detector_config), at least one of lower or upper must be set.",)name = serializers.CharField(required=False,@@ -539,9 +544,30 @@ class AlertSerializer(serializers.ModelSerializer):self.instance.calculation_interval if self.instance else AlertCalculationInterval.DAILY,)+ if "detector_config" in attrs:+ detector_config = attrs["detector_config"]+ elif self.instance is not None:+ detector_config = self.instance.detector_config+ else:+ detector_config = None++ require_threshold_bounds = detector_config is None and (+ self.instance is None or "threshold" in attrs or "detector_config" in attrs+ )+try:- validate_alert_config(query, condition, config, threshold_config, calculation_interval)+ validate_alert_config(+ query,+ condition,+ config,+ threshold_config,+ calculation_interval,+ detector_config=detector_config,+ require_threshold_bounds=require_threshold_bounds,+ )except ValueError as e:+ if str(e) == THRESHOLD_BOUNDS_REQUIRED_MESSAGE:+ raise ValidationError({"threshold": {"configuration": [THRESHOLD_BOUNDS_REQUIRED_MESSAGE]}})raise ValidationError(str(e))organization = self.context["get_organization"]()diff --git a/products/alerts/backend/api/test/test_alert.py b/products/alerts/backend/api/test/test_alert.pyindex 3d4a15df4327..9519c68d4ef8 100644--- a/products/alerts/backend/api/test/test_alert.py+++ b/products/alerts/backend/api/test/test_alert.py@@ -16,7 +16,7 @@ from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_value-from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Thresholdfrom products.cdp.backend.models.hog_functions.hog_function import HogFunction@@ -46,7 +46,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},"name": "alert name",- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"calculation_interval": "daily",}response = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request)@@ -66,7 +66,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"config": {"type": "TrendsAlertConfig", "series_index": 0},"detector_config": None,"threshold": {- "configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}},+ "configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}},"created_at": mock.ANY,"id": mock.ANY,"name": "",@@ -93,6 +93,62 @@ class TestAlert(APIBaseTest, QueryMatchingTest):alerts = self.client.get(f"/api/projects/{self.team.id}/alerts")assert len(alerts.json()["results"]) == 0+ def test_create_threshold_alert_rejects_empty_bounds(self) -> None:+ creation_request = {+ "insight": self.insight["id"],+ "subscribed_users": [self.user.id],+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},+ "config": {"type": "TrendsAlertConfig", "series_index": 0},+ "name": "alert name",+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "calculation_interval": "daily",+ }+ response = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request)+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "At least one threshold bound" in str(response.json())++ def test_patch_legacy_empty_bounds_alert_without_touching_threshold(self) -> None:+ threshold = Threshold.objects.create(+ team=self.team,+ insight_id=self.insight["id"],+ configuration={"type": InsightThresholdType.ABSOLUTE, "bounds": {}},+ )+ alert = AlertConfiguration.objects.create(+ team=self.team,+ insight_id=self.insight["id"],+ name="legacy no-op",+ condition={"type": AlertConditionType.ABSOLUTE_VALUE},+ config={"type": "TrendsAlertConfig", "series_index": 0},+ threshold=threshold,+ calculation_interval=AlertCalculationInterval.DAILY,+ enabled=True,+ )+ response = self.client.patch(+ f"/api/projects/{self.team.id}/alerts/{alert.id}",+ {"enabled": False},+ )+ assert response.status_code == status.HTTP_200_OK, response.content+ alert.refresh_from_db()+ assert alert.enabled is False++ def test_patch_empty_threshold_bounds_rejected(self) -> None:+ creation_request = {+ "insight": self.insight["id"],+ "subscribed_users": [self.user.id],+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},+ "config": {"type": "TrendsAlertConfig", "series_index": 0},+ "name": "alert name",+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},+ "calculation_interval": "daily",+ }+ alert_id = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()["id"]+ response = self.client.patch(+ f"/api/projects/{self.team.id}/alerts/{alert_id}",+ {"threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}}},+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "At least one threshold bound" in str(response.json())+def test_incorrect_creation(self) -> None:creation_request = {"subscribed_users": [@@ -130,7 +186,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "alert name",}alert = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()@@ -165,7 +221,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"subscribed_users": [self.user.id],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "checks limit test",}alert = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()@@ -199,7 +255,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"subscribed_users": [self.user.id],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "checks offset test",}alert = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()@@ -229,7 +285,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"subscribed_users": [self.user.id],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "checks date test",}alert = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()@@ -272,7 +328,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"subscribed_users": [self.user.id],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "checks window test",}alert = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()@@ -318,7 +374,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "alert name",}self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request)@@ -338,7 +394,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "alert name",}alert = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()@@ -373,7 +429,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"subscribed_users": [self.user.id],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "alert name",}alert = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()@@ -410,7 +466,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"subscribed_users": [self.user.id],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "alert name",}alert = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()@@ -457,7 +513,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "alert name","state": AlertState.FIRING,}@@ -506,7 +562,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):{"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.PERCENTAGE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.PERCENTAGE, "bounds": {"upper": 100}}},},"absolute value alerts require an absolute threshold",),@@ -520,7 +576,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):creation_request = {"insight": pie_insight["id"],"subscribed_users": [self.user.id],- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "alert name",**overrides,}@@ -544,7 +600,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"absolute_with_percentage_threshold_via_patch",{"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},- "threshold": {"configuration": {"type": InsightThresholdType.PERCENTAGE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.PERCENTAGE, "bounds": {"upper": 100}}},},"absolute value alerts require an absolute threshold",),@@ -556,7 +612,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"subscribed_users": [self.user.id],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "alert name",}alert = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()@@ -597,7 +653,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"subscribed_users": [self.user.id],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "alert name","calculation_interval": "weekly",}@@ -620,7 +676,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"subscribed_users": [self.user.id],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "quiet alert","schedule_restriction": {"blocked_windows": [{"start": "22:00", "end": "07:00"}]},}@@ -636,7 +692,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"subscribed_users": [self.user.id],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "bad quiet","schedule_restriction": {"blocked_windows": [@@ -655,7 +711,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"subscribed_users": [self.user.id],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "snap next","calculation_interval": "hourly",}@@ -679,7 +735,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"subscribed_users": [self.user.id],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "alert","schedule_restriction": {"blocked_windows": [{"start": "22:00", "end": "23:00"}]},}@@ -704,7 +760,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"subscribed_users": [self.user.id],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "quiet hours alert","schedule_restriction": {"blocked_windows": [{"start": "22:00", "end": "07:00"}]},**extra,@@ -833,7 +889,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):"subscribed_users": [self.user.id],"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"name": "patch me","calculation_interval": "daily",}@@ -890,7 +946,7 @@ class TestInvestigationAgentValidation(APIBaseTest):"condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},"name": "investigation alert",- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},"calculation_interval": "daily","detector_config": detector_config,"investigation_agent_enabled": enabled,@@ -1379,7 +1435,7 @@ class TestAlertAPIKeyAccess(APIBaseTest):"name": "New Alert","condition": {"type": AlertConditionType.ABSOLUTE_VALUE},"config": {"type": "TrendsAlertConfig", "series_index": 0},- "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {}}},+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},},HTTP_AUTHORIZATION=f"Bearer {api_key}",)diff --git a/products/alerts/backend/max_tools.py b/products/alerts/backend/max_tools.pyindex 7529e6750080..ea443b01c434 100644--- a/products/alerts/backend/max_tools.py+++ b/products/alerts/backend/max_tools.py@@ -21,6 +21,7 @@ from posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.rbac.user_access_control import AccessControlLevelfrom posthog.scopes import APIScopeObject+from posthog.tasks.alerts.utils import THRESHOLD_BOUNDS_REQUIRED_MESSAGEfrom products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Thresholdfrom products.product_analytics.backend.models.insight import Insight@@ -217,7 +218,7 @@ class UpsertAlertTool(MaxTool):user = self._userif action.upper_threshold is None and action.lower_threshold is None:- return "At least one threshold (upper or lower) must be provided.", {+ return THRESHOLD_BOUNDS_REQUIRED_MESSAGE, {"error": "validation_failed",}diff --git a/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx b/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsxindex 66d58301c057..879a58d2583a 100644--- a/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx+++ b/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx@@ -27,6 +27,7 @@ import { getSimulationRangeOptions } from './editAlertModalUtils'export interface AlertDefinitionSectionProps {alertForm: AlertFormTypealertMode: 'detector' | 'threshold'+ thresholdBoundsFormError?: stringisBreakdownValid: booleanisNonTimeSeriesDisplay: booleanalertSeries: Array<{ custom_name?: string | null; name?: string | null; event?: string | null }> | null@@ -46,6 +47,7 @@ export interface AlertDefinitionSectionProps {export function AlertDefinitionSection({alertForm,alertMode,+ thresholdBoundsFormError,isBreakdownValid,isNonTimeSeriesDisplay,alertSeries,@@ -134,116 +136,121 @@ export function AlertDefinitionSection({)}{alertMode === 'threshold' ? (- <div className="flex flex-wrap gap-x-3 gap-y-2 items-center">- <Group name={['condition']}>- <LemonField name="type">- <LemonSelect- fullWidth- className="w-40"- data-attr="alertForm-condition"- options={[- {- label: 'has value',- value: AlertConditionType.ABSOLUTE_VALUE,- },- {- label: 'increases by',- value: AlertConditionType.RELATIVE_INCREASE,- disabledReason:- isNonTimeSeriesDisplay &&- 'This condition is only supported for time series trends',- },- {- label: 'decreases by',- value: AlertConditionType.RELATIVE_DECREASE,- disabledReason:- isNonTimeSeriesDisplay &&- 'This condition is only supported for time series trends',- },- ]}- />- </LemonField>- </Group>- <div>less than</div>- <LemonField name="lower">- <LemonInput- type="number"- className="w-30"- data-attr="alertForm-lower-threshold"- value={- alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE &&- alertForm.threshold.configuration.bounds?.lower- ? alertForm.threshold.configuration.bounds?.lower * 100- : alertForm.threshold.configuration.bounds?.lower- }- onChange={(value) =>- onSetAlertFormValue('threshold', {- configuration: {- type: alertForm.threshold.configuration.type,- bounds: {- ...alertForm.threshold.configuration.bounds,- lower:- value &&- alertForm.threshold.configuration.type ===- InsightThresholdType.PERCENTAGE- ? value / 100- : value,- },- },- })- }- />- </LemonField>- <div>or more than</div>- <LemonField name="upper">- <LemonInput- type="number"- className="w-30"- data-attr="alertForm-upper-threshold"- value={- alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE &&- alertForm.threshold.configuration.bounds?.upper- ? alertForm.threshold.configuration.bounds?.upper * 100- : alertForm.threshold.configuration.bounds?.upper- }- onChange={(value) =>- onSetAlertFormValue('threshold', {- configuration: {- type: alertForm.threshold.configuration.type,- bounds: {- ...alertForm.threshold.configuration.bounds,- upper:- value &&- alertForm.threshold.configuration.type ===- InsightThresholdType.PERCENTAGE- ? value / 100- : value,- },- },- })- }- />- </LemonField>- {alertForm.condition.type !== AlertConditionType.ABSOLUTE_VALUE && (- <Group name={['threshold', 'configuration']}>+ <div className="deprecated-space-y-2">+ {thresholdBoundsFormError ? (+ <LemonBanner type="error">{thresholdBoundsFormError}</LemonBanner>+ ) : null}+ <div className="flex flex-wrap gap-x-3 gap-y-2 items-center">+ <Group name={['condition']}><LemonField name="type">- <LemonSegmentedButton+ <LemonSelect+ fullWidth+ className="w-40"+ data-attr="alertForm-condition"options={[{- value: InsightThresholdType.PERCENTAGE,- label: '%',- tooltip: 'Percent',+ label: 'has value',+ value: AlertConditionType.ABSOLUTE_VALUE,+ },+ {+ label: 'increases by',+ value: AlertConditionType.RELATIVE_INCREASE,+ disabledReason:+ isNonTimeSeriesDisplay &&+ 'This condition is only supported for time series trends',},{- value: InsightThresholdType.ABSOLUTE,- label: '#',- tooltip: 'Absolute number',+ label: 'decreases by',+ value: AlertConditionType.RELATIVE_DECREASE,+ disabledReason:+ isNonTimeSeriesDisplay &&+ 'This condition is only supported for time series trends',},]}/></LemonField></Group>- )}+ <div>less than</div>+ <LemonField name="lower">+ <LemonInput+ type="number"+ className="w-30"+ data-attr="alertForm-lower-threshold"+ value={+ alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE &&+ alertForm.threshold.configuration.bounds?.lower+ ? alertForm.threshold.configuration.bounds?.lower * 100+ : alertForm.threshold.configuration.bounds?.lower+ }+ onChange={(value) =>+ onSetAlertFormValue('threshold', {+ configuration: {+ type: alertForm.threshold.configuration.type,+ bounds: {+ ...alertForm.threshold.configuration.bounds,+ lower:+ value &&+ alertForm.threshold.configuration.type ===+ InsightThresholdType.PERCENTAGE+ ? value / 100+ : value,+ },+ },+ })+ }+ />+ </LemonField>+ <div>or more than</div>+ <LemonField name="upper">+ <LemonInput+ type="number"+ className="w-30"+ data-attr="alertForm-upper-threshold"+ value={+ alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE &&+ alertForm.threshold.configuration.bounds?.upper+ ? alertForm.threshold.configuration.bounds?.upper * 100+ : alertForm.threshold.configuration.bounds?.upper+ }+ onChange={(value) =>+ onSetAlertFormValue('threshold', {+ configuration: {+ type: alertForm.threshold.configuration.type,+ bounds: {+ ...alertForm.threshold.configuration.bounds,+ upper:+ value &&+ alertForm.threshold.configuration.type ===+ InsightThresholdType.PERCENTAGE+ ? value / 100+ : value,+ },+ },+ })+ }+ />+ </LemonField>+ {alertForm.condition.type !== AlertConditionType.ABSOLUTE_VALUE && (+ <Group name={['threshold', 'configuration']}>+ <LemonField name="type">+ <LemonSegmentedButton+ options={[+ {+ value: InsightThresholdType.PERCENTAGE,+ label: '%',+ tooltip: 'Percent',+ },+ {+ value: InsightThresholdType.ABSOLUTE,+ label: '#',+ tooltip: 'Absolute number',+ },+ ]}+ />+ </LemonField>+ </Group>+ )}+ </div></div>) : (<DetectorSelectordiff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.tsindex 9d6cea9167f2..f01907121fc0 100644--- a/products/alerts/frontend/generated/api.schemas.ts+++ b/products/alerts/frontend/generated/api.schemas.ts@@ -87,7 +87,7 @@ export interface ThresholdApi {readonly created_at: string/** Optional name for the threshold. */name?: string- /** Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). */+ /** Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). For threshold-based alerts (no detector_config), at least one of lower or upper must be set. */configuration: InsightThresholdApi}@@ -640,7 +640,7 @@ export interface ThresholdWithAlertApi {readonly created_at: string/** Optional name for the threshold. */name?: string- /** Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). */+ /** Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). For threshold-based alerts (no detector_config), at least one of lower or upper must be set. */configuration: InsightThresholdApireadonly alerts: readonly AlertApi[]}diff --git a/products/alerts/mcp/tools.yaml b/products/alerts/mcp/tools.yamlindex 064c6bb145fa..ee447c06c03d 100644--- a/products/alerts/mcp/tools.yaml+++ b/products/alerts/mcp/tools.yaml@@ -22,10 +22,11 @@ tools:description: >Create a new alert on an insight. Alerts can use either threshold-based conditions or anomaly detection. Forthreshold alerts: set condition (absolute_value, relative_increase, relative_decrease) and threshold- configuration with bounds. For anomaly detection: set detector_config with a detector type (zscore, mad,- iqr, threshold, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca) and parameters like threshold- (sensitivity 0-1, default 0.9) and window size. Ensemble detectors combine 2+ sub-detectors with AND/OR- logic. Requires an insight ID and at least one subscribed user.+ configuration with bounds — at least one of lower or upper is required (omit detector_config). For anomaly+ detection: set detector_config with a detector type (zscore, mad, iqr, threshold, copod, ecod, hbos,+ isolation_forest, knn, lof, ocsvm, pca) and parameters like threshold (sensitivity 0-1, default 0.9) and+ window size. Ensemble detectors combine 2+ sub-detectors with AND/OR logic. Requires an insight ID and at+ least one subscribed user.Note: subscribed_users only controls email recipients. For Slack or HTTPS webhook delivery, see the recipeon cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe@@ -96,8 +97,9 @@ tools:description: >Update an existing alert by ID. Can update name, threshold, condition, config, detector_config, subscribedusers, enabled state, calculation interval, and weekend skipping. Set detector_config to switch to anomaly- detection, or set it to null to switch back to threshold mode. To snooze an alert, set snoozed_until to a- relative date string (e.g. '2h', '1d'). To unsnooze, set snoozed_until to null.+ detection, or set it to null to switch back to threshold mode (threshold mode requires at least one of lower+ or upper in threshold.configuration.bounds). To snooze an alert, set snoozed_until to a relative date string+ (e.g. '2h', '1d'). To unsnooze, set snoozed_until to null.Note: Slack/webhook delivery for this alert lives as a HogFunction. See the recipe on cdp-functions-createfor the dedupe-and-create flow; to change or remove an existing destination, find it via cdp-functions-listdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex a815d6c9e3df..ad5a0ead33d7 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -247,7 +247,7 @@}},"alert-create": {- "description": "Create a new alert on an insight. Alerts can use either threshold-based conditions or anomaly detection. For threshold alerts: set condition (absolute_value, relative_increase, relative_decrease) and threshold configuration with bounds. For anomaly detection: set detector_config with a detector type (zscore, mad, iqr, threshold, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca) and parameters like threshold (sensitivity 0-1, default 0.9) and window size. Ensemble detectors combine 2+ sub-detectors with AND/OR logic. Requires an insight ID and at least one subscribed user.\nNote: subscribed_users only controls email recipients. For Slack or HTTPS webhook delivery, see the recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe (cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.",+ "description": "Create a new alert on an insight. Alerts can use either threshold-based conditions or anomaly detection. For threshold alerts: set condition (absolute_value, relative_increase, relative_decrease) and threshold configuration with bounds — at least one of lower or upper is required (omit detector_config). For anomaly detection: set detector_config with a detector type (zscore, mad, iqr, threshold, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca) and parameters like threshold (sensitivity 0-1, default 0.9) and window size. Ensemble detectors combine 2+ sub-detectors with AND/OR logic. Requires an insight ID and at least one subscribed user.\nNote: subscribed_users only controls email recipients. For Slack or HTTPS webhook delivery, see the recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe (cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.","category": "Alerts","feature": "alerts","summary": "Create alert",@@ -303,7 +303,7 @@}},"alert-update": {- "description": "Update an existing alert by ID. Can update name, threshold, condition, config, detector_config, subscribed users, enabled state, calculation interval, and weekend skipping. Set detector_config to switch to anomaly detection, or set it to null to switch back to threshold mode. To snooze an alert, set snoozed_until to a relative date string (e.g. '2h', '1d'). To unsnooze, set snoozed_until to null.\nNote: Slack/webhook delivery for this alert lives as a HogFunction. See the recipe on cdp-functions-create for the dedupe-and-create flow; to change or remove an existing destination, find it via cdp-functions-list (type=internal_destination, limit=1000) by matching filters.properties value against this alert's id, then use cdp-functions-partial-update or cdp-functions-delete.",+ "description": "Update an existing alert by ID. Can update name, threshold, condition, config, detector_config, subscribed users, enabled state, calculation interval, and weekend skipping. Set detector_config to switch to anomaly detection, or set it to null to switch back to threshold mode (threshold mode requires at least one of lower or upper in threshold.configuration.bounds). To snooze an alert, set snoozed_until to a relative date string (e.g. '2h', '1d'). To unsnooze, set snoozed_until to null.\nNote: Slack/webhook delivery for this alert lives as a HogFunction. See the recipe on cdp-functions-create for the dedupe-and-create flow; to change or remove an existing destination, find it via cdp-functions-list (type=internal_destination, limit=1000) by matching filters.properties value against this alert's id, then use cdp-functions-partial-update or cdp-functions-delete.","category": "Alerts","feature": "alerts","summary": "Update alert",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 7e6ba0f2f8bc..d12a3e2dd7b0 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -263,7 +263,7 @@}},"alert-create": {- "description": "Create a new alert on an insight. Alerts can use either threshold-based conditions or anomaly detection. For threshold alerts: set condition (absolute_value, relative_increase, relative_decrease) and threshold configuration with bounds. For anomaly detection: set detector_config with a detector type (zscore, mad, iqr, threshold, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca) and parameters like threshold (sensitivity 0-1, default 0.9) and window size. Ensemble detectors combine 2+ sub-detectors with AND/OR logic. Requires an insight ID and at least one subscribed user.\nNote: subscribed_users only controls email recipients. For Slack or HTTPS webhook delivery, see the recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe (cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.",+ "description": "Create a new alert on an insight. Alerts can use either threshold-based conditions or anomaly detection. For threshold alerts: set condition (absolute_value, relative_increase, relative_decrease) and threshold configuration with bounds — at least one of lower or upper is required (omit detector_config). For anomaly detection: set detector_config with a detector type (zscore, mad, iqr, threshold, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca) and parameters like threshold (sensitivity 0-1, default 0.9) and window size. Ensemble detectors combine 2+ sub-detectors with AND/OR logic. Requires an insight ID and at least one subscribed user.\nNote: subscribed_users only controls email recipients. For Slack or HTTPS webhook delivery, see the recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe (cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.","category": "Alerts","feature": "alerts","summary": "Create alert",@@ -319,7 +319,7 @@}},"alert-update": {- "description": "Update an existing alert by ID. Can update name, threshold, condition, config, detector_config, subscribed users, enabled state, calculation interval, and weekend skipping. Set detector_config to switch to anomaly detection, or set it to null to switch back to threshold mode. To snooze an alert, set snoozed_until to a relative date string (e.g. '2h', '1d'). To unsnooze, set snoozed_until to null.\nNote: Slack/webhook delivery for this alert lives as a HogFunction. See the recipe on cdp-functions-create for the dedupe-and-create flow; to change or remove an existing destination, find it via cdp-functions-list (type=internal_destination, limit=1000) by matching filters.properties value against this alert's id, then use cdp-functions-partial-update or cdp-functions-delete.",+ "description": "Update an existing alert by ID. Can update name, threshold, condition, config, detector_config, subscribed users, enabled state, calculation interval, and weekend skipping. Set detector_config to switch to anomaly detection, or set it to null to switch back to threshold mode (threshold mode requires at least one of lower or upper in threshold.configuration.bounds). To snooze an alert, set snoozed_until to a relative date string (e.g. '2h', '1d'). To unsnooze, set snoozed_until to null.\nNote: Slack/webhook delivery for this alert lives as a HogFunction. See the recipe on cdp-functions-create for the dedupe-and-create flow; to change or remove an existing destination, find it via cdp-functions-list (type=internal_destination, limit=1000) by matching filters.properties value against this alert's id, then use cdp-functions-partial-update or cdp-functions-delete.","category": "Alerts","feature": "alerts","summary": "Update alert",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d85056ad122b..16f14d5fa1a8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -7205,7 +7205,7 @@ export namespace Schemas {readonly created_at: string;/** Optional name for the threshold. */name?: string;- /** Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). */+ /** Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). For threshold-based alerts (no detector_config), at least one of lower or upper must be set. */configuration: InsightThreshold;}@@ -26582,7 +26582,7 @@ export namespace Schemas {readonly created_at: string;/** Optional name for the threshold. */name?: string;- /** Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). */+ /** Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). For threshold-based alerts (no detector_config), at least one of lower or upper must be set. */configuration: InsightThreshold;readonly alerts: readonly Alert[];}diff --git a/services/mcp/src/generated/alerts/api.ts b/services/mcp/src/generated/alerts/api.tsindex 7c89ed63530e..ece3f25f346e 100644--- a/services/mcp/src/generated/alerts/api.ts+++ b/services/mcp/src/generated/alerts/api.ts@@ -104,7 +104,7 @@ export const AlertsCreateBody = /* @__PURE__ */ zod.object({),}).describe(- 'Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage).'+ 'Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). For threshold-based alerts (no detector_config), at least one of lower or upper must be set.'),}).describe('Threshold configuration with bounds and type for evaluating the alert.'),@@ -1354,7 +1354,7 @@ export const AlertsPartialUpdateBody = /* @__PURE__ */ zod.object({),}).describe(- 'Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage).'+ 'Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). For threshold-based alerts (no detector_config), at least one of lower or upper must be set.'),}).optional()diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.jsonindex f7344076d6b1..cdf59e5ce2c0 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json@@ -2212,7 +2212,7 @@"description": "Threshold configuration with bounds and type for evaluating the alert.","properties": {"configuration": {- "description": "Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage).",+ "description": "Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). For threshold-based alerts (no detector_config), at least one of lower or upper must be set.","properties": {"bounds": {"anyOf": [diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.jsonindex 3dd4420bacc7..05b3130a77ae 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json@@ -2216,7 +2216,7 @@"description": "Threshold configuration with bounds and type for evaluating the alert.","properties": {"configuration": {- "description": "Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage).",+ "description": "Threshold bounds and type. Includes bounds (lower/upper floats) and type (absolute or percentage). For threshold-based alerts (no detector_config), at least one of lower or upper must be set.","properties": {"bounds": {"anyOf": [