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 anomaly alert insight entrypoint (#66429)

Radu Raicea878295c2221c
diff --git a/frontend/src/lib/components/Cards/CardMeta.tsx b/frontend/src/lib/components/Cards/CardMeta.tsx
index 7e5efbd29022..fcdc406b9eb8 100644
--- a/frontend/src/lib/components/Cards/CardMeta.tsx
+++ b/frontend/src/lib/components/Cards/CardMeta.tsx
@@ -104,6 +104,12 @@ export function CardMeta({
inStorybook() ||
inStorybookTestRunner() ||
(!!primaryWidth && primaryWidth > 480 && controlsAvailableSpace >= neededWidth)
+ const extraControlsWithLabel = extraControls
+ ? React.cloneElement(extraControls, {
+ ...extraControls.props,
+ showLabel: showControlsLabels,
+ })
+ : null
return (
<div
@@ -160,11 +166,7 @@ export function CardMeta({
</h5>
<div className="CardMeta__controls">
{refreshControl}
- {extraControls &&
- React.cloneElement(extraControls, {
- ...extraControls.props,
- showLabel: showControlsLabels,
- })}
+ {extraControlsWithLabel}
{showDetailsControls && setAreDetailsShown && (
<Tooltip title={detailsTooltip}>
<LemonButton
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index 66d58f58b4fc..dad35144492a 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -3,7 +3,7 @@ import './InsightCard.scss'
import { useMergeRefs } from '@floating-ui/react'
import clsx from 'clsx'
import { BindLogic, useActions, useValues } from 'kea'
-import React, { useLayoutEffect, useMemo, useRef, useState } from 'react'
+import React, { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { LayoutItem } from 'react-grid-layout'
import { useInView } from 'react-intersection-observer'
@@ -11,6 +11,7 @@ import { ApiError } from 'lib/api'
import { Resizeable } from 'lib/components/Cards/CardMeta'
import { FEATURE_FLAGS } from 'lib/constants'
import { usePageVisibility } from 'lib/hooks/usePageVisibility'
+import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { accessLevelSatisfied, getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
@@ -39,15 +40,22 @@ import {
DashboardType,
InsightColor,
InsightLogicProps,
+ InsightShortId,
QueryBasedInsightModel,
} from '~/types'
+import type { AlertType } from 'products/alerts/frontend/types'
+
import { DashboardResizeHandles } from '../handles'
import { EditModeEdge, EditModeEdgeOverlay } from './EditModeEdgeOverlay'
import { InsightMeta } from './InsightMeta'
const IS_STORYBOOK = inStorybook() || inStorybookTestRunner()
+const LazyEditAlertModal = React.lazy(() =>
+ import('products/alerts/frontend/views/EditAlertModal').then(({ EditAlertModal }) => ({ default: EditAlertModal }))
+)
+
const RESIZE_REDRAW_THROTTLE_MS = 33 // ~30x/sec
/**
@@ -115,6 +123,11 @@ function ResizeThrottledViz({ throttled, children }: { throttled: boolean; child
)
}
+type AlertModalState = {
+ alertId?: AlertType['id']
+ defaultToAnomalyDetection?: boolean
+}
+
export interface InsightCardProps extends Resizeable {
/** Insight to display. */
insight: QueryBasedInsightModel
@@ -172,6 +185,8 @@ export interface InsightCardProps extends Resizeable {
tile?: DashboardTile<QueryBasedInsightModel>
/** survey opportunity for this insight */
surveyOpportunity?: boolean
+ /** Show a direct action for creating an anomaly detection alert for this saved insight. */
+ showCreateAnomalyAlertButton?: boolean
/** Whether hovering near the card edge should hint that edit mode is available. */
canEnterEditModeFromEdge?: boolean
/** Called when the user clicks an edge hint to enter edit mode. */
@@ -217,6 +232,7 @@ function InsightCardInternal(
breakdownColorOverride: _breakdownColorOverride,
dataColorThemeId: _dataColorThemeId,
surveyOpportunity,
+ showCreateAnomalyAlertButton,
canEnterEditModeFromEdge,
onEnterEditModeFromEdge,
onDragHandleMouseDown,
@@ -279,6 +295,11 @@ function InsightCardInternal(
}
const [areDetailsShown, setAreDetailsShown] = useState(false)
+ const [alertModal, setAlertModal] = useState<AlertModalState | null>(null)
+ const openCreateAlertModal = useCallback(() => setAlertModal({}), [])
+ const openEditAlertModal = useCallback((alertId: AlertType['id']) => setAlertModal({ alertId }), [])
+ const openCreateAnomalyAlertModal = useCallback(() => setAlertModal({ defaultToAnomalyDetection: true }), [])
+ const closeAlertModal = useCallback(() => setAlertModal(null), [])
const hasResults = !!insight?.result || !!(insight as any)?.results
// Empty states that completely replace the Query component.
@@ -407,6 +428,10 @@ function InsightCardInternal(
variablesOverride={variablesOverride}
placement={placement}
surveyOpportunity={surveyOpportunity}
+ showCreateAnomalyAlertButton={showCreateAnomalyAlertButton}
+ onCreateAlert={openCreateAlertModal}
+ onEditAlert={openEditAlertModal}
+ onCreateAnomalyAlert={openCreateAnomalyAlertModal}
onDragHandleMouseDown={onDragHandleMouseDown}
/>
{vizContent}
@@ -416,6 +441,21 @@ function InsightCardInternal(
{canEnterEditModeFromEdge && !showResizeHandles && onEnterEditModeFromEdge && (
<EditModeEdgeOverlay onEnterEditMode={onEnterEditModeFromEdge} />
)}
+ {alertModal && insight.id && insight.short_id ? (
+ <React.Suspense fallback={<SpinnerOverlay />}>
+ <LazyEditAlertModal
+ isOpen
+ onClose={closeAlertModal}
+ alertId={alertModal.alertId}
+ insightId={insight.id}
+ insightShortId={insight.short_id as InsightShortId}
+ onEditSuccess={closeAlertModal}
+ insightLogicProps={insightLogicProps}
+ defaultToAnomalyDetection={alertModal.defaultToAnomalyDetection}
+ insightName={insight.name || insight.derived_name}
+ />
+ </React.Suspense>
+ ) : null}
{children /* RGL react-resizable-handle nodes injected by react-grid-layout */}
</div>
)
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index 76765ed28fe7..efde3aba34de 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -2,7 +2,7 @@ import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import React, { useCallback, useEffect, useRef, useState } from 'react'
-import { IconInfo, IconThumbsDown, IconThumbsUp } from '@posthog/icons'
+import { IconInfo, IconPulse, IconThumbsDown, IconThumbsUp } from '@posthog/icons'
import { lemonToast } from '@posthog/lemon-ui'
import { CardMeta } from 'lib/components/Cards/CardMeta'
@@ -34,7 +34,7 @@ import { useSummarizeInsight } from 'scenes/insights/summarizeInsight'
import { getOverrideWarningPropsForButton } from 'scenes/insights/utils'
import { SurveyOpportunityButton } from 'scenes/surveys/components/SurveyOpportunityButton'
import { SURVEY_CREATED_SOURCE } from 'scenes/surveys/constants'
-import { isSurveyableFunnelInsight } from 'scenes/surveys/utils/opportunityDetection'
+import { isSurveyableFunnelInsight, SurveyableFunnelInsight } from 'scenes/surveys/utils/opportunityDetection'
import { urls } from 'scenes/urls'
import { dashboardsModel } from '~/models/dashboardsModel'
@@ -54,7 +54,12 @@ import {
QueryBasedInsightModel,
} from '~/types'
-import { areAlertsSupportedForInsight, insightAlertsLogic } from 'products/alerts/frontend/logic/insightAlertsLogic'
+import {
+ areAlertsSupportedForInsight,
+ areAnomalyAlertsSupportedForInsight,
+ insightAlertsLogic,
+} from 'products/alerts/frontend/logic/insightAlertsLogic'
+import type { AlertType } from 'products/alerts/frontend/types'
import { ManageAlertsModal } from 'products/alerts/frontend/views/ManageAlertsModal'
import { DashboardInsightDisplayOptions } from './DashboardInsightDisplayOptions'
@@ -86,6 +91,7 @@ interface InsightMetaProps extends Pick<
| 'variablesOverride'
| 'placement'
| 'surveyOpportunity'
+ | 'showCreateAnomalyAlertButton'
> {
/** Called when the user mousedowns on the card meta (drag handle) in view mode to enter edit mode. */
onDragHandleMouseDown?: React.MouseEventHandler<HTMLDivElement>
@@ -94,6 +100,9 @@ interface InsightMetaProps extends Pick<
areDetailsShown?: boolean
setAreDetailsShown?: React.Dispatch<React.SetStateAction<boolean>>
persistDisplayOptions?: (node: Node) => void
+ onCreateAlert?: () => void
+ onEditAlert?: (alertId: AlertType['id']) => void
+ onCreateAnomalyAlert?: () => void
}
export function InsightMeta({
@@ -122,8 +131,12 @@ export function InsightMeta({
moreButtons,
placement,
surveyOpportunity,
+ showCreateAnomalyAlertButton,
onDragHandleMouseDown,
persistDisplayOptions,
+ onCreateAlert,
+ onEditAlert,
+ onCreateAnomalyAlert,
}: InsightMetaProps): JSX.Element {
const { short_id, name, next_allowed_client_refresh: nextAllowedClientRefresh } = insight
const tileFiltersOverride = tile?.filters_overrides
@@ -200,6 +213,9 @@ export function InsightMeta({
hogqlAlertsEnabled: !!featureFlags[FEATURE_FLAGS.HOGQL_INSIGHT_ALERTS],
funnelAlertsEnabled: !!featureFlags[FEATURE_FLAGS.FUNNEL_INSIGHT_ALERTS],
})
+ const canCreateAnomalyAlertForInsight = areAnomalyAlertsSupportedForInsight(query, {
+ hogqlAlertsEnabled: !!featureFlags[FEATURE_FLAGS.HOGQL_INSIGHT_ALERTS],
+ })
const showDisplayOptionsMenu = isUsedAsDashboardTile && canEditInsight && !!persistDisplayOptions
// Hoist the hook out of the More overlay so kea logics it mounts don't do so lazily inside a
@@ -241,16 +257,14 @@ export function InsightMeta({
</div>
) : null
- const surveyOpportunityButton =
- surveyOpportunity && isSurveyableFunnelInsight(insight) ? (
- <SurveyOpportunityButton
- insight={insight}
- disableAutoPromptSubmit={true}
- source={SURVEY_CREATED_SOURCE.INSIGHT_CROSS_SELL}
- fromProduct={ProductKey.PRODUCT_ANALYTICS}
- tooltip="Create a survey to understand why users are dropping off"
- />
- ) : null
+ const surveyOpportunityInsight = surveyOpportunity && isSurveyableFunnelInsight(insight) ? insight : null
+ const canShowCreateAnomalyAlert =
+ showCreateAnomalyAlertButton &&
+ canViewInsight &&
+ canCreateAnomalyAlertForInsight &&
+ !!short_id &&
+ !!insight.id &&
+ !!onCreateAnomalyAlert
// If user can't view the insight, show minimal interface
if (!canViewInsight) {
@@ -603,7 +617,16 @@ export function InsightMeta({
? 'Rename, duplicate, export, refresh and more…'
: 'Duplicate, export, refresh and more…'
}
- extraControls={surveyOpportunityButton ?? feedbackButtons}
+ extraControls={
+ placement !== DashboardPlacement.Public &&
+ (surveyOpportunityInsight || canShowCreateAnomalyAlert || feedbackButtons) ? (
+ <InsightMetaExtraControls
+ surveyOpportunityInsight={surveyOpportunityInsight}
+ onCreateAnomalyAlert={canShowCreateAnomalyAlert ? onCreateAnomalyAlert : undefined}
+ feedbackButtons={feedbackButtons}
+ />
+ ) : null
+ }
refreshControl={refreshControl}
/>
{showDashboardAlertsMenuItem && insight.id ? (
@@ -614,6 +637,8 @@ export function InsightMeta({
insightId={insight.id}
insightShortId={short_id as InsightShortId}
canCreateAlertForInsight={canCreateAlertForInsight}
+ onCreateAlert={onCreateAlert}
+ onEditAlert={onEditAlert}
insightQuery={query}
deferInitialAlertsLoad
/>
@@ -622,6 +647,54 @@ export function InsightMeta({
)
}
+interface InsightMetaExtraControlsProps {
+ showLabel?: boolean
+ surveyOpportunityInsight?: SurveyableFunnelInsight | null
+ onCreateAnomalyAlert?: () => void
+ feedbackButtons?: JSX.Element | null
+}
+
+function CreateAnomalyAlertButton({ onClick, showLabel }: { onClick: () => void; showLabel?: boolean }): JSX.Element {
+ return (
+ <LemonButton
+ size="xsmall"
+ type="primary"
+ icon={<IconPulse />}
+ onClick={onClick}
+ tooltip={!showLabel ? 'Create anomaly alert' : undefined}
+ data-attr="create-anomaly-alert-button"
+ >
+ {showLabel && 'Create anomaly alert'}
+ </LemonButton>
+ )
+}
+
+function InsightMetaExtraControls({
+ showLabel,
+ surveyOpportunityInsight,
+ onCreateAnomalyAlert,
+ feedbackButtons,
+}: InsightMetaExtraControlsProps): JSX.Element {
+ return (
+ <div className="flex items-center gap-1">
+ {surveyOpportunityInsight ? (
+ <SurveyOpportunityButton
+ insight={surveyOpportunityInsight}
+ disableAutoPromptSubmit={true}
+ source={SURVEY_CREATED_SOURCE.INSIGHT_CROSS_SELL}
+ fromProduct={ProductKey.PRODUCT_ANALYTICS}
+ showLabel={showLabel}
+ tooltip="Create a survey to understand why users are dropping off"
+ />
+ ) : null}
+ {onCreateAnomalyAlert ? (
+ <CreateAnomalyAlertButton onClick={onCreateAnomalyAlert} showLabel={showLabel} />
+ ) : null}
+ {feedbackButtons}
+ </div>
+ )
+}
+
export function InsightMetaContent({
title,
fallbackTitle,
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index cd0574661242..8ed524472811 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -248,7 +248,6 @@ export const FEATURE_FLAGS = {
AI_GATEWAY: 'ai-gateway', // owner: #team-ai-gateway, gates the AI gateway UI and llm_gateway:read on project secret API keys
/** Alert edit modal: check history chart + chart/table toggle (table remains when off). */
ALERTS_15_MINUTE_INTERVAL: 'alerts-15-minute-interval', // owner: #team-analytics-platform, gates 15-minute insight alert interval
- 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
diff --git a/frontend/src/scenes/dashboard/Dashboard.tsx b/frontend/src/scenes/dashboard/Dashboard.tsx
index 23b6099fe1bf..74f6a6617119 100644
--- a/frontend/src/scenes/dashboard/Dashboard.tsx
+++ b/frontend/src/scenes/dashboard/Dashboard.tsx
@@ -35,6 +35,7 @@ interface DashboardProps {
themes?: DataColorThemeModel[]
/** When set, the "Edit dashboard" menu item links to the dashboard editor with a back button pointing here. */
backTo?: { url: string; name: string }
+ showCreateAnomalyAlertButton?: boolean
}
const parseDashboardId = (id: string | undefined): number => (typeof id === 'string' ? parseInt(id, 10) : NaN)
@@ -52,17 +53,30 @@ export const scene: SceneExport<DashboardLogicProps> = {
productKey: ProductKey.PRODUCT_ANALYTICS,
}
-export function Dashboard({ id, dashboard, placement, themes, backTo }: DashboardProps): JSX.Element {
+export function Dashboard({
+ id,
+ dashboard,
+ placement,
+ themes,
+ backTo,
+ showCreateAnomalyAlertButton,
+}: DashboardProps): JSX.Element {
useMountedLogic(dataThemeLogic({ themes }))
return (
<BindLogic logic={dashboardLogic} props={{ id: parseDashboardId(id), placement, dashboard }}>
- <DashboardScene backTo={backTo} />
+ <DashboardScene backTo={backTo} showCreateAnomalyAlertButton={showCreateAnomalyAlertButton} />
</BindLogic>
)
}
-function DashboardScene({ backTo }: { backTo?: { url: string; name: string } }): JSX.Element {
+function DashboardScene({
+ backTo,
+ showCreateAnomalyAlertButton,
+}: {
+ backTo?: { url: string; name: string }
+ showCreateAnomalyAlertButton?: boolean
+}): JSX.Element {
const {
placement,
dashboard,
@@ -130,7 +144,7 @@ function DashboardScene({ backTo }: { backTo?: { url: string; name: string } }):
)}
</SceneStickyBar>
- <DashboardItems />
+ <DashboardItems showCreateAnomalyAlertButton={showCreateAnomalyAlertButton} />
</div>
)}
</SceneContent>
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index 975296d4a678..b42274dca7fb 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -40,6 +40,10 @@ const BASE_ROW_HEIGHT = 80
const BASE_MARGIN: [number, number] = [16, 16]
const CONTAINER_PADDING: [number, number] = [0, 0]
+interface DashboardItemsProps {
+ showCreateAnomalyAlertButton?: boolean
+}
+
/**
* Shallow prop compare, except: `style` by value (react-grid-layout rebuilds it every drag/resize mousemove even
* for tiles that haven't moved) and `children` ignored (the RGL-injected resize handles, recreated each render
@@ -63,7 +67,7 @@ const MemoizedDashboardButtonTileItem = memo(
) as typeof DashboardButtonTileItem
const MemoizedDashboardWidgetItem = memo(DashboardWidgetItem, gridTilePropsEqual) as typeof DashboardWidgetItem
-export function DashboardItems(): JSX.Element {
+export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsProps = {}): JSX.Element {
const {
dashboard,
tiles,
@@ -558,6 +562,7 @@ export function DashboardItems(): JSX.Element {
breakdownColorOverride={temporaryBreakdownColors}
dataColorThemeId={dataColorThemeId}
surveyOpportunity={tile.id === bestSurveyOpportunityFunnel?.id}
+ showCreateAnomalyAlertButton={showCreateAnomalyAlertButton}
{...commonTileProps}
/>
)
diff --git a/posthog/tasks/alerts/test/test_validate_alert_config.py b/posthog/tasks/alerts/test/test_validate_alert_config.py
index ba6b8040eb3f..5c797264f57b 100644
--- a/posthog/tasks/alerts/test/test_validate_alert_config.py
+++ b/posthog/tasks/alerts/test/test_validate_alert_config.py
@@ -443,6 +443,17 @@ class TestValidateAlertConfig:
detector_config={"type": "zscore", "threshold": 0.95, "window": 30},
)
+ def test_detector_alert_rejects_non_time_series_trend(self) -> None:
+ with pytest.raises(ValueError, match="Anomaly detection isn't supported for non time series trends"):
+ validate_alert_config(
+ _base_query(display="ActionsPie"),
+ _base_condition(),
+ _base_config(),
+ _base_threshold(),
+ "daily",
+ detector_config={"type": "zscore", "threshold": 0.95, "window": 30},
+ )
+
def test_any_row_hogql_alert_rejects_relative_conditions(self) -> None:
with pytest.raises(ValueError, match="Any-row SQL alerts only support absolute value conditions"):
validate_alert_config(
diff --git a/products/ai_observability/frontend/AIObservabilityScene.tsx b/products/ai_observability/frontend/AIObservabilityScene.tsx
index d2b665e2aa86..805e73aabd21 100644
--- a/products/ai_observability/frontend/AIObservabilityScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityScene.tsx
@@ -166,7 +166,11 @@ function AIObservabilityDashboard(): JSX.Element {
<Spinner captureTime />
</div>
) : (
- <Dashboard id={selectedDashboardId.toString()} placement={DashboardPlacement.Builtin} />
+ <Dashboard
+ id={selectedDashboardId.toString()}
+ placement={DashboardPlacement.Builtin}
+ showCreateAnomalyAlertButton
+ />
)}
</div>
</AIObservabilitySetupPrompt>
diff --git a/products/alerts/backend/api/test/test_alert.py b/products/alerts/backend/api/test/test_alert.py
index b65c4b475fa9..0152cc00efa3 100644
--- a/products/alerts/backend/api/test/test_alert.py
+++ b/products/alerts/backend/api/test/test_alert.py
@@ -858,6 +858,15 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
},
"not compatible with non time series",
),
+ (
+ "detector_on_non_time_series",
+ {
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "detector_config": {"type": "zscore", "threshold": 0.95, "window": 30},
+ },
+ "anomaly detection isn't supported for non time series trends",
+ ),
(
"absolute_with_percentage_threshold",
{
@@ -883,7 +892,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
}
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 expected_error_fragment in str(response.content).lower()
+ assert expected_error_fragment in response.json()["detail"].lower()
@parameterized.expand(
[
@@ -923,6 +932,31 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
assert expected_error_fragment in str(response.content).lower()
+ def test_patch_alert_rejects_detector_for_non_time_series(self) -> None:
+ pie_insight_data = deepcopy(self.default_insight_data)
+ pie_insight_data["query"]["trendsFilter"]["display"] = "ActionsPie"
+ pie_insight = self.client.post(f"/api/projects/{self.team.id}/insights", data=pie_insight_data).json()
+
+ alert = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ {
+ "insight": pie_insight["id"],
+ "subscribed_users": [self.user.id],
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},
+ "name": "alert name",
+ },
+ ).json()
+ assert "id" in alert, alert
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/alerts/{alert['id']}",
+ {"detector_config": {"type": "zscore", "threshold": 0.95, "window": 30}},
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "anomaly detection isn't supported for non time series trends" in response.json()["detail"].lower()
+
@parameterized.expand(
[
(
diff --git a/products/alerts/backend/evaluation/validation.py b/products/alerts/backend/evaluation/validation.py
index 109eafb5ee3a..141659942b77 100644
--- a/products/alerts/backend/evaluation/validation.py
+++ b/products/alerts/backend/evaluation/validation.py
@@ -113,6 +113,9 @@ def _validate_trends_alert_config(ctx: _AlertConfigValidationContext) -> None:
except Exception as e:
raise ValueError(f"Alert's insight has an invalid TrendsQuery: {e}")
+ if ctx.detector_config is not None and is_non_time_series_trend(trends_query):
+ raise ValueError("Anomaly detection isn't supported for non time series trends")
+
if ctx.parsed_condition.type in (
AlertConditionType.RELATIVE_INCREASE,
AlertConditionType.RELATIVE_DECREASE,
diff --git a/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx b/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
index 1e116f4a99ed..cd6d2ae828d7 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
+++ b/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
@@ -17,6 +17,7 @@ import { AlertConditionType, InsightThresholdType } from '~/queries/schema/schem
import { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'
import { getDefaultSimulationRange } from 'products/alerts/frontend/logic/alertIntervalHelpers'
+import { getDefaultAnomalyDetectorConfig } from 'products/alerts/frontend/logic/detectorConfigDefaults'
import { FunnelAlertPreview } from 'products/alerts/frontend/logic/funnelAlertPreview'
import { HogQLAlertPreview } from 'products/alerts/frontend/logic/hogqlAlertPreview'
import { fractionToPercentInput, rescaleFunnelBound } from 'products/alerts/frontend/logic/thresholdPercent'
@@ -27,7 +28,7 @@ import {
isHogQLAlertConfig,
isTrendsAlertConfig,
} from 'products/alerts/frontend/types'
-import { DetectorSelector, getDefaultWindow } from 'products/alerts/frontend/views/DetectorSelector'
+import { DetectorSelector } from 'products/alerts/frontend/views/DetectorSelector'
import { SimulationSummary } from 'products/alerts/frontend/views/SimulationSummary'
import { FunnelsDefinitionFields, HogQLDefinitionFields, TrendsDefinitionFields } from './AlertDefinitionFields'
@@ -71,7 +72,7 @@ export interface AlertDefinitionSectionProps {
trends: TrendsDefinitionProps
funnel: FunnelDefinitionProps
hogql: HogQLDefinitionProps
- anomalyDetectionEnabled: boolean
+ supportsAnomalyDetection: boolean
investigationAgentEnabled: boolean
simulationResult: AlertSimulationResult | null
simulationResultLoading: boolean
@@ -96,7 +97,7 @@ export function AlertDefinitionSection({
trends,
funnel,
hogql,
- anomalyDetectionEnabled,
+ supportsAnomalyDetection,
investigationAgentEnabled,
simulationResult,
simulationResultLoading,
@@ -151,18 +152,16 @@ export function AlertDefinitionSection({
/>
) : null}
- {anomalyDetectionEnabled && (
+ {supportsAnomalyDetection && (
<LemonSegmentedButton
fullWidth
value={alertMode}
onChange={(value) => {
if (value === 'detector') {
- onSetAlertFormValue('detector_config', {
- type: 'zscore',
- threshold: 0.95,
- window: getDefaultWindow(alertForm.calculation_interval),
- preprocessing: { diffs_n: 1 },
- })
+ onSetAlertFormValue(
+ 'detector_config',
+ getDefaultAnomalyDetectorConfig(alertForm.calculation_interval)
+ )
} else {
onSetAlertFormValue('detector_config', null)
}
@@ -177,7 +176,7 @@ export function AlertDefinitionSection({
value: 'detector',
label: 'Anomaly detection',
tooltip:
- 'Automatically detect unusual changes using AI (ohhh fancy, jk its just good old stats and ml stuff). No manual thresholds needed.',
+ 'Automatically detect unusual changes using statistical models. No fixed value threshold is required.',
},
]}
/>
diff --git a/products/alerts/frontend/logic/alertFormLogic.test.ts b/products/alerts/frontend/logic/alertFormLogic.test.ts
index 016576313039..b6ad53c766aa 100644
--- a/products/alerts/frontend/logic/alertFormLogic.test.ts
+++ b/products/alerts/frontend/logic/alertFormLogic.test.ts
@@ -1,3 +1,4 @@
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
@@ -154,6 +155,42 @@ describe('alertFormLogic', () => {
return logic
}
+ it.each([
+ ['ordinary', { insightInterval: 'day' as const }, '', AlertCalculationInterval.DAILY, null],
+ [
+ 'anomaly',
+ {
+ insightInterval: 'hour' as const,
+ defaultToAnomalyDetection: true,
+ insightName: 'Weekly signups',
+ },
+ 'Anomaly in Weekly signups',
+ AlertCalculationInterval.HOURLY,
+ {
+ type: 'zscore',
+ threshold: 0.95,
+ window: 168,
+ preprocessing: { diffs_n: 1 },
+ },
+ ],
+ ])(
+ 'prefills %s new alerts with the expected defaults',
+ (_name, alertProps, expectedName, expectedInterval, expectedDetectorConfig) => {
+ const logic = alertFormLogic({
+ alert: null,
+ insightId: 42,
+ onEditSuccess: jest.fn(),
+ insightVizDataLogicProps: insightLogicProps,
+ ...alertProps,
+ })
+ logic.mount()
+
+ expect(logic.values.alertForm.name).toBe(expectedName)
+ expect(logic.values.alertForm.calculation_interval).toBe(expectedInterval)
+ expect(logic.values.alertForm.detector_config).toEqual(expectedDetectorConfig)
+ }
+ )
+
it('shows success toast and no error toast when create succeeds', async () => {
const logic = mountForm()
@@ -163,7 +200,17 @@ describe('alertFormLogic', () => {
expect(createSpy).toHaveBeenCalledTimes(1)
expect(errorToastSpy).not.toHaveBeenCalled()
- expect(successToastSpy).toHaveBeenCalledWith('Alert created.')
+ expect(successToastSpy).toHaveBeenCalledWith('Alert created.', {
+ button: {
+ label: 'View all alerts',
+ action: expect.any(Function),
+ },
+ })
+
+ const toastOptions = successToastSpy.mock.calls[0][1] as { button: { action: () => void } }
+ toastOptions.button.action()
+ expect(router.values.location.pathname).toMatch(/\/insights$/)
+ expect(router.values.searchParams.tab).toBe('alerts')
})
// Funnels hide the #/% unit toggle and always compare a relative change as a percentage of the
@@ -204,7 +251,7 @@ describe('alertFormLogic', () => {
}).toFinishAllListeners()
expect(createSpy).toHaveBeenCalledTimes(1)
- expect(successToastSpy).toHaveBeenCalledWith('Alert created.')
+ expect(successToastSpy).toHaveBeenCalledWith('Alert created.', expect.any(Object))
expect(errorToastSpy).not.toHaveBeenCalled()
expect(captureExceptionSpy).toHaveBeenCalledWith(postSaveError)
})
diff --git a/products/alerts/frontend/logic/alertFormLogic.ts b/products/alerts/frontend/logic/alertFormLogic.ts
index bfe89944962f..40198ad55a54 100644
--- a/products/alerts/frontend/logic/alertFormLogic.ts
+++ b/products/alerts/frontend/logic/alertFormLogic.ts
@@ -1,6 +1,7 @@
import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
@@ -9,6 +10,7 @@ import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
+import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import {
@@ -42,6 +44,7 @@ import type { alertFormLogicType } from './alertFormLogicType'
import { getAlertFormValidationErrors } from './alertFormSchema'
import { alertLogic } from './alertLogic'
import { alertNotificationLogic } from './alertNotificationLogic'
+import { getDefaultAnomalyDetectorConfig } from './detectorConfigDefaults'
import { deriveFunnelAlertPreview, FunnelAlertPreview } from './funnelAlertPreview'
import { columnIsNumeric, deriveHogQLAlertPreview, HogQLAlertPreview } from './hogqlAlertPreview'
import { insightAlertsLogic } from './insightAlertsLogic'
@@ -127,6 +130,10 @@ export interface AlertFormLogicProps {
insightInterval?: IntervalType
/** Selects the default config type for new alerts based on the insight's query kind. */
insightAlertKind?: InsightAlertKind
+ /** Start new alerts in anomaly detection mode when opened from an anomaly-specific entrypoint. */
+ defaultToAnomalyDetection?: boolean
+ /** Used to prefill a human-readable name for anomaly alerts. */
+ insightName?: string | null
/** For funnel insights: whether it's a trends (historical) funnel, which alerts on the overall
* conversion rate over time rather than a single step snapshot. Drives the preview shape. */
insightIsTrendsFunnel?: boolean
@@ -212,6 +219,13 @@ function alertToFormType(alert: AlertType, insightId: QueryBasedInsightModel['id
}
}
+function defaultAlertName(props: AlertFormLogicProps, goalLines?: GoalLine[] | null): string {
+ if (props.defaultToAnomalyDetection) {
+ return props.insightName ? `Anomaly in ${props.insightName}` : 'Anomaly alert'
+ }
+ return goalLines && goalLines.length > 0 ? `Crossed ${goalLines[0].label}` : ''
+}
+
const getThresholdBounds = (goalLines?: GoalLine[] | null): InsightsThresholdBounds => {
if (goalLines == null || goalLines.length == 0) {
return {}
@@ -225,7 +239,10 @@ const getThresholdBounds = (goalLines?: GoalLine[] | null): InsightsThresholdBou
export const alertFormLogic = kea<alertFormLogicType>([
path(['lib', 'components', 'Alerts', 'alertFormLogic']),
props({} as AlertFormLogicProps),
- key(({ alert }) => alert?.id ?? 'new'),
+ key(
+ ({ alert, defaultToAnomalyDetection, insightId }) =>
+ alert?.id ?? `${defaultToAnomalyDetection ? 'new-anomaly' : 'new'}-${insightId}`
+ ),
connect((props: AlertFormLogicProps) => ({
values: [
@@ -293,34 +310,38 @@ export const alertFormLogic = kea<alertFormLogicType>([
alertForm: {
defaults: props.alert
? alertToFormType(props.alert, props.insightId)
- : ({
- id: undefined,
- name:
- values.goalLines && values.goalLines.length > 0 ? `Crossed ${values.goalLines[0].label}` : '',
- created_by: null,
- created_at: '',
- enabled: true,
- config: defaultConfigForInsight(props.insightAlertKind),
- threshold: {
- configuration: {
- type: InsightThresholdType.ABSOLUTE,
- bounds: getThresholdBounds(values.goalLines),
+ : (() => {
+ const calculationInterval = insightIntervalToAlertInterval(props.insightInterval)
+ return {
+ id: undefined,
+ name: defaultAlertName(props, values.goalLines),
+ created_by: null,
+ created_at: '',
+ enabled: true,
+ config: defaultConfigForInsight(props.insightAlertKind),
+ threshold: {
+ configuration: {
+ type: InsightThresholdType.ABSOLUTE,
+ bounds: getThresholdBounds(values.goalLines),
+ },
},
- },
- condition: {
- type: AlertConditionType.ABSOLUTE_VALUE,
- },
- subscribed_users: [],
- checks: [],
- calculation_interval: insightIntervalToAlertInterval(props.insightInterval),
- skip_weekend: false,
- schedule_restriction: null,
- detector_config: null,
- investigation_agent_enabled: false,
- investigation_gates_notifications: false,
- investigation_inconclusive_action: 'notify',
- insight: props.insightId,
- } as AlertFormType),
+ condition: {
+ type: AlertConditionType.ABSOLUTE_VALUE,
+ },
+ subscribed_users: [],
+ checks: [],
+ calculation_interval: calculationInterval,
+ skip_weekend: false,
+ schedule_restriction: null,
+ detector_config: props.defaultToAnomalyDetection
+ ? getDefaultAnomalyDetectorConfig(calculationInterval)
+ : null,
+ investigation_agent_enabled: false,
+ investigation_gates_notifications: false,
+ investigation_inconclusive_action: 'notify',
+ insight: props.insightId,
+ } as AlertFormType
+ })(),
errors: (alert: AlertFormType) => getAlertFormValidationErrors(alert),
submit: async (alert) => {
const entitlementCheck = blockSubmitWithoutEntitlement(alert.calculation_interval, {
@@ -403,12 +424,13 @@ export const alertFormLogic = kea<alertFormLogicType>([
}
}
+ const existingAlertId = alert.id
+ const isNewAlert = existingAlertId === undefined
let updatedAlert: AlertType
try {
- updatedAlert =
- alert.id === undefined
- ? await api.alerts.create(payload)
- : await api.alerts.update(alert.id, payload)
+ updatedAlert = isNewAlert
+ ? await api.alerts.create(payload)
+ : await api.alerts.update(existingAlertId, payload)
} catch (error: unknown) {
// `AlertViewSet` is a standard DRF ModelViewSet, so validation errors arrive as
// `{attr, detail}`. Anything else (network blip, non-ApiError thrown somehow) shouldn't
@@ -429,11 +451,18 @@ export const alertFormLogic = kea<alertFormLogicType>([
posthog.captureException(postSaveError)
}
- lemonToast.success(alert.id === undefined ? 'Alert created.' : 'Alert saved.')
- if (alert.id === undefined) {
+ if (isNewAlert) {
+ lemonToast.success('Alert created.', {
+ button: {
+ label: 'View all alerts',
+ action: () => router.actions.push(urls.alerts()),
+ },
+ })
tryShowMCPHint('alerts.create', {
derivedPrompt: alert.name ? `Create an alert called ${alert.name}` : undefined,
})
+ } else {
+ lemonToast.success('Alert saved.')
}
return alertToFormType(updatedAlert, props.insightId)
diff --git a/products/alerts/frontend/logic/detectorConfigDefaults.ts b/products/alerts/frontend/logic/detectorConfigDefaults.ts
new file mode 100644
index 000000000000..0dc362aa555c
--- /dev/null
+++ b/products/alerts/frontend/logic/detectorConfigDefaults.ts
@@ -0,0 +1,34 @@
+import { AlertCalculationInterval, SingleDetectorConfig } from '~/queries/schema/schema-general'
+
+export const DEFAULT_ANOMALY_DETECTION_THRESHOLD = 0.95
+
+/** Default window size in data points based on how often the alert checks.
+ * Every 15 minutes: 672 (7 days), Hourly: 168 (7 days), Daily: 90 (90 days),
+ * Weekly: 26 (6 months), Monthly: 12 (1 year). */
+export function getDefaultWindow(interval?: AlertCalculationInterval): number {
+ switch (interval) {
+ case AlertCalculationInterval.EVERY_15_MINUTES:
+ return 672
+ case AlertCalculationInterval.HOURLY:
+ return 168
+ case AlertCalculationInterval.WEEKLY:
+ return 26
+ case AlertCalculationInterval.MONTHLY:
+ return 12
+ default:
+ return 90
+ }
+}
+
+export function getDefaultZScoreDetectorConfig(window: number): SingleDetectorConfig {
+ return {
+ type: 'zscore',
+ threshold: DEFAULT_ANOMALY_DETECTION_THRESHOLD,
+ window,
+ preprocessing: { diffs_n: 1 },
+ }
+}
+
+export function getDefaultAnomalyDetectorConfig(interval?: AlertCalculationInterval): SingleDetectorConfig {
+ return getDefaultZScoreDetectorConfig(getDefaultWindow(interval))
+}
diff --git a/products/alerts/frontend/logic/insightAlertsLogic.test.ts b/products/alerts/frontend/logic/insightAlertsLogic.test.ts
index 1ee3319ef2a6..f63205e9e678 100644
--- a/products/alerts/frontend/logic/insightAlertsLogic.test.ts
+++ b/products/alerts/frontend/logic/insightAlertsLogic.test.ts
@@ -7,10 +7,15 @@ import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
-import { InsightLogicProps, InsightShortId } from '~/types'
+import { ChartDisplayType, InsightLogicProps, InsightShortId } from '~/types'
import type { AlertType } from '../types'
-import { alertsUnsupportedReason, areAlertsSupportedForInsight, insightAlertsLogic } from './insightAlertsLogic'
+import {
+ alertsUnsupportedReason,
+ areAlertsSupportedForInsight,
+ areAnomalyAlertsSupportedForInsight,
+ insightAlertsLogic,
+} from './insightAlertsLogic'
const Insight42 = '42' as InsightShortId
@@ -215,8 +220,30 @@ describe('areAlertsSupportedForInsight', () => {
expect(areAlertsSupportedForInsight(undefined)).toBe(false)
})
- it('returns true for trends insight viz with trendsFilter', () => {
- expect(areAlertsSupportedForInsight(API_QUERY)).toBe(true)
+ it.each([
+ ['with trendsFilter', API_QUERY],
+ [
+ 'without trendsFilter',
+ {
+ ...API_QUERY,
+ source: {
+ ...API_QUERY.source,
+ trendsFilter: undefined,
+ },
+ },
+ ],
+ [
+ 'with null trendsFilter',
+ {
+ ...API_QUERY,
+ source: {
+ ...API_QUERY.source,
+ trendsFilter: null,
+ },
+ },
+ ],
+ ])('returns true for trends insight viz %s', (_name, query) => {
+ expect(areAlertsSupportedForInsight(query)).toBe(true)
})
it('returns false for funnel insight viz when the funnel flag is off', () => {
@@ -239,15 +266,20 @@ describe('areAlertsSupportedForInsight', () => {
expect(areAlertsSupportedForInsight(withViz('flow'), opts)).toBe(false)
})
- it('returns false when trendsFilter is null', () => {
+ it.each<[string, ChartDisplayType | undefined, boolean]>([
+ ['line graph', ChartDisplayType.ActionsLineGraph, true],
+ ['default display', undefined, true],
+ ['bold number', ChartDisplayType.BoldNumber, false],
+ ['bar value', ChartDisplayType.ActionsBarValue, false],
+ ])('reports anomaly support for %s trends', (_name, display, expected) => {
const query = {
...API_QUERY,
source: {
...API_QUERY.source,
- trendsFilter: null,
+ trendsFilter: display ? { display } : null,
},
}
- expect(areAlertsSupportedForInsight(query)).toBe(false)
+ expect(areAnomalyAlertsSupportedForInsight(query)).toBe(expected)
})
})
@@ -259,8 +291,8 @@ describe('alertsUnsupportedReason', () => {
['all three', { hogqlAlertsEnabled: true, funnelAlertsEnabled: true }, ['trends', 'SQL', 'funnel'], []],
])('lists only enabled types: %s', (_name, options, included, excluded) => {
const reason = alertsUnsupportedReason(options)
- included.forEach((type) => expect(reason).toContain(type))
- excluded.forEach((type) => expect(reason).not.toContain(type))
+ expect(included.every((type) => reason.includes(type))).toBe(true)
+ expect(excluded.every((type) => !reason.includes(type))).toBe(true)
})
// A time-to-convert/flow funnel is itself a funnel, so the generic "funnel insights are supported"
diff --git a/products/alerts/frontend/logic/insightAlertsLogic.ts b/products/alerts/frontend/logic/insightAlertsLogic.ts
index ff13d5192898..4be31502be38 100644
--- a/products/alerts/frontend/logic/insightAlertsLogic.ts
+++ b/products/alerts/frontend/logic/insightAlertsLogic.ts
@@ -2,7 +2,7 @@ import { actions, afterMount, connect, kea, key, listeners, path, props, reducer
import { loaders } from 'kea-loaders'
import api from 'lib/api'
-import { FEATURE_FLAGS } from 'lib/constants'
+import { FEATURE_FLAGS, NON_TIME_SERIES_DISPLAY_TYPES } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
@@ -38,7 +38,7 @@ export const areAlertsSupportedForInsight = (
if (!query) {
return false
}
- if (isInsightVizNode(query) && isTrendsQuery(query.source) && query.source.trendsFilter !== null) {
+ if (isInsightVizNode(query) && isTrendsQuery(query.source)) {
return true
}
if (options.funnelAlertsEnabled && isInsightVizNode(query) && isFunnelsQuery(query.source)) {
@@ -50,6 +50,20 @@ export const areAlertsSupportedForInsight = (
return !!options.hogqlAlertsEnabled && containsHogQLQuery(query)
}
+export const areAnomalyAlertsSupportedForInsight = (
+ query?: Record<string, any> | null,
+ options: { hogqlAlertsEnabled?: boolean } = {}
+): boolean => {
+ if (!areAlertsSupportedForInsight(query, options)) {
+ return false
+ }
+ if (query && isInsightVizNode(query) && isTrendsQuery(query.source)) {
+ const display = query.source.trendsFilter?.display
+ return !display || !NON_TIME_SERIES_DISPLAY_TYPES.includes(display)
+ }
+ return true
+}
+
// List only the insight types this account can actually alert on — naming a flag-gated type the
// user doesn't have would disclose an unreleased feature.
const alertableInsightTypesLabel = (options: { hogqlAlertsEnabled?: boolean; funnelAlertsEnabled?: boolean }): string =>
diff --git a/products/alerts/frontend/views/DetectorSelector.tsx b/products/alerts/frontend/views/DetectorSelector.tsx
index a86b154deed2..3233ab1e483e 100644
--- a/products/alerts/frontend/views/DetectorSelector.tsx
+++ b/products/alerts/frontend/views/DetectorSelector.tsx
@@ -24,25 +24,11 @@ import {
ZScoreDetectorConfig,
} from '~/queries/schema/schema-general'
-/** Default anomaly probability threshold for all detectors. Higher = fewer alerts. */
-const DEFAULT_THRESHOLD = 0.95
-
-/** Default window size based on how often the alert checks.
- * Every 15 minutes: 672 (7 days), Hourly: 168 (7 days), Daily: 90, Weekly: 26 (6 months), Monthly: 12 (1 year). */
-export function getDefaultWindow(interval?: AlertCalculationInterval): number {
- switch (interval) {
- case AlertCalculationInterval.EVERY_15_MINUTES:
- return 672
- case AlertCalculationInterval.HOURLY:
- return 168
- case AlertCalculationInterval.WEEKLY:
- return 26
- case AlertCalculationInterval.MONTHLY:
- return 12
- default:
- return 90
- }
-}
+import {
+ DEFAULT_ANOMALY_DETECTION_THRESHOLD,
+ getDefaultZScoreDetectorConfig,
+ getDefaultWindow,
+} from '../logic/detectorConfigDefaults'
interface DetectorSelectorProps {
value: DetectorConfig | null
@@ -55,13 +41,13 @@ const DETECTOR_OPTIONS: Array<{ value: string; label: string; tooltip: string }>
value: DetectorType.COPOD,
label: 'COPOD',
tooltip:
- 'Scores each point against the historical distribution using copulas. Parameter-free, so it works without tuning a sensitivity threshold.',
+ 'Scores each point against the historical distribution using copulas. Useful when you want a distribution-based detector.',
},
{
value: DetectorType.ECOD,
label: 'ECOD',
tooltip:
- 'Scores each point against the empirical distribution of past values. Parameter-free and explainable — good when you need to justify why a point was flagged.',
+ 'Scores each point against the empirical distribution of past values. Useful when you want an explainable distribution-based detector.',
},
{
value: 'ensemble',
@@ -135,22 +121,27 @@ const SINGLE_DETECTOR_OPTIONS = DETECTOR_OPTIONS.filter((o) => o.value !== 'ense
function getDefaultSingleConfigs(window: number): Record<string, SingleDetectorConfig> {
return {
- zscore: { type: 'zscore', threshold: DEFAULT_THRESHOLD, window, preprocessing: { diffs_n: 1 } },
- mad: { type: 'mad', threshold: DEFAULT_THRESHOLD, window, preprocessing: { diffs_n: 1 } },
+ zscore: getDefaultZScoreDetectorConfig(window),
+ mad: {
+ type: 'mad',
+ threshold: DEFAULT_ANOMALY_DETECTION_THRESHOLD,
+ window,
+ preprocessing: { diffs_n: 1 },
+ },
iqr: { type: 'iqr', multiplier: 1.5, window },
threshold: { type: 'threshold' },
- ecod: { type: 'ecod', threshold: DEFAULT_THRESHOLD, window },
- copod: { type: 'copod', threshold: DEFAULT_THRESHOLD, window },
+ ecod: { type: 'ecod', threshold: DEFAULT_ANOMALY_DETECTION_THRESHOLD, window },
+ copod: { type: 'copod', threshold: DEFAULT_ANOMALY_DETECTION_THRESHOLD, window },
isolation_forest: {
type: 'isolation_forest',
- threshold: DEFAULT_THRESHOLD,
+ threshold: DEFAULT_ANOMALY_DETECTION_THRESHOLD,
n_estimators: 100,
window,
preprocessing: { diffs_n: 1, lags_n: 3 },
},
knn: {
type: 'knn',
- threshold: DEFAULT_THRESHOLD,
+ threshold: DEFAULT_ANOMALY_DETECTION_THRESHOLD,
n_neighbors: 5,
method: 'largest',
window,
@@ -158,14 +149,24 @@ function getDefaultSingleConfigs(window: number): Record<string, SingleDetectorC
},
lof: {
type: 'lof',
- threshold: DEFAULT_THRESHOLD,
+ threshold: DEFAULT_ANOMALY_DETECTION_THRESHOLD,
n_neighbors: 20,
window,
preprocessing: { diffs_n: 1, lags_n: 3 },
},
- hbos: { type: 'hbos', threshold: DEFAULT_THRESHOLD, n_bins: 10, window },
- ocsvm: { type: 'ocsvm', threshold: DEFAULT_THRESHOLD, window, preprocessing: { diffs_n: 1, lags_n: 3 } },
- pca: { type: 'pca', threshold: DEFAULT_THRESHOLD, window, preprocessing: { diffs_n: 1, lags_n: 3 } },
+ hbos: { type: 'hbos', threshold: DEFAULT_ANOMALY_DETECTION_THRESHOLD, n_bins: 10, window },
+ ocsvm: {
+ type: 'ocsvm',
+ threshold: DEFAULT_ANOMALY_DETECTION_THRESHOLD,
+ window,
+ preprocessing: { diffs_n: 1, lags_n: 3 },
+ },
+ pca: {
+ type: 'pca',
+ threshold: DEFAULT_ANOMALY_DETECTION_THRESHOLD,
+ window,
+ preprocessing: { diffs_n: 1, lags_n: 3 },
+ },
}
}
@@ -174,8 +175,13 @@ function getDefaultEnsemble(window: number): EnsembleDetectorConfig {
type: 'ensemble',
operator: EnsembleOperator.AND,
detectors: [
- { type: 'zscore', threshold: DEFAULT_THRESHOLD, window, preprocessing: { diffs_n: 1 } },
- { type: 'mad', threshold: DEFAULT_THRESHOLD, window, preprocessing: { diffs_n: 1 } },
+ getDefaultZScoreDetectorConfig(window),
+ {
+ type: 'mad',
+ threshold: DEFAULT_ANOMALY_DETECTION_THRESHOLD,
+ window,
+ preprocessing: { diffs_n: 1 },
+ },
],
}
}
@@ -382,14 +388,12 @@ function SingleDetectorConfigSection({
<div>
{(config.type === 'zscore' || config.type === 'mad') && (
<div className="grid grid-cols-2 gap-3">
- <SensitivityInput
- value={(config as ZScoreDetectorConfig | MADDetectorConfig).threshold ?? DEFAULT_THRESHOLD}
- onChange={(val) => onChange({ ...config, threshold: val } as SingleDetectorConfig)}
- tooltip={
- config.type === 'zscore'
- ? 'Anomaly probability threshold (0-1). Points scoring above this are flagged. Higher = fewer alerts.'
- : 'Anomaly probability threshold (0-1). Like Z-Score but uses median, making it robust to outliers. Higher = fewer alerts.'
+ <AnomalyThresholdInput
+ value={
+ (config as ZScoreDetectorConfig | MADDetectorConfig).threshold ??
+ DEFAULT_ANOMALY_DETECTION_THRESHOLD
}
+ onChange={(val) => onChange({ ...config, threshold: val } as SingleDetectorConfig)}
/>
<WindowSizeInput
config={config as ZScoreDetectorConfig | MADDetectorConfig}
@@ -465,25 +469,20 @@ function SingleDetectorConfigSection({
)
}
-function SensitivityInput({
- value,
- onChange,
- tooltip,
-}: {
- value: number
- onChange: (value: number) => void
- tooltip: string
-}): JSX.Element {
+function AnomalyThresholdInput({ value, onChange }: { value: number; onChange: (value: number) => void }): JSX.Element {
return (
<div>
- <Label text="Sensitivity" tooltip={tooltip} />
+ <Label
+ text="Anomaly threshold"
+ tooltip="Minimum anomaly probability required to trigger an alert (0-1). Higher values trigger fewer alerts."
+ />
<LemonInput
type="number"
min={0.5}
max={0.99}
step={0.05}
value={value}
- onChange={(val) => onChange(val ? parseFloat(String(val)) : DEFAULT_THRESHOLD)}
+ onChange={(val) => onChange(val ? parseFloat(String(val)) : DEFAULT_ANOMALY_DETECTION_THRESHOLD)}
/>
</div>
)
@@ -532,13 +531,12 @@ function ECODConfig({
}): JSX.Element {
return (
<div className="space-y-3 pl-4 border-l-2 border-border">
- <SensitivityInput
- value={config.threshold ?? DEFAULT_THRESHOLD}
+ <AnomalyThresholdInput
+ value={config.threshold ?? DEFAULT_ANOMALY_DETECTION_THRESHOLD}
onChange={(val) => onChange({ ...config, threshold: val })}
- tooltip="Anomaly probability threshold (0-1). Higher = fewer alerts."
/>
<WindowSizeInput config={config} onChange={onChange} calculationInterval={calculationInterval} />
- <p className="text-xs text-muted">Empirical cumulative distribution — parameter-free and interpretable.</p>
+ <p className="text-xs text-muted">Empirical cumulative distribution for interpretable anomaly scoring.</p>
</div>
)
}
@@ -554,13 +552,12 @@ function COPODConfig({
}): JSX.Element {
return (
<div className="space-y-3 pl-4 border-l-2 border-border">
- <SensitivityInput
- value={config.threshold ?? DEFAULT_THRESHOLD}
+ <AnomalyThresholdInput
+ value={config.threshold ?? DEFAULT_ANOMALY_DETECTION_THRESHOLD}
onChange={(val) => onChange({ ...config, threshold: val })}
- tooltip="Anomaly probability threshold (0-1). Higher = fewer alerts."
/>
<WindowSizeInput config={config} onChange={onChange} calculationInterval={calculationInterval} />
- <p className="text-xs text-muted">Copula-based detection — efficient and parameter-free.</p>
+ <p className="text-xs text-muted">Efficient copula-based anomaly scoring.</p>
</div>
)
}
@@ -576,10 +573,9 @@ function IsolationForestConfig({
}): JSX.Element {
return (
<div className="space-y-3 pl-4 border-l-2 border-border">
- <SensitivityInput
- value={config.threshold ?? DEFAULT_THRESHOLD}
+ <AnomalyThresholdInput
+ value={config.threshold ?? DEFAULT_ANOMALY_DETECTION_THRESHOLD}
onChange={(val) => onChange({ ...config, threshold: val })}
- tooltip="Anomaly probability threshold (0-1). Higher = fewer alerts."
/>
<div>
<Label text="Number of trees" tooltip="More trees = more accurate but slower. 100 is a good default." />
@@ -610,10 +606,9 @@ function KNNConfig({
}): JSX.Element {
return (
<div className="space-y-3 pl-4 border-l-2 border-border">
- <SensitivityInput
- value={config.threshold ?? DEFAULT_THRESHOLD}
+ <AnomalyThresholdInput
+ value={config.threshold ?? DEFAULT_ANOMALY_DETECTION_THRESHOLD}
onChange={(val) => onChange({ ...config, threshold: val })}
- tooltip="Anomaly probability threshold (0-1). Higher = fewer alerts."
/>
<div>
<Label
@@ -665,10 +660,9 @@ function LOFConfig({
}): JSX.Element {
return (
<div className="space-y-3 pl-4 border-l-2 border-border">
- <SensitivityInput
- value={config.threshold ?? DEFAULT_THRESHOLD}
+ <AnomalyThresholdInput
+ value={config.threshold ?? DEFAULT_ANOMALY_DETECTION_THRESHOLD}
onChange={(val) => onChange({ ...config, threshold: val })}
- tooltip="Anomaly probability threshold (0-1). Higher = fewer alerts."
/>
<div>
<Label
@@ -704,10 +698,9 @@ function HBOSConfig({
}): JSX.Element {
return (
<div className="space-y-3 pl-4 border-l-2 border-border">
- <SensitivityInput
- value={config.threshold ?? DEFAULT_THRESHOLD}
+ <AnomalyThresholdInput
+ value={config.threshold ?? DEFAULT_ANOMALY_DETECTION_THRESHOLD}
onChange={(val) => onChange({ ...config, threshold: val })}
- tooltip="Anomaly probability threshold (0-1). Higher = fewer alerts."
/>
<div>
<Label
@@ -741,10 +734,9 @@ function OCSVMConfig({
}): JSX.Element {
return (
<div className="space-y-3 pl-4 border-l-2 border-border">
- <SensitivityInput
- value={config.threshold ?? DEFAULT_THRESHOLD}
+ <AnomalyThresholdInput
+ value={config.threshold ?? DEFAULT_ANOMALY_DETECTION_THRESHOLD}
onChange={(val) => onChange({ ...config, threshold: val })}
- tooltip="Anomaly probability threshold (0-1). Higher = fewer alerts."
/>
<WindowSizeInput config={config} onChange={onChange} calculationInterval={calculationInterval} />
<p className="text-xs text-muted">
@@ -765,10 +757,9 @@ function PCAConfig({
}): JSX.Element {
return (
<div className="space-y-3 pl-4 border-l-2 border-border">
- <SensitivityInput
- value={config.threshold ?? DEFAULT_THRESHOLD}
+ <AnomalyThresholdInput
+ value={config.threshold ?? DEFAULT_ANOMALY_DETECTION_THRESHOLD}
onChange={(val) => onChange({ ...config, threshold: val })}
- tooltip="Anomaly probability threshold (0-1). Higher = fewer alerts."
/>
<WindowSizeInput config={config} onChange={onChange} calculationInterval={calculationInterval} />
<p className="text-xs text-muted">
diff --git a/products/alerts/frontend/views/EditAlertModal.tsx b/products/alerts/frontend/views/EditAlertModal.tsx
index 05934657e74d..274074a23184 100644
--- a/products/alerts/frontend/views/EditAlertModal.tsx
+++ b/products/alerts/frontend/views/EditAlertModal.tsx
@@ -45,7 +45,9 @@ interface EditAlertModalProps {
insightShortId: InsightShortId
onEditSuccess: (alertId?: AlertType['id'] | undefined) => void
onClose?: () => void
- insightLogicProps?: InsightLogicProps
+ insightLogicProps: InsightLogicProps
+ defaultToAnomalyDetection?: boolean
+ insightName?: string | null
}
export function EditAlertModal({
@@ -56,6 +58,8 @@ export function EditAlertModal({
onClose,
onEditSuccess,
insightLogicProps,
+ defaultToAnomalyDetection,
+ insightName,
}: EditAlertModalProps): JSX.Element {
const _alertLogic = alertLogic({ alertId })
const { alert, alertLoading } = useValues(_alertLogic)
@@ -68,7 +72,7 @@ export function EditAlertModal({
[onEditSuccess]
)
- const trendsLogic = trendsDataLogic({ dashboardItemId: insightShortId })
+ const trendsLogic = trendsDataLogic(insightLogicProps)
const {
alertSeries,
isNonTimeSeriesDisplay,
@@ -77,7 +81,7 @@ export function EditAlertModal({
interval: trendInterval,
} = useValues(trendsLogic)
- const { query } = useValues(insightVizDataLogic(insightLogicProps ?? { dashboardItemId: insightShortId }))
+ const { query } = useValues(insightVizDataLogic(insightLogicProps))
const funnelSource = !!query && isInsightVizNode(query) && isFunnelsQuery(query.source) ? query.source : null
const isFunnelInsight = funnelSource !== null
@@ -101,6 +105,8 @@ export function EditAlertModal({
insightVizDataLogicProps: insightLogicProps,
insightInterval: trendInterval ?? undefined,
insightAlertKind,
+ defaultToAnomalyDetection: !alertId && !isNonTimeSeriesDisplay && defaultToAnomalyDetection,
+ insightName,
insightIsTrendsFunnel: isTrendsFunnel,
}
const formLogic = alertFormLogic(formLogicProps)
@@ -131,7 +137,6 @@ export function EditAlertModal({
const { currentTeam } = useValues(teamLogic)
const projectTimezone = currentTeam?.timezone ?? 'UTC'
- const anomalyDetectionEnabled = useFeatureFlag('ALERTS_ANOMALY_DETECTION')
const inlineNotificationsEnabled = useFeatureFlag('ALERTS_INLINE_NOTIFICATIONS')
const investigationAgentEnabled = useFeatureFlag('ALERTS_INVESTIGATION_AGENT')
@@ -281,8 +286,8 @@ export function EditAlertModal({
valueColumnOptions: hogqlValueColumnOptions,
labelColumnOptions: hogqlLabelColumnOptions,
}}
- anomalyDetectionEnabled={
- anomalyDetectionEnabled && supportsAnomalyDetection(alertForm.config)
+ supportsAnomalyDetection={
+ !isNonTimeSeriesDisplay && supportsAnomalyDetection(alertForm.config)
}
investigationAgentEnabled={investigationAgentEnabled}
simulationResult={simulationResult}
@@ -376,7 +381,12 @@ export function EditAlertModal({
type="primary"
htmlType="submit"
loading={isAlertFormSubmitting}
- disabledReason={!alertFormChanged && !hasPendingNotifications && 'No changes to save'}
+ disabledReason={
+ !creatingNewAlert &&
+ !alertFormChanged &&
+ !hasPendingNotifications &&
+ 'No changes to save'
+ }
onClick={() => setAlertFormSubmitAttempted()}
>
{creatingNewAlert ? 'Create alert' : 'Save'}
diff --git a/products/alerts/frontend/views/ManageAlertsModal.tsx b/products/alerts/frontend/views/ManageAlertsModal.tsx
index 000b6568aa30..11c38d2cb9ad 100644
--- a/products/alerts/frontend/views/ManageAlertsModal.tsx
+++ b/products/alerts/frontend/views/ManageAlertsModal.tsx
@@ -98,6 +98,8 @@ interface ManageAlertsModalProps extends InsightAlertsLogicProps {
/** The insight's query, so the unsupported-reason copy can be specific (e.g. time-to-convert funnels). */
insightQuery?: Record<string, any> | null
onClose?: () => void
+ onCreateAlert?: () => void
+ onEditAlert?: (alertId: AlertType['id']) => void
}
export function ManageAlertsModal(props: ManageAlertsModalProps): JSX.Element {
@@ -109,6 +111,24 @@ export function ManageAlertsModal(props: ManageAlertsModalProps): JSX.Element {
const funnelAlertsEnabled = useFeatureFlag('FUNNEL_INSIGHT_ALERTS')
const showDeferredListSpinner = props.deferInitialAlertsLoad && props.isOpen && alertsLoading
+ const openAlert = (alertId: AlertType['id']): void => {
+ if (props.onEditAlert) {
+ props.onClose?.()
+ props.onEditAlert(alertId)
+ return
+ }
+
+ push(urls.insightAlert(props.insightShortId, alertId))
+ }
+ const createAlert = (): void => {
+ if (props.onCreateAlert) {
+ props.onClose?.()
+ props.onCreateAlert()
+ return
+ }
+
+ push(urls.insightAlert(props.insightShortId, 'new'))
+ }
return (
<LemonModal onClose={props.onClose} isOpen={props.isOpen} width={600} simple title="">
@@ -136,11 +156,7 @@ export function ManageAlertsModal(props: ManageAlertsModalProps): JSX.Element {
</div>
{alerts.map((alert) => (
- <AlertListItem
- key={alert.id}
- alert={alert}
- onClick={() => push(urls.insightAlert(props.insightShortId, alert.id))}
- />
+ <AlertListItem key={alert.id} alert={alert} onClick={() => openAlert(alert.id)} />
))}
</div>
) : (
@@ -155,7 +171,7 @@ export function ManageAlertsModal(props: ManageAlertsModalProps): JSX.Element {
<LemonModal.Footer>
<LemonButton
type="primary"
- onClick={() => push(urls.insightAlert(props.insightShortId, 'new'))}
+ onClick={createAlert}
disabledReason={
!props.canCreateAlertForInsight
? alertsUnsupportedReason({ hogqlAlertsEnabled, funnelAlertsEnabled }, props.insightQuery)