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 funnel insight alerts (conversion rate, absolute-only) (#62670)

Vasco de Krijger8b5476965bf0
diff --git a/frontend/src/lib/components/Alerts/AlertsButton.tsx b/frontend/src/lib/components/Alerts/AlertsButton.tsx
index 7b7e53cd5e82..402f1cf7d73d 100644
--- a/frontend/src/lib/components/Alerts/AlertsButton.tsx
+++ b/frontend/src/lib/components/Alerts/AlertsButton.tsx
@@ -10,7 +10,7 @@ import { urls } from 'scenes/urls'
import { InsightLogicProps, QueryBasedInsightModel } from '~/types'
-import { areAlertsSupportedForInsight, insightAlertsLogic } from './insightAlertsLogic'
+import { alertsUnsupportedReason, areAlertsSupportedForInsight, insightAlertsLogic } from './insightAlertsLogic'
export type AlertsButtonProps = LemonButtonProps & {
insight: Partial<QueryBasedInsightModel>
@@ -23,17 +23,15 @@ export function AlertsButton({ insight, insightLogicProps, text, ...props }: Ale
const logic = insightAlertsLogic({ insightId: insight.id!, insightLogicProps })
const { alerts } = useValues(logic)
const hogqlAlertsEnabled = useFeatureFlag('HOGQL_INSIGHT_ALERTS')
+ const funnelAlertsEnabled = useFeatureFlag('FUNNEL_INSIGHT_ALERTS')
- const supported = areAlertsSupportedForInsight(insight.query, { hogqlAlertsEnabled })
- // 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 availableTypes = ['trends', hogqlAlertsEnabled && 'SQL'].filter(Boolean).join(', ')
+ const supported = areAlertsSupportedForInsight(insight.query, { hogqlAlertsEnabled, funnelAlertsEnabled })
// Existing alerts must stay manageable even if the gating flag is later disabled —
// they keep evaluating server-side, so the user needs a way in to edit or disable them.
const disabledReason =
supported || (alerts?.length ?? 0) > 0
? undefined
- : `Alerts are only available for ${availableTypes} insights. Change the insight representation to add alerts.`
+ : alertsUnsupportedReason({ hogqlAlertsEnabled, funnelAlertsEnabled })
return (
<LemonButton
diff --git a/frontend/src/lib/components/Alerts/alertFormLogic.test.ts b/frontend/src/lib/components/Alerts/alertFormLogic.test.ts
index 315a50ca1486..22461147b7e2 100644
--- a/frontend/src/lib/components/Alerts/alertFormLogic.test.ts
+++ b/frontend/src/lib/components/Alerts/alertFormLogic.test.ts
@@ -23,6 +23,7 @@ import { InsightLogicProps, InsightShortId } from '~/types'
import { alertFormLogic, thresholdAlertHasBounds, type AlertFormType } from './alertFormLogic'
import { alertNotificationLogic } from './alertNotificationLogic'
+import { deriveFunnelAlertPreview } from './funnelAlertPreview'
import { deriveHogQLAlertPreview, HOGQL_ANY_ROW_MAX_ROWS, HOGQL_LAST_ROW_MAX_ROWS } from './hogqlAlertPreview'
import { insightAlertsLogic } from './insightAlertsLogic'
import type { AlertType } from './types'
@@ -663,4 +664,131 @@ describe('alertFormLogic', () => {
expect(preview?.status).toBe('ok')
})
})
+
+ describe('deriveFunnelAlertPreview', () => {
+ const FROM_START = { type: 'FunnelsAlertConfig', metric: 'conversion_from_start', funnel_step: null } as const
+ const steps = (...counts: number[]): Record<string, any>[] =>
+ counts.map((count, order) => ({ order, count, breakdown_value: null }))
+ const value = (label: string | null, rate: number, breaching: boolean): Record<string, any> => ({
+ label,
+ rate,
+ breaching,
+ })
+
+ it.each([
+ ['not a funnel config', { result: steps(100, 40) }, { type: 'HogQLAlertConfig' }, undefined, null],
+ ['no result loaded', null, FROM_START, undefined, null],
+ ['empty result', { result: [] }, FROM_START, undefined, null],
+ ['breakdown with an empty step list', { result: [[]] }, FROM_START, undefined, { status: 'no-data' }],
+ [
+ 'from_start at the last step, no bounds',
+ { result: steps(100, 40) },
+ FROM_START,
+ undefined,
+ { status: 'ok', values: [value(null, 40, false)], isBreakdown: false, hasBounds: false },
+ ],
+ [
+ 'lower bound breached flags the value and sets hasBounds',
+ { result: steps(100, 40) },
+ FROM_START,
+ { lower: 50 },
+ { status: 'ok', values: [value(null, 40, true)], isBreakdown: false, hasBounds: true },
+ ],
+ [
+ 'value within bounds is not breaching',
+ { result: steps(100, 40) },
+ FROM_START,
+ { lower: 30 },
+ { status: 'ok', values: [value(null, 40, false)], isBreakdown: false, hasBounds: true },
+ ],
+ [
+ 'upper bound breached flags the value',
+ { result: steps(100, 40) },
+ FROM_START,
+ { upper: 30 },
+ { status: 'ok', values: [value(null, 40, true)], isBreakdown: false, hasBounds: true },
+ ],
+ [
+ 'within a lower+upper range is not breaching',
+ { result: steps(100, 40) },
+ FROM_START,
+ { lower: 10, upper: 80 },
+ { status: 'ok', values: [value(null, 40, false)], isBreakdown: false, hasBounds: true },
+ ],
+ [
+ 'breaching the upper of a lower+upper range flags the value',
+ { result: steps(100, 40) },
+ FROM_START,
+ { lower: 10, upper: 30 },
+ { status: 'ok', values: [value(null, 40, true)], isBreakdown: false, hasBounds: true },
+ ],
+ [
+ 'from_previous divides by the prior step',
+ { result: steps(100, 50, 10) },
+ { type: 'FunnelsAlertConfig', metric: 'conversion_from_previous', funnel_step: 2 },
+ undefined,
+ { status: 'ok', values: [value(null, 20, false)], isBreakdown: false, hasBounds: false },
+ ],
+ [
+ 'zero base evaluates to 0%',
+ { result: steps(0, 5) },
+ FROM_START,
+ undefined,
+ { status: 'ok', values: [value(null, 0, false)], isBreakdown: false, hasBounds: false },
+ ],
+ [
+ 'breakdown computes a rate per value and flags only the breaching one',
+ {
+ result: [
+ [
+ { order: 0, count: 100, breakdown_value: 'US' },
+ { order: 1, count: 40, breakdown_value: 'US' },
+ ],
+ [
+ { order: 0, count: 80, breakdown_value: 'DE' },
+ { order: 1, count: 20, breakdown_value: 'DE' },
+ ],
+ ],
+ },
+ FROM_START,
+ { lower: 30 },
+ {
+ status: 'ok',
+ values: [value('US', 40, false), value('DE', 25, true)],
+ isBreakdown: true,
+ hasBounds: true,
+ },
+ ],
+ [
+ 'compared funnel evaluates the current period only',
+ {
+ result: [
+ { order: 0, count: 1000, compare_label: 'current', breakdown_value: null },
+ { order: 1, count: 100, compare_label: 'current', breakdown_value: null },
+ { order: 0, count: 800, compare_label: 'previous', breakdown_value: null },
+ { order: 1, count: 120, compare_label: 'previous', breakdown_value: null },
+ ],
+ },
+ FROM_START,
+ undefined,
+ { status: 'ok', values: [value(null, 10, false)], isBreakdown: false, hasBounds: false },
+ ],
+ [
+ 'compared funnel with only previous-period rows shows no-data, not unloaded',
+ {
+ result: [
+ { order: 0, count: 800, compare_label: 'previous', breakdown_value: null },
+ { order: 1, count: 120, compare_label: 'previous', breakdown_value: null },
+ ],
+ },
+ FROM_START,
+ undefined,
+ { status: 'no-data' },
+ ],
+ ])('%s', (_name, insightData, config, bounds, expected) => {
+ expect(
+ deriveFunnelAlertPreview(insightData as Record<string, any> | null, config as any, bounds as any)
+ ).toEqual(expected)
+ })
+ })
})
diff --git a/frontend/src/lib/components/Alerts/alertFormLogic.ts b/frontend/src/lib/components/Alerts/alertFormLogic.ts
index 7263d3bad8ca..4cfa76b82d85 100644
--- a/frontend/src/lib/components/Alerts/alertFormLogic.ts
+++ b/frontend/src/lib/components/Alerts/alertFormLogic.ts
@@ -32,6 +32,7 @@ import type { alertFormLogicType } from './alertFormLogicType'
import { getAlertFormValidationErrors } from './alertFormSchema'
import { alertLogic } from './alertLogic'
import { alertNotificationLogic } from './alertNotificationLogic'
+import { deriveFunnelAlertPreview, FunnelAlertPreview } from './funnelAlertPreview'
import { columnIsNumeric, deriveHogQLAlertPreview, HogQLAlertPreview } from './hogqlAlertPreview'
import { insightAlertsLogic } from './insightAlertsLogic'
import {
@@ -80,7 +81,7 @@ export function canCheckOngoingInterval(alert?: AlertType | AlertFormType): bool
}
/** The insight query kind an alert is built for; selects the default config type for new alerts. */
-export type InsightAlertKind = 'trends' | 'hogql'
+export type InsightAlertKind = 'trends' | 'hogql' | 'funnels'
export interface AlertFormLogicProps {
alert: AlertType | null
@@ -97,6 +98,9 @@ const defaultConfigForInsight = (kind: AlertFormLogicProps['insightAlertKind']):
// last_row is the default — the most common SQL alert shape is a chronological series.
return { type: 'HogQLAlertConfig', evaluation: 'last_row' }
}
+ if (kind === 'funnels') {
+ return { type: 'FunnelsAlertConfig', funnel_step: null, metric: 'conversion_from_start' }
+ }
return {
type: 'TrendsAlertConfig',
series_index: 0,
@@ -412,6 +416,20 @@ export const alertFormLogic = kea<alertFormLogicType>([
): HogQLAlertPreview | null =>
props.insightAlertKind === 'hogql' ? deriveHogQLAlertPreview(insightData, config, bounds) : null,
],
+ /** The conversion rate(s) a funnel alert would evaluate right now, with breach status; null until the result loads. */
+ funnelAlertPreview: [
+ (s) => [
+ s.insightData,
+ (state, logicProps) => s.alertForm(state, logicProps)?.config,
+ (state, logicProps) => s.alertForm(state, logicProps)?.threshold?.configuration?.bounds,
+ ],
+ (
+ insightData: Record<string, any> | null,
+ config: AlertConfig | null | undefined,
+ bounds: InsightsThresholdBounds | null | undefined
+ ): FunnelAlertPreview | null =>
+ props.insightAlertKind === 'funnels' ? deriveFunnelAlertPreview(insightData, config, bounds) : null,
+ ],
/** Result column names of the SQL insight, for the column pickers. */
hogqlResultColumns: [
(s) => [s.insightData],
diff --git a/frontend/src/lib/components/Alerts/alertPreviewShared.test.ts b/frontend/src/lib/components/Alerts/alertPreviewShared.test.ts
new file mode 100644
index 000000000000..a558805ad1b5
--- /dev/null
+++ b/frontend/src/lib/components/Alerts/alertPreviewShared.test.ts
@@ -0,0 +1,27 @@
+import { hasThresholdBounds, valueBreachesBounds } from './alertPreviewShared'
+
+describe('alertPreviewShared', () => {
+ it.each([
+ ['no bounds object', null, false],
+ ['undefined bounds', undefined, false],
+ ['empty bounds', {}, false],
+ ['lower only', { lower: 1 }, true],
+ ['upper only', { upper: 1 }, true],
+ ['both', { lower: 1, upper: 9 }, true],
+ ])('hasThresholdBounds: %s', (_name, bounds, expected) => {
+ expect(hasThresholdBounds(bounds as any)).toBe(expected)
+ })
+
+ it.each([
+ ['null value never breaches', null, { lower: 50 }, false],
+ ['no bounds never breaches', 5, null, false],
+ ['below lower breaches', 5, { lower: 10 }, true],
+ ['at lower is ok (strict <)', 10, { lower: 10 }, false],
+ ['above upper breaches', 15, { upper: 10 }, true],
+ ['at upper is ok (strict >)', 10, { upper: 10 }, false],
+ ['within a lower+upper range is ok', 40, { lower: 10, upper: 80 }, false],
+ ['above the upper of a range breaches', 90, { lower: 10, upper: 80 }, true],
+ ])('valueBreachesBounds: %s', (_name, value, bounds, expected) => {
+ expect(valueBreachesBounds(value as number | null, bounds as any)).toBe(expected)
+ })
+})
diff --git a/frontend/src/lib/components/Alerts/alertPreviewShared.ts b/frontend/src/lib/components/Alerts/alertPreviewShared.ts
new file mode 100644
index 000000000000..cb2c810cf258
--- /dev/null
+++ b/frontend/src/lib/components/Alerts/alertPreviewShared.ts
@@ -0,0 +1,17 @@
+import { InsightsThresholdBounds } from '~/queries/schema/schema-general'
+
+/** Whether a threshold has at least one bound set. Shared by the funnel and SQL configure-time
+ * previews so their breach logic can't drift. */
+export function hasThresholdBounds(bounds: InsightsThresholdBounds | null | undefined): boolean {
+ return !!bounds && (bounds.lower != null || bounds.upper != null)
+}
+
+/** Whether a value breaches the absolute bounds right now — mirrors the backend comparator's strict
+ * `< lower` / `> upper` (products/alerts/backend/evaluation/comparator.py). A null value never breaches.
+ * Single source of truth for both alert previews; keep it in sync with the comparator. */
+export function valueBreachesBounds(value: number | null, bounds: InsightsThresholdBounds | null | undefined): boolean {
+ if (value === null) {
+ return false
+ }
+ return (bounds?.lower != null && value < bounds.lower) || (bounds?.upper != null && value > bounds.upper)
+}
diff --git a/frontend/src/lib/components/Alerts/funnelAlertOptions.test.ts b/frontend/src/lib/components/Alerts/funnelAlertOptions.test.ts
new file mode 100644
index 000000000000..3717dc5d6e2b
--- /dev/null
+++ b/frontend/src/lib/components/Alerts/funnelAlertOptions.test.ts
@@ -0,0 +1,89 @@
+import { FunnelsAlertConfig } from '~/queries/schema/schema-general'
+
+import { funnelConfigForOptionKey, funnelConfigToOptionKey, funnelConversionOptions } from './funnelAlertOptions'
+
+describe('funnelAlertOptions', () => {
+ const flatValues = (labels: string[]): string[] =>
+ funnelConversionOptions(labels).flatMap((section) => section.options.map((o) => ('value' in o ? o.value : '')))
+
+ it('returns no options for a degenerate (<2 step) funnel', () => {
+ expect(funnelConversionOptions([])).toEqual([])
+ expect(funnelConversionOptions(['only'])).toEqual([])
+ })
+
+ it('collapses a 2-step funnel to a single overall option', () => {
+ const sections = funnelConversionOptions(['Visited', 'Signed up'])
+ expect(sections).toHaveLength(1)
+ expect(sections[0].options).toEqual([{ label: 'Visited → Signed up', value: 'overall' }])
+ })
+
+ it('groups a 3-step funnel into step-over-step + a From-entry group holding just the overall', () => {
+ const sections = funnelConversionOptions(['A', 'B', 'C'])
+ expect(sections.map((s) => s.title)).toEqual(['Step-over-step', 'From entry'])
+ // No intermediate cumulative step (start:2..N-2 is empty), so From entry holds only the overall.
+ expect(flatValues(['A', 'B', 'C'])).toEqual(['prev:1', 'prev:2', 'overall'])
+ })
+
+ it('puts cumulative intermediates and the overall together in From entry (5-step funnel)', () => {
+ const labels = ['Home', 'Product', 'Cart', 'Checkout', 'Order']
+ const sections = funnelConversionOptions(labels)
+ expect(sections.map((s) => s.title)).toEqual(['Step-over-step', 'From entry'])
+ // start:1 (== prev:1) stays in step-over-step; the overall is the final From-entry member.
+ expect(flatValues(labels)).toEqual(['prev:1', 'prev:2', 'prev:3', 'prev:4', 'start:2', 'start:3', 'overall'])
+ // The overall row is labeled by its span (first → last), with no "overall" prefix.
+ const fromEntry = sections.find((s) => s.title === 'From entry')!
+ expect(fromEntry.options.map((o) => ('label' in o ? o.label : ''))).toEqual([
+ 'Home → Cart',
+ 'Home → Checkout',
+ 'Home → Order',
+ ])
+ })
+
+ it('uses the real step labels in the option text', () => {
+ const sections = funnelConversionOptions(['Home', 'Product', 'Cart'])
+ const stepOverStep = sections.find((s) => s.title === 'Step-over-step')!
+ expect(stepOverStep.options.map((o) => ('label' in o ? o.label : ''))).toEqual([
+ 'Home → Product',
+ 'Product → Cart',
+ ])
+ })
+
+ const cfg = (metric: FunnelsAlertConfig['metric'], funnel_step: number | null): FunnelsAlertConfig => ({
+ type: 'FunnelsAlertConfig',
+ metric,
+ funnel_step,
+ })
+
+ it.each([
+ // [description, config, stepCount, expectedKey]
+ ['null step → overall', cfg('conversion_from_start', null), 5, 'overall'],
+ ['from_start at last step → overall', cfg('conversion_from_start', 4), 5, 'overall'],
+ ['from_start at step 1 → prev:1 (coincident rate)', cfg('conversion_from_start', 1), 5, 'prev:1'],
+ ['from_start at step 0 → prev:1', cfg('conversion_from_start', 0), 5, 'prev:1'],
+ ['from_start intermediate → start:i', cfg('conversion_from_start', 2), 5, 'start:2'],
+ ['from_previous → prev:i', cfg('conversion_from_previous', 3), 5, 'prev:3'],
+ ['from_previous null → last step-over-step', cfg('conversion_from_previous', null), 5, 'prev:4'],
+ ['from_previous at step 0 (invalid) → overall fallback', cfg('conversion_from_previous', 0), 5, 'overall'],
+ ['2-step from_previous → overall', cfg('conversion_from_previous', 1), 2, 'overall'],
+ ['2-step from_start → overall', cfg('conversion_from_start', null), 2, 'overall'],
+ ])('funnelConfigToOptionKey: %s', (_desc, config, stepCount, expected) => {
+ expect(funnelConfigToOptionKey(config, stepCount)).toBe(expected)
+ })
+
+ it.each([
+ ['overall', { metric: 'conversion_from_start', funnel_step: null }],
+ ['prev:2', { metric: 'conversion_from_previous', funnel_step: 2 }],
+ ['start:3', { metric: 'conversion_from_start', funnel_step: 3 }],
+ ])('funnelConfigForOptionKey: %s', (key, expected) => {
+ expect(funnelConfigForOptionKey(key)).toEqual(expected)
+ })
+
+ it('round-trips every emitted option key back to a key that maps to the same rate', () => {
+ const labels = ['Home', 'Product', 'Cart', 'Checkout', 'Order']
+ const keys = flatValues(labels)
+ const roundTripped = keys.map((key) =>
+ funnelConfigToOptionKey({ type: 'FunnelsAlertConfig', ...funnelConfigForOptionKey(key) }, labels.length)
+ )
+ expect(roundTripped).toEqual(keys)
+ })
+})
diff --git a/frontend/src/lib/components/Alerts/funnelAlertOptions.ts b/frontend/src/lib/components/Alerts/funnelAlertOptions.ts
new file mode 100644
index 000000000000..cf8ca1e7612d
--- /dev/null
+++ b/frontend/src/lib/components/Alerts/funnelAlertOptions.ts
@@ -0,0 +1,88 @@
+import { LemonSelectSection } from 'lib/lemon-ui/LemonSelect/LemonSelect'
+
+import { FunnelsAlertConfig } from '~/queries/schema/schema-general'
+
+/** Single-dropdown funnel conversion picker.
+ *
+ * The `{metric, funnel_step}` data model can express invalid combinations (e.g. `conversion_from_previous`
+ * at step 1, which has no prior step). Rather than expose two coupled dropdowns whose cartesian product
+ * includes nonsense, we enumerate only the valid conversions as labeled options keyed by a stable string,
+ * then map back to the config on selection. Each key encodes the underlying `{metric, funnel_step}`:
+ *
+ * - `overall` → whole-funnel conversion (first step → last step) {conversion_from_start, null}
+ * - `prev:<i>` → step-over-step conversion into step i (1-based index) {conversion_from_previous, i}
+ * - `start:<i>` → cumulative conversion from entry to step i {conversion_from_start, i}
+ *
+ * Two groups: "Step-over-step" (every adjacent transition) and "From entry" (cumulative reach from the
+ * first step). `start:1` is omitted because it equals `prev:1` (both are step1/step0) — it's covered by
+ * the step-over-step group. The overall conversion is the final, full-funnel member of the From-entry
+ * group (rather than its own section), so that group always reads as a complete set.
+ */
+
+const OVERALL = 'overall'
+
+export function funnelConversionOptions(stepLabels: string[]): LemonSelectSection<string>[] {
+ const n = stepLabels.length
+ if (n < 2) {
+ return []
+ }
+ const first = stepLabels[0]
+ const last = stepLabels[n - 1]
+
+ // A 2-step funnel has exactly one conversion; `prev:1` would just duplicate the overall rate.
+ if (n === 2) {
+ return [{ options: [{ label: `${first} → ${last}`, value: OVERALL }] }]
+ }
+
+ // Cumulative reach from entry to each intermediate step (step 1 is the first step-over-step), then
+ // the overall conversion as the full-funnel member so the group reads as a complete set.
+ const fromEntry = []
+ for (let step = 2; step <= n - 2; step++) {
+ fromEntry.push({ label: `${first} → ${stepLabels[step]}`, value: `start:${step}` })
+ }
+ // first → last is self-evidently the whole-funnel conversion, so it needs no "overall" label.
+ fromEntry.push({ label: `${first} → ${last}`, value: OVERALL })
+
+ return [
+ {
+ title: 'Step-over-step',
+ options: Array.from({ length: n - 1 }, (_, k) => {
+ const step = k + 1
+ return { label: `${stepLabels[step - 1]} → ${stepLabels[step]}`, value: `prev:${step}` }
+ }),
+ },
+ { title: 'From entry', options: fromEntry },
+ ]
+}
+
+/** Resolve the current config to the option key whose rate it computes, normalizing the equivalences
+ * above (null step = last step; `from_start` at step 1 = `prev:1`) so the dropdown always has a selection. */
+export function funnelConfigToOptionKey(config: FunnelsAlertConfig, stepCount: number): string {
+ const last = stepCount - 1
+ const index = config.funnel_step ?? last
+
+ if (config.metric === 'conversion_from_previous') {
+ // Step 1 (or below) is undefined for from-previous; fall back to overall rather than leave it blank.
+ return index <= 0 || stepCount === 2 ? OVERALL : `prev:${index}`
+ }
+ // conversion_from_start
+ if (index >= last) {
+ return OVERALL
+ }
+ if (index <= 1) {
+ return stepCount === 2 ? OVERALL : 'prev:1'
+ }
+ return `start:${index}`
+}
+
+/** Map a selected option key back to the config fields it sets. */
+export function funnelConfigForOptionKey(key: string): Pick<FunnelsAlertConfig, 'metric' | 'funnel_step'> {
+ if (key === OVERALL) {
+ return { metric: 'conversion_from_start', funnel_step: null }
+ }
+ const [kind, indexStr] = key.split(':')
+ const index = Number(indexStr)
+ return kind === 'prev'
+ ? { metric: 'conversion_from_previous', funnel_step: index }
+ : { metric: 'conversion_from_start', funnel_step: index }
+}
diff --git a/frontend/src/lib/components/Alerts/funnelAlertPreview.ts b/frontend/src/lib/components/Alerts/funnelAlertPreview.ts
new file mode 100644
index 000000000000..a3b81233dd0a
--- /dev/null
+++ b/frontend/src/lib/components/Alerts/funnelAlertPreview.ts
@@ -0,0 +1,100 @@
+import { InsightsThresholdBounds } from '~/queries/schema/schema-general'
+
+import { hasThresholdBounds, valueBreachesBounds } from './alertPreviewShared'
+import { AlertConfig, isFunnelsAlertConfig } from './types'
+
+export interface FunnelAlertPreviewValue {
+ label: string | null // breakdown value; null for a non-breakdown funnel
+ rate: number // 0–100
+ breaching: boolean
+}
+
+/** Advisory preview, mirroring the backend `_conversion_rate`/`_steps_per_breakdown`
+ * (products/alerts/backend/evaluation/funnels.py) — keep in sync if you change the backend math. */
+export type FunnelAlertPreview =
+ | { status: 'no-data' }
+ | { status: 'ok'; values: FunnelAlertPreviewValue[]; isBreakdown: boolean; hasBounds: boolean }
+
+interface FunnelStep {
+ count: number
+ breakdown_value?: unknown
+}
+
+const _conversionRate = (steps: FunnelStep[], stepIndex: number, fromPrevious: boolean): number | null => {
+ if (stepIndex < 0 || stepIndex >= steps.length) {
+ return null
+ }
+ const baseIndex = fromPrevious ? stepIndex - 1 : 0
+ if (baseIndex < 0) {
+ return null // conversion_from_previous is undefined at the first step
+ }
+ const base = steps[baseIndex]?.count ?? 0
+ const target = steps[stepIndex]?.count ?? 0
+ return base === 0 ? 0 : (target / base) * 100
+}
+
+const _breakdownLabel = (steps: FunnelStep[]): string | null => {
+ const breakdown = steps[0]?.breakdown_value
+ if (breakdown == null) {
+ return null
+ }
+ return Array.isArray(breakdown) ? breakdown.join(', ') : String(breakdown)
+}
+
+// Current unless explicitly tagged as another compare period; non-compared rows have no label.
+// Positive check so any future compare label is excluded too.
+const _isCurrentPeriodRow = (row: any): boolean =>
+ row == null || typeof row !== 'object' || row.compare_label == null || row.compare_label === 'current'
+
+/** Keep only current-period rows from a compare-enabled funnel result (mirror of the backend's
+ * `_current_period_only`); no-op when compare is off. */
+function _currentPeriodOnly(result: any[]): any[] {
+ if (Array.isArray(result[0])) {
+ // Breakdown: the runner emits previous-period breakdowns as their own groups that filter to
+ // empty — drop them, or they'd surface as a misleading whole-preview "no-data".
+ return result
+ .map((steps) => (Array.isArray(steps) ? steps.filter((row) => _isCurrentPeriodRow(row)) : steps))
+ .filter((steps) => !Array.isArray(steps) || steps.length > 0)
+ }
+ return result.filter((row) => _isCurrentPeriodRow(row))
+}
+
+export function deriveFunnelAlertPreview(
+ insightData: Record<string, any> | null,
+ config: AlertConfig | null | undefined,
+ bounds: InsightsThresholdBounds | null | undefined
+): FunnelAlertPreview | null {
+ if (!isFunnelsAlertConfig(config)) {
+ return null
+ }
+ const rawResult = insightData?.result
+ if (!Array.isArray(rawResult) || rawResult.length === 0) {
+ return null // No result loaded yet — fall back to the static hint
+ }
+ // Compare-enabled funnels concatenate current + previous period rows (tagged compare_label).
+ // Alerts evaluate the current period, so drop previous rows before normalizing (mirrors the backend).
+ const result = _currentPeriodOnly(rawResult)
+ if (result.length === 0) {
+ // Data existed but was all previous-period (compare on, no current rows) — show no-data, not
+ // the "not loaded yet" hint.
+ return { status: 'no-data' }
+ }
+ // A non-breakdown funnel returns list[step]; a breakdown funnel returns list[list[step]].
+ const isBreakdown = Array.isArray(result[0])
+ const breakdowns: FunnelStep[][] = isBreakdown ? result : [result]
+ if (breakdowns.some((steps) => !Array.isArray(steps) || steps.length === 0)) {
+ return { status: 'no-data' }
+ }
+
+ const fromPrevious = config.metric === 'conversion_from_previous'
+ const values: FunnelAlertPreviewValue[] = []
+ for (const steps of breakdowns) {
+ const stepIndex = config.funnel_step ?? steps.length - 1
+ const rate = _conversionRate(steps, stepIndex, fromPrevious)
+ if (rate === null) {
+ return null // out-of-range / undefined config — the picker and validation prevent this
+ }
+ values.push({ label: _breakdownLabel(steps), rate, breaching: valueBreachesBounds(rate, bounds) })
+ }
+ return { status: 'ok', values, isBreakdown, hasBounds: hasThresholdBounds(bounds) }
+}
diff --git a/frontend/src/lib/components/Alerts/hogqlAlertPreview.ts b/frontend/src/lib/components/Alerts/hogqlAlertPreview.ts
index fc091633ef09..2d4575670f4b 100644
--- a/frontend/src/lib/components/Alerts/hogqlAlertPreview.ts
+++ b/frontend/src/lib/components/Alerts/hogqlAlertPreview.ts
@@ -1,5 +1,6 @@
import { InsightsThresholdBounds } from '~/queries/schema/schema-general'
+import { hasThresholdBounds, valueBreachesBounds } from './alertPreviewShared'
import { AlertConfig, isHogQLAlertConfig } from './types'
/** Mirror of the backend's ANY_ROW_MAX_ROWS (products/alerts/backend/evaluation/hogql.py) — keep
@@ -145,17 +146,14 @@ export function deriveHogQLAlertPreview(
}
// Per-row view (and backtest): with absolute bounds, mark which rows would breach right now.
- const hasBounds = !!bounds && (bounds.lower != null || bounds.upper != null)
+ const bounded = hasThresholdBounds(bounds)
const previewRows: HogQLAlertPreviewRow[] = rows.map((row, i) => {
const value = _cellValue(row, valueIndex)
const labelCell = labelIndex !== null && Array.isArray(row) && labelIndex < row.length ? row[labelIndex] : null
return {
label: labelCell != null ? String(labelCell) : `row ${i + 1}`,
value,
- breaching:
- hasBounds &&
- value !== null &&
- ((bounds.lower != null && value < bounds.lower) || (bounds.upper != null && value > bounds.upper)),
+ breaching: valueBreachesBounds(value, bounds),
}
})
@@ -170,7 +168,7 @@ export function deriveHogQLAlertPreview(
currentValue,
previousValue,
rowCount: rows.length,
- breachingRows: hasBounds ? previewRows.filter((row) => row.breaching).length : null,
+ breachingRows: bounded ? previewRows.filter((row) => row.breaching).length : null,
rows: previewRows,
}
}
diff --git a/frontend/src/lib/components/Alerts/insightAlertsLogic.test.ts b/frontend/src/lib/components/Alerts/insightAlertsLogic.test.ts
index 88c0e9997095..e0fcb9360e13 100644
--- a/frontend/src/lib/components/Alerts/insightAlertsLogic.test.ts
+++ b/frontend/src/lib/components/Alerts/insightAlertsLogic.test.ts
@@ -9,7 +9,7 @@ import { NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { InsightLogicProps, InsightShortId } from '~/types'
-import { areAlertsSupportedForInsight, insightAlertsLogic } from './insightAlertsLogic'
+import { alertsUnsupportedReason, areAlertsSupportedForInsight, insightAlertsLogic } from './insightAlertsLogic'
import type { AlertType } from './types'
const Insight42 = '42' as InsightShortId
@@ -219,10 +219,14 @@ describe('areAlertsSupportedForInsight', () => {
expect(areAlertsSupportedForInsight(API_QUERY)).toBe(true)
})
- it('returns false for funnel insight viz', () => {
+ it('returns false for funnel insight viz when the funnel flag is off', () => {
expect(areAlertsSupportedForInsight(FUNNEL_QUERY)).toBe(false)
})
+ it('returns true for funnel insight viz when funnelAlertsEnabled', () => {
+ expect(areAlertsSupportedForInsight(FUNNEL_QUERY, { funnelAlertsEnabled: true })).toBe(true)
+ })
+
it('returns false when trendsFilter is null', () => {
const query = {
...API_QUERY,
@@ -234,3 +238,16 @@ describe('areAlertsSupportedForInsight', () => {
expect(areAlertsSupportedForInsight(query)).toBe(false)
})
})
+
+describe('alertsUnsupportedReason', () => {
+ it.each([
+ ['only trends (no flags)', {}, ['trends'], ['SQL', 'funnel']],
+ ['trends + SQL', { hogqlAlertsEnabled: true }, ['trends', 'SQL'], ['funnel']],
+ ['trends + funnel', { funnelAlertsEnabled: true }, ['trends', 'funnel'], ['SQL']],
+ ['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))
+ })
+})
diff --git a/frontend/src/lib/components/Alerts/insightAlertsLogic.ts b/frontend/src/lib/components/Alerts/insightAlertsLogic.ts
index fb22f97eb542..ea9d0e787bdf 100644
--- a/frontend/src/lib/components/Alerts/insightAlertsLogic.ts
+++ b/frontend/src/lib/components/Alerts/insightAlertsLogic.ts
@@ -8,7 +8,13 @@ import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { AlertConditionType, BreakdownFilter, GoalLine, InsightThresholdType } from '~/queries/schema/schema-general'
-import { containsHogQLQuery, hasBreakdownFilter, isInsightVizNode, isTrendsQuery } from '~/queries/utils'
+import {
+ containsHogQLQuery,
+ hasBreakdownFilter,
+ isFunnelsQuery,
+ isInsightVizNode,
+ isTrendsQuery,
+} from '~/queries/utils'
import { InsightLogicProps } from '~/types'
import type { insightAlertsLogicType } from './insightAlertsLogicType'
@@ -27,7 +33,7 @@ export interface InsightAlertsLogicProps {
export const areAlertsSupportedForInsight = (
query?: Record<string, any> | null,
- options: { hogqlAlertsEnabled?: boolean } = {}
+ options: { hogqlAlertsEnabled?: boolean; funnelAlertsEnabled?: boolean } = {}
): boolean => {
if (!query) {
return false
@@ -35,9 +41,23 @@ export const areAlertsSupportedForInsight = (
if (isInsightVizNode(query) && isTrendsQuery(query.source) && query.source.trendsFilter !== null) {
return true
}
+ if (options.funnelAlertsEnabled && isInsightVizNode(query) && isFunnelsQuery(query.source)) {
+ return true
+ }
return !!options.hogqlAlertsEnabled && containsHogQLQuery(query)
}
+// 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 =>
+ ['trends', options.hogqlAlertsEnabled && 'SQL', options.funnelAlertsEnabled && 'funnel'].filter(Boolean).join(', ')
+
+export const alertsUnsupportedReason = (options: {
+ hogqlAlertsEnabled?: boolean
+ funnelAlertsEnabled?: boolean
+}): string =>
+ `Alerts are only available for ${alertableInsightTypesLabel(options)} insights. Change the insight representation to add alerts.`
+
/** Map absolute-threshold alerts to chart goal lines (shared by trends and SQL charts). */
export function alertsToThresholdGoalLines(alerts: AlertType[]): GoalLine[] {
return alerts.flatMap((alert) => {
@@ -220,7 +240,11 @@ export const insightAlertsLogic = kea<insightAlertsLogicType>([
listeners(({ actions, values }) => ({
setQuery: ({ query }) => {
const hogqlAlertsEnabled = !!values.featureFlags[FEATURE_FLAGS.HOGQL_INSIGHT_ALERTS]
- if (values.alerts.length === 0 || areAlertsSupportedForInsight(query, { hogqlAlertsEnabled })) {
+ const funnelAlertsEnabled = !!values.featureFlags[FEATURE_FLAGS.FUNNEL_INSIGHT_ALERTS]
+ if (
+ values.alerts.length === 0 ||
+ areAlertsSupportedForInsight(query, { hogqlAlertsEnabled, funnelAlertsEnabled })
+ ) {
actions.setShouldShowAlertDeletionWarning(false)
} else {
actions.setShouldShowAlertDeletionWarning(true)
diff --git a/frontend/src/lib/components/Alerts/types.ts b/frontend/src/lib/components/Alerts/types.ts
index d2b4aa606ce9..ecf79894f0a0 100644
--- a/frontend/src/lib/components/Alerts/types.ts
+++ b/frontend/src/lib/components/Alerts/types.ts
@@ -5,13 +5,14 @@ import {
AlertScheduleRestrictionWindow,
AlertState,
DetectorConfig,
+ FunnelsAlertConfig,
HogQLAlertConfig,
InsightThreshold,
TrendsAlertConfig,
} from '~/queries/schema/schema-general'
import { QueryBasedInsightModel, UserBasicType } from '~/types'
-export type AlertConfig = TrendsAlertConfig | HogQLAlertConfig
+export type AlertConfig = TrendsAlertConfig | HogQLAlertConfig | FunnelsAlertConfig
export const isTrendsAlertConfig = (config: AlertConfig | null | undefined): config is TrendsAlertConfig =>
config?.type === 'TrendsAlertConfig'
@@ -19,6 +20,9 @@ export const isTrendsAlertConfig = (config: AlertConfig | null | undefined): con
export const isHogQLAlertConfig = (config: AlertConfig | null | undefined): config is HogQLAlertConfig =>
config?.type === 'HogQLAlertConfig'
+export const isFunnelsAlertConfig = (config: AlertConfig | null | undefined): config is FunnelsAlertConfig =>
+ config?.type === 'FunnelsAlertConfig'
+
/** SQL alert in any-row mode: every result row is checked (one entity per row), which changes
* row labeling and history rendering versus the single-value modes. */
export const isAnyRowHogQLConfig = (config: AlertConfig | null | undefined): boolean =>
diff --git a/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx b/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx
index afbefe2d4c07..5b6e6c5c420e 100644
--- a/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx
+++ b/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx
@@ -14,13 +14,14 @@ import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { formatDate } from 'lib/utils/datetime'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
+import { getDisplayNameFromEntityNode } from 'scenes/insights/utils'
import { teamLogic } from 'scenes/teamLogic'
import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { AlertCalculationInterval, AlertState } from '~/queries/schema/schema-general'
-import { containsHogQLQuery } from '~/queries/utils'
+import { containsHogQLQuery, isFunnelsQuery, isInsightVizNode } from '~/queries/utils'
import { AvailableFeature, InsightLogicProps, InsightShortId, QueryBasedInsightModel } from '~/types'
import { AlertAdvancedOptionsSection } from 'products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection'
@@ -80,7 +81,16 @@ export function EditAlertModal({
const { query } = useValues(insightVizDataLogic(insightLogicProps ?? { dashboardItemId: insightShortId }))
- const insightAlertKind: 'hogql' | 'trends' = containsHogQLQuery(query) ? 'hogql' : 'trends'
+ const funnelSource = !!query && isInsightVizNode(query) && isFunnelsQuery(query.source) ? query.source : null
+ const isFunnelInsight = funnelSource !== null
+ const funnelStepLabels = (funnelSource?.series ?? []).map(
+ (node, index) => getDisplayNameFromEntityNode(node) ?? `Step ${index + 1}`
+ )
+ const insightAlertKind: 'hogql' | 'funnels' | 'trends' = containsHogQLQuery(query)
+ ? 'hogql'
+ : isFunnelInsight
+ ? 'funnels'
+ : 'trends'
const formLogicProps = {
alert,
@@ -100,6 +110,7 @@ export function EditAlertModal({
simulationDateFrom,
thresholdBoundsFormError,
hogqlAlertPreview,
+ funnelAlertPreview,
hogqlResultColumns,
hogqlValueColumnOptions,
hogqlLabelColumnOptions,
@@ -263,6 +274,8 @@ export function EditAlertModal({
isNonTimeSeriesDisplay={isNonTimeSeriesDisplay}
alertSeries={alertSeries}
formulaNodes={formulaNodes}
+ funnelStepLabels={funnelStepLabels}
+ funnelPreview={funnelAlertPreview}
hogqlPreview={hogqlAlertPreview}
hogqlColumns={hogqlResultColumns}
hogqlValueColumnOptions={hogqlValueColumnOptions}
diff --git a/frontend/src/lib/components/Alerts/views/ManageAlertsModal.tsx b/frontend/src/lib/components/Alerts/views/ManageAlertsModal.tsx
index 827045ed5189..a2fcc8d0de14 100644
--- a/frontend/src/lib/components/Alerts/views/ManageAlertsModal.tsx
+++ b/frontend/src/lib/components/Alerts/views/ManageAlertsModal.tsx
@@ -3,6 +3,7 @@ import { router } from 'kea-router'
import { Link } from '@posthog/lemon-ui'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { LemonTag } from 'lib/lemon-ui/LemonTag'
@@ -14,7 +15,7 @@ import { urls } from 'scenes/urls'
import { AlertState, InsightThresholdType } from '~/queries/schema/schema-general'
import { InsightShortId } from '~/types'
-import { InsightAlertsLogicProps, insightAlertsLogic } from '../insightAlertsLogic'
+import { InsightAlertsLogicProps, alertsUnsupportedReason, insightAlertsLogic } from '../insightAlertsLogic'
import { AlertType } from '../types'
export function AlertStateIndicator({ alert }: { alert: AlertType }): JSX.Element {
@@ -102,6 +103,8 @@ export function ManageAlertsModal(props: ManageAlertsModalProps): JSX.Element {
const logic = insightAlertsLogic(props)
const { alerts, alertsLoading } = useValues(logic)
+ const hogqlAlertsEnabled = useFeatureFlag('HOGQL_INSIGHT_ALERTS')
+ const funnelAlertsEnabled = useFeatureFlag('FUNNEL_INSIGHT_ALERTS')
const showDeferredListSpinner = props.deferInitialAlertsLoad && props.isOpen && alertsLoading
@@ -153,7 +156,7 @@ export function ManageAlertsModal(props: ManageAlertsModalProps): JSX.Element {
onClick={() => push(urls.insightAlert(props.insightShortId, 'new'))}
disabledReason={
!props.canCreateAlertForInsight
- ? 'Alerts are only available for trends. Change the insight representation to add alerts.'
+ ? alertsUnsupportedReason({ hogqlAlertsEnabled, funnelAlertsEnabled })
: undefined
}
>
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index 57658faccb9b..a7a2cd6418b5 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -196,6 +196,7 @@ export function InsightMeta({
const showDashboardAlertsMenuItem = isUsedAsDashboardTile && !!dashboardId && !!insight.id && canViewInsight
const canCreateAlertForInsight = areAlertsSupportedForInsight(query, {
hogqlAlertsEnabled: !!featureFlags[FEATURE_FLAGS.HOGQL_INSIGHT_ALERTS],
+ funnelAlertsEnabled: !!featureFlags[FEATURE_FLAGS.FUNNEL_INSIGHT_ALERTS],
})
const showDisplayOptionsMenu = isUsedAsDashboardTile && canEditInsight && !!persistDisplayOptions
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index f596cb05ca74..5ebf6b115a0e 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -21954,6 +21954,11 @@
"required": ["action", "form_answers"],
"type": "object"
},
+ "FunnelConversionMetric": {
+ "description": "How a funnel alert measures conversion at its step. `conversion_from_start` = step count / first-step count; `conversion_from_previous` = step count / previous-step count.",
+ "enum": ["conversion_from_start", "conversion_from_previous"],
+ "type": "string"
+ },
"FunnelConversionWindowTimeUnit": {
"enum": ["second", "minute", "hour", "day", "week", "month"],
"type": "string"
@@ -22481,6 +22486,32 @@
"required": ["kind", "source"],
"type": "object"
},
+ "FunnelsAlertConfig": {
+ "additionalProperties": false,
+ "description": "Alert config for funnel insights. Evaluates the conversion rate (as a percentage) at one step.",
+ "properties": {
+ "funnel_step": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Zero-based step index to evaluate. Null = the last step (overall conversion)."
+ },
+ "metric": {
+ "$ref": "#/definitions/FunnelConversionMetric"
+ },
+ "type": {
+ "const": "FunnelsAlertConfig",
+ "type": "string"
+ }
+ },
+ "required": ["type", "metric"],
+ "type": "object"
+ },
"FunnelsDataWarehouseNode": {
"additionalProperties": false,
"properties": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 332489d43f35..f5f74116d4f2 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -4907,6 +4907,18 @@ export interface HogQLAlertConfig {
label_column?: string | null
}
+/** How a funnel alert measures conversion at its step.
+ * `conversion_from_start` = step count / first-step count; `conversion_from_previous` = step count / previous-step count. */
+export type FunnelConversionMetric = 'conversion_from_start' | 'conversion_from_previous'
+
+/** Alert config for funnel insights. Evaluates the conversion rate (as a percentage) at one step. */
+export interface FunnelsAlertConfig {
+ type: 'FunnelsAlertConfig'
+ /** Zero-based step index to evaluate. Null = the last step (overall conversion). */
+ funnel_step?: integer | null
+ metric: FunnelConversionMetric
+}
+
/** One blocked period for quiet hours: 24-hour HH:MM in the project timezone; interval is half-open [start, end). */
export interface AlertScheduleRestrictionWindow {
start: string
diff --git a/frontend/src/scenes/insights/InsightModals.tsx b/frontend/src/scenes/insights/InsightModals.tsx
index f8fc3c0894da..d1818c059939 100644
--- a/frontend/src/scenes/insights/InsightModals.tsx
+++ b/frontend/src/scenes/insights/InsightModals.tsx
@@ -92,7 +92,8 @@ function InsightAlertsModals({ insightLogicProps }: { insightLogicProps: Insight
const { push } = useActions(router)
const hogqlAlertsEnabled = useFeatureFlag('HOGQL_INSIGHT_ALERTS')
- const canCreateAlertForInsight = areAlertsSupportedForInsight(query, { hogqlAlertsEnabled })
+ const funnelAlertsEnabled = useFeatureFlag('FUNNEL_INSIGHT_ALERTS')
+ const canCreateAlertForInsight = areAlertsSupportedForInsight(query, { hogqlAlertsEnabled, funnelAlertsEnabled })
return (
<>
diff --git a/frontend/src/scenes/insights/InsightPageHeader.tsx b/frontend/src/scenes/insights/InsightPageHeader.tsx
index 31d96cb88d09..e65ccae07299 100644
--- a/frontend/src/scenes/insights/InsightPageHeader.tsx
+++ b/frontend/src/scenes/insights/InsightPageHeader.tsx
@@ -84,7 +84,8 @@ export function InsightPageHeader({ insightLogicProps }: { insightLogicProps: In
typeof lastBreadcrumb?.name === 'string' ? lastBreadcrumb.name : insight.name || insight.derived_name
const hogqlAlertsEnabled = useFeatureFlag('HOGQL_INSIGHT_ALERTS')
- const canCreateAlertForInsight = areAlertsSupportedForInsight(query, { hogqlAlertsEnabled })
+ const funnelAlertsEnabled = useFeatureFlag('FUNNEL_INSIGHT_ALERTS')
+ const canCreateAlertForInsight = areAlertsSupportedForInsight(query, { hogqlAlertsEnabled, funnelAlertsEnabled })
const insightDisplayName = insight?.name || insight?.derived_name
diff --git a/posthog/schema.py b/posthog/schema.py
index 297b94b4eee3..5bfb93e94df3 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -105,6 +105,7 @@ from posthog.schema_enums import (
FileSystemIconType as FileSystemIconType,
FilterLogicalOperator as FilterLogicalOperator,
FunnelAggregateByHogQL as FunnelAggregateByHogQL,
+ FunnelConversionMetric as FunnelConversionMetric,
FunnelConversionWindowTimeUnit as FunnelConversionWindowTimeUnit,
FunnelCorrelationResultsType as FunnelCorrelationResultsType,
FunnelLayout as FunnelLayout,
@@ -5247,6 +5248,18 @@ class FunnelExclusionSteps(BaseModel):
funnelToStep: int
+class FunnelsAlertConfig(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ funnel_step: int | None = Field(
+ default=None,
+ description=("Zero-based step index to evaluate. Null = the last step (overall conversion)."),
+ )
+ metric: FunnelConversionMetric
+ type: Literal["FunnelsAlertConfig"] = "FunnelsAlertConfig"
+
+
class FunnelsFilterLegacy(BaseModel):
model_config = ConfigDict(
extra="forbid",
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index fbbae6ff41b9..7195d91b3c92 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -1915,6 +1915,11 @@ class FilterLogicalOperator(StrEnum):
OR_ = "OR"
+class FunnelConversionMetric(StrEnum):
+ CONVERSION_FROM_START = "conversion_from_start"
+ CONVERSION_FROM_PREVIOUS = "conversion_from_previous"
+
+
class FunnelConversionWindowTimeUnit(StrEnum):
SECOND = "second"
MINUTE = "minute"
diff --git a/posthog/tasks/alerts/test/test_validate_alert_config.py b/posthog/tasks/alerts/test/test_validate_alert_config.py
index f6a31fce1343..d192205a5176 100644
--- a/posthog/tasks/alerts/test/test_validate_alert_config.py
+++ b/posthog/tasks/alerts/test/test_validate_alert_config.py
@@ -33,6 +33,17 @@ def _hogql_query() -> dict[str, Any]:
return {"kind": "HogQLQuery", "query": "SELECT count() FROM events"}
+def _funnels_config(metric: str = "conversion_from_start") -> dict[str, Any]:
+ return {"type": "FunnelsAlertConfig", "metric": metric, "funnel_step": None}
+
+
+def _funnels_query() -> dict[str, Any]:
+ return {
+ "kind": "FunnelsQuery",
+ "series": [{"kind": "EventsNode", "event": "a"}, {"kind": "EventsNode", "event": "b"}],
+ }
+
+
def _base_threshold(type: str = "absolute", bounds: dict[str, Any] | None = None) -> dict[str, Any]:
config: dict[str, Any] = {"type": type}
if bounds is None:
@@ -280,6 +291,78 @@ class TestValidateAlertConfig:
"daily",
"Absolute value alerts require an absolute threshold",
),
+ (
+ "valid_funnels_config",
+ _funnels_query(),
+ _base_condition("absolute_value"),
+ _funnels_config(),
+ _base_threshold(),
+ "daily",
+ None,
+ ),
+ (
+ "funnels_config_with_trends_query_rejected",
+ _base_query(),
+ _base_condition("absolute_value"),
+ _funnels_config(),
+ _base_threshold(),
+ "daily",
+ "Funnel alert config requires a FunnelsQuery insight",
+ ),
+ (
+ "funnels_relative_decrease_rejected",
+ _funnels_query(),
+ _base_condition("relative_decrease"),
+ _funnels_config(),
+ _base_threshold(),
+ "daily",
+ "Funnel alerts only support absolute value conditions",
+ ),
+ (
+ "funnels_relative_increase_rejected",
+ _funnels_query(),
+ _base_condition("relative_increase"),
+ _funnels_config(),
+ _base_threshold(),
+ "daily",
+ "Funnel alerts only support absolute value conditions",
+ ),
+ (
+ "funnels_from_previous_at_step_zero_rejected",
+ _funnels_query(),
+ _base_condition("absolute_value"),
+ {"type": "FunnelsAlertConfig", "metric": "conversion_from_previous", "funnel_step": 0},
+ _base_threshold(),
+ "daily",
+ "undefined at the first step",
+ ),
+ (
+ "funnels_negative_step_rejected",
+ _funnels_query(),
+ _base_condition("absolute_value"),
+ {"type": "FunnelsAlertConfig", "metric": "conversion_from_start", "funnel_step": -1},
+ _base_threshold(),
+ "daily",
+ "funnel_step must be >= 0",
+ ),
+ (
+ "funnels_step_out_of_range_rejected",
+ _funnels_query(), # a 2-step funnel
+ _base_condition("absolute_value"),
+ {"type": "FunnelsAlertConfig", "metric": "conversion_from_start", "funnel_step": 5},
+ _base_threshold(),
+ "daily",
+ r"funnel_step 5 is out of range \(funnel has 2 steps\)",
+ ),
+ (
+ "funnels_non_steps_viz_rejected",
+ {**_funnels_query(), "funnelsFilter": {"funnelVizType": "time_to_convert"}},
+ _base_condition("absolute_value"),
+ _funnels_config(),
+ _base_threshold(),
+ "daily",
+ "Funnel alerts require a steps funnel",
+ ),
]
)
def test_validate_alert_config(
diff --git a/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr b/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr
index 0839c952c78f..a1c0325ab25a 100644
--- a/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr
+++ b/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr
@@ -11,6 +11,14 @@
OR query @? '$.** ? (
@.kind == "InsightVizNode" &&
(!exists(@.version) || @.version == null || @.version < 4)
+ )'
+ OR query @? '$.** ? (
+ @.kind == "RetentionQuery" &&
+ (!exists(@.version) || @.version == null || @.version < 2)
+ )'
+ OR query @? '$.** ? (
+ @.kind == "StickinessQuery" &&
+ (!exists(@.version) || @.version == null || @.version < 2)
)'
OR query @? '$.** ? (
@.kind == "TrendsQuery" &&
diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.py
index e16c827cbe9d..dfa203b2196f 100644
--- a/products/alerts/backend/api/alert.py
+++ b/products/alerts/backend/api/alert.py
@@ -20,6 +20,7 @@ from posthog.schema import (
AlertCondition,
AlertState,
DetectorConfig,
+ FunnelsAlertConfig,
HogQLAlertConfig,
InsightThreshold,
NodeKind,
@@ -83,7 +84,7 @@ class AlertConfigUnion(RootModel):
"""Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the
generated frontend types and MCP tool schemas) in sync with every kind alerts support."""
- root: Annotated[TrendsAlertConfig | HogQLAlertConfig, PydanticField(discriminator="type")]
+ root: Annotated[TrendsAlertConfig | HogQLAlertConfig | FunnelsAlertConfig, PydanticField(discriminator="type")]
@extend_schema_field(AlertConfigUnion) # type: ignore[arg-type]
@@ -226,7 +227,10 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
"interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to "
"the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, "
"'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and "
- "label_column (names the evaluated row(s) in breach messages, in every evaluation mode)."
+ "label_column (names the evaluated row(s) in breach messages, in every evaluation mode). "
+ "FunnelsAlertConfig (funnel insights): funnel_step (the step to monitor, null for the overall "
+ "last step) and metric ('conversion_from_start' or 'conversion_from_previous'); funnel alerts "
+ "only support absolute_value conditions."
),
)
detector_config = DetectorConfigField(required=False, allow_null=True)
@@ -544,18 +548,26 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
raise ValidationError("Alerts are not supported for this insight.")
if kind == NodeKind.HOG_QL_QUERY and not self._hogql_alerts_enabled():
raise ValidationError("SQL insight alerts are not enabled for your account.")
+ if kind == NodeKind.FUNNELS_QUERY and not self._funnel_alerts_enabled():
+ raise ValidationError("Funnel insight alerts are not enabled for your account.")
def _hogql_alerts_enabled(self) -> bool:
+ return self._insight_alert_flag_enabled("hogql-insight-alerts")
+
+ def _funnel_alerts_enabled(self) -> bool:
+ return self._insight_alert_flag_enabled("funnel-insight-alerts")
+
+ def _insight_alert_flag_enabled(self, flag: str) -> bool:
# Scope the flag to the alert's organization (via team scope), not the user's current
# organization — otherwise a user in multiple orgs could flip their current org to a
- # flag-on org and create a SQL alert in a team where the flag is disabled. get_organization
- # is always injected by TeamAndOrgViewSetMixin; access it unconditionally so the org-scoping
+ # flag-on org and create an alert in a team where the flag is disabled. get_organization is
+ # always injected by TeamAndOrgViewSetMixin; access it unconditionally so the org-scoping
# invariant can't silently degrade to an unscoped check.
user = self.context["request"].user
org = self.context["get_organization"]()
return bool(
posthoganalytics.feature_enabled(
- "hogql-insight-alerts",
+ flag,
str(user.distinct_id),
groups={"organization": str(org.id)},
)
diff --git a/products/alerts/backend/api/test/test_alert.py b/products/alerts/backend/api/test/test_alert.py
index cd82fffae1b0..89eb347809de 100644
--- a/products/alerts/backend/api/test/test_alert.py
+++ b/products/alerts/backend/api/test/test_alert.py
@@ -131,7 +131,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
def test_existing_alert_hidden_when_insight_viewer_access_is_lost(self) -> None:
# An existing alert must not outlive viewer access to its linked insight: otherwise its
# check history (breaching rows / values) leaks on read, and a PATCH that omits `insight`
- # bypasses the create-time check. The queryset gate hides it from list, retrieve, and update.
+ # bypasses the create-time check. The queryset gate hides it from list, retrieve, update, and delete.
creation_request = {
"insight": self.insight["id"],
"subscribed_users": [self.user.id],
@@ -151,11 +151,47 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
retrieve = self.client.get(f"/api/projects/{self.team.id}/alerts/{alert_id}")
listed = self.client.get(f"/api/projects/{self.team.id}/alerts")
update = self.client.patch(f"/api/projects/{self.team.id}/alerts/{alert_id}", {"name": "renamed"})
+ delete = self.client.delete(f"/api/projects/{self.team.id}/alerts/{alert_id}")
assert retrieve.status_code == status.HTTP_404_NOT_FOUND, retrieve.content
assert update.status_code == status.HTTP_404_NOT_FOUND, update.content
+ assert delete.status_code == status.HTTP_404_NOT_FOUND, delete.content
assert [a["id"] for a in listed.json()["results"]] == []
+ def test_create_alert_on_funnel_insight_is_flag_gated(self) -> None:
+ funnel_insight = self.client.post(
+ f"/api/projects/{self.team.id}/insights",
+ data={
+ "query": {
+ "kind": "FunnelsQuery",
+ "series": [
+ {"kind": "EventsNode", "event": "$pageview"},
+ {"kind": "EventsNode", "event": "$autocapture"},
+ ],
+ }
+ },
+ ).json()
+ creation_request = {
+ "insight": funnel_insight["id"],
+ "subscribed_users": [self.user.id],
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "FunnelsAlertConfig", "metric": "conversion_from_start", "funnel_step": None},
+ "name": "funnel alert",
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 50}}},
+ "calculation_interval": "daily",
+ }
+
+ # Flag off: the insight gate rejects funnel alerts.
+ with mock.patch("products.alerts.backend.api.alert.posthoganalytics.feature_enabled", return_value=False):
+ 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 "Funnel insight alerts are not enabled" in str(response.content)
+
+ # Flag on: the same request is accepted.
+ with mock.patch("products.alerts.backend.api.alert.posthoganalytics.feature_enabled", return_value=True):
+ response = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request)
+ assert response.status_code == status.HTTP_201_CREATED, response.content
+
def test_create_threshold_alert_rejects_empty_bounds(self) -> None:
creation_request = {
"insight": self.insight["id"],
@@ -474,7 +510,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
assert response.status_code == status.HTTP_200_OK
insight_without_alert_support = deepcopy(self.default_insight_data)
- insight_without_alert_support["query"] = {"kind": "FunnelsQuery", "series": []}
+ insight_without_alert_support["query"] = {"kind": "RetentionQuery", "retentionFilter": {}}
self.client.patch(
f"/api/projects/{self.team.id}/insights/{another_insight['id']}",
data=insight_without_alert_support,
@@ -519,7 +555,51 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
# Changing to a kind that cannot carry alerts still cascades.
self.client.patch(
f"/api/projects/{self.team.id}/insights/{hogql_insight['id']}",
- data={"query": {"kind": "FunnelsQuery", "series": []}},
+ data={"query": {"kind": "RetentionQuery", "retentionFilter": {}}},
+ )
+ response = self.client.get(f"/api/projects/{self.team.id}/alerts/{alert['id']}")
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_funnel_alert_survives_insight_update_and_is_listed_on_insight(self) -> None:
+ funnel_insight_data: dict[str, Any] = {
+ "query": {
+ "kind": "FunnelsQuery",
+ "series": [
+ {"kind": "EventsNode", "event": "$pageview"},
+ {"kind": "EventsNode", "event": "$autocapture"},
+ ],
+ },
+ }
+ funnel_insight = self.client.post(f"/api/projects/{self.team.id}/insights", data=funnel_insight_data).json()
+
+ with mock.patch("products.alerts.backend.api.alert.posthoganalytics.feature_enabled", return_value=True):
+ alert = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ {
+ "insight": funnel_insight["id"],
+ "subscribed_users": [self.user.id],
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "FunnelsAlertConfig", "metric": "conversion_from_start", "funnel_step": None},
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 50}}},
+ "name": "funnel alert",
+ },
+ ).json()
+
+ # The insight response must list the alert inline — the UI trusts this list on reload.
+ insight_response = self.client.get(f"/api/projects/{self.team.id}/insights/{funnel_insight['id']}").json()
+ assert [a["id"] for a in insight_response["alerts"]] == [alert["id"]]
+
+ # Updating the insight while it stays funnel-backed must not cascade-delete the alert.
+ updated = deepcopy(funnel_insight_data)
+ updated["query"]["series"][1]["event"] = "$pageleave"
+ self.client.patch(f"/api/projects/{self.team.id}/insights/{funnel_insight['id']}", data=updated)
+ response = self.client.get(f"/api/projects/{self.team.id}/alerts/{alert['id']}")
+ assert response.status_code == status.HTTP_200_OK
+
+ # Changing to a kind that cannot carry alerts still cascades.
+ self.client.patch(
+ f"/api/projects/{self.team.id}/insights/{funnel_insight['id']}",
+ data={"query": {"kind": "RetentionQuery", "retentionFilter": {}}},
)
response = self.client.get(f"/api/projects/{self.team.id}/alerts/{alert['id']}")
assert response.status_code == status.HTTP_404_NOT_FOUND
@@ -598,6 +678,48 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
)
assert self.client.get(f"/api/projects/{self.team.id}/alerts/{alert_id}").status_code == status.HTTP_200_OK
+ def test_funnel_flag_enforced_on_config_only_patch(self) -> None:
+ # Object-level enforcement for the funnel flag, mirroring the SQL gate: a config-only PATCH
+ # (no `insight`) skips the field-level validate_insight, so validate() must re-check the flag.
+ funnel_insight = self.client.post(
+ f"/api/projects/{self.team.id}/insights",
+ data={
+ "query": {
+ "kind": "FunnelsQuery",
+ "series": [
+ {"kind": "EventsNode", "event": "$pageview"},
+ {"kind": "EventsNode", "event": "$autocapture"},
+ ],
+ }
+ },
+ ).json()
+ with mock.patch("products.alerts.backend.api.alert.posthoganalytics.feature_enabled", return_value=True):
+ alert = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ {
+ "insight": funnel_insight["id"],
+ "subscribed_users": [self.user.id],
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "FunnelsAlertConfig", "metric": "conversion_from_start", "funnel_step": None},
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 50}}},
+ "name": "funnel alert",
+ },
+ )
+ assert alert.status_code == status.HTTP_201_CREATED, alert.content
+ alert_id = alert.json()["id"]
+
+ config_patch = {
+ "config": {"type": "FunnelsAlertConfig", "metric": "conversion_from_previous", "funnel_step": 1}
+ }
+ with mock.patch("products.alerts.backend.api.alert.posthoganalytics.feature_enabled", return_value=False):
+ blocked = self.client.patch(f"/api/projects/{self.team.id}/alerts/{alert_id}", config_patch)
+ assert blocked.status_code == status.HTTP_400_BAD_REQUEST, blocked.content
+ assert "Funnel insight alerts are not enabled" in str(blocked.content)
+
+ with mock.patch("products.alerts.backend.api.alert.posthoganalytics.feature_enabled", return_value=True):
+ allowed = self.client.patch(f"/api/projects/{self.team.id}/alerts/{alert_id}", config_patch)
+ assert allowed.status_code == status.HTTP_200_OK, allowed.content
+
def test_alert_is_deleted_on_insight_soft_delete(self) -> None:
another_insight = self.client.post(
f"/api/projects/{self.team.id}/insights", data=self.default_insight_data
diff --git a/products/alerts/backend/evaluation/comparator.py b/products/alerts/backend/evaluation/comparator.py
index 8bbb197e8ab1..01a3dd1d19a7 100644
--- a/products/alerts/backend/evaluation/comparator.py
+++ b/products/alerts/backend/evaluation/comparator.py
@@ -28,9 +28,16 @@ def _breach_messages(
interval_type: IntervalType | None = None,
series: str | None = None,
is_current_interval: bool = False,
+ unit: str = "",
) -> list[str]:
is_percentage = threshold_type == InsightThresholdType.PERCENTAGE
- formatted_value = f"{calculated_value:.2%}" if is_percentage else calculated_value
+
+ # `unit` (e.g. "%" for funnel conversion rates, which are absolute 0–100 values) keeps the
+ # notification consistent with the configure-time UI. PERCENTAGE thresholds already render their own %.
+ def _fmt(value: float) -> str:
+ return f"{value:.2%}" if is_percentage else f"{value}{unit}"
+
+ formatted_value = _fmt(calculated_value)
match condition_type:
case AlertConditionType.ABSOLUTE_VALUE:
@@ -53,12 +60,14 @@ def _breach_messages(
context = ""
if bounds.lower is not None and calculated_value < bounds.lower:
- lower_value = f"{bounds.lower:.2%}" if is_percentage else bounds.lower
- return [f"{subject}{context} ({formatted_value}) {condition_text} less than lower threshold ({lower_value})"]
+ return [
+ f"{subject}{context} ({formatted_value}) {condition_text} less than lower threshold ({_fmt(bounds.lower)})"
+ ]
if bounds.upper is not None and calculated_value > bounds.upper:
- upper_value = f"{bounds.upper:.2%}" if is_percentage else bounds.upper
- return [f"{subject}{context} ({formatted_value}) {condition_text} more than upper threshold ({upper_value})"]
+ return [
+ f"{subject}{context} ({formatted_value}) {condition_text} more than upper threshold ({_fmt(bounds.upper)})"
+ ]
return []
@@ -133,6 +142,7 @@ def evaluate_threshold(
interval_type=result.interval_type,
series=s.label,
is_current_interval=s.is_current_interval,
+ unit=result.unit,
)
if breaches:
if not result.aggregate_breaches:
diff --git a/products/alerts/backend/evaluation/contract.py b/products/alerts/backend/evaluation/contract.py
index 65524a3121e5..c1d722e61c8c 100644
--- a/products/alerts/backend/evaluation/contract.py
+++ b/products/alerts/backend/evaluation/contract.py
@@ -38,6 +38,7 @@ class ExtractionResult:
interval_type: IntervalType | None = None # breach-message interval framing (time-series trends only)
subject: str = "The insight value" # breach-message subject
framed: bool = True # include the "(label) for current/previous interval" framing
+ unit: str = "" # appended to breach-message values (e.g. "%" for funnel conversion rates)
# Detector-path-only: True means the query returned zero rows, so the metric is genuinely 0. An
# empty ``series`` with this False instead means rows existed but none were long enough to score —
# the detector reports that as an uncomputed value (None). Threshold extractors never set this
diff --git a/products/alerts/backend/evaluation/dispatcher.py b/products/alerts/backend/evaluation/dispatcher.py
index 6ffec43c82d3..49542a08eb00 100644
--- a/products/alerts/backend/evaluation/dispatcher.py
+++ b/products/alerts/backend/evaluation/dispatcher.py
@@ -7,6 +7,7 @@ from posthog.utils import get_from_dict_or_attr
from products.alerts.backend.evaluation.comparator import evaluate_threshold
from products.alerts.backend.evaluation.contract import DetectorExtractor, Extractor
from products.alerts.backend.evaluation.detector import TrendsDetectorExtractor, evaluate_with_detector
+from products.alerts.backend.evaluation.funnels import FunnelsExtractor
from products.alerts.backend.evaluation.hogql import HogQLDetectorExtractor, HogQLExtractor
from products.alerts.backend.evaluation.trends import TrendsExtractor
from products.alerts.backend.models.alert import AlertConfiguration
@@ -16,6 +17,7 @@ from products.product_analytics.backend.models.insight import Insight
EXTRACTORS: dict[NodeKind, Extractor] = {
NodeKind.TRENDS_QUERY: TrendsExtractor(),
NodeKind.HOG_QL_QUERY: HogQLExtractor(),
+ NodeKind.FUNNELS_QUERY: FunnelsExtractor(),
}
# The anomaly-detector path mirrors EXTRACTORS: one detector extractor per kind, scored by the shared
diff --git a/products/alerts/backend/evaluation/funnels.py b/products/alerts/backend/evaluation/funnels.py
new file mode 100644
index 000000000000..60208ec8b9ae
--- /dev/null
+++ b/products/alerts/backend/evaluation/funnels.py
@@ -0,0 +1,157 @@
+from typing import Any, cast
+
+from posthog.schema import (
+ AlertCondition,
+ AlertConditionType,
+ FunnelConversionMetric,
+ FunnelsAlertConfig,
+ FunnelsQuery,
+ FunnelVizType,
+)
+
+from posthog.api.services.query import ExecutionMode
+from posthog.caching.calculate_results import calculate_for_query_based_insight
+from posthog.event_usage import EventSource
+
+from products.alerts.backend.evaluation.contract import (
+ AlertExtractionError,
+ ComparableSeries,
+ ExtractionResult,
+ SeriesPoint,
+)
+from products.alerts.backend.models.alert import AlertConfiguration
+from products.product_analytics.backend.models.insight import Insight
+
+_FUNNEL_SUBJECT = "The funnel conversion rate"
+
+
+class FunnelsExtractor:
+ """Normalize a funnel insight into a conversion-rate ``ComparableSeries`` (a percentage) per breakdown.
+
+ A breakdown funnel yields one series per breakdown value and fires if ANY breaches (matching trends).
+ """
+
+ def extract(self, alert: AlertConfiguration, insight: Insight, query: Any) -> ExtractionResult:
+ funnels_query = FunnelsQuery.model_validate(query)
+ viz = funnels_query.funnelsFilter.funnelVizType if funnels_query.funnelsFilter else None
+ if viz not in (None, FunnelVizType.STEPS):
+ raise AlertExtractionError(
+ f"Funnel alerts require a steps funnel, but this insight uses '{viz}'. "
+ "Switch the funnel to the steps view to alert on conversion."
+ )
+
+ if not (alert.config and alert.config.get("type") == "FunnelsAlertConfig"):
+ raise AlertExtractionError(f"Unsupported alert config type: {alert.config}")
+ config = FunnelsAlertConfig.model_validate(alert.config)
+
+ condition = AlertCondition.model_validate(alert.condition)
+ if condition.type != AlertConditionType.ABSOLUTE_VALUE:
+ raise AlertExtractionError("Funnel alerts only support absolute value conditions.")
+
+ calculation_result = calculate_for_query_based_insight(
+ insight,
+ team=alert.team,
+ execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
+ user=alert.created_by,
+ analytics_props={"source": EventSource.ALERT},
+ )
+
+ breakdowns = _steps_per_breakdown(_current_period_only(calculation_result.result), alert)
+ series = [
+ ComparableSeries(
+ label=_breakdown_label(steps),
+ points=[SeriesPoint(date=None, value=_conversion_rate(steps, config))],
+ current_index=0,
+ )
+ for steps in breakdowns
+ ]
+ return ExtractionResult(
+ series=series,
+ is_breakdown=len(breakdowns) > 1,
+ subject=_FUNNEL_SUBJECT,
+ framed=False,
+ unit="%", # conversion rates are 0–100 percentages; match the configure-time UI
+ )
+
+
+def _is_current_period_row(row: Any) -> bool:
+ # Current unless explicitly tagged as another compare period; non-compared rows carry no
+ # compare_label and count as current. Positive check so any future compare label is excluded too.
+ return not isinstance(row, dict) or row.get("compare_label") in (None, "current")
+
+
+def _current_period_only(result: Any) -> Any:
+ """Keep only current-period rows from a compare-enabled funnel result before normalizing.
+
+ With compare-to-previous on, the funnel runner concatenates current + previous rows (each tagged
+ ``compare_label``). Funnel alerts evaluate the current period; without this, ``funnel_step: null``
+ (the default) would resolve to a previous-period last row and mix periods. No-op when compare is off.
+
+ For a breakdown funnel the runner emits the previous-period breakdowns as their own groups, which
+ filter down to empty — drop those, or an empty group would resolve ``funnel_step`` to -1 and raise.
+ """
+ if not isinstance(result, list):
+ return result
+ if result and isinstance(result[0], list):
+ filtered = [[row for row in steps if _is_current_period_row(row)] for steps in result]
+ return [steps for steps in filtered if steps]
+ return [row for row in result if _is_current_period_row(row)]
+
+
+def _steps_per_breakdown(result: Any, alert: AlertConfiguration) -> list[list[dict[str, Any]]]:
+ """Normalize the funnel result into a list of step-lists (one per breakdown value).
+
+ A non-breakdown funnel returns ``list[step]``; a breakdown funnel returns ``list[list[step]]``.
+ """
+ # ``None`` means the query layer swallowed an error — raise (not AlertExtractionError) to avoid
+ # a misfire, matching the trends/SQL extractors. An empty/wrong-shaped result is a config-level
+ # "no data" case routed to the errored-alert path.
+ if result is None:
+ raise RuntimeError(f"No results found for insight with alert id = {alert.id}")
+ if not result or not isinstance(result, list):
+ raise AlertExtractionError("Funnel alert query returned no steps.")
+ if isinstance(result[0], list):
+ return cast(list[list[dict[str, Any]]], result)
+ return [cast(list[dict[str, Any]], result)]
+
+
+def _breakdown_label(steps: list[dict[str, Any]]) -> str:
+ breakdown = steps[0].get("breakdown_value") if steps else None
+ if breakdown is None:
+ return "conversion"
+ return ", ".join(str(v) for v in breakdown) if isinstance(breakdown, list) else str(breakdown)
+
+
+def _step_count(steps: list[dict[str, Any]], index: int) -> float:
+ # Route a malformed step shape to the errored-alert path (like the SQL extractor's _numeric_cell)
+ # rather than letting a raw KeyError/TypeError surface as an internal crash.
+ step = steps[index]
+ if not isinstance(step, dict):
+ raise AlertExtractionError(f"Funnel step {index} is malformed (expected an object, got {type(step).__name__}).")
+ count = step.get("count")
+ if isinstance(count, bool) or not isinstance(count, int | float):
+ raise AlertExtractionError(f"Funnel step {index} has a non-numeric count: {count!r}.")
+ return count
+
+
+def _conversion_rate(steps: list[dict[str, Any]], config: FunnelsAlertConfig) -> float:
+ """Conversion rate (0–100) for the configured step and metric."""
+ step_count = len(steps)
+ step_index = config.funnel_step if config.funnel_step is not None else step_count - 1
+ if step_index < 0 or step_index >= step_count:
+ raise AlertExtractionError(f"funnel_step {step_index} is out of range (funnel has {step_count} steps).")
+
+ if config.metric == FunnelConversionMetric.CONVERSION_FROM_PREVIOUS:
+ if step_index == 0:
+ raise AlertExtractionError(
+ "conversion_from_previous is undefined at the first step (there is no prior step); "
+ "use conversion_from_start instead."
+ )
+ base_index = step_index - 1
+ else:
+ base_index = 0
+
+ base = _step_count(steps, base_index)
+ if base == 0:
+ return 0.0
+ return _step_count(steps, step_index) / base * 100
diff --git a/products/alerts/backend/evaluation/test/test_comparator.py b/products/alerts/backend/evaluation/test/test_comparator.py
index e5c122626a66..e8b7dd25b3fe 100644
--- a/products/alerts/backend/evaluation/test/test_comparator.py
+++ b/products/alerts/backend/evaluation/test/test_comparator.py
@@ -62,6 +62,17 @@ def test_absolute_breach_detection(value, lower, upper, expected_message):
assert expected_message in result.breaches[0]
+def test_unit_suffix_renders_in_breach_message():
+ # Funnel conversion rates are absolute 0–100 values carried with a "%" unit so the notification
+ # matches the configure-time UI (which shows a % suffix).
+ series = [ComparableSeries(label="conversion", points=[SeriesPoint(date=None, value=40.0)], current_index=0)]
+ result = ExtractionResult(series=series, subject="The funnel conversion rate", framed=False, unit="%")
+ out = evaluate_threshold(result, ABSOLUTE, _threshold(lower=50))
+ assert out.breaches is not None and len(out.breaches) == 1
+ assert "(40.0%)" in out.breaches[0]
+ assert "lower threshold (50.0%)" in out.breaches[0]
+
+
@pytest.mark.parametrize(
"values,current_index,is_current,condition,threshold_type,upper,expected_value,expected_message",
[
diff --git a/products/alerts/backend/evaluation/test/test_funnels_extractor.py b/products/alerts/backend/evaluation/test/test_funnels_extractor.py
new file mode 100644
index 000000000000..f3b8a1a32b15
--- /dev/null
+++ b/products/alerts/backend/evaluation/test/test_funnels_extractor.py
@@ -0,0 +1,146 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import AlertConditionType
+
+from products.alerts.backend.evaluation.contract import AlertExtractionError
+from products.alerts.backend.evaluation.funnels import FunnelsExtractor
+
+CALC_PATH = "products.alerts.backend.evaluation.funnels.calculate_for_query_based_insight"
+
+
+def _steps(*counts: int) -> list[dict]:
+ return [{"order": i, "count": c, "breakdown_value": None} for i, c in enumerate(counts)]
+
+
+def _query(viz: str | None = None) -> dict:
+ query: dict = {
+ "kind": "FunnelsQuery",
+ "series": [{"kind": "EventsNode", "event": "step_a"}, {"kind": "EventsNode", "event": "step_b"}],
+ }
+ if viz is not None:
+ query["funnelsFilter"] = {"funnelVizType": viz}
+ return query
+
+
+def _alert(config: dict | None = None, condition_type: str = AlertConditionType.ABSOLUTE_VALUE) -> MagicMock:
+ alert = MagicMock()
+ alert.config = config or {"type": "FunnelsAlertConfig", "metric": "conversion_from_start", "funnel_step": None}
+ alert.condition = {"type": condition_type}
+ return alert
+
+
+def _extract(
+ result, *, config: dict | None = None, viz: str | None = None, condition_type=AlertConditionType.ABSOLUTE_VALUE
+):
+ with patch(CALC_PATH) as calc:
+ calc.return_value = MagicMock(result=result)
+ return FunnelsExtractor().extract(_alert(config, condition_type), MagicMock(), _query(viz))
+
+
+def _config(metric: str = "conversion_from_start", funnel_step: int | None = None) -> dict:
+ return {"type": "FunnelsAlertConfig", "metric": metric, "funnel_step": funnel_step}
+
+
+ "counts,config,expected",
+ [
+ ((100, 40), None, 40.0), # from_start, last step: 40/100
+ ((100, 50, 30), _config("conversion_from_previous", 2), 60.0), # step-over-step: 30/50
+ ((200, 50, 10), _config("conversion_from_start", 1), 25.0), # from_start at step 1: 50/200
+ ((0, 0), None, 0.0), # zero base → 0 rate
+ ],
+)
+def test_conversion_rate(counts, config, expected):
+ result = _extract(_steps(*counts), config=config)
+ assert result.series[0].points[0].value == expected
+
+
+def test_result_is_unframed_single_series():
+ result = _extract(_steps(100, 40))
+ assert result.subject == "The funnel conversion rate"
+ assert result.framed is False
+ assert result.is_breakdown is False
+
+
+ "result,config,viz,condition_type,match",
+ [
+ (_steps(100, 40), _config("conversion_from_start", 5), None, AlertConditionType.ABSOLUTE_VALUE, "out of range"),
+ (
+ _steps(100, 40),
+ _config("conversion_from_previous", 0),
+ None,
+ AlertConditionType.ABSOLUTE_VALUE,
+ "undefined at the first step",
+ ),
+ (_steps(100, 40), None, "time_to_convert", AlertConditionType.ABSOLUTE_VALUE, "steps funnel"),
+ (_steps(100, 40), None, None, AlertConditionType.RELATIVE_INCREASE, "absolute value conditions"),
+ (_steps(100, 40), None, None, AlertConditionType.RELATIVE_DECREASE, "absolute value conditions"),
+ ([], None, None, AlertConditionType.ABSOLUTE_VALUE, "no steps"),
+ ([{"order": 0}, {"order": 1}], None, None, AlertConditionType.ABSOLUTE_VALUE, "non-numeric count"),
+ ([{"order": 0, "count": 100}, "broken"], None, None, AlertConditionType.ABSOLUTE_VALUE, "malformed"),
+ ],
+)
+def test_extract_raises_extraction_error(result, config, viz, condition_type, match):
+ with pytest.raises(AlertExtractionError, match=match):
+ _extract(result, config=config, viz=viz, condition_type=condition_type)
+
+
+def test_none_result_raises_runtime_error():
+ # A None result means the query layer swallowed an error — surface it as RuntimeError (not
+ # AlertExtractionError) so it routes to the harder failure path, matching the other extractors.
+ with pytest.raises(RuntimeError, match="No results found"):
+ _extract(None)
+
+
+def test_breakdown_yields_one_series_per_value():
+ # list-of-lists => breakdown; two breakdown values
+ us = [{"order": 0, "count": 100, "breakdown_value": "US"}, {"order": 1, "count": 40, "breakdown_value": "US"}]
+ de = [{"order": 0, "count": 80, "breakdown_value": "DE"}, {"order": 1, "count": 20, "breakdown_value": "DE"}]
+ result = _extract([us, de])
+ assert result.is_breakdown is True
+ assert len(result.series) == 2
+ assert result.series[0].label == "US" and result.series[0].points[0].value == 40.0
+ assert result.series[1].label == "DE" and result.series[1].points[0].value == 25.0
+
+
+def test_compared_funnel_evaluates_current_period_only():
+ # A compare-enabled funnel concatenates current + previous rows (tagged compare_label); the
+ # extractor evaluates the current period only.
+ compared = [
+ {"order": 0, "count": 1000, "compare_label": "current"},
+ {"order": 1, "count": 100, "compare_label": "current"},
+ {"order": 0, "count": 800, "compare_label": "previous"},
+ {"order": 1, "count": 120, "compare_label": "previous"},
+ ]
+ result = _extract(compared)
+ assert result.is_breakdown is False
+ assert len(result.series) == 1
+ assert result.series[0].points[0].value == 10.0 # current period: 100/1000
+
+
+def test_breakdown_compared_funnel_evaluates_current_breakdowns_only():
+ # Breakdown + compare: the runner emits the current breakdown groups followed by the previous
+ # ones. The previous groups filter to empty and must be dropped — an empty group previously made
+ # funnel_step resolve to -1 and raised "out of range" instead of evaluating the current breakdowns.
+ us_current = [
+ {"order": 0, "count": 100, "breakdown_value": "US", "compare_label": "current"},
+ {"order": 1, "count": 40, "breakdown_value": "US", "compare_label": "current"},
+ ]
+ de_current = [
+ {"order": 0, "count": 80, "breakdown_value": "DE", "compare_label": "current"},
+ {"order": 1, "count": 20, "breakdown_value": "DE", "compare_label": "current"},
+ ]
+ us_previous = [
+ {"order": 0, "count": 90, "breakdown_value": "US", "compare_label": "previous"},
+ {"order": 1, "count": 30, "breakdown_value": "US", "compare_label": "previous"},
+ ]
+ de_previous = [
+ {"order": 0, "count": 70, "breakdown_value": "DE", "compare_label": "previous"},
+ {"order": 1, "count": 10, "breakdown_value": "DE", "compare_label": "previous"},
+ ]
+ result = _extract([us_current, de_current, us_previous, de_previous])
+ assert result.is_breakdown is True
+ assert {s.label for s in result.series} == {"US", "DE"} # current breakdowns only, no crash
+ assert {s.label: s.points[0].value for s in result.series} == {"US": 40.0, "DE": 25.0}
diff --git a/products/alerts/backend/evaluation/validation.py b/products/alerts/backend/evaluation/validation.py
index 8618961c6f6c..826ffddd8a09 100644
--- a/products/alerts/backend/evaluation/validation.py
+++ b/products/alerts/backend/evaluation/validation.py
@@ -7,6 +7,10 @@ from posthog.schema import (
AlertCalculationInterval,
AlertCondition,
AlertConditionType,
+ FunnelConversionMetric,
+ FunnelsAlertConfig,
+ FunnelsQuery,
+ FunnelVizType,
HogQLAlertConfig,
HogQLAlertEvaluation,
InsightThreshold,
@@ -141,11 +145,46 @@ def _validate_trends_alert_config(ctx: _AlertConfigValidationContext) -> None:
validate_threshold_bounds_required(ctx.threshold_config)
+def _validate_funnels_alert_config(ctx: _AlertConfigValidationContext) -> None:
+ # A funnel STEPS result is a single snapshot (no prior window), so only absolute conditions apply.
+ if ctx.query_kind != NodeKind.FUNNELS_QUERY:
+ raise ValueError(f"Funnel alert config requires a FunnelsQuery insight, got '{ctx.query_kind}'")
+ if ctx.parsed_condition.type != AlertConditionType.ABSOLUTE_VALUE:
+ raise ValueError("Funnel alerts only support absolute value conditions")
+ try:
+ parsed = FunnelsAlertConfig.model_validate(ctx.config)
+ except Exception:
+ raise ValueError(f"Alert has invalid FunnelsAlertConfig: {ctx.config}")
+ try:
+ funnels_query = FunnelsQuery.model_validate(ctx.query)
+ except Exception as e:
+ raise ValueError(f"Alert's insight has an invalid FunnelsQuery: {e}")
+ # Reject non-steps funnels (time-to-convert, trends) at config time, mirroring the extractor's
+ # eval-time guard — otherwise the alert saves but errors on its first check.
+ viz = funnels_query.funnelsFilter.funnelVizType if funnels_query.funnelsFilter else None
+ if viz not in (None, FunnelVizType.STEPS):
+ raise ValueError(f"Funnel alerts require a steps funnel, but this insight uses '{viz}'")
+ step = parsed.funnel_step
+ if step is not None:
+ if step < 0:
+ raise ValueError(f"funnel_step must be >= 0, got {step}")
+ # The series count is the result step count for a STEPS funnel (exclusion nodes live in
+ # funnelsFilter, not series), so this matches the extractor's eval-time range check.
+ if step >= len(funnels_query.series):
+ raise ValueError(f"funnel_step {step} is out of range (funnel has {len(funnels_query.series)} steps)")
+ if parsed.metric == FunnelConversionMetric.CONVERSION_FROM_PREVIOUS and step == 0:
+ raise ValueError("conversion_from_previous is undefined at the first step; use conversion_from_start instead")
+ _validate_condition_threshold_compatibility(ctx.parsed_condition, ctx.threshold_config)
+ if ctx.require_threshold_bounds and ctx.detector_config is None:
+ validate_threshold_bounds_required(ctx.threshold_config)
+
+
# Per-config-type validators, mirroring the extractor registry in dispatcher.py: one entry per
# config type the threshold path supports. Adding a kind = adding an entry here and an extractor.
_ALERT_CONFIG_VALIDATORS: dict[str, Callable[[_AlertConfigValidationContext], None]] = {
"HogQLAlertConfig": _validate_hogql_alert_config,
"TrendsAlertConfig": _validate_trends_alert_config,
+ "FunnelsAlertConfig": _validate_funnels_alert_config,
}
diff --git a/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx b/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx
index 3f8eeba01351..ec3670d73de7 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx
+++ b/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx
@@ -1,10 +1,17 @@
import { Group } from 'kea-forms'
import { IconInfo } from '@posthog/icons'
-import { LemonSelect, Tooltip } from '@posthog/lemon-ui'
+import { LemonBanner, LemonSelect, LemonTag, Tooltip } from '@posthog/lemon-ui'
import { AlertFormType } from 'lib/components/Alerts/alertFormLogic'
+import {
+ funnelConfigForOptionKey,
+ funnelConfigToOptionKey,
+ funnelConversionOptions,
+} from 'lib/components/Alerts/funnelAlertOptions'
+import { FunnelAlertPreview } from 'lib/components/Alerts/funnelAlertPreview'
import { HogQLAlertPreview } from 'lib/components/Alerts/hogqlAlertPreview'
+import { isFunnelsAlertConfig } from 'lib/components/Alerts/types'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { alphabet } from 'lib/utils/strings'
@@ -58,6 +65,112 @@ export function TrendsDefinitionFields({
)
}
+// Cap the named breaching breakdown values so a high-cardinality breakdown can't produce a runaway
+// banner string (mirrors the SQL preview's table cap); the rest collapse into "+N more".
+const FUNNEL_BREACH_PREVIEW_CAP = 5
+
+/** Conversion-rate read-out + breach/ok status (mirrors the SQL alert's preview). */
+function FunnelAlertPreviewBanner({ preview }: { preview: FunnelAlertPreview | null }): JSX.Element | null {
+ if (preview === null) {
+ return (
+ <LemonBanner type="info" className="w-full">
+ Load the insight to preview the conversion rate this alert will evaluate.
+ </LemonBanner>
+ )
+ }
+ if (preview.status === 'no-data') {
+ return (
+ <LemonBanner type="info" className="w-full">
+ This funnel has no data for the selected steps yet, so the alert can't evaluate a conversion rate. Try
+ adjusting the funnel steps or the date range.
+ </LemonBanner>
+ )
+ }
+ const format = (rate: number): string => `${rate.toFixed(1)}%`
+ const breaching = preview.values.filter((value) => value.breaching)
+ const wouldFire = breaching.length > 0
+ // Same at-a-glance breach/ok tag as the SQL alert preview; only meaningful once a threshold is set.
+ const statusTag = preview.hasBounds ? (
+ <LemonTag type={wouldFire ? 'warning' : 'success'} className="mr-2">
+ {wouldFire ? 'breach' : 'ok'}
+ </LemonTag>
+ ) : null
+
+ if (preview.isBreakdown) {
+ const rates = preview.values.map((value) => value.rate)
+ return (
+ <LemonBanner type={wouldFire ? 'warning' : 'info'} className="w-full">
+ {statusTag}
+ Across {preview.values.length} breakdown values, currently{' '}
+ <strong>
+ {format(Math.min(...rates))}–{format(Math.max(...rates))}
+ </strong>
+ {/* The tag + banner colour carry the breach/ok state; only add what they can't — which
+ values breach, or (when no threshold is set yet) a prompt to set one. */}
+ {!preview.hasBounds ? (
+ <> — fires if any value breaches. Set a threshold to preview.</>
+ ) : wouldFire ? (
+ <>
+ {' '}
+ ·{' '}
+ {breaching
+ .slice(0, FUNNEL_BREACH_PREVIEW_CAP)
+ .map((value) => `${value.label ?? 'conversion'} ${format(value.rate)}`)
+ .join(', ')}
+ {breaching.length > FUNNEL_BREACH_PREVIEW_CAP
+ ? ` +${breaching.length - FUNNEL_BREACH_PREVIEW_CAP} more`
+ : ''}
+ </>
+ ) : null}
+ </LemonBanner>
+ )
+ }
+
+ return (
+ <LemonBanner type={wouldFire ? 'warning' : 'info'} className="w-full">
+ {statusTag}
+ Currently converting at <strong>{format(preview.values[0].rate)}</strong>
+ {!preview.hasBounds ? <> — set a threshold to preview whether it would fire.</> : null}
+ </LemonBanner>
+ )
+}
+
+/** Funnels: a single valid-conversion picker over the `{metric, funnel_step}` config — see funnelAlertOptions. */
+export function FunnelsDefinitionFields({
+ alertForm,
+ stepLabels,
+ funnelPreview,
+ onSetAlertFormValue,
+}: {
+ alertForm: AlertFormType
+ stepLabels: string[]
+ funnelPreview: FunnelAlertPreview | null
+ onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
+}): JSX.Element {
+ const config = isFunnelsAlertConfig(alertForm.config) ? alertForm.config : null
+ return (
+ <div className="flex flex-wrap gap-3 items-center">
+ <div>Alert on</div>
+ <LemonSelect
+ fullWidth
+ className="flex-auto"
+ data-attr="alertForm-funnel-conversion"
+ placeholder="Select a conversion"
+ // Wide funnels generate ~2 options per step; cap the menu so it scrolls instead of overflowing.
+ menu={{ className: '!max-h-[400px]' }}
+ value={config ? funnelConfigToOptionKey(config, stepLabels.length) : undefined}
+ onChange={(key) =>
+ // Each key fully determines the config, so build a fresh one rather than spreading
+ // the previous config (whose type/metric/funnel_step would all be overwritten anyway).
+ onSetAlertFormValue('config', { type: 'FunnelsAlertConfig', ...funnelConfigForOptionKey(key) })
+ }
+ options={funnelConversionOptions(stepLabels)}
+ />
+ <FunnelAlertPreviewBanner preview={funnelPreview} />
+ </div>
+ )
+}
+
/** SQL: pick the evaluation mode and (when the result is multi-column) the value/label columns,
* plus the live preview of what the alert would evaluate. */
export function HogQLDefinitionFields({
diff --git a/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx b/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
index efc356997983..52ac14a4f575 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
+++ b/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
@@ -12,8 +12,15 @@ import {
} from '@posthog/lemon-ui'
import { AlertFormType } from 'lib/components/Alerts/alertFormLogic'
+import { FunnelAlertPreview } from 'lib/components/Alerts/funnelAlertPreview'
import { HogQLAlertPreview } from 'lib/components/Alerts/hogqlAlertPreview'
-import { AlertSimulationResult, isAnyRowHogQLConfig, isTrendsAlertConfig } from 'lib/components/Alerts/types'
+import {
+ AlertSimulationResult,
+ isAnyRowHogQLConfig,
+ isFunnelsAlertConfig,
+ isHogQLAlertConfig,
+ isTrendsAlertConfig,
+} from 'lib/components/Alerts/types'
import { DetectorSelector, getDefaultWindow } from 'lib/components/Alerts/views/DetectorSelector'
import { SimulationSummary } from 'lib/components/Alerts/views/SimulationSummary'
import { LemonField } from 'lib/lemon-ui/LemonField'
@@ -22,7 +29,7 @@ import { AlertConditionType, InsightThresholdType } from '~/queries/schema/schem
import { getDefaultSimulationRange } from 'products/alerts/frontend/logic/alertIntervalHelpers'
-import { HogQLDefinitionFields, TrendsDefinitionFields } from './AlertDefinitionFields'
+import { FunnelsDefinitionFields, HogQLDefinitionFields, TrendsDefinitionFields } from './AlertDefinitionFields'
import { getSimulationRangeOptions } from './editAlertModalUtils'
export interface AlertDefinitionSectionProps {
@@ -33,6 +40,10 @@ export interface AlertDefinitionSectionProps {
isNonTimeSeriesDisplay: boolean
alertSeries: Array<{ custom_name?: string | null; name?: string | null; event?: string | null }> | null
formulaNodes: Array<{ formula: string; custom_name?: string | null }> | undefined
+ /** The funnel's step labels (real event/series names), used to populate the conversion picker. */
+ funnelStepLabels: string[]
+ /** The conversion rate(s) a funnel alert would evaluate right now; null until the result loads. */
+ funnelPreview: FunnelAlertPreview | null
/** What a SQL alert would evaluate right now; null until the insight result loads. */
hogqlPreview: HogQLAlertPreview | null
/** Result column names of the SQL insight, for the column pickers. */
@@ -66,6 +77,8 @@ export function AlertDefinitionSection({
isNonTimeSeriesDisplay,
alertSeries,
formulaNodes,
+ funnelStepLabels,
+ funnelPreview,
hogqlPreview,
hogqlColumns,
hogqlValueColumnOptions,
@@ -81,13 +94,18 @@ export function AlertDefinitionSection({
onClearSimulation,
onClearSimulationOverlay,
}: AlertDefinitionSectionProps): JSX.Element {
+ // Funnel alerts evaluate a single conversion-rate snapshot (always a 0–100%), so relative
+ // conditions have no prior value to compare against — they're omitted entirely below.
+ const isFunnelAlert = isFunnelsAlertConfig(alertForm.config)
+ const supportsRelativeConditions = !isFunnelAlert
const relativeConditionDisabledReason =
(isNonTimeSeriesDisplay && 'This condition is only supported for time series trends') ||
(isHogQLAnyRow(alertForm) &&
"Rows in any-row mode aren't a time series — switch to 'the latest value' for relative conditions")
return (
<>
- {isBreakdownValid && (
+ {/* Trends-specific copy; funnels have their own breakdown messaging in the preview banner. */}
+ {isBreakdownValid && isTrendsAlertConfig(alertForm.config) && (
<LemonBanner type="warning">
{alertMode === 'detector'
? 'For trends with breakdown, the detector will independently monitor each breakdown value (up to 25) and fire if any is anomalous.'
@@ -101,7 +119,14 @@ export function AlertDefinitionSection({
isBreakdownValid={isBreakdownValid}
alertMode={alertMode}
/>
- ) : (
+ ) : isFunnelAlert ? (
+ <FunnelsDefinitionFields
+ alertForm={alertForm}
+ stepLabels={funnelStepLabels}
+ funnelPreview={funnelPreview}
+ onSetAlertFormValue={onSetAlertFormValue}
+ />
+ ) : isHogQLAlertConfig(alertForm.config) ? (
<HogQLDefinitionFields
alertForm={alertForm}
hogqlPreview={hogqlPreview}
@@ -110,7 +135,7 @@ export function AlertDefinitionSection({
hogqlLabelColumnOptions={hogqlLabelColumnOptions}
onSetAlertFormValue={onSetAlertFormValue}
/>
- )}
+ ) : null}
{anomalyDetectionEnabled && (
<LemonSegmentedButton
@@ -150,37 +175,37 @@ export function AlertDefinitionSection({
<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">
- <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: relativeConditionDisabledReason,
- },
- {
- label: 'decreases by',
- value: AlertConditionType.RELATIVE_DECREASE,
- disabledReason: relativeConditionDisabledReason,
- },
- ]}
- />
- </LemonField>
- </Group>
+ {supportsRelativeConditions && (
+ <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: relativeConditionDisabledReason,
+ },
+ {
+ label: 'decreases by',
+ value: AlertConditionType.RELATIVE_DECREASE,
+ disabledReason: relativeConditionDisabledReason,
+ },
+ ]}
+ />
+ </LemonField>
+ </Group>
+ )}
<div>less than</div>
<LemonField name="lower">
<LemonInput
type="number"
className="w-30"
data-attr="alertForm-lower-threshold"
+ suffix={isFunnelAlert ? <span aria-label="percent">%</span> : undefined}
value={
alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE &&
alertForm.threshold.configuration.bounds?.lower
@@ -211,6 +236,7 @@ export function AlertDefinitionSection({
type="number"
className="w-30"
data-attr="alertForm-upper-threshold"
+ suffix={isFunnelAlert ? <span aria-label="percent">%</span> : undefined}
value={
alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE &&
alertForm.threshold.configuration.bounds?.upper
diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.ts
index f2c5bd845bb0..c4e42e171c1d 100644
--- a/products/alerts/frontend/generated/api.schemas.ts
+++ b/products/alerts/frontend/generated/api.schemas.ts
@@ -213,11 +213,31 @@ export interface HogQLAlertConfigApi {
type: HogQLAlertConfigApiType
}
+export type FunnelConversionMetricApi = (typeof FunnelConversionMetricApi)[keyof typeof FunnelConversionMetricApi]
+
+export const FunnelConversionMetricApi = {
+ ConversionFromStart: 'conversion_from_start',
+ ConversionFromPrevious: 'conversion_from_previous',
+} as const
+
+export type FunnelsAlertConfigApiType = (typeof FunnelsAlertConfigApiType)[keyof typeof FunnelsAlertConfigApiType]
+
+export const FunnelsAlertConfigApiType = {
+ FunnelsAlertConfig: 'FunnelsAlertConfig',
+} as const
+
+export interface FunnelsAlertConfigApi {
+ /** Zero-based step index to evaluate. Null = the last step (overall conversion). */
+ funnel_step?: number | null
+ metric: FunnelConversionMetricApi
+ type: FunnelsAlertConfigApiType
+}
+
/**
* Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the
* generated frontend types and MCP tool schemas) in sync with every kind alerts support.
*/
-export type AlertConfigUnionApi = TrendsAlertConfigApi | HogQLAlertConfigApi
+export type AlertConfigUnionApi = TrendsAlertConfigApi | HogQLAlertConfigApi | FunnelsAlertConfigApi
export interface PreprocessingConfigApi {
/** Order of differencing. 0 = raw values, 1 = first-order diffs (default: 0) */
@@ -495,7 +515,7 @@ export interface AlertApi {
* @nullable
*/
readonly checks_total: number | null
- /** Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). */
+ /** Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). FunnelsAlertConfig (funnel insights): funnel_step (the step to monitor, null for the overall last step) and metric ('conversion_from_start' or 'conversion_from_previous'); funnel alerts only support absolute_value conditions. */
config?: AlertConfigUnionApi | null
detector_config?: DetectorConfigApi | null
/** How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.
@@ -576,7 +596,7 @@ export interface PatchedAlertApi {
* @nullable
*/
readonly checks_total?: number | null
- /** Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). */
+ /** Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). FunnelsAlertConfig (funnel insights): funnel_step (the step to monitor, null for the overall last step) and metric ('conversion_from_start' or 'conversion_from_previous'); funnel alerts only support absolute_value conditions. */
config?: AlertConfigUnionApi | null
detector_config?: DetectorConfigApi | null
/** How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.
diff --git a/products/alerts/frontend/generated/api.zod.ts b/products/alerts/frontend/generated/api.zod.ts
index 58951ac5cc52..3a165e83fdf4 100644
--- a/products/alerts/frontend/generated/api.zod.ts
+++ b/products/alerts/frontend/generated/api.zod.ts
@@ -52,6 +52,7 @@ export const alertsSimulateCreateBodyDetectorConfigOneOnethreeTypeDefault = `pca
export const alertsSimulateCreateBodySeriesIndexDefault = 0
export const alertsSimulateCreateBodyConfigOneOneTypeDefault = `TrendsAlertConfig`
export const alertsSimulateCreateBodyConfigOneTwoTypeDefault = `HogQLAlertConfig`
+export const alertsSimulateCreateBodyConfigOneThreeTypeDefault = `FunnelsAlertConfig`
export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({
insight: zod.number().describe('Insight ID to simulate the detector on.'),
@@ -1105,6 +1106,16 @@ export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({
),
type: zod.enum(['HogQLAlertConfig']).default(alertsSimulateCreateBodyConfigOneTwoTypeDefault),
}),
+ zod.object({
+ funnel_step: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe('Zero-based step index to evaluate. Null = the last step (overall conversion).'),
+ metric: zod.enum(['conversion_from_start', 'conversion_from_previous']),
+ type: zod
+ .enum(['FunnelsAlertConfig'])
+ .default(alertsSimulateCreateBodyConfigOneThreeTypeDefault),
+ }),
])
.describe(
'Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support.'
diff --git a/products/alerts/mcp/tools.yaml b/products/alerts/mcp/tools.yaml
index e4a298f39683..39cb42142b04 100644
--- a/products/alerts/mcp/tools.yaml
+++ b/products/alerts/mcp/tools.yaml
@@ -36,7 +36,10 @@ tools:
truncation), or 'any_row' (every row is checked and the alert fires if any value breaches; absolute_value
condition only). label_column names the evaluated row(s) in breach messages in every evaluation mode
(defaults to the first non-evaluated column). Label values appear in delivered notifications — avoid label
- columns containing PII. Anomaly detection (detector_config) is only supported for trends insights.
+ columns containing PII. Funnel insights: FunnelsAlertConfig — funnel_step picks the step to monitor (null
+ for the overall last step) and metric is 'conversion_from_start' or 'conversion_from_previous'; funnel
+ alerts only support absolute_value conditions. Anomaly detection (detector_config) is supported for trends
+ and SQL insights (not funnels).
Note: subscribed_users only controls email recipients. For Slack, HTTPS webhook, or Discord delivery, see
the recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe
@@ -107,7 +110,7 @@ tools:
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 (trends insights only), or set it to null to switch back to threshold mode (threshold mode
+ detection (trends and SQL insights), 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). For SQL-insight alerts the
config is HogQLAlertConfig (column, evaluation 'last_row'/'first_row'/'any_row', label_column). To snooze an
alert, set snoozed_until to a relative date string (e.g. '2h', '1d'). To unsnooze, set snoozed_until to
diff --git a/products/product_analytics/backend/models/insight.py b/products/product_analytics/backend/models/insight.py
index e67495d5e249..63a4627f8267 100644
--- a/products/product_analytics/backend/models/insight.py
+++ b/products/product_analytics/backend/models/insight.py
@@ -417,13 +417,14 @@ class Insight(RootTeamMixin, FileSystemSyncMixin, models.Model):
@property
def alertable_query_kind(self) -> "NodeKind | None":
- """The insight's alert-capable query kind (trends or SQL today), or None if alerts aren't
- supported. Pure kind check — feature-flag gating is the caller's responsibility, so existing
- alerts keep displaying and survive insight edits regardless of the flag."""
+ # Pure kind check (no flag gating — that's the caller's job), so existing alerts keep
+ # displaying and survive insight edits when a flag is off.
from posthog.schema import NodeKind # noqa: PLC0415
kind = self._unwrapped_query_kind()
- return NodeKind(kind) if kind in (NodeKind.TRENDS_QUERY, NodeKind.HOG_QL_QUERY) else None
+ return (
+ NodeKind(kind) if kind in (NodeKind.TRENDS_QUERY, NodeKind.HOG_QL_QUERY, NodeKind.FUNNELS_QUERY) else None
+ )
def generate_query_metadata(self):
from posthog.hogql_queries.query_metadata import extract_query_metadata
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 00ef1780567b..e7599abe7d42 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -772,7 +772,7 @@
"feature_flag": "agent-platform"
},
"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 — 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.\nThe config type must match the insight kind. Trends insights: TrendsAlertConfig (series_index, check_ongoing_interval). SQL/HogQL insights: HogQLAlertConfig — column picks which result column to evaluate (defaults to the single numeric column), evaluation is required and selects how rows are read: 'last_row' (query ordered oldest->newest, the last row is the current value), 'first_row' (query ordered newest->oldest, the first row is the current value — pair with a LIMIT, and it is unaffected by result truncation), or 'any_row' (every row is checked and the alert fires if any value breaches; absolute_value condition only). label_column names the evaluated row(s) in breach messages in every evaluation mode (defaults to the first non-evaluated column). Label values appear in delivered notifications — avoid label columns containing PII. Anomaly detection (detector_config) is only supported for trends insights.\nNote: subscribed_users only controls email recipients. For Slack, HTTPS webhook, or Discord 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.\nThe config type must match the insight kind. Trends insights: TrendsAlertConfig (series_index, check_ongoing_interval). SQL/HogQL insights: HogQLAlertConfig — column picks which result column to evaluate (defaults to the single numeric column), evaluation is required and selects how rows are read: 'last_row' (query ordered oldest->newest, the last row is the current value), 'first_row' (query ordered newest->oldest, the first row is the current value — pair with a LIMIT, and it is unaffected by result truncation), or 'any_row' (every row is checked and the alert fires if any value breaches; absolute_value condition only). label_column names the evaluated row(s) in breach messages in every evaluation mode (defaults to the first non-evaluated column). Label values appear in delivered notifications — avoid label columns containing PII. Funnel insights: FunnelsAlertConfig — funnel_step picks the step to monitor (null for the overall last step) and metric is 'conversion_from_start' or 'conversion_from_previous'; funnel alerts only support absolute_value conditions. Anomaly detection (detector_config) is supported for trends and SQL insights (not funnels).\nNote: subscribed_users only controls email recipients. For Slack, HTTPS webhook, or Discord 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",
@@ -828,7 +828,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 (trends insights only), 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). For SQL-insight alerts the config is HogQLAlertConfig (column, evaluation 'last_row'/'first_row'/'any_row', label_column). 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/Discord 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 (trends and SQL insights), 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). For SQL-insight alerts the config is HogQLAlertConfig (column, evaluation 'last_row'/'first_row'/'any_row', label_column). 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/Discord 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.json
index 863cee41ae52..6951f18b13cd 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -802,7 +802,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 — 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.\nThe config type must match the insight kind. Trends insights: TrendsAlertConfig (series_index, check_ongoing_interval). SQL/HogQL insights: HogQLAlertConfig — column picks which result column to evaluate (defaults to the single numeric column), evaluation is required and selects how rows are read: 'last_row' (query ordered oldest->newest, the last row is the current value), 'first_row' (query ordered newest->oldest, the first row is the current value — pair with a LIMIT, and it is unaffected by result truncation), or 'any_row' (every row is checked and the alert fires if any value breaches; absolute_value condition only). label_column names the evaluated row(s) in breach messages in every evaluation mode (defaults to the first non-evaluated column). Label values appear in delivered notifications — avoid label columns containing PII. Anomaly detection (detector_config) is only supported for trends insights.\nNote: subscribed_users only controls email recipients. For Slack, HTTPS webhook, or Discord 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.\nThe config type must match the insight kind. Trends insights: TrendsAlertConfig (series_index, check_ongoing_interval). SQL/HogQL insights: HogQLAlertConfig — column picks which result column to evaluate (defaults to the single numeric column), evaluation is required and selects how rows are read: 'last_row' (query ordered oldest->newest, the last row is the current value), 'first_row' (query ordered newest->oldest, the first row is the current value — pair with a LIMIT, and it is unaffected by result truncation), or 'any_row' (every row is checked and the alert fires if any value breaches; absolute_value condition only). label_column names the evaluated row(s) in breach messages in every evaluation mode (defaults to the first non-evaluated column). Label values appear in delivered notifications — avoid label columns containing PII. Funnel insights: FunnelsAlertConfig — funnel_step picks the step to monitor (null for the overall last step) and metric is 'conversion_from_start' or 'conversion_from_previous'; funnel alerts only support absolute_value conditions. Anomaly detection (detector_config) is supported for trends and SQL insights (not funnels).\nNote: subscribed_users only controls email recipients. For Slack, HTTPS webhook, or Discord 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",
@@ -858,7 +858,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 (trends insights only), 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). For SQL-insight alerts the config is HogQLAlertConfig (column, evaluation 'last_row'/'first_row'/'any_row', label_column). 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/Discord 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 (trends and SQL insights), 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). For SQL-insight alerts the config is HogQLAlertConfig (column, evaluation 'last_row'/'first_row'/'any_row', label_column). 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/Discord 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.ts
index f48d29ceec53..2824903a1e99 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8800,11 +8800,33 @@ export namespace Schemas {
type: HogQLAlertConfigType;
}
+ export type FunnelConversionMetric = typeof FunnelConversionMetric[keyof typeof FunnelConversionMetric];
+
+
+ export const FunnelConversionMetric = {
+ ConversionFromStart: 'conversion_from_start',
+ ConversionFromPrevious: 'conversion_from_previous',
+ } as const;
+
+ export type FunnelsAlertConfigType = typeof FunnelsAlertConfigType[keyof typeof FunnelsAlertConfigType];
+
+
+ export const FunnelsAlertConfigType = {
+ FunnelsAlertConfig: 'FunnelsAlertConfig',
+ } as const;
+
+ export interface FunnelsAlertConfig {
+ /** Zero-based step index to evaluate. Null = the last step (overall conversion). */
+ funnel_step?: number | null;
+ metric: FunnelConversionMetric;
+ type: FunnelsAlertConfigType;
+ }
+
/**
* Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the
* generated frontend types and MCP tool schemas) in sync with every kind alerts support.
*/
- export type AlertConfigUnion = TrendsAlertConfig | HogQLAlertConfig;
+ export type AlertConfigUnion = TrendsAlertConfig | HogQLAlertConfig | FunnelsAlertConfig;
export interface PreprocessingConfig {
/** Order of differencing. 0 = raw values, 1 = first-order diffs (default: 0) */
@@ -9052,7 +9074,7 @@ export namespace Schemas {
* @nullable
*/
readonly checks_total: number | null;
- /** Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). */
+ /** Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). FunnelsAlertConfig (funnel insights): funnel_step (the step to monitor, null for the overall last step) and metric ('conversion_from_start' or 'conversion_from_previous'); funnel alerts only support absolute_value conditions. */
config?: AlertConfigUnion | null;
detector_config?: DetectorConfig | null;
/** How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.
@@ -35022,7 +35044,7 @@ export namespace Schemas {
* @nullable
*/
readonly checks_total?: number | null;
- /** Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). */
+ /** Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). FunnelsAlertConfig (funnel insights): funnel_step (the step to monitor, null for the overall last step) and metric ('conversion_from_start' or 'conversion_from_previous'); funnel alerts only support absolute_value conditions. */
config?: AlertConfigUnion | null;
detector_config?: DetectorConfig | null;
/** How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.
diff --git a/services/mcp/src/generated/alerts/api.ts b/services/mcp/src/generated/alerts/api.ts
index 7b22479234dc..89cc73085107 100644
--- a/services/mcp/src/generated/alerts/api.ts
+++ b/services/mcp/src/generated/alerts/api.ts
@@ -42,6 +42,7 @@ export const AlertsCreateParams = /* @__PURE__ */ zod.object({
export const alertsCreateBodyConfigOneOneTypeDefault = `TrendsAlertConfig`
export const alertsCreateBodyConfigOneTwoTypeDefault = `HogQLAlertConfig`
+export const alertsCreateBodyConfigOneThreeTypeDefault = `FunnelsAlertConfig`
export const alertsCreateBodyDetectorConfigOneOneDetectorsItemOneTypeDefault = `zscore`
export const alertsCreateBodyDetectorConfigOneOneDetectorsItemTwoTypeDefault = `mad`
export const alertsCreateBodyDetectorConfigOneOneDetectorsItemThreeTypeDefault = `iqr`
@@ -155,6 +156,14 @@ export const AlertsCreateBody = /* @__PURE__ */ zod.object({
),
type: zod.enum(['HogQLAlertConfig']).default(alertsCreateBodyConfigOneTwoTypeDefault),
}),
+ zod.object({
+ funnel_step: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe('Zero-based step index to evaluate. Null = the last step (overall conversion).'),
+ metric: zod.enum(['conversion_from_start', 'conversion_from_previous']),
+ type: zod.enum(['FunnelsAlertConfig']).default(alertsCreateBodyConfigOneThreeTypeDefault),
+ }),
])
.describe(
'Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support.'
@@ -163,7 +172,7 @@ export const AlertsCreateBody = /* @__PURE__ */ zod.object({
])
.optional()
.describe(
- "Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode)."
+ "Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). FunnelsAlertConfig (funnel insights): funnel_step (the step to monitor, null for the overall last step) and metric ('conversion_from_start' or 'conversion_from_previous'); funnel alerts only support absolute_value conditions."
),
detector_config: zod
.union([
@@ -1315,6 +1324,7 @@ export const AlertsPartialUpdateParams = /* @__PURE__ */ zod.object({
export const alertsPartialUpdateBodyConfigOneOneTypeDefault = `TrendsAlertConfig`
export const alertsPartialUpdateBodyConfigOneTwoTypeDefault = `HogQLAlertConfig`
+export const alertsPartialUpdateBodyConfigOneThreeTypeDefault = `FunnelsAlertConfig`
export const alertsPartialUpdateBodyDetectorConfigOneOneDetectorsItemOneTypeDefault = `zscore`
export const alertsPartialUpdateBodyDetectorConfigOneOneDetectorsItemTwoTypeDefault = `mad`
export const alertsPartialUpdateBodyDetectorConfigOneOneDetectorsItemThreeTypeDefault = `iqr`
@@ -1431,6 +1441,16 @@ export const AlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
),
type: zod.enum(['HogQLAlertConfig']).default(alertsPartialUpdateBodyConfigOneTwoTypeDefault),
}),
+ zod.object({
+ funnel_step: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe('Zero-based step index to evaluate. Null = the last step (overall conversion).'),
+ metric: zod.enum(['conversion_from_start', 'conversion_from_previous']),
+ type: zod
+ .enum(['FunnelsAlertConfig'])
+ .default(alertsPartialUpdateBodyConfigOneThreeTypeDefault),
+ }),
])
.describe(
'Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support.'
@@ -1439,7 +1459,7 @@ export const AlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
])
.optional()
.describe(
- "Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode)."
+ "Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). FunnelsAlertConfig (funnel insights): funnel_step (the step to monitor, null for the overall last step) and metric ('conversion_from_start' or 'conversion_from_previous'); funnel alerts only support absolute_value conditions."
),
detector_config: zod
.union([
@@ -2614,6 +2634,7 @@ export const alertsSimulateCreateBodyDetectorConfigOneOnethreeTypeDefault = `pca
export const alertsSimulateCreateBodySeriesIndexDefault = 0
export const alertsSimulateCreateBodyConfigOneOneTypeDefault = `TrendsAlertConfig`
export const alertsSimulateCreateBodyConfigOneTwoTypeDefault = `HogQLAlertConfig`
+export const alertsSimulateCreateBodyConfigOneThreeTypeDefault = `FunnelsAlertConfig`
export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({
insight: zod.number().describe('Insight ID to simulate the detector on.'),
@@ -3667,6 +3688,16 @@ export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({
),
type: zod.enum(['HogQLAlertConfig']).default(alertsSimulateCreateBodyConfigOneTwoTypeDefault),
}),
+ zod.object({
+ funnel_step: zod
+ .union([zod.number(), zod.null()])
+ .optional()
+ .describe('Zero-based step index to evaluate. Null = the last step (overall conversion).'),
+ metric: zod.enum(['conversion_from_start', 'conversion_from_previous']),
+ type: zod
+ .enum(['FunnelsAlertConfig'])
+ .default(alertsSimulateCreateBodyConfigOneThreeTypeDefault),
+ }),
])
.describe(
'Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support.'
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json
index fa3e358725a3..3c193d29f026 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json
@@ -91,6 +91,32 @@
},
"required": ["evaluation"],
"type": "object"
+ },
+ {
+ "properties": {
+ "funnel_step": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Zero-based step index to evaluate. Null = the last step (overall conversion)."
+ },
+ "metric": {
+ "enum": ["conversion_from_start", "conversion_from_previous"],
+ "type": "string"
+ },
+ "type": {
+ "default": "FunnelsAlertConfig",
+ "enum": ["FunnelsAlertConfig"],
+ "type": "string"
+ }
+ },
+ "required": ["metric"],
+ "type": "object"
}
],
"description": "Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support."
@@ -99,7 +125,7 @@
"type": "null"
}
],
- "description": "Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode)."
+ "description": "Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). FunnelsAlertConfig (funnel insights): funnel_step (the step to monitor, null for the overall last step) and metric ('conversion_from_start' or 'conversion_from_previous'); funnel alerts only support absolute_value conditions."
},
"detector_config": {
"anyOf": [
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json
index 5a432feca0b0..39a52ea66b4e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json
@@ -68,6 +68,32 @@
},
"required": ["evaluation"],
"type": "object"
+ },
+ {
+ "properties": {
+ "funnel_step": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Zero-based step index to evaluate. Null = the last step (overall conversion)."
+ },
+ "metric": {
+ "enum": ["conversion_from_start", "conversion_from_previous"],
+ "type": "string"
+ },
+ "type": {
+ "default": "FunnelsAlertConfig",
+ "enum": ["FunnelsAlertConfig"],
+ "type": "string"
+ }
+ },
+ "required": ["metric"],
+ "type": "object"
}
],
"description": "Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support."
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json
index 049dd5270a63..782505447ab8 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json
@@ -91,6 +91,32 @@
},
"required": ["evaluation"],
"type": "object"
+ },
+ {
+ "properties": {
+ "funnel_step": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Zero-based step index to evaluate. Null = the last step (overall conversion)."
+ },
+ "metric": {
+ "enum": ["conversion_from_start", "conversion_from_previous"],
+ "type": "string"
+ },
+ "type": {
+ "default": "FunnelsAlertConfig",
+ "enum": ["FunnelsAlertConfig"],
+ "type": "string"
+ }
+ },
+ "required": ["metric"],
+ "type": "object"
}
],
"description": "Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support."
@@ -99,7 +125,7 @@
"type": "null"
}
],
- "description": "Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode)."
+ "description": "Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). FunnelsAlertConfig (funnel insights): funnel_step (the step to monitor, null for the overall last step) and metric ('conversion_from_start' or 'conversion_from_previous'); funnel alerts only support absolute_value conditions."
},
"detector_config": {
"anyOf": [