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): support historical trends funnel alerts (#66864)

Vasco de Krijgerb3d52aefcb72
diff --git a/frontend/src/lib/components/Alerts/AlertsButton.tsx b/frontend/src/lib/components/Alerts/AlertsButton.tsx
index 402f1cf7d73d..b1097bf016ea 100644
--- a/frontend/src/lib/components/Alerts/AlertsButton.tsx
+++ b/frontend/src/lib/components/Alerts/AlertsButton.tsx
@@ -31,7 +31,7 @@ export function AlertsButton({ insight, insightLogicProps, text, ...props }: Ale
const disabledReason =
supported || (alerts?.length ?? 0) > 0
? undefined
- : alertsUnsupportedReason({ hogqlAlertsEnabled, funnelAlertsEnabled })
+ : alertsUnsupportedReason({ hogqlAlertsEnabled, funnelAlertsEnabled }, insight.query)
return (
<LemonButton
diff --git a/frontend/src/lib/components/Alerts/alertFormLogic.test.ts b/frontend/src/lib/components/Alerts/alertFormLogic.test.ts
index 22461147b7e2..c4bc13d1a622 100644
--- a/frontend/src/lib/components/Alerts/alertFormLogic.test.ts
+++ b/frontend/src/lib/components/Alerts/alertFormLogic.test.ts
@@ -21,11 +21,18 @@ import {
import { initKeaTests } from '~/test/init'
import { InsightLogicProps, InsightShortId } from '~/types'
-import { alertFormLogic, thresholdAlertHasBounds, type AlertFormType } from './alertFormLogic'
+import {
+ alertFormLogic,
+ canCheckOngoingInterval,
+ ongoingIntervalField,
+ 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 { supportsOngoingInterval } from './types'
import type { AlertType } from './types'
const Insight42 = '42' as InsightShortId
@@ -159,6 +166,28 @@ describe('alertFormLogic', () => {
expect(successToastSpy).toHaveBeenCalledWith('Alert created.')
})
+ // Funnels hide the #/% unit toggle and always compare a relative change as a percentage of the
+ // prior period, so a funnel relative alert must persist with a PERCENTAGE threshold even if the
+ // form still carries an ABSOLUTE type. Regresses if the submit-side force is dropped.
+ it('persists a funnel relative alert with a PERCENTAGE threshold', async () => {
+ const logic = mountForm()
+ logic.actions.setAlertFormValues({
+ ...makeFormDefaults({
+ config: { type: 'FunnelsAlertConfig', metric: 'conversion_from_start', funnel_step: null },
+ condition: { type: AlertConditionType.RELATIVE_DECREASE },
+ threshold: { configuration: { type: InsightThresholdType.ABSOLUTE, bounds: { lower: 0.2 } } },
+ }),
+ checks: undefined,
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.submitAlertForm()
+ }).toFinishAllListeners()
+
+ expect(createSpy).toHaveBeenCalledTimes(1)
+ expect(createSpy.mock.calls[0][0].threshold.configuration.type).toBe(InsightThresholdType.PERCENTAGE)
+ })
+
// Regression test for ticket #353:
// A post-save side-effect (e.g. the parent `onEditSuccess` callback) throwing must NOT surface as
// "Error saving alert: undefined: undefined" — the alert was already created successfully (HTTP 201).
@@ -787,8 +816,214 @@ describe('alertFormLogic', () => {
],
])('%s', (_name, insightData, config, bounds, expected) => {
expect(
- deriveFunnelAlertPreview(insightData as Record<string, any> | null, config as any, bounds as any)
+ deriveFunnelAlertPreview(insightData as Record<string, any> | null, config as any, bounds as any, false)
).toEqual(expected)
})
+
+ // Trends funnels return a conversion-rate time series; the alert evaluates the last complete
+ // period by default, or the latest in-progress one when check_ongoing_interval is set.
+ const trend = (data: (number | null)[], breakdown_value: unknown = null): Record<string, any> => ({
+ data,
+ days: data.map((_, i) => `d${i}`),
+ breakdown_value,
+ })
+ const ongoing = { ...FROM_START, check_ongoing_interval: true } as const
+ it.each([
+ [
+ 'default evaluates the last complete period (the latest is in progress)',
+ { result: [trend([10, 25, 40])] },
+ FROM_START,
+ { lower: 50 },
+ undefined,
+ undefined,
+ { status: 'ok', values: [value(null, 25, true)], isBreakdown: false, hasBounds: true },
+ ],
+ [
+ // Regression guard: the backend skips a null anchor, so the preview must not read it as a
+ // breaching 0% against a lower bound.
+ 'a null anchor period is treated as no data, not a 0% breach',
+ { result: [trend([null, 25])] },
+ FROM_START,
+ { lower: 50 },
+ undefined,
+ undefined,
+ { status: 'ok', values: [value(null, 0, false)], isBreakdown: false, hasBounds: true },
+ ],
+ [
+ 'check_ongoing_interval evaluates the latest (in-progress) period',
+ { result: [trend([10, 25, 40])] },
+ ongoing,
+ { lower: 30 },
+ undefined,
+ undefined,
+ { status: 'ok', values: [value(null, 40, false)], isBreakdown: false, hasBounds: true },
+ ],
+ [
+ 'breakdown yields one value per series and drops previous-period rows',
+ {
+ result: [
+ { ...trend([10, 40], ['Chrome']), compare_label: 'current' },
+ { ...trend([5, 20], ['Safari']), compare_label: 'current' },
+ { ...trend([8, 30], ['Chrome']), compare_label: 'previous' },
+ ],
+ },
+ FROM_START,
+ { lower: 8 },
+ undefined,
+ undefined,
+ {
+ status: 'ok',
+ values: [value('Chrome', 10, false), value('Safari', 5, true)],
+ isBreakdown: true,
+ hasBounds: true,
+ },
+ ],
+ [
+ // 5 is the in-progress period (skipped by default); compares 30 against 40 — a 10-point
+ // drop, over the 8-point upper bound → breach.
+ 'relative decrease evaluates the last complete period vs the prior one',
+ { result: [trend([40, 30, 5])] },
+ FROM_START,
+ { upper: 8 },
+ AlertConditionType.RELATIVE_DECREASE,
+ InsightThresholdType.ABSOLUTE,
+ {
+ status: 'ok',
+ values: [{ label: null, rate: 30, previousRate: 40, breaching: true }],
+ isBreakdown: false,
+ hasBounds: true,
+ relative: true,
+ },
+ ],
+ [
+ // check_ongoing → anchor the latest period (5) against the prior one (30): a 25-point drop.
+ 'relative decrease with check_ongoing_interval diffs the in-progress period',
+ { result: [trend([40, 30, 5])] },
+ ongoing,
+ { upper: 8 },
+ AlertConditionType.RELATIVE_DECREASE,
+ InsightThresholdType.ABSOLUTE,
+ {
+ status: 'ok',
+ values: [{ label: null, rate: 5, previousRate: 30, breaching: true }],
+ isBreakdown: false,
+ hasBounds: true,
+ relative: true,
+ },
+ ],
+ [
+ // 60 → 40 is a 33% relative drop; percentage bounds are a ratio (0.3), so 0.333 breaches —
+ // mirroring the backend comparator's _relative_value.
+ 'relative decrease with a percentage threshold compares the ratio change',
+ { result: [trend([60, 40])] },
+ ongoing,
+ { upper: 0.3 },
+ AlertConditionType.RELATIVE_DECREASE,
+ InsightThresholdType.PERCENTAGE,
+ {
+ status: 'ok',
+ values: [{ label: null, rate: 40, previousRate: 60, breaching: true }],
+ isBreakdown: false,
+ hasBounds: true,
+ relative: true,
+ },
+ ],
+ [
+ 'relative with only one complete period flags no prior',
+ { result: [trend([30, 20])] }, // 20 is in progress; only one complete period
+ FROM_START,
+ { upper: 5 },
+ AlertConditionType.RELATIVE_DECREASE,
+ InsightThresholdType.ABSOLUTE,
+ {
+ status: 'ok',
+ values: [{ label: null, rate: 30, breaching: false }],
+ isBreakdown: false,
+ hasBounds: true,
+ relative: true,
+ },
+ ],
+ ])('trends funnel: %s', (_name, insightData, config, bounds, conditionType, thresholdType, expected) => {
+ expect(
+ deriveFunnelAlertPreview(
+ insightData as Record<string, any> | null,
+ config as any,
+ bounds as any,
+ true,
+ conditionType as any,
+ thresholdType as any
+ )
+ ).toEqual(expected)
+ })
+ })
+
+ describe('ongoing-interval gating', () => {
+ const funnelConfig = { type: 'FunnelsAlertConfig', metric: 'conversion_from_start', funnel_step: null }
+ const trendsAbsoluteWithUpper = (condition: AlertConditionType): any => ({
+ condition: { type: condition },
+ threshold: { configuration: { bounds: { upper: 10 } } },
+ })
+
+ // supportsOngoingInterval is config-level: trends and funnels carry check_ongoing_interval; the
+ // steps-vs-trends funnel gate lives in canCheckOngoingInterval below.
+ it.each([
+ ['trends config', { type: 'TrendsAlertConfig', series_index: 0 }, true],
+ ['funnel config', funnelConfig, true],
+ ['SQL config', { type: 'HogQLAlertConfig', evaluation: 'last_row' }, false],
+ ['null', null, false],
+ ])('supportsOngoingInterval(%s) === %s', (_name, config, expected) => {
+ expect(supportsOngoingInterval(config as any)).toBe(expected)
+ })
+
+ it('canCheckOngoingInterval: a steps funnel cannot, a trends funnel can', () => {
+ const funnelAlert: any = { config: funnelConfig, condition: { type: AlertConditionType.RELATIVE_DECREASE } }
+ expect(canCheckOngoingInterval(funnelAlert, { isTrendsFunnel: false })).toBe(false)
+ expect(canCheckOngoingInterval(funnelAlert, { isTrendsFunnel: true })).toBe(true)
+ })
+
+ it.each([
+ ['absolute value with an upper bound', AlertConditionType.ABSOLUTE_VALUE, true],
+ ['relative increase with an upper bound', AlertConditionType.RELATIVE_INCREASE, true],
+ ['relative decrease (never)', AlertConditionType.RELATIVE_DECREASE, false],
+ ])('canCheckOngoingInterval trends: %s → %s', (_name, condition, expected) => {
+ expect(canCheckOngoingInterval(trendsAbsoluteWithUpper(condition))).toBe(expected)
+ })
+
+ it('canCheckOngoingInterval trends: absolute without an upper bound cannot', () => {
+ const alert: any = {
+ condition: { type: AlertConditionType.ABSOLUTE_VALUE },
+ threshold: { configuration: { bounds: {} } },
+ }
+ expect(canCheckOngoingInterval(alert)).toBe(false)
+ })
+
+ // The util the advanced-options section renders from — one place for the per-kind branching.
+ it.each([
+ [
+ 'trends, eligible',
+ { type: 'TrendsAlertConfig', series_index: 0, check_ongoing_interval: true },
+ true,
+ true,
+ true,
+ false,
+ ],
+ [
+ 'trends, ineligible (shown but disabled)',
+ { type: 'TrendsAlertConfig', series_index: 0, check_ongoing_interval: true },
+ false,
+ true,
+ false,
+ true,
+ ],
+ ['steps funnel (canCheck false → hidden)', funnelConfig, false, false, false, true],
+ ['trends funnel (canCheck true → shown, no reason)', funnelConfig, true, true, false, false],
+ ['SQL (never shown)', { type: 'HogQLAlertConfig', evaluation: 'last_row' }, false, false, false, true],
+ ])('ongoingIntervalField: %s', (_name, config, canCheck, show, checked, hasReason) => {
+ const field = ongoingIntervalField(config as any, canCheck)
+ expect(field.show).toBe(show)
+ expect(field.checked).toBe(checked)
+ expect(field.disabledReason !== undefined).toBe(hasReason)
+ expect(field.tooltip.length).toBeGreaterThan(0)
+ })
})
})
diff --git a/frontend/src/lib/components/Alerts/alertFormLogic.ts b/frontend/src/lib/components/Alerts/alertFormLogic.ts
index 4cfa76b82d85..75e561f0b103 100644
--- a/frontend/src/lib/components/Alerts/alertFormLogic.ts
+++ b/frontend/src/lib/components/Alerts/alertFormLogic.ts
@@ -41,8 +41,10 @@ import {
AlertType,
AlertTypeWrite,
AnomalyPoint,
+ isFunnelsAlertConfig,
isHogQLAlertConfig,
isTrendsAlertConfig,
+ supportsOngoingInterval,
} from './types'
export { THRESHOLD_BOUNDS_FORM_ERROR, thresholdAlertHasBounds } from './alertFormSchema'
@@ -70,7 +72,16 @@ export type AlertFormType = Pick<
insight?: QueryBasedInsightModel['id']
}
-export function canCheckOngoingInterval(alert?: AlertType | AlertFormType): boolean {
+export function canCheckOngoingInterval(
+ alert?: AlertType | AlertFormType,
+ { isTrendsFunnel = false }: { isTrendsFunnel?: boolean } = {}
+): boolean {
+ // A funnel conversion rate isn't biased low over a partial period, so a trends funnel can always
+ // check the ongoing one (steps funnels have no periods). A trends count is cumulative, so it's only
+ // safe for an absolute/increase check above an upper bound.
+ if (isFunnelsAlertConfig(alert?.config)) {
+ return isTrendsFunnel
+ }
const upper = alert?.threshold?.configuration?.bounds?.upper
return (
(alert?.condition?.type === AlertConditionType.ABSOLUTE_VALUE ||
@@ -80,6 +91,32 @@ export function canCheckOngoingInterval(alert?: AlertType | AlertFormType): bool
)
}
+const ONGOING_DISABLED_REASON =
+ 'Can only alert for ongoing period when checking for absolute value/increase above a set upper threshold.'
+const ONGOING_TOOLTIP_FUNNEL =
+ 'By default the alert uses the most recently completed period. Enable this to evaluate the current, still-in-progress period instead — useful to be alerted sooner, at the cost of a partial datapoint.'
+const ONGOING_TOOLTIP_TRENDS =
+ "Checks the insight value for the ongoing period (current week/month) that hasn't yet completed. Use this if you want to be alerted right away when the insight value rises/increases above threshold"
+
+export interface OngoingIntervalField {
+ show: boolean
+ checked: boolean
+ disabledReason?: string
+ tooltip: string
+}
+
+/** State of the "Check ongoing period" advanced-option, keyed on alert kind — so the per-kind
+ * branching lives here rather than growing inside the component as more alert types are added. */
+export function ongoingIntervalField(config: AlertConfig | null | undefined, canCheck: boolean): OngoingIntervalField {
+ return {
+ // Trends alerts show the toggle even when ineligible (disabled); funnels only when eligible.
+ show: supportsOngoingInterval(config) && (isTrendsAlertConfig(config) || canCheck),
+ checked: supportsOngoingInterval(config) && !!config.check_ongoing_interval && canCheck,
+ disabledReason: canCheck ? undefined : ONGOING_DISABLED_REASON,
+ tooltip: isFunnelsAlertConfig(config) ? ONGOING_TOOLTIP_FUNNEL : ONGOING_TOOLTIP_TRENDS,
+ }
+}
+
/** The insight query kind an alert is built for; selects the default config type for new alerts. */
export type InsightAlertKind = 'trends' | 'hogql' | 'funnels'
@@ -91,6 +128,9 @@ export interface AlertFormLogicProps {
insightInterval?: IntervalType
/** Selects the default config type for new alerts based on the insight's query kind. */
insightAlertKind?: InsightAlertKind
+ /** For funnel insights: whether it's a trends (historical) funnel, which alerts on the overall
+ * conversion rate over time rather than a single step snapshot. Drives the preview shape. */
+ insightIsTrendsFunnel?: boolean
}
const defaultConfigForInsight = (kind: AlertFormLogicProps['insightAlertKind']): AlertConfig => {
@@ -332,6 +372,14 @@ export const alertFormLogic = kea<alertFormLogicType>([
if (payload.condition.type === AlertConditionType.ABSOLUTE_VALUE) {
payload.threshold.configuration.type = InsightThresholdType.ABSOLUTE
}
+ // Funnels express relative change as a percentage of the prior period; the absolute (#)
+ // unit is hidden in the funnel UI, so persist PERCENTAGE for any funnel relative condition.
+ if (
+ isFunnelsAlertConfig(payload.config) &&
+ payload.condition.type !== AlertConditionType.ABSOLUTE_VALUE
+ ) {
+ payload.threshold.configuration.type = InsightThresholdType.PERCENTAGE
+ }
const upsertToParent = (updatedAlert: AlertType): void => {
if (props.insightVizDataLogicProps) {
@@ -422,13 +470,26 @@ export const alertFormLogic = kea<alertFormLogicType>([
s.insightData,
(state, logicProps) => s.alertForm(state, logicProps)?.config,
(state, logicProps) => s.alertForm(state, logicProps)?.threshold?.configuration?.bounds,
+ (state, logicProps) => s.alertForm(state, logicProps)?.condition?.type,
+ (state, logicProps) => s.alertForm(state, logicProps)?.threshold?.configuration?.type,
],
(
insightData: Record<string, any> | null,
config: AlertConfig | null | undefined,
- bounds: InsightsThresholdBounds | null | undefined
+ bounds: InsightsThresholdBounds | null | undefined,
+ conditionType: AlertConditionType | undefined,
+ thresholdType: InsightThresholdType | undefined
): FunnelAlertPreview | null =>
- props.insightAlertKind === 'funnels' ? deriveFunnelAlertPreview(insightData, config, bounds) : null,
+ props.insightAlertKind === 'funnels'
+ ? deriveFunnelAlertPreview(
+ insightData,
+ config,
+ bounds,
+ !!props.insightIsTrendsFunnel,
+ conditionType,
+ thresholdType
+ )
+ : null,
],
/** Result column names of the SQL insight, for the column pickers. */
hogqlResultColumns: [
diff --git a/frontend/src/lib/components/Alerts/funnelAlertPreview.ts b/frontend/src/lib/components/Alerts/funnelAlertPreview.ts
index a3b81233dd0a..38772e391004 100644
--- a/frontend/src/lib/components/Alerts/funnelAlertPreview.ts
+++ b/frontend/src/lib/components/Alerts/funnelAlertPreview.ts
@@ -1,25 +1,96 @@
-import { InsightsThresholdBounds } from '~/queries/schema/schema-general'
+import { AlertConditionType, InsightsThresholdBounds, InsightThresholdType } 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
+ rate: number // 0–100 — the period the alert evaluates (latest, or last complete for relative)
breaching: boolean
+ previousRate?: number // relative only: the prior period's rate the change is measured against
}
-/** 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. */
+/** Advisory preview, mirroring the backend funnel strategies
+ * (products/alerts/backend/evaluation/funnel_strategies.py) — keep in sync if you change the backend math. */
export type FunnelAlertPreview =
| { status: 'no-data' }
- | { status: 'ok'; values: FunnelAlertPreviewValue[]; isBreakdown: boolean; hasBounds: boolean }
+ // `relative`: the alert fires on the period-over-period change. The values carry the last complete
+ // period and the one before it, and `breaching` reflects the change against the threshold.
+ | { status: 'ok'; values: FunnelAlertPreviewValue[]; isBreakdown: boolean; hasBounds: boolean; relative?: boolean }
+
+/** Period-over-period change the alert evaluates, mirroring the backend comparator's `_relative_value`:
+ * an absolute threshold compares the raw percentage-point change; a percentage threshold the ratio. */
+function _relativeChange(
+ conditionType: AlertConditionType,
+ thresholdType: InsightThresholdType | undefined,
+ anchor: number,
+ previous: number
+): number {
+ const numerator = conditionType === AlertConditionType.RELATIVE_INCREASE ? anchor - previous : previous - anchor
+ if (thresholdType !== InsightThresholdType.PERCENTAGE) {
+ return numerator
+ }
+ if (previous === 0) {
+ return anchor === 0 ? 0 : Infinity
+ }
+ return numerator / previous
+}
interface FunnelStep {
count: number
breakdown_value?: unknown
}
+// A trends funnel series is a conversion-rate time series, not a step list: `data` holds the 0–100
+// rate per period. A gap period can be null; the backend maps it to None and skips it, so the preview
+// treats a null anchor as no-data rather than reading it as a (potentially breaching) 0.
+interface FunnelTrendsSeries {
+ data?: (number | null)[]
+ breakdown_value?: unknown
+}
+
+function _deriveTrendsPreview(
+ series: FunnelTrendsSeries[],
+ bounds: InsightsThresholdBounds | null | undefined,
+ thresholdType: InsightThresholdType | undefined,
+ conditionType: AlertConditionType | undefined,
+ checkOngoing: boolean
+): FunnelAlertPreview {
+ const relative =
+ conditionType === AlertConditionType.RELATIVE_INCREASE || conditionType === AlertConditionType.RELATIVE_DECREASE
+ const values: FunnelAlertPreviewValue[] = series.map((s) => {
+ const data = s.data ?? []
+ const label = _breakdownLabel(s.breakdown_value)
+ // By default the latest period is still in progress, so anchor on the last complete one;
+ // check_ongoing_interval anchors on the latest. Clamped to 0 like the backend's
+ // `max(len - 1 if ongoing else len - 2, 0)`.
+ const anchorIndex = Math.max(checkOngoing ? data.length - 1 : data.length - 2, 0)
+ const anchor = data[anchorIndex]
+ // The backend skips a null/gap anchor period (no fire); mirror that rather than reading it as 0.
+ if (typeof anchor !== 'number') {
+ return { label, rate: 0, breaching: false }
+ }
+ if (!relative) {
+ return { label, rate: anchor, breaching: valueBreachesBounds(anchor, bounds) }
+ }
+ // Relative: diff the anchor against the period before it (same as the backend comparator).
+ const prev = anchorIndex >= 1 ? data[anchorIndex - 1] : undefined
+ const previousRate = typeof prev === 'number' ? prev : undefined
+ const breaching =
+ previousRate === undefined
+ ? false
+ : valueBreachesBounds(_relativeChange(conditionType!, thresholdType, anchor, previousRate), bounds)
+ return { label, rate: anchor, previousRate, breaching }
+ })
+ return {
+ status: 'ok',
+ values,
+ isBreakdown: series.length > 1,
+ hasBounds: hasThresholdBounds(bounds),
+ ...(relative ? { relative: true } : {}),
+ }
+}
+
const _conversionRate = (steps: FunnelStep[], stepIndex: number, fromPrevious: boolean): number | null => {
if (stepIndex < 0 || stepIndex >= steps.length) {
return null
@@ -33,8 +104,7 @@ const _conversionRate = (steps: FunnelStep[], stepIndex: number, fromPrevious: b
return base === 0 ? 0 : (target / base) * 100
}
-const _breakdownLabel = (steps: FunnelStep[]): string | null => {
- const breakdown = steps[0]?.breakdown_value
+const _breakdownLabel = (breakdown: unknown): string | null => {
if (breakdown == null) {
return null
}
@@ -62,7 +132,10 @@ function _currentPeriodOnly(result: any[]): any[] {
export function deriveFunnelAlertPreview(
insightData: Record<string, any> | null,
config: AlertConfig | null | undefined,
- bounds: InsightsThresholdBounds | null | undefined
+ bounds: InsightsThresholdBounds | null | undefined,
+ isTrendsFunnel: boolean,
+ conditionType?: AlertConditionType,
+ thresholdType?: InsightThresholdType
): FunnelAlertPreview | null {
if (!isFunnelsAlertConfig(config)) {
return null
@@ -79,6 +152,10 @@ export function deriveFunnelAlertPreview(
// the "not loaded yet" hint.
return { status: 'no-data' }
}
+ // A trends funnel returns conversion-rate time series rather than step lists.
+ if (isTrendsFunnel) {
+ return _deriveTrendsPreview(result, bounds, thresholdType, conditionType, !!config.check_ongoing_interval)
+ }
// 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]
@@ -94,7 +171,11 @@ export function deriveFunnelAlertPreview(
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) })
+ values.push({
+ label: _breakdownLabel(steps[0]?.breakdown_value),
+ rate,
+ breaching: valueBreachesBounds(rate, bounds),
+ })
}
return { status: 'ok', values, isBreakdown, hasBounds: hasThresholdBounds(bounds) }
}
diff --git a/frontend/src/lib/components/Alerts/insightAlertsLogic.test.ts b/frontend/src/lib/components/Alerts/insightAlertsLogic.test.ts
index e0fcb9360e13..4755d629ffe2 100644
--- a/frontend/src/lib/components/Alerts/insightAlertsLogic.test.ts
+++ b/frontend/src/lib/components/Alerts/insightAlertsLogic.test.ts
@@ -227,6 +227,18 @@ describe('areAlertsSupportedForInsight', () => {
expect(areAlertsSupportedForInsight(FUNNEL_QUERY, { funnelAlertsEnabled: true })).toBe(true)
})
+ it('supports steps and trends funnels but not time-to-convert or flow', () => {
+ const withViz = (funnelVizType?: string): Record<string, any> => ({
+ ...FUNNEL_QUERY,
+ source: { ...FUNNEL_QUERY.source, funnelsFilter: { funnelVizType } },
+ })
+ const opts = { funnelAlertsEnabled: true }
+ expect(areAlertsSupportedForInsight(withViz('steps'), opts)).toBe(true)
+ expect(areAlertsSupportedForInsight(withViz('trends'), opts)).toBe(true)
+ expect(areAlertsSupportedForInsight(withViz('time_to_convert'), opts)).toBe(false)
+ expect(areAlertsSupportedForInsight(withViz('flow'), opts)).toBe(false)
+ })
+
it('returns false when trendsFilter is null', () => {
const query = {
...API_QUERY,
@@ -250,4 +262,22 @@ describe('alertsUnsupportedReason', () => {
included.forEach((type) => expect(reason).toContain(type))
excluded.forEach((type) => expect(reason).not.toContain(type))
})
+
+ // A time-to-convert/flow funnel is itself a funnel, so the generic "funnel insights are supported"
+ // copy reads as a contradiction; the reason should name the real cause instead.
+ it('gives a funnel-viz-specific reason for time-to-convert / flow funnels', () => {
+ const funnelWithViz = (funnelVizType: string): Record<string, any> => ({
+ ...FUNNEL_QUERY,
+ source: { ...FUNNEL_QUERY.source, funnelsFilter: { funnelVizType } },
+ })
+ const options = { funnelAlertsEnabled: true }
+ for (const viz of ['time_to_convert', 'flow']) {
+ const reason = alertsUnsupportedReason(options, funnelWithViz(viz))
+ expect(reason).toContain('conversion rate')
+ expect(reason).toContain('steps or trends')
+ expect(reason).not.toContain('only available for')
+ }
+ // No query → backward-compatible generic copy.
+ expect(alertsUnsupportedReason(options)).toContain('only available for')
+ })
})
diff --git a/frontend/src/lib/components/Alerts/insightAlertsLogic.ts b/frontend/src/lib/components/Alerts/insightAlertsLogic.ts
index ea9d0e787bdf..682e3c7a56aa 100644
--- a/frontend/src/lib/components/Alerts/insightAlertsLogic.ts
+++ b/frontend/src/lib/components/Alerts/insightAlertsLogic.ts
@@ -15,7 +15,7 @@ import {
isInsightVizNode,
isTrendsQuery,
} from '~/queries/utils'
-import { InsightLogicProps } from '~/types'
+import { FunnelVizType, InsightLogicProps } from '~/types'
import type { insightAlertsLogicType } from './insightAlertsLogicType'
import { AlertType, AnomalyPoint, isTrendsAlertConfig } from './types'
@@ -42,7 +42,10 @@ export const areAlertsSupportedForInsight = (
return true
}
if (options.funnelAlertsEnabled && isInsightVizNode(query) && isFunnelsQuery(query.source)) {
- return true
+ // Steps and trends both alert on a conversion-rate percentage. Time-to-convert (a duration)
+ // and flow (a sankey) have no conversion-rate metric, so they aren't supported.
+ const vizType = query.source.funnelsFilter?.funnelVizType
+ return vizType !== FunnelVizType.TimeToConvert && vizType !== FunnelVizType.Flow
}
return !!options.hogqlAlertsEnabled && containsHogQLQuery(query)
}
@@ -52,11 +55,23 @@ export const areAlertsSupportedForInsight = (
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.`
+export const alertsUnsupportedReason = (
+ options: {
+ hogqlAlertsEnabled?: boolean
+ funnelAlertsEnabled?: boolean
+ },
+ query?: Record<string, any> | null
+): string => {
+ // A funnel on a viz type without a conversion-rate metric otherwise reads as a contradiction —
+ // "funnel insights are supported" while standing on a blocked funnel. Name the real reason instead.
+ if (options.funnelAlertsEnabled && query && isInsightVizNode(query) && isFunnelsQuery(query.source)) {
+ const vizType = query.source.funnelsFilter?.funnelVizType
+ if (vizType === FunnelVizType.TimeToConvert || vizType === FunnelVizType.Flow) {
+ return "Alerts track a conversion rate, which time-to-convert and flow funnels don't have. Switch to the steps or trends view to add an alert."
+ }
+ }
+ return `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[] {
diff --git a/frontend/src/lib/components/Alerts/thresholdPercent.test.ts b/frontend/src/lib/components/Alerts/thresholdPercent.test.ts
new file mode 100644
index 000000000000..536bda8a5afc
--- /dev/null
+++ b/frontend/src/lib/components/Alerts/thresholdPercent.test.ts
@@ -0,0 +1,34 @@
+import { InsightThresholdType } from '~/queries/schema/schema-general'
+
+import { fractionToPercentInput, rescaleFunnelBound } from './thresholdPercent'
+
+describe('thresholdPercent', () => {
+ // Stored 0–1 fractions render as percentage inputs without float noise — guards the ×100
+ // round-trip surfacing values like 7.000000000000001 (regresses if the rounding is dropped).
+ it.each([
+ [undefined, undefined],
+ [0.99, 99],
+ [0.077, 7.7],
+ [0.3333, 33.33],
+ [1, 100],
+ ])('fractionToPercentInput(%p) === %p', (fraction, expected) => {
+ expect(fractionToPercentInput(fraction)).toBe(expected)
+ })
+
+ // Flipping a funnel's condition flips the threshold unit; the bound must rescale so the on-screen
+ // number is preserved (regresses to a ×100 blowup — 99 → 9900 — if the rescale is dropped).
+ it.each([
+ [99, InsightThresholdType.PERCENTAGE, 0.99],
+ [0.99, InsightThresholdType.ABSOLUTE, 99],
+ [7, InsightThresholdType.PERCENTAGE, 0.07],
+ [undefined, InsightThresholdType.PERCENTAGE, undefined],
+ ])('rescaleFunnelBound(%p, %s) === %p', (value, toType, expected) => {
+ expect(rescaleFunnelBound(value as number | undefined, toType)).toBe(expected)
+ })
+
+ it('preserves the displayed number across a unit switch instead of ×100-ing it', () => {
+ // Entered as "99%" under a has-value (ABSOLUTE) condition, then switched to relative.
+ const asFraction = rescaleFunnelBound(99, InsightThresholdType.PERCENTAGE)
+ expect(fractionToPercentInput(asFraction)).toBe(99) // was 9900 before the fix
+ })
+})
diff --git a/frontend/src/lib/components/Alerts/thresholdPercent.ts b/frontend/src/lib/components/Alerts/thresholdPercent.ts
new file mode 100644
index 000000000000..23f8b6534283
--- /dev/null
+++ b/frontend/src/lib/components/Alerts/thresholdPercent.ts
@@ -0,0 +1,21 @@
+import { InsightThresholdType } from '~/queries/schema/schema-general'
+
+// PERCENTAGE thresholds are stored as a 0–1 fraction and shown ×100; ABSOLUTE ones store the raw
+// percent. These helpers keep the on-screen number stable across that boundary and round the
+// round-trip so it doesn't surface floating-point noise (e.g. 7.000000000000001).
+
+const roundPercent = (value: number): number => Math.round(value * 1e6) / 1e6
+
+/** Render a stored 0–1 fraction as a percentage input value, rounded to avoid float noise. */
+export const fractionToPercentInput = (fraction: number | undefined): number | undefined =>
+ typeof fraction === 'number' ? roundPercent(fraction * 100) : undefined
+
+/** Convert a bound between the relative (0–1 fraction, PERCENTAGE) and absolute (raw percent) units so
+ * the displayed number is preserved when a funnel's condition flips the threshold type — rather than
+ * jumping ×100 / ÷100. */
+export const rescaleFunnelBound = (value: number | undefined, toType: InsightThresholdType): number | undefined => {
+ if (typeof value !== 'number') {
+ return undefined
+ }
+ return toType === InsightThresholdType.PERCENTAGE ? roundPercent(value / 100) : roundPercent(value * 100)
+}
diff --git a/frontend/src/lib/components/Alerts/types.ts b/frontend/src/lib/components/Alerts/types.ts
index ecf79894f0a0..c166b40f2461 100644
--- a/frontend/src/lib/components/Alerts/types.ts
+++ b/frontend/src/lib/components/Alerts/types.ts
@@ -32,11 +32,14 @@ export const isAnyRowHogQLConfig = (config: AlertConfig | null | undefined): boo
// checks, so the intent ("does this alert kind support X") is explicit. Kept separate even where
// they coincide today (all trends-only) because the capabilities are independent and may diverge.
-/** Trends alerts evaluate a time-bucketed series, so they can check the current (incomplete)
- * interval. SQL and funnel alerts evaluate whatever the query returns — no partial interval.
- * Type guard so call sites can read the trends-only `check_ongoing_interval` after the check. */
-export const supportsOngoingInterval = (config: AlertConfig | null | undefined): config is TrendsAlertConfig =>
- isTrendsAlertConfig(config)
+/** Trends alerts and historical-trend funnels evaluate a time-bucketed series, so they can check the
+ * current (incomplete) interval. SQL alerts evaluate whatever the query returns — no partial interval.
+ * Type guard so call sites can read `check_ongoing_interval` after the check. This is config-level: a
+ * steps funnel also matches (it carries the field), so the UI additionally gates the funnel case on
+ * whether it's a trends funnel — only those are a time series. */
+export const supportsOngoingInterval = (
+ config: AlertConfig | null | undefined
+): config is TrendsAlertConfig | FunnelsAlertConfig => isTrendsAlertConfig(config) || isFunnelsAlertConfig(config)
/** Trends and funnel alerts evaluate over the insight's time window/interval; SQL alerts own their
* own window inside the query, so there's no interval to echo in the UI. */
diff --git a/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx b/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx
index ce36c8aac2dc..98cddd15c88c 100644
--- a/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx
+++ b/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx
@@ -22,7 +22,7 @@ import { userLogic } from 'scenes/userLogic'
import { AlertCalculationInterval, AlertState } from '~/queries/schema/schema-general'
import { containsHogQLQuery, isFunnelsQuery, isInsightVizNode } from '~/queries/utils'
-import { AvailableFeature, InsightLogicProps, InsightShortId, QueryBasedInsightModel } from '~/types'
+import { AvailableFeature, FunnelVizType, InsightLogicProps, InsightShortId, QueryBasedInsightModel } from '~/types'
import { AlertAdvancedOptionsSection } from 'products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection'
import { AlertDefinitionSection } from 'products/alerts/frontend/components/editAlertModal/AlertDefinitionSection'
@@ -83,6 +83,10 @@ export function EditAlertModal({
const funnelSource = !!query && isInsightVizNode(query) && isFunnelsQuery(query.source) ? query.source : null
const isFunnelInsight = funnelSource !== null
+ // Trends funnels alert on the overall conversion rate over time, so they skip the step picker and
+ // the preview reads the latest period instead of a step snapshot. The backend dispatches on the
+ // same viz type — see funnel_strategies.py.
+ const isTrendsFunnel = funnelSource?.funnelsFilter?.funnelVizType === FunnelVizType.Trends
const funnelStepLabels = (funnelSource?.series ?? []).map(
(node, index) => getDisplayNameFromEntityNode(node) ?? `Step ${index + 1}`
)
@@ -99,6 +103,7 @@ export function EditAlertModal({
insightVizDataLogicProps: insightLogicProps,
insightInterval: trendInterval ?? undefined,
insightAlertKind,
+ insightIsTrendsFunnel: isTrendsFunnel,
}
const formLogic = alertFormLogic(formLogicProps)
const {
@@ -154,7 +159,7 @@ export function EditAlertModal({
}, [insightLogicProps, insightId])
const creatingNewAlert = alertForm.id === undefined
- const can_check_ongoing_interval = canCheckOngoingInterval(alertForm)
+ const can_check_ongoing_interval = canCheckOngoingInterval(alertForm, { isTrendsFunnel })
const alertMode = alertForm.detector_config ? 'detector' : 'threshold'
const nextPlannedEvaluationStale = useMemo(
() =>
@@ -192,9 +197,9 @@ export function EditAlertModal({
const enabledAdvancedOptionsCount = useMemo(() => {
let n = 0
if (
- can_check_ongoing_interval &&
supportsOngoingInterval(alertForm.config) &&
- alertForm.config.check_ongoing_interval
+ alertForm.config.check_ongoing_interval &&
+ can_check_ongoing_interval
) {
n += 1
}
@@ -271,7 +276,11 @@ export function EditAlertModal({
thresholdBoundsFormError={thresholdBoundsFormError}
isNonTimeSeriesDisplay={isNonTimeSeriesDisplay}
trends={{ alertSeries, formulaNodes, isBreakdownValid }}
- funnel={{ stepLabels: funnelStepLabels, preview: funnelAlertPreview }}
+ funnel={{
+ stepLabels: funnelStepLabels,
+ preview: funnelAlertPreview,
+ isTrendsFunnel,
+ }}
hogql={{
preview: hogqlAlertPreview,
columns: hogqlResultColumns,
diff --git a/frontend/src/lib/components/Alerts/views/ManageAlertsModal.tsx b/frontend/src/lib/components/Alerts/views/ManageAlertsModal.tsx
index a2fcc8d0de14..4e286294d095 100644
--- a/frontend/src/lib/components/Alerts/views/ManageAlertsModal.tsx
+++ b/frontend/src/lib/components/Alerts/views/ManageAlertsModal.tsx
@@ -95,6 +95,8 @@ interface ManageAlertsModalProps extends InsightAlertsLogicProps {
isOpen: boolean
insightShortId: InsightShortId
canCreateAlertForInsight: boolean
+ /** The insight's query, so the unsupported-reason copy can be specific (e.g. time-to-convert funnels). */
+ insightQuery?: Record<string, any> | null
onClose?: () => void
}
@@ -156,7 +158,7 @@ export function ManageAlertsModal(props: ManageAlertsModalProps): JSX.Element {
onClick={() => push(urls.insightAlert(props.insightShortId, 'new'))}
disabledReason={
!props.canCreateAlertForInsight
- ? alertsUnsupportedReason({ hogqlAlertsEnabled, funnelAlertsEnabled })
+ ? alertsUnsupportedReason({ hogqlAlertsEnabled, funnelAlertsEnabled }, props.insightQuery)
: undefined
}
>
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index 990ad15485ba..e6bfcbd957ef 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -613,6 +613,7 @@ export function InsightMeta({
insightId={insight.id}
insightShortId={short_id as InsightShortId}
canCreateAlertForInsight={canCreateAlertForInsight}
+ insightQuery={query}
deferInitialAlertsLoad
/>
) : null}
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 5a804edb7e0b..360b60d6f1b4 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -23138,6 +23138,10 @@
"additionalProperties": false,
"description": "Alert config for funnel insights. Evaluates the conversion rate (as a percentage) at one step.",
"properties": {
+ "check_ongoing_interval": {
+ "description": "When true, evaluate the current (still in-progress) period; by default only completed periods are used.",
+ "type": "boolean"
+ },
"funnel_step": {
"anyOf": [
{
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index d0c522572137..4fa8f0bfbf89 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -5125,6 +5125,8 @@ export interface FunnelsAlertConfig {
/** Zero-based step index to evaluate. Null = the last step (overall conversion). */
funnel_step?: integer | null
metric: FunnelConversionMetric
+ /** When true, evaluate the current (still in-progress) period; by default only completed periods are used. */
+ check_ongoing_interval?: boolean
}
/** One blocked period for quiet hours: 24-hour HH:MM in the project timezone; interval is half-open [start, end). */
diff --git a/frontend/src/scenes/insights/InsightModals.tsx b/frontend/src/scenes/insights/InsightModals.tsx
index d1818c059939..35471fdc787b 100644
--- a/frontend/src/scenes/insights/InsightModals.tsx
+++ b/frontend/src/scenes/insights/InsightModals.tsx
@@ -105,6 +105,7 @@ function InsightAlertsModals({ insightLogicProps }: { insightLogicProps: Insight
insightId={insight.id as number}
insightShortId={insight.short_id as InsightShortId}
canCreateAlertForInsight={canCreateAlertForInsight}
+ insightQuery={query}
/>
)}
diff --git a/posthog/schema.py b/posthog/schema.py
index cd2fbdc6264d..aefb7168ce73 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -5340,6 +5340,12 @@ class FunnelsAlertConfig(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ check_ongoing_interval: bool | None = Field(
+ default=None,
+ description=(
+ "When true, evaluate the current (still in-progress) period; by default only completed periods are used."
+ ),
+ )
funnel_step: int | None = Field(
default=None,
description=("Zero-based step index to evaluate. Null = the last step (overall conversion)."),
diff --git a/posthog/tasks/alerts/test/test_validate_alert_config.py b/posthog/tasks/alerts/test/test_validate_alert_config.py
index d192205a5176..ba6b8040eb3f 100644
--- a/posthog/tasks/alerts/test/test_validate_alert_config.py
+++ b/posthog/tasks/alerts/test/test_validate_alert_config.py
@@ -316,7 +316,7 @@ class TestValidateAlertConfig:
_funnels_config(),
_base_threshold(),
"daily",
- "Funnel alerts only support absolute value conditions",
+ "This funnel only supports absolute value conditions",
),
(
"funnels_relative_increase_rejected",
@@ -325,7 +325,7 @@ class TestValidateAlertConfig:
_funnels_config(),
_base_threshold(),
"daily",
- "Funnel alerts only support absolute value conditions",
+ "This funnel only supports absolute value conditions",
),
(
"funnels_from_previous_at_step_zero_rejected",
@@ -355,13 +355,49 @@ class TestValidateAlertConfig:
r"funnel_step 5 is out of range \(funnel has 2 steps\)",
),
(
- "funnels_non_steps_viz_rejected",
+ "funnels_trends_viz_accepted",
+ {**_funnels_query(), "funnelsFilter": {"funnelVizType": "trends"}},
+ _base_condition("absolute_value"),
+ _funnels_config(),
+ _base_threshold(),
+ "daily",
+ None,
+ ),
+ (
+ "funnels_time_to_convert_viz_rejected",
{**_funnels_query(), "funnelsFilter": {"funnelVizType": "time_to_convert"}},
_base_condition("absolute_value"),
_funnels_config(),
_base_threshold(),
"daily",
- "Funnel alerts require a steps funnel",
+ "aren't supported for the",
+ ),
+ (
+ "funnels_flow_viz_rejected",
+ {**_funnels_query(), "funnelsFilter": {"funnelVizType": "flow"}},
+ _base_condition("absolute_value"),
+ _funnels_config(),
+ _base_threshold(),
+ "daily",
+ "aren't supported for the",
+ ),
+ (
+ "funnels_trends_relative_condition_accepted",
+ {**_funnels_query(), "funnelsFilter": {"funnelVizType": "trends"}},
+ _base_condition("relative_increase"),
+ _funnels_config(),
+ _base_threshold(),
+ "daily",
+ None,
+ ),
+ (
+ "funnels_steps_relative_condition_rejected",
+ _funnels_query(), # defaults to a steps funnel
+ _base_condition("relative_increase"),
+ _funnels_config(),
+ _base_threshold(),
+ "daily",
+ "only supports absolute value conditions",
),
]
)
diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.py
index 56c54f095517..73555e4102ee 100644
--- a/products/alerts/backend/api/alert.py
+++ b/products/alerts/backend/api/alert.py
@@ -227,8 +227,10 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
"'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."
+ "last step), metric ('conversion_from_start' or 'conversion_from_previous'), and "
+ "check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). "
+ "Steps funnels support only absolute_value conditions; historical-trend funnels also support "
+ "relative_increase/relative_decrease (compared against the prior period)."
),
)
detector_config = DetectorConfigField(required=False, allow_null=True)
diff --git a/products/alerts/backend/evaluation/funnel_strategies.py b/products/alerts/backend/evaluation/funnel_strategies.py
new file mode 100644
index 000000000000..9bd3e72a7b8c
--- /dev/null
+++ b/products/alerts/backend/evaluation/funnel_strategies.py
@@ -0,0 +1,207 @@
+from typing import Any, cast
+
+from posthog.schema import FunnelConversionMetric, FunnelsAlertConfig, FunnelsQuery, FunnelVizType
+
+from products.alerts.backend.evaluation.contract import AlertExtractionError, ComparableSeries, SeriesPoint
+
+# Funnel alerts evaluate a conversion-rate percentage (0–100): a steps funnel at the configured step,
+# a trends funnel at the latest period. Other viz types (time-to-convert, flow) have no conversion-rate
+# metric and aren't supported — see strategy_for_viz.
+_CONVERSION_RATE_SUBJECT = "The funnel conversion rate"
+_CONVERSION_RATE_UNIT = "%"
+
+
+class FunnelVizStrategy:
+ """Per-viz-type behavior for funnel alerts: how to validate the config and read the query result
+ into a ``ComparableSeries`` the shared comparator can evaluate, plus the breach-message subject
+ and value unit. Selected by ``funnelVizType`` via ``strategy_for_viz`` — the funnel analogue of
+ the per-kind extractor registry in dispatcher.py. Adding a viz type = adding a subclass here.
+ """
+
+ subject: str
+ unit: str
+ # Whether relative (increase/decrease) conditions make sense: only for viz types that produce a
+ # time series with a prior value to compare against. A single snapshot (steps) has none.
+ supports_relative_conditions: bool = False
+
+ def validate_config(self, funnels_query: FunnelsQuery, config: FunnelsAlertConfig) -> None:
+ """Reject configs this viz type can't evaluate, at alert save time (raises ``ValueError``).
+ Default: nothing to reject — only the steps funnel has a per-step config to range-check."""
+ return None
+
+ def to_series(self, result: Any, config: FunnelsAlertConfig) -> list[ComparableSeries]:
+ """Normalize the funnel query result into one ``ComparableSeries`` per breakdown value."""
+ raise NotImplementedError
+
+
+class StepsFunnelStrategy(FunnelVizStrategy):
+ """Steps funnel: a single conversion-rate snapshot at the configured step (one point per series)."""
+
+ subject = _CONVERSION_RATE_SUBJECT
+ unit = _CONVERSION_RATE_UNIT
+
+ def validate_config(self, funnels_query: FunnelsQuery, config: FunnelsAlertConfig) -> None:
+ step = config.funnel_step
+ if step is not None:
+ if step < 0:
+ raise ValueError(f"funnel_step must be >= 0, got {step}")
+ # Exclusion nodes live in funnelsFilter, not series, so the series count is the result step
+ # count for a STEPS funnel — matching 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 config.metric == FunnelConversionMetric.CONVERSION_FROM_PREVIOUS and step == 0:
+ raise ValueError(
+ "conversion_from_previous is undefined at the first step; use conversion_from_start instead"
+ )
+
+ def to_series(self, result: Any, config: FunnelsAlertConfig) -> list[ComparableSeries]:
+ # A steps funnel is a single snapshot: the condition is always absolute (enforced upstream) and
+ # check_ongoing_interval has no meaning (there are no periods), so neither is read here.
+ breakdowns = _steps_per_breakdown(_current_period_only(result))
+ return [
+ ComparableSeries(
+ label=_label_for_breakdown(steps[0].get("breakdown_value") if steps else None),
+ points=[SeriesPoint(date=None, value=_conversion_rate(steps, config))],
+ current_index=0,
+ )
+ for steps in breakdowns
+ ]
+
+
+class HistoricalTrendsFunnelStrategy(FunnelVizStrategy):
+ """Historical-trend funnel: a time series of overall conversion rates. ``funnel_step``/``metric``
+ don't apply (the trend is the whole-funnel rate set by funnelsFilter), so the default no-op
+ ``validate_config`` is inherited. Being a time series, it supports relative conditions too."""
+
+ subject = _CONVERSION_RATE_SUBJECT
+ unit = _CONVERSION_RATE_UNIT
+ supports_relative_conditions = True
+
+ def to_series(self, result: Any, config: FunnelsAlertConfig) -> list[ComparableSeries]:
+ series_dicts = _require_series_list(_current_period_only(result), "trends")
+ # By default evaluate the last *complete* period — the latest one is still in progress, so
+ # anchoring there would read a partial rate (and, for relative, diff a partial against a complete
+ # one). check_ongoing_interval opts into that in-progress period. The anchor is the same for
+ # absolute and relative conditions; relative then diffs it against the period before it.
+ anchor_current = bool(config.check_ongoing_interval)
+ series: list[ComparableSeries] = []
+ for entry in series_dicts:
+ if not isinstance(entry, dict):
+ raise AlertExtractionError(
+ f"Funnel trends series is malformed (expected an object, got {type(entry).__name__})."
+ )
+ data = entry.get("data") or []
+ dates = entry.get("days") or [None] * len(data)
+ points = [SeriesPoint(date=date, value=_numeric_or_none(value)) for date, value in zip(dates, data)]
+ if not points:
+ # No periods in range — represent as a single missing point so the comparator skips it.
+ points = [SeriesPoint(date=None, value=None)]
+ current_index = max(len(points) - 1 if anchor_current else len(points) - 2, 0)
+ label = _label_for_breakdown(entry.get("breakdown_value"))
+ series.append(ComparableSeries(label=label, points=points, current_index=current_index))
+ return series
+
+
+# Mirrors EXTRACTORS in dispatcher.py: one strategy per supported funnel viz type. A funnel with no
+# explicit viz type defaults to STEPS (matching the schema default), resolved in strategy_for_viz.
+FUNNEL_VIZ_STRATEGIES: dict[FunnelVizType, FunnelVizStrategy] = {
+ FunnelVizType.STEPS: StepsFunnelStrategy(),
+ FunnelVizType.TRENDS: HistoricalTrendsFunnelStrategy(),
+}
+
+
+def strategy_for_viz(viz: FunnelVizType | None) -> FunnelVizStrategy:
+ # ValueError (not KeyError) so the API maps an unsupported viz to a 400 at save time.
+ strategy = FUNNEL_VIZ_STRATEGIES.get(viz or FunnelVizType.STEPS)
+ if strategy is None:
+ raise ValueError(f"Funnel alerts aren't supported for the '{viz}' visualization.")
+ return strategy
+
+
+def _is_current_period_row(row: Any) -> bool:
+ 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, a steps funnel's
+ default last-row resolution or a trends series would mix periods. No-op when compare is off.
+
+ For a breakdown steps funnel the runner emits the previous-period breakdowns as their own groups,
+ which filter 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 _require_series_list(result: Any, viz_label: str) -> list[Any]:
+ if not result or not isinstance(result, list):
+ raise AlertExtractionError(f"Funnel {viz_label} alert query returned no data.")
+ return result
+
+
+def _steps_per_breakdown(result: Any) -> list[list[dict[str, Any]]]:
+ """Normalize a steps 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]]``.
+ """
+ series = _require_series_list(result, "steps")
+ if isinstance(series[0], list):
+ return cast(list[list[dict[str, Any]]], series)
+ return [cast(list[dict[str, Any]], series)]
+
+
+def _label_for_breakdown(breakdown: Any) -> str:
+ # Mirrors the frontend's `_breakdownLabel`.
+ if breakdown is None:
+ return "conversion"
+ return ", ".join(str(v) for v in breakdown) if isinstance(breakdown, list) else str(breakdown)
+
+
+def _numeric_or_none(value: Any) -> float | None:
+ # Route a non-numeric metric to "no data this interval" (the comparator skips a None anchor)
+ # rather than letting a type error surface as an internal crash.
+ if isinstance(value, bool) or not isinstance(value, int | float):
+ return None
+ return float(value)
+
+
+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/funnels.py b/products/alerts/backend/evaluation/funnels.py
index c85c2213e37f..0d3ff23aef2c 100644
--- a/products/alerts/backend/evaluation/funnels.py
+++ b/products/alerts/backend/evaluation/funnels.py
@@ -1,34 +1,40 @@
-from typing import Any, cast
+from typing import Any
-from posthog.schema import (
- AlertCondition,
- AlertConditionType,
- FunnelConversionMetric,
- FunnelsAlertConfig,
- FunnelsQuery,
- FunnelVizType,
-)
+from posthog.schema import AlertCondition, AlertConditionType, FunnelsAlertConfig, FunnelsQuery, IntervalType
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.evaluation.contract import AlertExtractionError, ExtractionResult, lookback_intervals_for
+from products.alerts.backend.evaluation.funnel_strategies import strategy_for_viz
from products.alerts.backend.models.alert import AlertConfiguration
from products.product_analytics.backend.models.insight import Insight
-_FUNNEL_SUBJECT = "The funnel conversion rate"
+
+def _trailing_date_range_override(interval: IntervalType | None, periods: int) -> dict:
+ # Widen the insight's date range to the last `periods` intervals (no date_to, so the current
+ # interval is included) — mirrors the trends extractor so a relative funnel alert always has a
+ # prior period to diff against, regardless of the insight's saved range.
+ match interval:
+ case IntervalType.DAY:
+ unit = "d"
+ case IntervalType.WEEK:
+ unit = "w"
+ case IntervalType.MONTH:
+ unit = "m"
+ case _:
+ unit = "h"
+ return {"date_from": f"-{periods}{unit}"}
class FunnelsExtractor:
- """Normalize a funnel insight into a conversion-rate ``ComparableSeries`` (a percentage) per breakdown.
+ """Normalize a funnel insight into a ``ComparableSeries`` (one per breakdown) for the comparator.
- A breakdown funnel yields one series per breakdown value and fires if ANY breaches (matching trends).
+ The shared scaffolding lives here — config/condition guards and running the query — while the
+ viz-type-specific work (what metric to read, how to shape the result) is delegated to a
+ ``FunnelVizStrategy`` selected by ``funnelVizType``. A breakdown funnel yields one series per
+ breakdown value and fires if ANY breaches (matching trends).
"""
def extract(
@@ -36,124 +42,48 @@ class FunnelsExtractor:
) -> 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."
- )
+ strategy = strategy_for_viz(viz)
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.")
+ # Relative conditions need a prior value to compare against, which only a time-series viz
+ # (historical trends) has — a steps snapshot is absolute-only.
+ if condition.type != AlertConditionType.ABSOLUTE_VALUE and not strategy.supports_relative_conditions:
+ raise AlertExtractionError("This funnel only supports absolute value conditions.")
+
+ # A relative condition diffs against the prior period, but the insight's own date range may be
+ # too short to yield one — leaving the alert silently inert. Widen it to the trailing intervals
+ # the comparator needs (mirroring the trends extractor). Absolute conditions read the insight's
+ # configured range as-is: a steps snapshot, or the trends last-complete period.
+ filters_override = (
+ None
+ if condition.type == AlertConditionType.ABSOLUTE_VALUE
+ else _trailing_date_range_override(funnels_query.interval, lookback_intervals_for(condition))
+ )
calculation_result = calculate_for_query_based_insight(
insight,
team=alert.team,
execution_mode=execution_mode,
user=alert.created_by,
+ filters_override=filters_override,
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
- ]
+ # 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 trends extractor
+ # (and the shared error message the alert-failure dashboards bucket on).
+ if calculation_result.result is None:
+ raise RuntimeError(f"No results found for insight with alert id = {alert.id}")
+
+ series = strategy.to_series(calculation_result.result, config)
return ExtractionResult(
series=series,
- is_breakdown=len(breakdowns) > 1,
- subject=_FUNNEL_SUBJECT,
+ is_breakdown=len(series) > 1,
+ subject=strategy.subject,
framed=False,
- unit="%", # conversion rates are 0–100 percentages; match the configure-time UI
+ unit=strategy.unit, # conversion rates are absolute 0–100 percentages
)
-
-
-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 e8b7dd25b3fe..ff158be48223 100644
--- a/products/alerts/backend/evaluation/test/test_comparator.py
+++ b/products/alerts/backend/evaluation/test/test_comparator.py
@@ -84,6 +84,8 @@ def test_unit_suffix_renders_in_breach_message():
([20.0, 8.0, 5.0], 1, False, DECREASE, InsightThresholdType.ABSOLUTE, 5, 12.0, "decreased"),
# percentage: (20 - 10) / 10 = 1.0
([10.0, 20.0, 30.0], 1, False, INCREASE, InsightThresholdType.PERCENTAGE, 0.5, 1.0, None),
+ # percentage decrease: (20 - 8) / 20 = 0.6, over the 0.5 upper bound → breach
+ ([20.0, 8.0, 5.0], 1, False, DECREASE, InsightThresholdType.PERCENTAGE, 0.5, 0.6, "decreased"),
# percentage with a zero base → inf
([0.0, 10.0, 20.0], 1, False, INCREASE, InsightThresholdType.PERCENTAGE, 0.5, float("inf"), None),
],
diff --git a/products/alerts/backend/evaluation/test/test_funnels_extractor.py b/products/alerts/backend/evaluation/test/test_funnels_extractor.py
index 3ca70e5fc5dc..baa73e9c82cb 100644
--- a/products/alerts/backend/evaluation/test/test_funnels_extractor.py
+++ b/products/alerts/backend/evaluation/test/test_funnels_extractor.py
@@ -41,8 +41,13 @@ def _extract(
return FunnelsExtractor().extract(_alert(config, condition_type), MagicMock(), _query(viz), IF_STALE)
-def _config(metric: str = "conversion_from_start", funnel_step: int | None = None) -> dict:
- return {"type": "FunnelsAlertConfig", "metric": metric, "funnel_step": funnel_step}
+def _config(
+ metric: str = "conversion_from_start", funnel_step: int | None = None, check_ongoing_interval: bool | None = None
+) -> dict:
+ config: dict = {"type": "FunnelsAlertConfig", "metric": metric, "funnel_step": funnel_step}
+ if check_ongoing_interval is not None:
+ config["check_ongoing_interval"] = check_ongoing_interval
+ return config
@pytest.mark.parametrize(
@@ -77,10 +82,9 @@ def test_result_is_unframed_single_series():
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"),
+ ([], None, None, AlertConditionType.ABSOLUTE_VALUE, "no data"),
([{"order": 0}, {"order": 1}], None, None, AlertConditionType.ABSOLUTE_VALUE, "non-numeric count"),
([{"order": 0, "count": 100}, "broken"], None, None, AlertConditionType.ABSOLUTE_VALUE, "malformed"),
],
@@ -97,6 +101,74 @@ def test_none_result_raises_runtime_error():
_extract(None)
+def _trends_series(data: list[float], *, breakdown_value=None) -> dict:
+ days = [f"2024-01-{i + 1:02d}" for i in range(len(data))]
+ series: dict = {"count": len(data), "data": data, "days": days, "labels": days}
+ if breakdown_value is not None:
+ series["breakdown_value"] = breakdown_value
+ return series
+
+
+ "condition_type,check_ongoing,expected_index,expected_value",
+ [
+ # Default: the latest period is in progress, so anchor the last *complete* one.
+ (AlertConditionType.ABSOLUTE_VALUE, False, 1, 20.0),
+ # check_ongoing_interval anchors the latest (in-progress) period instead.
+ (AlertConditionType.ABSOLUTE_VALUE, True, 2, 40.0),
+ # Relative conditions use the same anchor (then diff it against the period before it).
+ (AlertConditionType.RELATIVE_INCREASE, False, 1, 20.0),
+ (AlertConditionType.RELATIVE_INCREASE, True, 2, 40.0),
+ ],
+)
+def test_trends_funnel_anchor_selection(condition_type, check_ongoing, expected_index, expected_value):
+ result = _extract(
+ [_trends_series([10.0, 20.0, 40.0])],
+ viz="trends",
+ condition_type=condition_type,
+ config=_config(check_ongoing_interval=check_ongoing),
+ )
+ assert result.subject == "The funnel conversion rate"
+ assert result.unit == "%"
+ assert result.is_breakdown is False
+ series = result.series[0]
+ assert series.current_index == expected_index
+ assert series.points[series.current_index].value == expected_value
+
+
+def test_trends_funnel_breakdown_yields_one_series_per_value():
+ # check_ongoing_interval so the anchor is the latest (only) interesting point per breakdown.
+ result = _extract(
+ [
+ _trends_series([10.0, 40.0], breakdown_value=["Chrome"]),
+ _trends_series([5.0, 20.0], breakdown_value=["Safari"]),
+ ],
+ viz="trends",
+ config=_config(check_ongoing_interval=True),
+ )
+ assert result.is_breakdown is True
+ assert {s.label: s.points[s.current_index].value for s in result.series} == {"Chrome": 40.0, "Safari": 20.0}
+
+
+def test_trends_funnel_compare_evaluates_current_period_only():
+ current = {**_trends_series([10.0, 40.0]), "compare_label": "current"}
+ previous = {**_trends_series([8.0, 30.0]), "compare_label": "previous"}
+ result = _extract([current, previous], viz="trends", config=_config(check_ongoing_interval=True))
+ assert len(result.series) == 1
+ assert result.series[0].points[result.series[0].current_index].value == 40.0
+
+
+def test_trends_funnel_empty_result_raises_extraction_error():
+ with pytest.raises(AlertExtractionError, match="no data"):
+ _extract([], viz="trends")
+
+
+def test_unsupported_viz_raises():
+ # Time-to-convert and flow funnels have no conversion-rate metric, so they aren't supported.
+ with pytest.raises(ValueError, match="aren't supported for the"):
+ _extract(_steps(100, 40), viz="time_to_convert")
+
+
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"}]
@@ -147,3 +219,25 @@ def test_breakdown_compared_funnel_evaluates_current_breakdowns_only():
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}
+
+
+def test_trends_funnel_relative_widens_date_range_to_cover_lookback():
+ # A relative condition diffs against a prior period; the insight's own range may not yield one, so
+ # the extractor widens it to the trailing intervals the comparator needs (here: 3 days).
+ query = _query("trends")
+ query["interval"] = "day"
+ with patch(CALC_PATH) as calc:
+ calc.return_value = MagicMock(result=[_trends_series([10.0, 20.0, 40.0])])
+ FunnelsExtractor().extract(
+ _alert(condition_type=AlertConditionType.RELATIVE_INCREASE), MagicMock(), query, IF_STALE
+ )
+ assert calc.call_args.kwargs["filters_override"] == {"date_from": "-3d"}
+
+
+def test_absolute_funnel_does_not_override_the_insight_date_range():
+ # Absolute conditions read the insight's configured range as-is — widening would change what a
+ # steps-funnel alert has always evaluated.
+ with patch(CALC_PATH) as calc:
+ calc.return_value = MagicMock(result=_steps(100, 40))
+ FunnelsExtractor().extract(_alert(), MagicMock(), _query("steps"), IF_STALE)
+ assert calc.call_args.kwargs["filters_override"] is None
diff --git a/products/alerts/backend/evaluation/validation.py b/products/alerts/backend/evaluation/validation.py
index 826ffddd8a09..e12dd6a3f3c5 100644
--- a/products/alerts/backend/evaluation/validation.py
+++ b/products/alerts/backend/evaluation/validation.py
@@ -7,10 +7,8 @@ from posthog.schema import (
AlertCalculationInterval,
AlertCondition,
AlertConditionType,
- FunnelConversionMetric,
FunnelsAlertConfig,
FunnelsQuery,
- FunnelVizType,
HogQLAlertConfig,
HogQLAlertEvaluation,
InsightThreshold,
@@ -24,6 +22,7 @@ from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, is_non_time_series_tr
from posthog.utils import get_from_dict_or_attr
from products.alerts.backend.evaluation.dispatcher import DETECTOR_EXTRACTORS
+from products.alerts.backend.evaluation.funnel_strategies import strategy_for_viz
THRESHOLD_BOUNDS_REQUIRED_MESSAGE = "At least one threshold bound (lower or upper) must be provided."
@@ -146,11 +145,8 @@ def _validate_trends_alert_config(ctx: _AlertConfigValidationContext) -> None:
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:
@@ -159,21 +155,14 @@ def _validate_funnels_alert_config(ctx: _AlertConfigValidationContext) -> None:
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.
+ # Resolve the strategy first (rejects unsupported viz types), then delegate viz-specific rules to
+ # the same strategy the extractor uses at eval time, so config-time and eval-time views can't drift.
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")
+ strategy = strategy_for_viz(viz)
+ # Relative conditions need a prior value, which only a time-series viz (historical trends) has.
+ if ctx.parsed_condition.type != AlertConditionType.ABSOLUTE_VALUE and not strategy.supports_relative_conditions:
+ raise ValueError("This funnel only supports absolute value conditions")
+ strategy.validate_config(funnels_query, parsed)
_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)
diff --git a/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx b/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx
index 91544277d77c..620fcf9bfa6d 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx
+++ b/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx
@@ -3,8 +3,7 @@ import { Group } from 'kea-forms'
import { IconInfo } from '@posthog/icons'
import { LemonCheckbox, LemonCollapse, Tooltip } from '@posthog/lemon-ui'
-import { AlertFormType } from 'lib/components/Alerts/alertFormLogic'
-import { supportsOngoingInterval } from 'lib/components/Alerts/types'
+import { AlertFormType, ongoingIntervalField } from 'lib/components/Alerts/alertFormLogic'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { AlertCalculationInterval } from '~/queries/schema/schema-general'
@@ -28,6 +27,7 @@ export function AlertAdvancedOptionsSection({
enabledAdvancedOptionsCount,
onSetAlertFormValue,
}: AlertAdvancedOptionsSectionProps): JSX.Element {
+ const ongoing = ongoingIntervalField(alertForm?.config, can_check_ongoing_interval)
return (
<div className="deprecated-space-y-2">
<LemonCollapse
@@ -54,29 +54,19 @@ export function AlertAdvancedOptionsSection({
},
content: (
<div className="space-y-2">
- {supportsOngoingInterval(alertForm?.config) && (
+ {ongoing.show && (
<Group name={['config']}>
<div className="flex gap-1">
<LemonField name="check_ongoing_interval">
<LemonCheckbox
- checked={
- can_check_ongoing_interval &&
- alertForm.config.check_ongoing_interval
- }
+ checked={ongoing.checked}
data-attr="alertForm-check-ongoing-interval"
fullWidth
label="Check ongoing period"
- disabledReason={
- !can_check_ongoing_interval &&
- 'Can only alert for ongoing period when checking for absolute value/increase above a set upper threshold.'
- }
+ disabledReason={ongoing.disabledReason}
/>
</LemonField>
- <Tooltip
- title="Checks the insight value for the ongoing period (current week/month) that hasn't yet completed. Use this if you want to be alerted right away when the insight value rises/increases above threshold"
- placement="right"
- delayMs={0}
- >
+ <Tooltip title={ongoing.tooltip} placement="right" delayMs={0}>
<IconInfo />
</Tooltip>
</div>
diff --git a/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx b/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx
index ec3670d73de7..2f960cd4f3eb 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx
+++ b/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx
@@ -96,6 +96,32 @@ function FunnelAlertPreviewBanner({ preview }: { preview: FunnelAlertPreview | n
</LemonTag>
) : null
+ if (preview.relative) {
+ // Relative alerts evaluate the change between the period being checked and the one before it
+ // (the checkbox controls whether that's the in-progress period); `breaching` reflects the change.
+ const first = preview.values[0]
+ const hasPrior = preview.values.some((value) => value.previousRate !== undefined)
+ return (
+ <LemonBanner type={wouldFire ? 'warning' : 'info'} className="w-full">
+ {statusTag}
+ {!hasPrior ? (
+ <>Needs an earlier completed period to compare against — extend the date range.</>
+ ) : preview.isBreakdown ? (
+ <>
+ Across {preview.values.length} breakdown values, comparing each period against the one before it
+ {wouldFire ? `: ${breaching.map((value) => value.label ?? 'conversion').join(', ')}` : ''}.
+ </>
+ ) : (
+ <>
+ Evaluating <strong>{format(first.rate)}</strong> against{' '}
+ <strong>{format(first.previousRate as number)}</strong> (the prior period).
+ </>
+ )}
+ {!preview.hasBounds ? <> Set a threshold to preview whether it would fire.</> : null}
+ </LemonBanner>
+ )
+ }
+
if (preview.isBreakdown) {
const rates = preview.values.map((value) => value.rate)
return (
@@ -135,19 +161,33 @@ function FunnelAlertPreviewBanner({ preview }: { preview: FunnelAlertPreview | n
)
}
-/** Funnels: a single valid-conversion picker over the `{metric, funnel_step}` config — see funnelAlertOptions. */
+/** Funnels: a single valid-conversion picker over the `{metric, funnel_step}` config — see funnelAlertOptions.
+ * A trends funnel charts the overall (whole-funnel) conversion rate over time, so there's no per-step
+ * choice to make — it shows just the preview of the latest period's rate. */
export function FunnelsDefinitionFields({
alertForm,
stepLabels,
funnelPreview,
+ isTrendsFunnel,
onSetAlertFormValue,
}: {
alertForm: AlertFormType
stepLabels: string[]
funnelPreview: FunnelAlertPreview | null
+ isTrendsFunnel: boolean
onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
}): JSX.Element {
const config = isFunnelsAlertConfig(alertForm.config) ? alertForm.config : null
+ if (isTrendsFunnel) {
+ // A trends funnel charts the overall conversion rate over time, so there's no per-step choice.
+ // The in-progress-period toggle lives in Advanced options, mirroring the trends-alert equivalent.
+ return (
+ <div className="flex flex-wrap gap-3 items-center">
+ <div>Alert on the overall conversion rate</div>
+ <FunnelAlertPreviewBanner preview={funnelPreview} />
+ </div>
+ )
+ }
return (
<div className="flex flex-wrap gap-3 items-center">
<div>Alert on</div>
diff --git a/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx b/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
index af6053aeee1a..c749247ffe01 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
+++ b/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
@@ -14,6 +14,7 @@ import {
import { AlertFormType } from 'lib/components/Alerts/alertFormLogic'
import { FunnelAlertPreview } from 'lib/components/Alerts/funnelAlertPreview'
import { HogQLAlertPreview } from 'lib/components/Alerts/hogqlAlertPreview'
+import { fractionToPercentInput, rescaleFunnelBound } from 'lib/components/Alerts/thresholdPercent'
import {
AlertSimulationResult,
isAnyRowHogQLConfig,
@@ -46,6 +47,8 @@ export interface FunnelDefinitionProps {
stepLabels: string[]
/** Conversion rate(s) the alert would evaluate now; null until the result loads. */
preview: FunnelAlertPreview | null
+ /** A trends funnel alerts on the overall rate over time, so it skips the step picker. */
+ isTrendsFunnel: boolean
}
export interface HogQLDefinitionProps {
@@ -104,10 +107,10 @@ 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.
+ // A steps funnel evaluates a single conversion-rate snapshot, so relative conditions have no prior
+ // value to compare against. A historical-trend funnel is a time series, so it does support them.
const isFunnelAlert = isFunnelsAlertConfig(alertForm.config)
- const supportsRelativeConditions = !isFunnelAlert
+ const supportsRelativeConditions = !isFunnelAlert || funnel.isTrendsFunnel
const relativeConditionDisabledReason =
(isNonTimeSeriesDisplay && 'This condition is only supported for time series trends') ||
(isHogQLAnyRow(alertForm) &&
@@ -134,6 +137,7 @@ export function AlertDefinitionSection({
alertForm={alertForm}
stepLabels={funnel.stepLabels}
funnelPreview={funnel.preview}
+ isTrendsFunnel={funnel.isTrendsFunnel}
onSetAlertFormValue={onSetAlertFormValue}
/>
) : isHogQLAlertConfig(alertForm.config) ? (
@@ -188,24 +192,55 @@ export function AlertDefinitionSection({
{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,
- },
- ]}
- />
+ {({ value, onChange }) => (
+ <LemonSelect
+ fullWidth
+ className="w-40"
+ data-attr="alertForm-condition"
+ value={value}
+ onChange={(newType) => {
+ onChange(newType)
+ if (!isFunnelAlert) {
+ return
+ }
+ // Funnels have no #/% toggle: a relative condition uses a
+ // PERCENTAGE threshold (0–1 fraction), "has value" an
+ // ABSOLUTE one (raw percent). Keep the type in sync with the
+ // condition and rescale the bounds so the on-screen number is
+ // preserved across the switch instead of jumping ×100 / ÷100.
+ const cfg = alertForm.threshold.configuration
+ const targetType =
+ newType === AlertConditionType.ABSOLUTE_VALUE
+ ? InsightThresholdType.ABSOLUTE
+ : InsightThresholdType.PERCENTAGE
+ if (cfg.type === targetType) {
+ return
+ }
+ onSetAlertFormValue('threshold', {
+ configuration: {
+ type: targetType,
+ bounds: {
+ lower: rescaleFunnelBound(cfg.bounds?.lower, targetType),
+ upper: rescaleFunnelBound(cfg.bounds?.upper, targetType),
+ },
+ },
+ })
+ }}
+ 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>
)}
@@ -217,9 +252,8 @@ export function AlertDefinitionSection({
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
- ? alertForm.threshold.configuration.bounds?.lower * 100
+ alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE
+ ? fractionToPercentInput(alertForm.threshold.configuration.bounds?.lower)
: alertForm.threshold.configuration.bounds?.lower
}
onChange={(value) =>
@@ -248,9 +282,8 @@ export function AlertDefinitionSection({
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
- ? alertForm.threshold.configuration.bounds?.upper * 100
+ alertForm.threshold.configuration.type === InsightThresholdType.PERCENTAGE
+ ? fractionToPercentInput(alertForm.threshold.configuration.bounds?.upper)
: alertForm.threshold.configuration.bounds?.upper
}
onChange={(value) =>
@@ -271,7 +304,9 @@ export function AlertDefinitionSection({
}
/>
</LemonField>
- {alertForm.condition.type !== AlertConditionType.ABSOLUTE_VALUE && (
+ {/* Funnels always compare as a percentage of the prior period, so the unit
+ toggle is hidden for them (the threshold is pinned to PERCENTAGE). */}
+ {!isFunnelAlert && alertForm.condition.type !== AlertConditionType.ABSOLUTE_VALUE && (
<Group name={['threshold', 'configuration']}>
<LemonField name="type">
<LemonSegmentedButton
diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.ts
index c4e42e171c1d..77676b432b57 100644
--- a/products/alerts/frontend/generated/api.schemas.ts
+++ b/products/alerts/frontend/generated/api.schemas.ts
@@ -227,6 +227,8 @@ export const FunnelsAlertConfigApiType = {
} as const
export interface FunnelsAlertConfigApi {
+ /** When true, evaluate the current (still in-progress) period; by default only completed periods are used. */
+ check_ongoing_interval?: boolean | null
/** Zero-based step index to evaluate. Null = the last step (overall conversion). */
funnel_step?: number | null
metric: FunnelConversionMetricApi
@@ -515,7 +517,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). 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. */
+ /** 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), metric ('conversion_from_start' or 'conversion_from_previous'), and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease (compared against the prior period). */
config?: AlertConfigUnionApi | null
detector_config?: DetectorConfigApi | null
/** How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.
@@ -596,7 +598,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). 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. */
+ /** 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), metric ('conversion_from_start' or 'conversion_from_previous'), and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease (compared against the prior period). */
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 3a165e83fdf4..2f084cc97a0e 100644
--- a/products/alerts/frontend/generated/api.zod.ts
+++ b/products/alerts/frontend/generated/api.zod.ts
@@ -1107,6 +1107,12 @@ export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({
type: zod.enum(['HogQLAlertConfig']).default(alertsSimulateCreateBodyConfigOneTwoTypeDefault),
}),
zod.object({
+ check_ongoing_interval: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'When true, evaluate the current (still in-progress) period; by default only completed periods are used.'
+ ),
funnel_step: zod
.union([zod.number(), zod.null()])
.optional()
diff --git a/products/alerts/mcp/tools.yaml b/products/alerts/mcp/tools.yaml
index 39cb42142b04..7a1c261bc31a 100644
--- a/products/alerts/mcp/tools.yaml
+++ b/products/alerts/mcp/tools.yaml
@@ -37,9 +37,11 @@ tools:
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).
+ for the overall last step), metric is 'conversion_from_start' or 'conversion_from_previous', and
+ check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps
+ funnels support only absolute_value conditions; historical-trend funnels also support
+ relative_increase/relative_decrease. 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
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index f579d1574469..808e468cea10 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -817,7 +817,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. 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.",
+ "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), metric is 'conversion_from_start' or 'conversion_from_previous', and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease. 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",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 793b6e0968b6..33ffc829ca15 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -847,7 +847,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. 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.",
+ "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), metric is 'conversion_from_start' or 'conversion_from_previous', and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease. 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",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ffb971ab2d10..e8b5770bce16 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8686,6 +8686,8 @@ export namespace Schemas {
} as const;
export interface FunnelsAlertConfig {
+ /** When true, evaluate the current (still in-progress) period; by default only completed periods are used. */
+ check_ongoing_interval?: boolean | null;
/** Zero-based step index to evaluate. Null = the last step (overall conversion). */
funnel_step?: number | null;
metric: FunnelConversionMetric;
@@ -8944,7 +8946,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). 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. */
+ /** 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), metric ('conversion_from_start' or 'conversion_from_previous'), and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease (compared against the prior period). */
config?: AlertConfigUnion | null;
detector_config?: DetectorConfig | null;
/** How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.
@@ -35781,7 +35783,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). 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. */
+ /** 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), metric ('conversion_from_start' or 'conversion_from_previous'), and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease (compared against the prior period). */
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 89cc73085107..c8e3afd4d734 100644
--- a/services/mcp/src/generated/alerts/api.ts
+++ b/services/mcp/src/generated/alerts/api.ts
@@ -157,6 +157,12 @@ export const AlertsCreateBody = /* @__PURE__ */ zod.object({
type: zod.enum(['HogQLAlertConfig']).default(alertsCreateBodyConfigOneTwoTypeDefault),
}),
zod.object({
+ check_ongoing_interval: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'When true, evaluate the current (still in-progress) period; by default only completed periods are used.'
+ ),
funnel_step: zod
.union([zod.number(), zod.null()])
.optional()
@@ -172,7 +178,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). 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."
+ "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), metric ('conversion_from_start' or 'conversion_from_previous'), and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease (compared against the prior period)."
),
detector_config: zod
.union([
@@ -1442,6 +1448,12 @@ export const AlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
type: zod.enum(['HogQLAlertConfig']).default(alertsPartialUpdateBodyConfigOneTwoTypeDefault),
}),
zod.object({
+ check_ongoing_interval: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'When true, evaluate the current (still in-progress) period; by default only completed periods are used.'
+ ),
funnel_step: zod
.union([zod.number(), zod.null()])
.optional()
@@ -1459,7 +1471,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). 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."
+ "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), metric ('conversion_from_start' or 'conversion_from_previous'), and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease (compared against the prior period)."
),
detector_config: zod
.union([
@@ -3689,6 +3701,12 @@ export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({
type: zod.enum(['HogQLAlertConfig']).default(alertsSimulateCreateBodyConfigOneTwoTypeDefault),
}),
zod.object({
+ check_ongoing_interval: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'When true, evaluate the current (still in-progress) period; by default only completed periods are used.'
+ ),
funnel_step: zod
.union([zod.number(), zod.null()])
.optional()
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 3c193d29f026..0822671ce26d 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json
@@ -94,6 +94,17 @@
},
{
"properties": {
+ "check_ongoing_interval": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "When true, evaluate the current (still in-progress) period; by default only completed periods are used."
+ },
"funnel_step": {
"anyOf": [
{
@@ -125,7 +136,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). 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."
+ "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), metric ('conversion_from_start' or 'conversion_from_previous'), and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease (compared against the prior period)."
},
"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 39a52ea66b4e..0c4ee54fa1db 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json
@@ -71,6 +71,17 @@
},
{
"properties": {
+ "check_ongoing_interval": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "When true, evaluate the current (still in-progress) period; by default only completed periods are used."
+ },
"funnel_step": {
"anyOf": [
{
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 782505447ab8..541cb04b73a2 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json
@@ -94,6 +94,17 @@
},
{
"properties": {
+ "check_ongoing_interval": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "When true, evaluate the current (still in-progress) period; by default only completed periods are used."
+ },
"funnel_step": {
"anyOf": [
{
@@ -125,7 +136,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). 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."
+ "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), metric ('conversion_from_start' or 'conversion_from_previous'), and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease (compared against the prior period)."
},
"detector_config": {
"anyOf": [