Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(alerts): add SQL (HogQL) insight alerts (#62669)

Vasco de Krijger99dcb5975371
diff --git a/frontend/src/lib/components/Alerts/AlertsButton.tsx b/frontend/src/lib/components/Alerts/AlertsButton.tsx
index 684d64acbb77..7b7e53cd5e82 100644
--- a/frontend/src/lib/components/Alerts/AlertsButton.tsx
+++ b/frontend/src/lib/components/Alerts/AlertsButton.tsx
@@ -4,6 +4,7 @@ import { router } from 'kea-router'
import { IconBell } from '@posthog/icons'
import { LemonButton, LemonButtonProps } from '@posthog/lemon-ui'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { IconWithCount } from 'lib/lemon-ui/icons'
import { urls } from 'scenes/urls'
@@ -21,16 +22,24 @@ export function AlertsButton({ insight, insightLogicProps, text, ...props }: Ale
const { push } = useActions(router)
const logic = insightAlertsLogic({ insightId: insight.id!, insightLogicProps })
const { alerts } = useValues(logic)
+ const hogqlAlertsEnabled = useFeatureFlag('HOGQL_INSIGHT_ALERTS')
+
+ const supported = areAlertsSupportedForInsight(insight.query, { hogqlAlertsEnabled })
+ // List only the insight types this account can actually alert on — naming a flag-gated type the
+ // user doesn't have would disclose an unreleased feature.
+ const availableTypes = ['trends', hogqlAlertsEnabled && 'SQL'].filter(Boolean).join(', ')
+ // Existing alerts must stay manageable even if the gating flag is later disabled —
+ // they keep evaluating server-side, so the user needs a way in to edit or disable them.
+ const disabledReason =
+ supported || (alerts?.length ?? 0) > 0
+ ? undefined
+ : `Alerts are only available for ${availableTypes} insights. Change the insight representation to add alerts.`
return (
<LemonButton
data-attr="manage-alerts-button"
onClick={() => push(urls.insightAlerts(insight.short_id!))}
- disabledReason={
- !areAlertsSupportedForInsight(insight.query)
- ? 'Alerts are only available for trends. Change the insight representation to add alerts.'
- : undefined
- }
+ disabledReason={disabledReason}
{...props}
icon={
<IconWithCount count={alerts?.length} showZero={false}>
diff --git a/frontend/src/lib/components/Alerts/alertFormLogic.test.ts b/frontend/src/lib/components/Alerts/alertFormLogic.test.ts
index 9612dfc188b4..ec4498e2a074 100644
--- a/frontend/src/lib/components/Alerts/alertFormLogic.test.ts
+++ b/frontend/src/lib/components/Alerts/alertFormLogic.test.ts
@@ -14,6 +14,7 @@ import { userLogic } from 'scenes/userLogic'
import {
AlertCalculationInterval,
AlertConditionType,
+ HogQLAlertConfig,
InsightThresholdType,
NodeKind,
} from '~/queries/schema/schema-general'
@@ -22,6 +23,7 @@ import { InsightLogicProps, InsightShortId } from '~/types'
import { alertFormLogic, thresholdAlertHasBounds, type AlertFormType } from './alertFormLogic'
import { alertNotificationLogic } from './alertNotificationLogic'
+import { deriveHogQLAlertPreview, HOGQL_ANY_ROW_MAX_ROWS, HOGQL_LAST_ROW_MAX_ROWS } from './hogqlAlertPreview'
import { insightAlertsLogic } from './insightAlertsLogic'
import type { AlertType } from './types'
@@ -293,4 +295,365 @@ describe('alertFormLogic', () => {
)
expect(successToastSpy).not.toHaveBeenCalled()
})
+
+ describe('hogql column prefill', () => {
+ function mountHogqlForm(configOverrides: Record<string, any>): ReturnType<typeof alertFormLogic.build> {
+ const logic = alertFormLogic({
+ alert: null,
+ insightId: 42,
+ onEditSuccess: jest.fn(),
+ insightVizDataLogicProps: insightLogicProps,
+ insightInterval: 'day',
+ insightAlertKind: 'hogql',
+ })
+ logic.mount()
+ logic.actions.setAlertFormValue('config', {
+ type: 'HogQLAlertConfig',
+ evaluation: 'last_row',
+ ...configOverrides,
+ })
+ return logic
+ }
+
+ it.each([
+ {
+ name: 'prefills the single numeric column when none is picked (no label in last-row mode)',
+ config: {},
+ insightData: {
+ columns: ['day', 'count'],
+ results: [
+ ['2026-06-01', 1],
+ ['2026-06-02', 2],
+ ],
+ },
+ expectedColumn: 'count',
+ expectedLabelColumn: undefined,
+ },
+ {
+ name: 'keeps an explicit pick',
+ config: { column: 'a' },
+ insightData: { columns: ['a', 'b'], results: [[1, 2]] },
+ expectedColumn: 'a',
+ expectedLabelColumn: undefined,
+ },
+ {
+ name: 'prefills the last numeric column when several are numeric',
+ config: {},
+ insightData: { columns: ['a', 'b'], results: [[1, 2]] },
+ expectedColumn: 'b',
+ expectedLabelColumn: undefined,
+ },
+ {
+ name: 'skips a trailing non-numeric column when picking the last numeric one',
+ config: {},
+ insightData: { columns: ['value', 'day'], results: [[5, '2026-06-01']] },
+ expectedColumn: 'value',
+ expectedLabelColumn: undefined,
+ },
+ {
+ name: 'does not prefill when no column is numeric',
+ config: {},
+ insightData: { columns: ['a', 'b'], results: [['x', 'y']] },
+ expectedColumn: undefined,
+ expectedLabelColumn: undefined,
+ },
+ {
+ name: 'does not prefill single-column results (picker hidden, auto keeps working on rename)',
+ config: {},
+ insightData: { columns: ['count'], results: [[5]] },
+ expectedColumn: undefined,
+ expectedLabelColumn: undefined,
+ },
+ {
+ name: 'prefills the first non-evaluated column as the label in any-row mode',
+ config: { evaluation: 'any_row' },
+ insightData: { columns: ['day', 'count'], results: [['2026-06-01', 1]] },
+ expectedColumn: 'count',
+ expectedLabelColumn: 'day',
+ },
+ {
+ name: 'keeps an explicit label pick',
+ config: { evaluation: 'any_row', label_column: 'a' },
+ insightData: { columns: ['day', 'a', 'b'], results: [['2026-06-01', 1, 2]] },
+ expectedColumn: 'b',
+ expectedLabelColumn: 'a',
+ },
+ ])('$name', async ({ config, insightData, expectedColumn, expectedLabelColumn }) => {
+ const logic = mountHogqlForm(config)
+ insightDataLogic(insightLogicProps).actions.setInsightData(insightData)
+ await expectLogic(logic).toFinishAllListeners()
+ const formConfig = logic.values.alertForm.config as HogQLAlertConfig
+ expect(formConfig.column).toEqual(expectedColumn)
+ expect(formConfig.label_column).toEqual(expectedLabelColumn)
+ })
+
+ it('does not prefill when editing an existing alert (would dirty the form / clobber a saved column)', async () => {
+ const logic = alertFormLogic({
+ alert: makeSavedAlert({ config: { type: 'HogQLAlertConfig' } as any }),
+ insightId: 42,
+ onEditSuccess: jest.fn(),
+ insightVizDataLogicProps: insightLogicProps,
+ insightInterval: 'day',
+ insightAlertKind: 'hogql',
+ })
+ logic.mount()
+ insightDataLogic(insightLogicProps).actions.setInsightData({
+ columns: ['day', 'count'],
+ results: [['x', 1]],
+ })
+ await expectLogic(logic).toFinishAllListeners()
+ const formConfig = logic.values.alertForm.config as HogQLAlertConfig
+ expect(formConfig.column).toBeUndefined()
+ expect(logic.values.alertFormChanged).toBe(false)
+ })
+ })
+
+ describe('hogql column options', () => {
+ function mountWithData(insightData: Record<string, any>): ReturnType<typeof alertFormLogic.build> {
+ const logic = alertFormLogic({
+ alert: null,
+ insightId: 42,
+ onEditSuccess: jest.fn(),
+ insightVizDataLogicProps: insightLogicProps,
+ insightInterval: 'day',
+ insightAlertKind: 'hogql',
+ })
+ logic.mount()
+ logic.actions.setAlertFormValue('config', { type: 'HogQLAlertConfig', evaluation: 'last_row' })
+ insightDataLogic(insightLogicProps).actions.setInsightData(insightData)
+ return logic
+ }
+
+ it('value options are the numeric columns only', () => {
+ const logic = mountWithData({ columns: ['day', 'count'], results: [['2026-06-01', 1]] })
+ expect(logic.values.hogqlValueColumnOptions).toEqual([{ label: 'count', value: 'count' }])
+ })
+
+ it('value options fall back to every column when nothing is numeric (avoids a dead-end picker)', () => {
+ const logic = mountWithData({ columns: ['a', 'b'], results: [['x', 'y']] })
+ expect(logic.values.hogqlValueColumnOptions).toEqual([
+ { label: 'a', value: 'a' },
+ { label: 'b', value: 'b' },
+ ])
+ })
+
+ it('label options exclude the evaluated column', async () => {
+ const logic = mountWithData({ columns: ['day', 'count'], results: [['2026-06-01', 1]] })
+ // Wait for the prefill to materialize the evaluated column, then it should drop out of the label options.
+ await expectLogic(logic).toFinishAllListeners()
+ expect((logic.values.alertForm.config as HogQLAlertConfig).column).toEqual('count')
+ expect(logic.values.hogqlLabelColumnOptions).toEqual([{ label: 'day', value: 'day' }])
+ })
+ })
+
+ describe('deriveHogQLAlertPreview', () => {
+ const HOGQL_CONFIG = { type: 'HogQLAlertConfig' } as const
+ const ANY_ROW_CONFIG = { type: 'HogQLAlertConfig', evaluation: 'any_row' } as const
+ const ok = (overrides: Record<string, any>): Record<string, any> => ({
+ status: 'ok',
+ mode: 'last_row',
+ columnName: null,
+ labelColumnName: null,
+ currentValue: 0,
+ previousValue: null,
+ rowCount: 1,
+ breachingRows: null,
+ rows: expect.any(Array),
+ ...overrides,
+ })
+
+ it.each([
+ ['no result loaded', null, HOGQL_CONFIG, null, null],
+ ['result not an array', { result: 'oops' }, HOGQL_CONFIG, null, null],
+ ['empty result', { result: [] }, HOGQL_CONFIG, null, { status: 'no-rows' }],
+ ['rows are not arrays', { result: [{ a: 1 }] }, HOGQL_CONFIG, null, { status: 'bad-shape' }],
+ [
+ 'date column is skipped by the numeric heuristic',
+ {
+ result: [
+ ['2024-01-01', 5],
+ ['2024-01-02', 7],
+ ],
+ columns: ['day', 'count'],
+ },
+ HOGQL_CONFIG,
+ null,
+ ok({
+ columnName: 'count',
+ labelColumnName: 'day',
+ currentValue: 7,
+ previousValue: 5,
+ rowCount: 2,
+ rows: [
+ { label: '2024-01-01', value: 5, breaching: false },
+ { label: '2024-01-02', value: 7, breaching: false },
+ ],
+ }),
+ ],
+ [
+ 'two numeric columns are ambiguous',
+ { result: [[1, 2]], columns: ['a', 'b'] },
+ HOGQL_CONFIG,
+ null,
+ { status: 'ambiguous-columns', columnNames: ['a', 'b'] },
+ ],
+ [
+ 'explicit column pick',
+ { result: [[1, 2]], columns: ['a', 'b'] },
+ { type: 'HogQLAlertConfig', column: 'b' },
+ null,
+ ok({ columnName: 'b', labelColumnName: 'a', currentValue: 2 }),
+ ],
+ [
+ 'explicit column missing from result',
+ { result: [[1]], columns: ['a'] },
+ { type: 'HogQLAlertConfig', column: 'gone' },
+ null,
+ { status: 'missing-column', column: 'gone', columnNames: ['a'] },
+ ],
+ [
+ 'non-numeric value',
+ { result: [['n/a']], columns: ['count'] },
+ HOGQL_CONFIG,
+ null,
+ { status: 'not-numeric', value: 'n/a' },
+ ],
+ [
+ 'non-finite value',
+ { result: [[Infinity]], columns: ['count'] },
+ HOGQL_CONFIG,
+ null,
+ { status: 'not-numeric', value: 'Infinity' },
+ ],
+ [
+ 'null bucket evaluates as 0',
+ { result: [[null]], columns: ['count'] },
+ HOGQL_CONFIG,
+ null,
+ ok({ columnName: 'count', currentValue: 0 }),
+ ],
+ [
+ 'multiple rows expose previous value',
+ { result: [[3], [7]], columns: ['count'] },
+ HOGQL_CONFIG,
+ null,
+ ok({ columnName: 'count', currentValue: 7, previousValue: 3, rowCount: 2 }),
+ ],
+ [
+ 'backtest counts breaching rows against bounds',
+ { result: [[3], [7], [12]], columns: ['count'] },
+ HOGQL_CONFIG,
+ { upper: 10 },
+ ok({ columnName: 'count', currentValue: 12, previousValue: 7, rowCount: 3, breachingRows: 1 }),
+ ],
+ [
+ 'boolean value is not numeric',
+ { result: [[true]], columns: ['flag'] },
+ HOGQL_CONFIG,
+ null,
+ { status: 'not-numeric', value: 'true' },
+ ],
+ [
+ 'null cell evaluates as 0 and can breach in any-row mode',
+ { result: [['US', null]], columns: ['country', 'count'] },
+ // The all-null column defeats the numeric heuristic, so pick it explicitly.
+ { type: 'HogQLAlertConfig', evaluation: 'any_row', column: 'count' },
+ { upper: -1 },
+ ok({
+ mode: 'any_row',
+ columnName: 'count',
+ labelColumnName: 'country',
+ currentValue: 0,
+ previousValue: null,
+ rowCount: 1,
+ breachingRows: 1,
+ rows: [{ label: 'US', value: 0, breaching: true }],
+ }),
+ ],
+ [
+ 'any-row over the row cap',
+ {
+ result: Array.from({ length: HOGQL_ANY_ROW_MAX_ROWS + 1 }, (_, i) => [i]),
+ columns: ['count'],
+ },
+ { type: 'HogQLAlertConfig', evaluation: 'any_row' },
+ null,
+ { status: 'too-many-rows', rowCount: HOGQL_ANY_ROW_MAX_ROWS + 1 },
+ ],
+ [
+ 'last-row at the truncation cap warns (tail may be truncated)',
+ {
+ result: Array.from({ length: HOGQL_LAST_ROW_MAX_ROWS }, (_, i) => [i]),
+ columns: ['count'],
+ },
+ { type: 'HogQLAlertConfig', evaluation: 'last_row' },
+ null,
+ { status: 'last-row-truncated', rowCount: HOGQL_LAST_ROW_MAX_ROWS },
+ ],
+ [
+ 'missing explicit label column',
+ { result: [['US', 1]], columns: ['country', 'count'] },
+ { type: 'HogQLAlertConfig', evaluation: 'any_row', label_column: 'gone' },
+ null,
+ { status: 'missing-column', column: 'gone', columnNames: ['country', 'count'] },
+ ],
+ [
+ 'single column rows label by row number',
+ { result: [[5], [50]], columns: ['count'] },
+ { type: 'HogQLAlertConfig', evaluation: 'any_row' },
+ { upper: 10 },
+ ok({
+ mode: 'any_row',
+ columnName: 'count',
+ currentValue: 50,
+ previousValue: 5,
+ rowCount: 2,
+ breachingRows: 1,
+ rows: [
+ { label: 'row 1', value: 5, breaching: false },
+ { label: 'row 2', value: 50, breaching: true },
+ ],
+ }),
+ ],
+ [
+ 'any-row mode reports breaching rows',
+ {
+ result: [
+ ['US', 0.1],
+ ['DE', 0.4],
+ ],
+ columns: ['country', 'error_rate'],
+ },
+ ANY_ROW_CONFIG,
+ { upper: 0.25 },
+ ok({
+ mode: 'any_row',
+ columnName: 'error_rate',
+ labelColumnName: 'country',
+ currentValue: 0.4,
+ previousValue: 0.1,
+ rowCount: 2,
+ breachingRows: 1,
+ rows: [
+ { label: 'US', value: 0.1, breaching: false },
+ { label: 'DE', value: 0.4, breaching: true },
+ ],
+ }),
+ ],
+ ])('%s', (_name, insightData, config, bounds, expected) => {
+ expect(
+ deriveHogQLAlertPreview(insightData as Record<string, any> | null, config as any, bounds as any)
+ ).toEqual(expected)
+ })
+
+ it('first_row is immune to the last_row truncation cap (reads the head)', () => {
+ const result = Array.from({ length: HOGQL_LAST_ROW_MAX_ROWS }, (_, i) => [i])
+ const preview = deriveHogQLAlertPreview(
+ { result, columns: ['count'] },
+ { type: 'HogQLAlertConfig', evaluation: 'first_row' } as any,
+ null
+ )
+ expect(preview?.status).toBe('ok')
+ })
+ })
})
diff --git a/frontend/src/lib/components/Alerts/alertFormLogic.ts b/frontend/src/lib/components/Alerts/alertFormLogic.ts
index 6a6670bc9b8b..aa119fb9ae13 100644
--- a/frontend/src/lib/components/Alerts/alertFormLogic.ts
+++ b/frontend/src/lib/components/Alerts/alertFormLogic.ts
@@ -1,11 +1,13 @@
import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import { loaders } from 'kea-loaders'
+import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
import api, { ApiError } from 'lib/api'
import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
import { userLogic } from 'scenes/userLogic'
@@ -13,6 +15,7 @@ import {
AlertCalculationInterval,
AlertConditionType,
GoalLine,
+ HogQLAlertConfig,
InsightThresholdType,
InsightsThresholdBounds,
} from '~/queries/schema/schema-general'
@@ -29,8 +32,17 @@ import type { alertFormLogicType } from './alertFormLogicType'
import { getAlertFormValidationErrors } from './alertFormSchema'
import { alertLogic } from './alertLogic'
import { alertNotificationLogic } from './alertNotificationLogic'
+import { columnIsNumeric, deriveHogQLAlertPreview, HogQLAlertPreview } from './hogqlAlertPreview'
import { insightAlertsLogic } from './insightAlertsLogic'
-import { AlertSimulationResult, AlertType, AlertTypeWrite, AnomalyPoint } from './types'
+import {
+ AlertConfig,
+ AlertSimulationResult,
+ AlertType,
+ AlertTypeWrite,
+ AnomalyPoint,
+ isHogQLAlertConfig,
+ isTrendsAlertConfig,
+} from './types'
export { THRESHOLD_BOUNDS_FORM_ERROR, thresholdAlertHasBounds } from './alertFormSchema'
@@ -67,12 +79,29 @@ export function canCheckOngoingInterval(alert?: AlertType | AlertFormType): bool
)
}
+/** The insight query kind an alert is built for; selects the default config type for new alerts. */
+export type InsightAlertKind = 'trends' | 'hogql'
+
export interface AlertFormLogicProps {
alert: AlertType | null
insightId: QueryBasedInsightModel['id']
onEditSuccess: (alertId?: AlertType['id']) => void
insightVizDataLogicProps?: InsightLogicProps
insightInterval?: IntervalType
+ /** Selects the default config type for new alerts based on the insight's query kind. */
+ insightAlertKind?: InsightAlertKind
+}
+
+const defaultConfigForInsight = (kind: AlertFormLogicProps['insightAlertKind']): AlertConfig => {
+ if (kind === 'hogql') {
+ // last_row is the default — the most common SQL alert shape is a chronological series.
+ return { type: 'HogQLAlertConfig', evaluation: 'last_row' }
+ }
+ return {
+ type: 'TrendsAlertConfig',
+ series_index: 0,
+ check_ongoing_interval: false,
+ }
}
/**
@@ -156,7 +185,12 @@ export const alertFormLogic = kea<alertFormLogicType>([
key(({ alert }) => alert?.id ?? 'new'),
connect((props: AlertFormLogicProps) => ({
- values: [trendsDataLogic({ dashboardId: undefined, ...props.insightVizDataLogicProps }), ['goalLines']],
+ values: [
+ trendsDataLogic({ dashboardId: undefined, ...props.insightVizDataLogicProps }),
+ ['goalLines'],
+ insightVizDataLogic({ dashboardItemId: undefined, ...props.insightVizDataLogicProps }),
+ ['insightData'],
+ ],
})),
actions({
@@ -194,10 +228,11 @@ export const alertFormLogic = kea<alertFormLogicType>([
if (!detectorConfig || !props.insightId) {
return null
}
+ const formConfig = values.alertForm.config
return await api.alerts.simulate({
insight: props.insightId,
detector_config: detectorConfig,
- series_index: values.alertForm.config?.series_index ?? 0,
+ series_index: isTrendsAlertConfig(formConfig) ? formConfig.series_index : 0,
date_from:
values.simulationDateFrom ??
getDefaultSimulationRange(values.alertForm.calculation_interval),
@@ -219,11 +254,7 @@ export const alertFormLogic = kea<alertFormLogicType>([
created_by: null,
created_at: '',
enabled: true,
- config: {
- type: 'TrendsAlertConfig',
- series_index: 0,
- check_ongoing_interval: false,
- },
+ config: defaultConfigForInsight(props.insightAlertKind),
threshold: {
configuration: {
type: InsightThresholdType.ABSOLUTE,
@@ -266,10 +297,13 @@ export const alertFormLogic = kea<alertFormLogicType>([
isHighFrequencyAlertInterval(alert.calculation_interval)) &&
alert.skip_weekend,
// can only check ongoing interval for absolute value/increase alerts with upper threshold
- config: {
- ...alert.config,
- check_ongoing_interval: canCheckOngoingInterval(alert) && alert.config.check_ongoing_interval,
- },
+ config: isTrendsAlertConfig(alert.config)
+ ? {
+ ...alert.config,
+ check_ongoing_interval:
+ canCheckOngoingInterval(alert) && alert.config.check_ongoing_interval,
+ }
+ : alert.config,
detector_config: alert.detector_config ?? null,
// Investigation agent only applies to anomaly (detector-based) alerts — force off otherwise.
investigation_agent_enabled: alert.detector_config
@@ -349,7 +383,7 @@ export const alertFormLogic = kea<alertFormLogicType>([
},
})),
- selectors({
+ selectors(({ props }) => ({
thresholdBoundsFormError: [
(s) => [s.alertFormSubmitAttempted, s.alertFormErrors],
(submitAttempted, alertFormErrors): string | undefined => {
@@ -360,7 +394,106 @@ export const alertFormLogic = kea<alertFormLogicType>([
return typeof thresholdError === 'string' ? thresholdError : undefined
},
],
- }),
+ hogqlAlertPreview: [
+ // Inputs are narrowed to the fields the preview reads, so name/interval/etc. keystrokes
+ // don't re-derive it (the per-row map can cover up to HOGQL_ANY_ROW_MAX_ROWS rows).
+ (s) => [
+ s.insightData,
+ (state, logicProps) => s.alertForm(state, logicProps)?.config,
+ (state, logicProps) => s.alertForm(state, logicProps)?.threshold?.configuration?.bounds,
+ ],
+ (
+ insightData: Record<string, any> | null,
+ config: AlertConfig | null | undefined,
+ bounds: InsightsThresholdBounds | null | undefined
+ ): HogQLAlertPreview | null =>
+ props.insightAlertKind === 'hogql' ? deriveHogQLAlertPreview(insightData, config, bounds) : null,
+ ],
+ /** Result column names of the SQL insight, for the column pickers. */
+ hogqlResultColumns: [
+ (s) => [s.insightData],
+ (insightData): string[] | null =>
+ props.insightAlertKind === 'hogql' && Array.isArray(insightData?.columns)
+ ? insightData.columns.map(String)
+ : null,
+ ],
+ /** Result columns with numeric cells — the only valid picks for the evaluated column. */
+ hogqlNumericColumns: [
+ (s) => [s.insightData, s.hogqlResultColumns],
+ (insightData, resultColumns): string[] | null =>
+ resultColumns && Array.isArray(insightData?.result)
+ ? resultColumns.filter((_, index) => columnIsNumeric(insightData.result, index))
+ : null,
+ ],
+ /** Default evaluated column for the picker: the last numeric column (SQL convention puts
+ * the measure last). Bolder than the backend's single-numeric fallback because the user
+ * sees the prefilled pick and it's stored explicitly. Null when the picker is hidden
+ * (single-column results) or nothing numeric is detectable. */
+ hogqlSuggestedColumn: [
+ (s) => [s.hogqlResultColumns, s.hogqlNumericColumns],
+ (resultColumns, numericColumns): string | null =>
+ (resultColumns?.length ?? 0) > 1 && numericColumns && numericColumns.length > 0
+ ? numericColumns[numericColumns.length - 1]
+ : null,
+ ],
+ /** Unset SQL config fields to materialize: the evaluated column (last numeric) and, in
+ * any-row mode, the label (first column that isn't evaluated — the backend fallback).
+ * Computed together so prefilling lands in a single form write with no ordering
+ * between the fields. Null when there's nothing to fill. */
+ hogqlConfigPrefill: [
+ (s) => [
+ s.hogqlResultColumns,
+ s.hogqlSuggestedColumn,
+ (state, logicProps) => s.alertForm(state, logicProps)?.config,
+ ],
+ (
+ resultColumns: string[] | null,
+ suggestedColumn: string | null,
+ config: AlertConfig | null | undefined
+ ): Partial<Pick<HogQLAlertConfig, 'column' | 'label_column'>> | null => {
+ if (!isHogQLAlertConfig(config)) {
+ return null
+ }
+ const patch: Partial<Pick<HogQLAlertConfig, 'column' | 'label_column'>> = {}
+ if (config.column == null && suggestedColumn != null) {
+ patch.column = suggestedColumn
+ }
+ const evaluated = config.column ?? suggestedColumn
+ if (config.evaluation === 'any_row' && config.label_column == null && evaluated != null) {
+ const label = resultColumns?.find((column) => column !== evaluated)
+ if (label != null) {
+ patch.label_column = label
+ }
+ }
+ return Object.keys(patch).length > 0 ? patch : null
+ },
+ ],
+ /** Options for the evaluated-column picker: the numeric columns. Falls back to every
+ * column when the result isn't loaded or nothing numeric was detected — an empty
+ * picker would be a dead end. A stored pick missing from the options still renders
+ * on the select button, but can't be re-picked. */
+ hogqlValueColumnOptions: [
+ (s) => [s.hogqlResultColumns, s.hogqlNumericColumns],
+ (resultColumns: string[] | null, numericColumns: string[] | null): { label: string; value: string }[] => {
+ const columns =
+ numericColumns === null || numericColumns.length === 0 ? (resultColumns ?? []) : numericColumns
+ return columns.map((column) => ({ label: column, value: column }))
+ },
+ ],
+ /** Options for the label-column picker: every column except the evaluated one. */
+ hogqlLabelColumnOptions: [
+ (s) => [s.hogqlResultColumns, (state, logicProps) => s.alertForm(state, logicProps)?.config],
+ (
+ resultColumns: string[] | null,
+ config: AlertConfig | null | undefined
+ ): { label: string; value: string }[] => {
+ const evaluated = isHogQLAlertConfig(config) ? (config.column ?? null) : null
+ return (resultColumns ?? [])
+ .filter((column) => column !== evaluated)
+ .map((column) => ({ label: column, value: column }))
+ },
+ ],
+ })),
listeners(({ props, values, actions }) => {
const getParentLogic = (): ReturnType<typeof insightAlertsLogic.build> | undefined => {
@@ -470,7 +603,8 @@ export const alertFormLogic = kea<alertFormLogicType>([
}))
)
} else {
- const seriesIndex = values.alertForm.config?.series_index ?? 0
+ const formConfig = values.alertForm.config
+ const seriesIndex = isTrendsAlertConfig(formConfig) ? formConfig.series_index : 0
anomalyPoints = simulationResult.triggered_indices.map((idx) => ({
index: idx,
date: simulationResult.dates[idx] ?? '',
@@ -495,4 +629,25 @@ export const alertFormLogic = kea<alertFormLogicType>([
},
}
}),
+
+ subscriptions(({ props, values, actions }) =>
+ // Create-only: prefilling an existing alert would dirty the form on passive open and,
+ // if the query result shape drifted since save, silently rewrite a stored column. New
+ // alerts have nothing to clobber. A subscription (not a listener) because the suggestion
+ // derives from another logic's loader — there is no single action to listen to. Never
+ // fires for single-column results (picker hidden there); those stay implicit so they
+ // keep working on column renames.
+ props.insightAlertKind !== 'hogql' || props.alert
+ ? {}
+ : {
+ // Materialize the suggested picks into the form, so the pickers show the actual
+ // choice and the saved config is explicit.
+ hogqlConfigPrefill: (patch: Partial<Pick<HogQLAlertConfig, 'column' | 'label_column'>> | null) => {
+ const config = values.alertForm?.config
+ if (patch != null && isHogQLAlertConfig(config)) {
+ actions.setAlertFormValue('config', { ...config, ...patch })
+ }
+ },
+ }
+ ),
])
diff --git a/frontend/src/lib/components/Alerts/hogqlAlertPreview.ts b/frontend/src/lib/components/Alerts/hogqlAlertPreview.ts
new file mode 100644
index 000000000000..fc091633ef09
--- /dev/null
+++ b/frontend/src/lib/components/Alerts/hogqlAlertPreview.ts
@@ -0,0 +1,176 @@
+import { InsightsThresholdBounds } from '~/queries/schema/schema-general'
+
+import { AlertConfig, isHogQLAlertConfig } from './types'
+
+/** Mirror of the backend's ANY_ROW_MAX_ROWS (products/alerts/backend/evaluation/hogql.py) — keep
+ * the two in sync. Advisory only; the backend extractor is the evaluation-time authority. */
+export const HOGQL_ANY_ROW_MAX_ROWS = 50
+
+/** Mirror of the backend's LAST_ROW_MAX_ROWS (= MAX_SELECT_RETURNED_ROWS). In last_row mode the
+ * backend rejects a result this large because the tail may be truncated, so the last row may not be
+ * the true last row. first_row is immune — it reads the head. */
+export const HOGQL_LAST_ROW_MAX_ROWS = 50000
+
+/** One result row as the alert would read it, for the configure-time preview table. */
+export interface HogQLAlertPreviewRow {
+ /** Label-column value, falling back to the row number — mirrors the backend's row labeling. */
+ label: string
+ value: number | null
+ breaching: boolean
+}
+
+/** What a SQL alert would evaluate right now, mirroring the backend extractor's column
+ * resolution and shape checks so problems surface at configure time, not at the first check.
+ * This is the advisory half of the PREVIEW MIRROR CONTRACT — the rule inventory lives on
+ * `HogQLExtractor` in products/alerts/backend/evaluation/hogql.py; any rule change there must
+ * land here and in both test suites. */
+export type HogQLAlertPreview =
+ | { status: 'no-rows' }
+ | { status: 'bad-shape' }
+ | { status: 'too-many-rows'; rowCount: number }
+ | { status: 'last-row-truncated'; rowCount: number }
+ | { status: 'ambiguous-columns'; columnNames: string[] | null }
+ | { status: 'missing-column'; column: string; columnNames: string[] | null }
+ | { status: 'not-numeric'; value: string }
+ | {
+ status: 'ok'
+ mode: 'last_row' | 'first_row' | 'any_row'
+ /** Resolved evaluated column name; null when the result has no column metadata. */
+ columnName: string | null
+ /** Resolved label column name; null when rows are labeled by row number. */
+ labelColumnName: string | null
+ currentValue: number
+ previousValue: number | null
+ rowCount: number
+ /** Rows whose value breaches the current absolute bounds; null when not computable. */
+ breachingRows: number | null
+ rows: HogQLAlertPreviewRow[]
+ }
+
+const _cellValue = (row: unknown, index: number): number | null => {
+ if (!Array.isArray(row) || index >= row.length) {
+ return null
+ }
+ const cell = row[index]
+ if (cell === null) {
+ return 0 // None buckets evaluate as 0, matching the backend
+ }
+ return typeof cell === 'number' && Number.isFinite(cell) ? cell : null
+}
+
+/** Mirror of the backend's `_column_is_numeric` (products/alerts/backend/evaluation/hogql.py): a
+ * column is numeric by its most recent non-null value. Advisory only — the backend owns
+ * authoritative resolution, so drift just yields a wrong picker suggestion, not a wrong evaluation.
+ * Caveat: a trailing footer/total row with a string cell will mislabel an otherwise-numeric column. */
+export const columnIsNumeric = (rows: unknown[], index: number): boolean => {
+ for (let i = rows.length - 1; i >= 0; i--) {
+ const row = rows[i]
+ if (!Array.isArray(row) || index >= row.length) {
+ return false
+ }
+ const cell = row[index]
+ if (cell === null) {
+ continue
+ }
+ return typeof cell === 'number' && Number.isFinite(cell)
+ }
+ return false
+}
+
+export function deriveHogQLAlertPreview(
+ insightData: Record<string, any> | null,
+ config: AlertConfig | null | undefined,
+ bounds: InsightsThresholdBounds | null | undefined
+): HogQLAlertPreview | null {
+ const rows = insightData?.result
+ if (!Array.isArray(rows)) {
+ return null // No result loaded yet — fall back to the static hint
+ }
+ if (rows.length === 0) {
+ return { status: 'no-rows' }
+ }
+ const hogqlConfig = isHogQLAlertConfig(config) ? config : null
+ const mode = hogqlConfig?.evaluation ?? 'last_row'
+ // first_row reads the head (newest first), last_row/any_row the tail; the anchor row is what
+ // last_row/first_row evaluate and what the shape check applies to.
+ const anchorRow = mode === 'first_row' ? rows[0] : rows[rows.length - 1]
+ if (!Array.isArray(anchorRow)) {
+ return { status: 'bad-shape' }
+ }
+ const lastRow = anchorRow
+ if (mode === 'any_row' && rows.length > HOGQL_ANY_ROW_MAX_ROWS) {
+ return { status: 'too-many-rows', rowCount: rows.length }
+ }
+ if (mode === 'last_row' && rows.length >= HOGQL_LAST_ROW_MAX_ROWS) {
+ return { status: 'last-row-truncated', rowCount: rows.length }
+ }
+ const columnNames = Array.isArray(insightData?.columns) ? insightData.columns.map(String) : null
+
+ // Resolve the evaluated column the way the backend does: explicit pick, single column,
+ // or the single numeric column — anything else needs the user to choose.
+ let valueIndex: number
+ if (hogqlConfig?.column != null) {
+ const index = columnNames?.indexOf(hogqlConfig.column) ?? -1
+ if (index < 0) {
+ return { status: 'missing-column', column: hogqlConfig.column, columnNames }
+ }
+ valueIndex = index
+ } else if (lastRow.length === 1) {
+ valueIndex = 0
+ } else {
+ const numericIndexes = Array.from({ length: lastRow.length }, (_, i) => i).filter((i) =>
+ columnIsNumeric(rows, i)
+ )
+ if (numericIndexes.length !== 1) {
+ return { status: 'ambiguous-columns', columnNames }
+ }
+ valueIndex = numericIndexes[0]
+ }
+
+ const currentValue = _cellValue(lastRow, valueIndex)
+ if (currentValue === null) {
+ return { status: 'not-numeric', value: String(lastRow[valueIndex]) }
+ }
+
+ // Label column: explicit pick, else the first non-evaluated column (e.g. the GROUP BY key).
+ let labelIndex: number | null = null
+ if (hogqlConfig?.label_column != null) {
+ const index = columnNames?.indexOf(hogqlConfig.label_column) ?? -1
+ if (index < 0) {
+ return { status: 'missing-column', column: hogqlConfig.label_column, columnNames }
+ }
+ labelIndex = index
+ } else if (lastRow.length > 1) {
+ labelIndex = Array.from({ length: lastRow.length }, (_, i) => i).find((i) => i !== valueIndex) ?? null
+ }
+
+ // Per-row view (and backtest): with absolute bounds, mark which rows would breach right now.
+ const hasBounds = !!bounds && (bounds.lower != null || bounds.upper != null)
+ const previewRows: HogQLAlertPreviewRow[] = rows.map((row, i) => {
+ const value = _cellValue(row, valueIndex)
+ const labelCell = labelIndex !== null && Array.isArray(row) && labelIndex < row.length ? row[labelIndex] : null
+ return {
+ label: labelCell != null ? String(labelCell) : `row ${i + 1}`,
+ value,
+ breaching:
+ hasBounds &&
+ value !== null &&
+ ((bounds.lower != null && value < bounds.lower) || (bounds.upper != null && value > bounds.upper)),
+ }
+ })
+
+ // Previous row is the second from the anchor end: tail for last_row, head for first_row.
+ const previousRow = mode === 'first_row' ? rows[1] : rows[rows.length - 2]
+ const previousValue = rows.length > 1 ? _cellValue(previousRow, valueIndex) : null
+ return {
+ status: 'ok',
+ mode,
+ columnName: columnNames?.[valueIndex] ?? null,
+ labelColumnName: labelIndex !== null ? (columnNames?.[labelIndex] ?? null) : null,
+ currentValue,
+ previousValue,
+ rowCount: rows.length,
+ breachingRows: hasBounds ? previewRows.filter((row) => row.breaching).length : null,
+ rows: previewRows,
+ }
+}
diff --git a/frontend/src/lib/components/Alerts/insightAlertsLogic.ts b/frontend/src/lib/components/Alerts/insightAlertsLogic.ts
index 06347acfdc8b..fb22f97eb542 100644
--- a/frontend/src/lib/components/Alerts/insightAlertsLogic.ts
+++ b/frontend/src/lib/components/Alerts/insightAlertsLogic.ts
@@ -2,15 +2,17 @@ import { actions, afterMount, connect, kea, key, listeners, path, props, reducer
import { loaders } from 'kea-loaders'
import api from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { AlertConditionType, BreakdownFilter, GoalLine, InsightThresholdType } from '~/queries/schema/schema-general'
-import { isInsightVizNode, isTrendsQuery, hasBreakdownFilter } from '~/queries/utils'
+import { containsHogQLQuery, hasBreakdownFilter, isInsightVizNode, isTrendsQuery } from '~/queries/utils'
import { InsightLogicProps } from '~/types'
import type { insightAlertsLogicType } from './insightAlertsLogicType'
-import { AlertType, AnomalyPoint } from './types'
+import { AlertType, AnomalyPoint, isTrendsAlertConfig } from './types'
export interface InsightAlertsLogicProps {
insightId: number
@@ -23,8 +25,49 @@ export interface InsightAlertsLogicProps {
deferInitialAlertsLoad?: boolean
}
-export const areAlertsSupportedForInsight = (query?: Record<string, any> | null): boolean => {
- return !!query && isInsightVizNode(query) && isTrendsQuery(query.source) && query.source.trendsFilter !== null
+export const areAlertsSupportedForInsight = (
+ query?: Record<string, any> | null,
+ options: { hogqlAlertsEnabled?: boolean } = {}
+): boolean => {
+ if (!query) {
+ return false
+ }
+ if (isInsightVizNode(query) && isTrendsQuery(query.source) && query.source.trendsFilter !== null) {
+ return true
+ }
+ return !!options.hogqlAlertsEnabled && containsHogQLQuery(query)
+}
+
+/** Map absolute-threshold alerts to chart goal lines (shared by trends and SQL charts). */
+export function alertsToThresholdGoalLines(alerts: AlertType[]): GoalLine[] {
+ return alerts.flatMap((alert) => {
+ if (
+ alert.threshold.configuration.type !== InsightThresholdType.ABSOLUTE ||
+ alert.condition.type !== AlertConditionType.ABSOLUTE_VALUE ||
+ !alert.threshold.configuration.bounds
+ ) {
+ return []
+ }
+
+ const bounds = alert.threshold.configuration.bounds
+
+ const annotations: GoalLine[] = []
+ if (bounds.upper != null) {
+ annotations.push({
+ label: `${alert.name} Upper Threshold`,
+ value: bounds.upper,
+ })
+ }
+
+ if (bounds.lower != null) {
+ annotations.push({
+ label: `${alert.name} Lower Threshold`,
+ value: bounds.lower,
+ })
+ }
+
+ return annotations
+ })
}
export const insightAlertsLogic = kea<insightAlertsLogicType>([
@@ -47,6 +90,8 @@ export const insightAlertsLogic = kea<insightAlertsLogicType>([
['showAlertThresholdLines', 'breakdownFilter'],
insightLogic(props.insightLogicProps),
['insight'],
+ featureFlagLogic,
+ ['featureFlags'],
],
})),
@@ -98,38 +143,8 @@ export const insightAlertsLogic = kea<insightAlertsLogicType>([
selectors({
alertThresholdLines: [
(s) => [s.alerts, s.showAlertThresholdLines],
- (alerts: AlertType[], showAlertThresholdLines: boolean): GoalLine[] => {
- const result = alerts.flatMap((alert) => {
- if (
- !showAlertThresholdLines ||
- alert.threshold.configuration.type !== InsightThresholdType.ABSOLUTE ||
- alert.condition.type !== AlertConditionType.ABSOLUTE_VALUE ||
- !alert.threshold.configuration.bounds
- ) {
- return []
- }
-
- const bounds = alert.threshold.configuration.bounds
-
- const annotations = []
- if (bounds?.upper != null) {
- annotations.push({
- label: `${alert.name} Upper Threshold`,
- value: bounds?.upper,
- })
- }
-
- if (bounds?.lower != null) {
- annotations.push({
- label: `${alert.name} Lower Threshold`,
- value: bounds?.lower,
- })
- }
-
- return annotations
- })
- return result
- },
+ (alerts: AlertType[], showAlertThresholdLines: boolean): GoalLine[] =>
+ showAlertThresholdLines ? alertsToThresholdGoalLines(alerts) : [],
],
/** Whether the insight has any detector-based alerts (used to show/hide the toggle). */
hasDetectorAlerts: [
@@ -165,7 +180,7 @@ export const insightAlertsLogic = kea<insightAlertsLogicType>([
if (!alert.detector_config || !alert.checks?.length) {
return []
}
- const defaultSeriesIndex = alert.config?.series_index ?? 0
+ const defaultSeriesIndex = isTrendsAlertConfig(alert.config) ? alert.config.series_index : 0
return alert.checks.flatMap((check) => {
if (!check.triggered_dates?.length) {
return []
@@ -204,7 +219,8 @@ export const insightAlertsLogic = kea<insightAlertsLogicType>([
listeners(({ actions, values }) => ({
setQuery: ({ query }) => {
- if (values.alerts.length === 0 || areAlertsSupportedForInsight(query)) {
+ const hogqlAlertsEnabled = !!values.featureFlags[FEATURE_FLAGS.HOGQL_INSIGHT_ALERTS]
+ if (values.alerts.length === 0 || areAlertsSupportedForInsight(query, { hogqlAlertsEnabled })) {
actions.setShouldShowAlertDeletionWarning(false)
} else {
actions.setShouldShowAlertDeletionWarning(true)
diff --git a/frontend/src/lib/components/Alerts/types.ts b/frontend/src/lib/components/Alerts/types.ts
index 615875a1e1fb..df1ac8bdb026 100644
--- a/frontend/src/lib/components/Alerts/types.ts
+++ b/frontend/src/lib/components/Alerts/types.ts
@@ -5,12 +5,42 @@ import {
AlertScheduleRestrictionWindow,
AlertState,
DetectorConfig,
+ HogQLAlertConfig,
InsightThreshold,
TrendsAlertConfig,
} from '~/queries/schema/schema-general'
import { QueryBasedInsightModel, UserBasicType } from '~/types'
-export type AlertConfig = TrendsAlertConfig
+export type AlertConfig = TrendsAlertConfig | HogQLAlertConfig
+
+export const isTrendsAlertConfig = (config: AlertConfig | null | undefined): config is TrendsAlertConfig =>
+ config?.type === 'TrendsAlertConfig'
+
+export const isHogQLAlertConfig = (config: AlertConfig | null | undefined): config is HogQLAlertConfig =>
+ config?.type === 'HogQLAlertConfig'
+
+/** SQL alert in any-row mode: every result row is checked (one entity per row), which changes
+ * row labeling and history rendering versus the single-value modes. */
+export const isAnyRowHogQLConfig = (config: AlertConfig | null | undefined): boolean =>
+ isHogQLAlertConfig(config) && config.evaluation === 'any_row'
+
+// Capability helpers — read at call sites instead of bare `isTrendsAlertConfig`/`isHogQLAlertConfig`
+// 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 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. */
+export const supportsTimeWindow = (config: AlertConfig | null | undefined): boolean => !isHogQLAlertConfig(config)
+
+/** Anomaly detection currently only has a trends detector extractor. */
+export const supportsAnomalyDetection = (config: AlertConfig | null | undefined): config is TrendsAlertConfig =>
+ isTrendsAlertConfig(config)
export type BlockedWindow = AlertScheduleRestrictionWindow
diff --git a/frontend/src/lib/components/Alerts/views/AlertHistorySection.tsx b/frontend/src/lib/components/Alerts/views/AlertHistorySection.tsx
index c1aa727e8105..f12e3ff8ea6c 100644
--- a/frontend/src/lib/components/Alerts/views/AlertHistorySection.tsx
+++ b/frontend/src/lib/components/Alerts/views/AlertHistorySection.tsx
@@ -21,8 +21,10 @@ import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
import { IconOpenInNew } from 'lib/lemon-ui/icons'
import { formatDate } from 'lib/utils/datetime'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { alertLogic, CHART_CHECKS_LIMIT, TABLE_CHECKS_PAGE_SIZE } from '../alertLogic'
+import { isAnyRowHogQLConfig } from '../types'
import type { AlertCheck, AlertType, InvestigationVerdict } from '../types'
const VERDICT_CONFIG: Record<InvestigationVerdict, { label: string; className: string; tooltip: string }> = {
@@ -138,6 +140,7 @@ export function AlertHistorySection({ alertId }: { alertId: AlertType['id'] }):
const { selectAlertHistoryView, alertHistoryTablePageForward, alertHistoryTablePageBackward } = useActions(logic)
const investigationAgentEnabled = alertHistoryIsAnomalyDetection && !!alert?.investigation_agent_enabled
+ const isAnyRowSqlAlert = isAnyRowHogQLConfig(alert?.config)
const checkHistoryColumns = useMemo((): LemonTableColumn<AlertCheck, keyof AlertCheck | undefined>[] => {
const columns: LemonTableColumn<AlertCheck, keyof AlertCheck | undefined>[] = [
@@ -176,6 +179,27 @@ export function AlertHistorySection({ alertId }: { alertId: AlertType['id'] }):
render: (_value, check) => <InvestigationCell check={check} />,
})
}
+ if (isAnyRowSqlAlert) {
+ columns.push({
+ title: 'Breaching rows',
+ render: (_value, check) => {
+ const meta = check.triggered_metadata as {
+ breaching_rows?: { label: string; value: number }[]
+ breaching_row_count?: number
+ } | null
+ const rows = meta?.breaching_rows
+ if (!rows?.length) {
+ return '—'
+ }
+ const shown = rows
+ .slice(0, 3)
+ .map((row) => `${row.label} (${humanFriendlyNumber(row.value)})`)
+ .join(', ')
+ const total = meta?.breaching_row_count ?? rows.length
+ return total > 3 ? `${shown} +${total - 3} more` : shown
+ },
+ })
+ }
columns.push({
title: 'Targets notified',
key: 'targets_notified',
@@ -183,7 +207,7 @@ export function AlertHistorySection({ alertId }: { alertId: AlertType['id'] }):
render: (_value, check) => (check.targets_notified ? 'Yes' : 'No'),
})
return columns
- }, [alertHistoryIsAnomalyDetection, investigationAgentEnabled])
+ }, [alertHistoryIsAnomalyDetection, investigationAgentEnabled, isAnyRowSqlAlert])
if (!alert) {
return null
diff --git a/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx b/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx
index 7d47829ead46..afbefe2d4c07 100644
--- a/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx
+++ b/frontend/src/lib/components/Alerts/views/EditAlertModal.tsx
@@ -13,12 +13,14 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { formatDate } from 'lib/utils/datetime'
+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { teamLogic } from 'scenes/teamLogic'
import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { AlertCalculationInterval, AlertState } from '~/queries/schema/schema-general'
+import { containsHogQLQuery } from '~/queries/utils'
import { AvailableFeature, InsightLogicProps, InsightShortId, QueryBasedInsightModel } from '~/types'
import { AlertAdvancedOptionsSection } from 'products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection'
@@ -33,6 +35,7 @@ import { alertNotificationLogic } from '../alertNotificationLogic'
import { isNextPlannedEvaluationStale } from '../alertSchedulingStale'
import { insightAlertsLogic } from '../insightAlertsLogic'
import { SnoozeButton } from '../SnoozeButton'
+import { supportsAnomalyDetection, supportsOngoingInterval } from '../types'
import type { AlertType } from '../types'
import { AlertHistorySection, AlertHistorySectionSkeleton } from './AlertHistorySection'
@@ -75,12 +78,17 @@ export function EditAlertModal({
interval: trendInterval,
} = useValues(trendsLogic)
+ const { query } = useValues(insightVizDataLogic(insightLogicProps ?? { dashboardItemId: insightShortId }))
+
+ const insightAlertKind: 'hogql' | 'trends' = containsHogQLQuery(query) ? 'hogql' : 'trends'
+
const formLogicProps = {
alert,
insightId,
onEditSuccess: _onEditSuccess,
insightVizDataLogicProps: insightLogicProps,
insightInterval: trendInterval ?? undefined,
+ insightAlertKind,
}
const formLogic = alertFormLogic(formLogicProps)
const {
@@ -91,6 +99,10 @@ export function EditAlertModal({
simulationResultLoading,
simulationDateFrom,
thresholdBoundsFormError,
+ hogqlAlertPreview,
+ hogqlResultColumns,
+ hogqlValueColumnOptions,
+ hogqlLabelColumnOptions,
} = useValues(formLogic)
const {
deleteAlert,
@@ -136,12 +148,27 @@ export function EditAlertModal({
const alertMode = alertForm.detector_config ? 'detector' : 'threshold'
const nextPlannedEvaluationStale = useMemo(
() =>
- isNextPlannedEvaluationStale(creatingNewAlert, alert, {
- calculation_interval: alertForm.calculation_interval,
- schedule_restriction: alertForm.schedule_restriction,
- skip_weekend: alertForm.skip_weekend,
- config: alertForm.config,
- }),
+ isNextPlannedEvaluationStale(
+ creatingNewAlert,
+ alert
+ ? {
+ calculation_interval: alert.calculation_interval,
+ schedule_restriction: alert.schedule_restriction,
+ skip_weekend: alert.skip_weekend,
+ config: supportsOngoingInterval(alert.config)
+ ? { check_ongoing_interval: alert.config.check_ongoing_interval }
+ : null,
+ }
+ : null,
+ {
+ calculation_interval: alertForm.calculation_interval,
+ schedule_restriction: alertForm.schedule_restriction,
+ skip_weekend: alertForm.skip_weekend,
+ config: supportsOngoingInterval(alertForm.config)
+ ? { check_ongoing_interval: alertForm.config.check_ongoing_interval }
+ : null,
+ }
+ ),
[
alert,
alertForm.calculation_interval,
@@ -154,7 +181,11 @@ export function EditAlertModal({
const enabledAdvancedOptionsCount = useMemo(() => {
let n = 0
- if (can_check_ongoing_interval && alertForm.config.check_ongoing_interval) {
+ if (
+ can_check_ongoing_interval &&
+ supportsOngoingInterval(alertForm.config) &&
+ alertForm.config.check_ongoing_interval
+ ) {
n += 1
}
if (
@@ -170,7 +201,7 @@ export function EditAlertModal({
return n
}, [
alertForm.calculation_interval,
- alertForm.config.check_ongoing_interval,
+ alertForm.config,
alertForm.schedule_restriction?.blocked_windows?.length,
alertForm.skip_weekend,
can_check_ongoing_interval,
@@ -232,7 +263,13 @@ export function EditAlertModal({
isNonTimeSeriesDisplay={isNonTimeSeriesDisplay}
alertSeries={alertSeries}
formulaNodes={formulaNodes}
- anomalyDetectionEnabled={anomalyDetectionEnabled}
+ hogqlPreview={hogqlAlertPreview}
+ hogqlColumns={hogqlResultColumns}
+ hogqlValueColumnOptions={hogqlValueColumnOptions}
+ hogqlLabelColumnOptions={hogqlLabelColumnOptions}
+ anomalyDetectionEnabled={
+ anomalyDetectionEnabled && supportsAnomalyDetection(alertForm.config)
+ }
investigationAgentEnabled={investigationAgentEnabled}
simulationResult={simulationResult}
simulationResultLoading={simulationResultLoading}
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index c41549af4174..ef999ccfa219 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -197,7 +197,9 @@ export function InsightMeta({
: true
const showDashboardAlertsMenuItem = isUsedAsDashboardTile && !!dashboardId && !!insight.id && canViewInsight
- const canCreateAlertForInsight = areAlertsSupportedForInsight(query)
+ const canCreateAlertForInsight = areAlertsSupportedForInsight(query, {
+ hogqlAlertsEnabled: !!featureFlags[FEATURE_FLAGS.HOGQL_INSIGHT_ALERTS],
+ })
const canToggleDisplayLabels = isUsedAsDashboardTile && canEditInsight && canToggleDisplayLabelsForInsight
const canToggleLegend = isUsedAsDashboardTile && canEditInsight && canToggleLegendForInsight
diff --git a/frontend/src/lib/components/TerraformExporter/alertHclExporter.ts b/frontend/src/lib/components/TerraformExporter/alertHclExporter.ts
index a07345bcc222..118ec1b12827 100644
--- a/frontend/src/lib/components/TerraformExporter/alertHclExporter.ts
+++ b/frontend/src/lib/components/TerraformExporter/alertHclExporter.ts
@@ -1,6 +1,6 @@
import { formatHclValue, sanitizeResourceName } from 'lib/components/TerraformExporter/hclExporterFormattingUtils'
-import { AlertType } from '~/lib/components/Alerts/types'
+import { AlertType, isTrendsAlertConfig } from '~/lib/components/Alerts/types'
import { HogFunctionType } from '~/types'
import { FieldMapping, HclExportOptions, HclExportResult, ResourceExporter, generateHCL } from './hclExporter'
@@ -59,14 +59,16 @@ const ALERT_FIELD_MAPPINGS: FieldMapping<Partial<AlertType>, AlertHclExportOptio
{
source: 'config',
target: 'series_index',
- shouldInclude: (_, alert) => alert.config?.series_index !== undefined,
- transform: (_, alert) => formatHclValue(alert.config?.series_index),
+ shouldInclude: (_, alert) => isTrendsAlertConfig(alert.config) && alert.config.series_index !== undefined,
+ transform: (_, alert) => (isTrendsAlertConfig(alert.config) ? formatHclValue(alert.config.series_index) : ''),
},
{
source: 'config',
target: 'check_ongoing_interval',
- shouldInclude: (_, alert) => alert.config?.check_ongoing_interval !== undefined,
- transform: (_, alert) => formatHclValue(alert.config?.check_ongoing_interval),
+ shouldInclude: (_, alert) =>
+ isTrendsAlertConfig(alert.config) && alert.config.check_ongoing_interval !== undefined,
+ transform: (_, alert) =>
+ isTrendsAlertConfig(alert.config) ? formatHclValue(alert.config.check_ongoing_interval) : '',
},
{
source: 'skip_weekend',
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 18e4d63cdc18..5e3bd6ea1500 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -317,10 +317,12 @@ export const FEATURE_FLAGS = {
FIELD_NOTES: 'field-notes', // owner: @adamleith
FLAG_EVALUATION_TAGS: 'flag-evaluation-tags', // owner: @dmarticus #team-feature-flags
FLAGGED_FEATURE_INDICATOR: 'flagged-feature-indicator', // owner: @benjackwhite
+ FUNNEL_INSIGHT_ALERTS: 'funnel-insight-alerts', // owner: @vdekrijger, gates alerts on funnel insights (conversion rate)
GROUP_PROFILE_EXPERIMENT: 'group-profile-experiment', // owner: @arthurdedeus #team-customer-analytics
HACKATHONS_SUBSCRIPTIONS: 'hackathons_subscriptions', // owner: #team-analytics-platform, gates listing subscription delivery history and AI change summaries
HEALTH_ALERTS: 'health-alerts', // owner: #team-growth, gates the central /health/alerts scene and per-page Alerts buttons
HEALTH_ASK_AI: 'health-ask-ai', // owner: @jordanm-posthog #team-web-analytics, gates the "Ask PostHog AI" buttons on the Health overview
+ HOGQL_INSIGHT_ALERTS: 'hogql-insight-alerts', // owner: @vdekrijger, gates alerts on SQL-backed (HogQL) insights
IDENTITY_MATCHING: 'identity-matching', // owner: #team-growth
INSIGHT_SUBSCRIBE_PROMINENT_BUTTON: 'insight-subscribe-prominent-button', // owner: @mattp #team-analytics-platform multivariate=control,test
INTER_PROJECT_TRANSFERS: 'inter-project-transfers', // owner: @reecejones #team-platform-features
diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
index f5508e75500e..2dd5d58009cd 100644
--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
@@ -6,10 +6,12 @@ import { useCallback, useRef, useState } from 'react'
import { IconGear } from '@posthog/icons'
import { LemonButton, LemonDivider } from '@posthog/lemon-ui'
+import { alertsToThresholdGoalLines, insightAlertsLogic } from 'lib/components/Alerts/insightAlertsLogic'
import { ExportButton } from 'lib/components/ExportButton/ExportButton'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { InsightErrorState, StatelessInsightLoadingState } from 'scenes/insights/EmptyStates'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
+import { insightLogic } from 'scenes/insights/insightLogic'
import { HogQLBoldNumber } from 'scenes/insights/views/BoldNumber/BoldNumber'
import { urls } from 'scenes/urls'
@@ -185,6 +187,24 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
const { seriesBreakdownData } = useValues(seriesBreakdownLogic({ key: dataVisualizationProps.key }))
const { goalLines } = useValues(displayLogic)
+ // Overlay alert threshold bounds on the chart, like trends does — only when rendering a saved
+ // insight (the SQL editor and other unsaved contexts have no alerts to show). Deliberately maps
+ // alerts directly instead of using the alertThresholdLines selector: that selector gates on the
+ // trends-only showAlertThresholdLines viz setting, which DataVisualizationNode doesn't have, so
+ // going through it would hide the lines on SQL charts entirely.
+ const alertsInsightProps = (props.context?.insightProps as InsightLogicProps | undefined) ?? {
+ dashboardItemId: undefined,
+ }
+ const { insight } = useValues(insightLogic(alertsInsightProps))
+ const { alerts } = useValues(
+ insightAlertsLogic({
+ insightId: insight?.id ?? 0,
+ insightLogicProps: alertsInsightProps,
+ deferInitialAlertsLoad: !insight?.id,
+ })
+ )
+ const alertThresholdLines = insight?.id ? alertsToThresholdGoalLines(alerts) : []
+
const { toggleChartSettingsPanel } = useActions(dataVisualizationLogic)
const { queryId, pollResponse } = useValues(dataNodeLogic)
@@ -245,7 +265,7 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
visualizationType={effectiveVisualizationType}
chartSettings={chartSettings}
dashboardId={dashboardId}
- goalLines={goalLines}
+ goalLines={[...alertThresholdLines, ...goalLines]}
presetChartHeight={presetChartHeight}
/>
)
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 3704407d78ce..761d70b654a3 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -23300,6 +23300,35 @@
"enum": ["hog", "hogJson", "hogQL", "hogQLExpr", "hogTemplate", "liquid"],
"type": "string"
},
+ "HogQLAlertConfig": {
+ "additionalProperties": false,
+ "description": "Alert config for HogQL/SQL-backed insights. The query owns its own time window.",
+ "properties": {
+ "column": {
+ "description": "Name of the result column to evaluate. When unset, the single numeric column is used (an error if the result has more than one numeric column).",
+ "type": ["string", "null"]
+ },
+ "evaluation": {
+ "$ref": "#/definitions/HogQLAlertEvaluation",
+ "description": "How to read the result rows — an explicit choice, no implicit default."
+ },
+ "label_column": {
+ "description": "In `any_row` mode, the column whose value labels each row in breach messages. When unset, the first non-evaluated column is used, falling back to the row number.",
+ "type": ["string", "null"]
+ },
+ "type": {
+ "const": "HogQLAlertConfig",
+ "type": "string"
+ }
+ },
+ "required": ["type", "evaluation"],
+ "type": "object"
+ },
+ "HogQLAlertEvaluation": {
+ "description": "How a SQL alert reads the query result. `last_row` = the query is ordered oldest→newest and the last row is the current value; `first_row` = the query is ordered newest→oldest and the first row is the current value (this mode bounds the fetch with a LIMIT since only the head is read); `any_row` = every row is checked and the alert fires if any value breaches (absolute conditions only).",
+ "enum": ["last_row", "first_row", "any_row"],
+ "type": "string"
+ },
"HogQLAutocomplete": {
"additionalProperties": false,
"properties": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 86d862d87f0d..a6804684a7f1 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -4819,6 +4819,26 @@ export interface TrendsAlertConfig {
check_ongoing_interval?: boolean
}
+/** How a SQL alert reads the query result.
+ * `last_row` = the query is ordered oldest→newest and the last row is the current value;
+ * `first_row` = the query is ordered newest→oldest and the first row is the current value
+ * (this mode bounds the fetch with a LIMIT since only the head is read);
+ * `any_row` = every row is checked and the alert fires if any value breaches (absolute conditions only). */
+export type HogQLAlertEvaluation = 'last_row' | 'first_row' | 'any_row'
+
+/** Alert config for HogQL/SQL-backed insights. The query owns its own time window. */
+export interface HogQLAlertConfig {
+ type: 'HogQLAlertConfig'
+ /** Name of the result column to evaluate. When unset, the single numeric column is used
+ * (an error if the result has more than one numeric column). */
+ column?: string | null
+ /** How to read the result rows — an explicit choice, no implicit default. */
+ evaluation: HogQLAlertEvaluation
+ /** In `any_row` mode, the column whose value labels each row in breach messages.
+ * When unset, the first non-evaluated column is used, falling back to the row number. */
+ label_column?: string | null
+}
+
/** One blocked period for quiet hours: 24-hour HH:MM in the project timezone; interval is half-open [start, end). */
export interface AlertScheduleRestrictionWindow {
start: string
diff --git a/frontend/src/scenes/insights/InsightModals.tsx b/frontend/src/scenes/insights/InsightModals.tsx
index 792ef71ae74d..f8fc3c0894da 100644
--- a/frontend/src/scenes/insights/InsightModals.tsx
+++ b/frontend/src/scenes/insights/InsightModals.tsx
@@ -8,6 +8,7 @@ import { ManageAlertsModal } from 'lib/components/Alerts/views/ManageAlertsModal
import { SharingModal } from 'lib/components/Sharing/SharingModal'
import { SubscriptionsModal } from 'lib/components/Subscriptions/SubscriptionsModal'
import { TerraformExportModal } from 'lib/components/TerraformExporter/TerraformExportModal'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { NewDashboardModal } from 'scenes/dashboard/NewDashboardModal'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
@@ -90,7 +91,8 @@ function InsightAlertsModals({ insightLogicProps }: { insightLogicProps: Insight
const { query } = useValues(insightDataLogic(insightProps))
const { push } = useActions(router)
- const canCreateAlertForInsight = areAlertsSupportedForInsight(query)
+ const hogqlAlertsEnabled = useFeatureFlag('HOGQL_INSIGHT_ALERTS')
+ const canCreateAlertForInsight = areAlertsSupportedForInsight(query, { hogqlAlertsEnabled })
return (
<>
diff --git a/frontend/src/scenes/insights/InsightPageHeader.tsx b/frontend/src/scenes/insights/InsightPageHeader.tsx
index 92a630bd96f6..00d009eb0a4b 100644
--- a/frontend/src/scenes/insights/InsightPageHeader.tsx
+++ b/frontend/src/scenes/insights/InsightPageHeader.tsx
@@ -5,6 +5,7 @@ import { useMemo } from 'react'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { areAlertsSupportedForInsight } from 'lib/components/Alerts/insightAlertsLogic'
import { InsightSubscribeProminentButton } from 'lib/components/Scenes/InsightSubscribeProminentButton'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
@@ -63,7 +64,8 @@ export function InsightPageHeader({ insightLogicProps }: { insightLogicProps: In
const defaultInsightName =
typeof lastBreadcrumb?.name === 'string' ? lastBreadcrumb.name : insight.name || insight.derived_name
- const canCreateAlertForInsight = areAlertsSupportedForInsight(query)
+ const hogqlAlertsEnabled = useFeatureFlag('HOGQL_INSIGHT_ALERTS')
+ const canCreateAlertForInsight = areAlertsSupportedForInsight(query, { hogqlAlertsEnabled })
const insightDisplayName = insight?.name || insight?.derived_name
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
index daaa730d0a2c..0d41e8df1146 100644
--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
@@ -853,10 +853,11 @@
'__static_attributes__',
'__str__',
'_meta',
+ '_unwrapped_query_kind',
'alert_set',
+ 'alertable_query_kind',
'alertconfiguration_set',
'annotation_set',
- 'are_alerts_supported',
'caching_state',
'caching_states',
'created_by_id',
diff --git a/posthog/schema.py b/posthog/schema.py
index 957885e3ddc2..02a7650b6539 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -123,6 +123,7 @@ from posthog.schema_enums import (
HedgehogActorSkinOption as HedgehogActorSkinOption,
HideViewedRecordings as HideViewedRecordings,
HogLanguage as HogLanguage,
+ HogQLAlertEvaluation as HogQLAlertEvaluation,
HrefMatching as HrefMatching,
InCohortVia as InCohortVia,
InfinityValue as InfinityValue,
@@ -5298,6 +5299,32 @@ class HeatmapSettings(BaseModel):
yAxisLabel: str | None = None
+class HogQLAlertConfig(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ column: str | None = Field(
+ default=None,
+ description=(
+ "Name of the result column to evaluate. When unset, the single numeric"
+ " column is used (an error if the result has more than one numeric column)."
+ ),
+ )
+ evaluation: HogQLAlertEvaluation = Field(
+ ...,
+ description=("How to read the result rows — an explicit choice, no implicit default."),
+ )
+ label_column: str | None = Field(
+ default=None,
+ description=(
+ "In `any_row` mode, the column whose value labels each row in breach"
+ " messages. When unset, the first non-evaluated column is used, falling"
+ " back to the row number."
+ ),
+ )
+ type: Literal["HogQLAlertConfig"] = "HogQLAlertConfig"
+
+
class HogQLAutocompleteResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index c4a165afd0e0..b53d64807d00 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -2020,6 +2020,12 @@ class HogLanguage(StrEnum):
LIQUID = "liquid"
+class HogQLAlertEvaluation(StrEnum):
+ LAST_ROW = "last_row"
+ FIRST_ROW = "first_row"
+ ANY_ROW = "any_row"
+
+
class BounceRatePageViewMode(StrEnum):
COUNT_PAGEVIEWS = "count_pageviews"
UNIQ_URLS = "uniq_urls"
diff --git a/posthog/tasks/alerts/test/test_validate_alert_config.py b/posthog/tasks/alerts/test/test_validate_alert_config.py
index 6079d47c1355..8768892cd777 100644
--- a/posthog/tasks/alerts/test/test_validate_alert_config.py
+++ b/posthog/tasks/alerts/test/test_validate_alert_config.py
@@ -4,7 +4,7 @@ import pytest
from parameterized import parameterized
-from posthog.tasks.alerts.utils import validate_alert_config
+from products.alerts.backend.evaluation.validation import validate_alert_config
def _base_condition(type: str = "absolute_value") -> dict[str, Any]:
@@ -25,6 +25,14 @@ def _base_query(series_count: int = 1, display: str | None = None) -> dict[str,
return query
+def _hogql_config() -> dict[str, Any]:
+ return {"type": "HogQLAlertConfig", "evaluation": "last_row"}
+
+
+def _hogql_query() -> dict[str, Any]:
+ return {"kind": "HogQLQuery", "query": "SELECT count() FROM events"}
+
+
def _base_threshold(type: str = "absolute", bounds: dict[str, Any] | None = None) -> dict[str, Any]:
config: dict[str, Any] = {"type": type}
if bounds is None:
@@ -245,6 +253,33 @@ class TestValidateAlertConfig:
None,
"Invalid calculation interval: None",
),
+ (
+ "valid_hogql_config",
+ _hogql_query(),
+ _base_condition(),
+ _hogql_config(),
+ _base_threshold(),
+ "daily",
+ None,
+ ),
+ (
+ "hogql_config_with_trends_query_rejected",
+ _base_query(),
+ _base_condition(),
+ _hogql_config(),
+ _base_threshold(),
+ "daily",
+ "SQL alert config requires a HogQLQuery insight",
+ ),
+ (
+ "hogql_absolute_condition_with_percentage_threshold_rejected",
+ _hogql_query(),
+ _base_condition("absolute_value"),
+ _hogql_config(),
+ _base_threshold(type="percentage"),
+ "daily",
+ "Absolute value alerts require an absolute threshold",
+ ),
]
)
def test_validate_alert_config(
@@ -263,12 +298,18 @@ class TestValidateAlertConfig:
with pytest.raises(ValueError, match=expected_error_fragment):
validate_alert_config(query, condition, config, threshold_config, calculation_interval)
- def test_threshold_alert_requires_at_least_one_bound(self) -> None:
+ @parameterized.expand(
+ [
+ ("hogql", _hogql_query(), _hogql_config()),
+ ("trends", _base_query(), _base_config()),
+ ]
+ )
+ def test_threshold_alert_requires_at_least_one_bound(self, _name: str, query: dict, config: dict) -> None:
with pytest.raises(ValueError, match="At least one threshold bound"):
validate_alert_config(
- _base_query(),
+ query,
_base_condition(),
- _base_config(),
+ config,
_base_threshold(bounds={}),
"daily",
)
@@ -283,6 +324,58 @@ class TestValidateAlertConfig:
detector_config={"type": "zscore", "threshold": 0.95, "window": 30},
)
+ def test_any_row_hogql_alert_rejects_relative_conditions(self) -> None:
+ with pytest.raises(ValueError, match="Any-row SQL alerts only support absolute value conditions"):
+ validate_alert_config(
+ _hogql_query(),
+ _base_condition("relative_increase"),
+ {"type": "HogQLAlertConfig", "evaluation": "any_row"},
+ _base_threshold(type="percentage"),
+ "daily",
+ )
+
+ def test_invalid_hogql_config_rejected(self) -> None:
+ with pytest.raises(ValueError, match="invalid HogQLAlertConfig"):
+ validate_alert_config(
+ _hogql_query(),
+ _base_condition(),
+ {"type": "HogQLAlertConfig", "evaluation": "sideways"},
+ _base_threshold(),
+ "daily",
+ )
+
+ def test_hogql_config_without_evaluation_rejected(self) -> None:
+ # ``evaluation`` is required — no silent default.
+ with pytest.raises(ValueError, match="invalid HogQLAlertConfig"):
+ validate_alert_config(
+ _hogql_query(),
+ _base_condition(),
+ {"type": "HogQLAlertConfig"},
+ _base_threshold(),
+ "daily",
+ )
+
+ def test_first_row_hogql_alert_accepts_relative_conditions(self) -> None:
+ # Unlike any_row, first_row is a time axis (newest first), so relative is valid.
+ validate_alert_config(
+ _hogql_query(),
+ _base_condition("relative_increase"),
+ {"type": "HogQLAlertConfig", "evaluation": "first_row"},
+ _base_threshold(type="percentage"),
+ "daily",
+ )
+
+ def test_detector_config_rejected_for_non_trends_insight(self) -> None:
+ with pytest.raises(ValueError, match="Anomaly detection alerts are only supported for trends insights"):
+ validate_alert_config(
+ _hogql_query(),
+ _base_condition(),
+ _hogql_config(),
+ _base_threshold(),
+ "daily",
+ detector_config={"type": "zscore", "threshold": 0.95, "window": 30},
+ )
+
def test_skips_threshold_bounds_when_not_required(self) -> None:
validate_alert_config(
_base_query(),
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.py
index ff7de94399c0..04a04286663d 100644
--- a/posthog/tasks/alerts/utils.py
+++ b/posthog/tasks/alerts/utils.py
@@ -6,26 +6,13 @@ from django.utils import timezone
import pytz
import structlog
from dateutil.relativedelta import MO, relativedelta
-from pydantic import ValidationError as PydanticValidationError
-
-from posthog.schema import (
- AlertCalculationInterval,
- AlertCondition,
- AlertConditionType,
- AlertState,
- ChartDisplayType,
- InsightThreshold,
- InsightThresholdType,
- NodeKind,
- TrendsAlertConfig,
- TrendsQuery,
-)
+
+from posthog.schema import AlertCalculationInterval, AlertState, ChartDisplayType, NodeKind, TrendsQuery
from posthog.cdp.internal_events import InternalEventEvent, produce_internal_event
from posthog.email import EmailMessage
from posthog.exceptions_capture import capture_exception
from posthog.tasks.alerts.schedule_restriction import snap_candidate_utc_to_schedule_restriction
-from posthog.utils import get_from_dict_or_attr
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, derive_detector_event_fields
@@ -59,120 +46,6 @@ def is_non_time_series_trend(query: TrendsQuery) -> bool:
return display in NON_TIME_SERIES_DISPLAY_TYPES
-THRESHOLD_BOUNDS_REQUIRED_MESSAGE = "At least one threshold bound (lower or upper) must be provided."
-
-
-def insight_threshold_has_bounds(threshold_config: dict | None) -> bool:
- if threshold_config is None:
- return False
- try:
- threshold = InsightThreshold.model_validate(threshold_config)
- except PydanticValidationError:
- return False
- bounds = threshold.bounds
- if bounds is None:
- return False
- return bounds.lower is not None or bounds.upper is not None
-
-
-def validate_threshold_bounds_required(threshold_config: dict | None) -> None:
- if not insight_threshold_has_bounds(threshold_config):
- raise ValueError(THRESHOLD_BOUNDS_REQUIRED_MESSAGE)
-
-
-def _validate_condition_threshold_compatibility(
- parsed_condition: AlertCondition, threshold_config: dict | None
-) -> InsightThreshold | None:
- """Parse the threshold and enforce condition/threshold compatibility shared by all insight kinds."""
- if threshold_config is None:
- return None
- try:
- threshold = InsightThreshold.model_validate(threshold_config)
- except Exception:
- raise ValueError(f"Alert has invalid threshold configuration: {threshold_config}")
- if parsed_condition.type == AlertConditionType.ABSOLUTE_VALUE and threshold.type != InsightThresholdType.ABSOLUTE:
- raise ValueError(
- "Absolute value alerts require an absolute threshold, but a percentage threshold was configured"
- )
- return threshold
-
-
-def validate_alert_config(
- query: dict,
- condition: dict | None,
- config: dict | None,
- threshold_config: dict | None = None,
- calculation_interval: str | None = None,
- detector_config: dict | None = None,
- require_threshold_bounds: bool = True,
-) -> None:
- """Validate alert configuration dicts. Raises ValueError on failure."""
- if not calculation_interval or not isinstance(calculation_interval, str):
- raise ValueError(f"Invalid calculation interval: {calculation_interval}")
- try:
- AlertCalculationInterval(calculation_interval)
- except ValueError:
- raise ValueError(f"Invalid calculation interval: {calculation_interval}")
-
- try:
- parsed_condition = AlertCondition.model_validate(condition)
- except Exception:
- raise ValueError(f"Alert has invalid condition: {condition}")
-
- config_type = config.get("type") if isinstance(config, dict) else None
-
- kind = get_from_dict_or_attr(query, "kind")
- if kind in WRAPPER_NODE_KINDS:
- query = get_from_dict_or_attr(query, "source")
- kind = get_from_dict_or_attr(query, "kind")
-
- if config_type != "TrendsAlertConfig":
- raise ValueError(f"Unsupported alert config type: {config}")
- try:
- parsed_config = TrendsAlertConfig.model_validate(config)
- except Exception:
- raise ValueError(f"Alert has invalid TrendsAlertConfig: {config}")
-
- if kind != NodeKind.TRENDS_QUERY:
- raise ValueError(f"Alert's insight query kind '{kind}' is not supported (only TrendsQuery)")
-
- try:
- trends_query = TrendsQuery.model_validate(query)
- except Exception as e:
- raise ValueError(f"Alert's insight has an invalid TrendsQuery: {e}")
-
- if parsed_condition.type in (
- AlertConditionType.RELATIVE_INCREASE,
- AlertConditionType.RELATIVE_DECREASE,
- ) and is_non_time_series_trend(trends_query):
- raise ValueError(
- f"Relative alert condition '{parsed_condition.type}' is not compatible with non time series trends"
- )
-
- formula_nodes = trends_query.trendsFilter.formulaNodes if trends_query.trendsFilter else None
- result_count = len(formula_nodes) if formula_nodes else len(trends_query.series)
- if parsed_config.series_index >= result_count:
- raise ValueError(f"series_index {parsed_config.series_index} is out of range (query has {result_count} series)")
-
- threshold = _validate_condition_threshold_compatibility(parsed_condition, threshold_config)
- if (
- threshold is not None
- and parsed_config.check_ongoing_interval
- and parsed_condition.type
- in (
- AlertConditionType.ABSOLUTE_VALUE,
- AlertConditionType.RELATIVE_INCREASE,
- )
- ):
- if not threshold.bounds or threshold.bounds.upper is None:
- raise ValueError(
- f"check_ongoing_interval is only supported for alert condition {parsed_condition.type} when upper threshold is specified"
- )
-
- if require_threshold_bounds and detector_config is None:
- validate_threshold_bounds_required(threshold_config)
-
-
def calculation_interval_to_order(interval: AlertCalculationInterval | None) -> int:
match interval:
case AlertCalculationInterval.EVERY_15_MINUTES:
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index be2c5fa6318f..467874472f5f 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -24,7 +24,6 @@ from posthog.tasks.alerts.utils import (
next_check_time,
record_alert_delivery,
skip_because_of_weekend,
- validate_alert_config,
)
from posthog.temporal.alerts.investigation import claim_investigation_slot, should_trigger_investigation
from posthog.temporal.alerts.types import (
@@ -40,6 +39,7 @@ from posthog.temporal.alerts.types import (
from posthog.temporal.common.heartbeat import Heartbeater
from products.alerts.backend.evaluation import check_alert_for_insight
+from products.alerts.backend.evaluation.validation import validate_alert_config
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
from products.notifications.backend.facade.api import (
NotificationData,
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index 0257ea90a3d1..d32382d6b27e 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -23,7 +23,7 @@ from posthog.schema import (
from posthog.errors import CHQueryErrorTooManySimultaneousQueries
from posthog.models import User
-from posthog.tasks.alerts.utils import THRESHOLD_BOUNDS_REQUIRED_MESSAGE, AlertEvaluationResult
+from posthog.tasks.alerts.utils import AlertEvaluationResult
from posthog.temporal.alerts.activities import cleanup_alert_checks, evaluate_alert, notify_alert, prepare_alert
from posthog.temporal.alerts.types import (
EvaluateAlertActivityInputs,
@@ -33,6 +33,7 @@ from posthog.temporal.alerts.types import (
SkipReason,
)
+from products.alerts.backend.evaluation.validation import THRESHOLD_BOUNDS_REQUIRED_MESSAGE
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Threshold
from products.product_analytics.backend.models.insight import Insight
diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.py
index 5b93670c6bcf..f0824a21f230 100644
--- a/products/alerts/backend/api/alert.py
+++ b/products/alerts/backend/api/alert.py
@@ -1,9 +1,15 @@
import uuid
+from typing import Annotated, Any
from zoneinfo import ZoneInfo
from django.db.models import OuterRef, QuerySet, Subquery
+import posthoganalytics
from drf_spectacular.utils import OpenApiParameter, OpenApiTypes, extend_schema, extend_schema_view
+from pydantic import (
+ Field as PydanticField,
+ RootModel,
+)
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
@@ -14,7 +20,9 @@ from posthog.schema import (
AlertCondition,
AlertState,
DetectorConfig,
+ HogQLAlertConfig,
InsightThreshold,
+ NodeKind,
TrendsAlertConfig,
)
@@ -29,15 +37,12 @@ from posthog.resource_limits import LimitKey, check_count_limit
from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.tasks.alerts.detector import MAX_DETECTOR_BREAKDOWN_VALUES
from posthog.tasks.alerts.schedule_restriction import validate_and_normalize_schedule_restriction
-from posthog.tasks.alerts.utils import (
- THRESHOLD_BOUNDS_REQUIRED_MESSAGE,
- next_check_at_after_schedule_restriction_change,
- validate_alert_config,
-)
+from posthog.tasks.alerts.utils import next_check_at_after_schedule_restriction_change
from posthog.utils import relative_date_parse
from products.alerts.backend.api.alert_schedule_restriction import AlertScheduleRestriction
from products.alerts.backend.evaluation.detector import simulate_detector_on_insight
+from products.alerts.backend.evaluation.validation import THRESHOLD_BOUNDS_REQUIRED_MESSAGE, validate_alert_config
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold
from products.product_analytics.backend.models.insight import Insight
@@ -56,6 +61,13 @@ def _validate_every_15_minutes_interval(
raise ValidationError({"calculation_interval": [error]})
+def _require_insight_viewer_access(context: dict[str, Any], insight: Insight) -> None:
+ # Team scoping alone doesn't gate per-object insight access controls, so require viewer access
+ # explicitly — alert write/simulate access must not expose a restricted insight's results.
+ if not context["view"].user_access_control.check_access_level_for_object(insight, "viewer"):
+ raise ValidationError("Viewer access to this insight is required.")
+
+
@extend_schema_field(InsightThreshold) # type: ignore[arg-type]
class ThresholdConfigurationField(serializers.JSONField):
pass
@@ -66,8 +78,15 @@ class AlertConditionField(serializers.JSONField):
pass
-@extend_schema_field(TrendsAlertConfig) # type: ignore[arg-type]
-class TrendsAlertConfigField(serializers.JSONField):
+class AlertConfigUnion(RootModel):
+ """Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the
+ generated frontend types and MCP tool schemas) in sync with every kind alerts support."""
+
+ root: Annotated[TrendsAlertConfig | HogQLAlertConfig, PydanticField(discriminator="type")]
+
+
+@extend_schema_field(AlertConfigUnion) # type: ignore[arg-type]
+class AlertConfigField(serializers.JSONField):
pass
@@ -197,10 +216,17 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
allow_null=True,
help_text="Alert condition type. Determines how the value is evaluated: absolute_value, relative_increase, or relative_decrease.",
)
- config = TrendsAlertConfigField(
+ config = AlertConfigField(
required=False,
allow_null=True,
- help_text="Trends-specific alert configuration. Includes series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval).",
+ help_text=(
+ "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 (labels rows in breach messages for any_row)."
+ ),
)
detector_config = DetectorConfigField(required=False, allow_null=True)
insight = TeamScopedPrimaryKeyRelatedField(
@@ -501,10 +527,39 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
return value
def validate_insight(self, value):
- if value and not value.are_alerts_supported:
- raise ValidationError("Alerts are not supported for this insight.")
+ if not value:
+ return value
+ _require_insight_viewer_access(self.context, value)
+ self._enforce_alert_feature_flags(value)
return value
+ def _enforce_alert_feature_flags(self, insight) -> None:
+ # Enforced from the object-level validate() so it runs on every create and update — including
+ # a PATCH that omits `insight` (which skips this field-level validator), so an alert can't be
+ # repointed at a flag-gated insight kind in an account where the flag is off. The model stays
+ # flag-agnostic so existing alerts keep working when the flag is off.
+ kind = insight.alertable_query_kind
+ if kind is None:
+ raise ValidationError("Alerts are not supported for this insight.")
+ if kind == NodeKind.HOG_QL_QUERY and not self._hogql_alerts_enabled():
+ raise ValidationError("SQL insight alerts are not enabled for your account.")
+
+ def _hogql_alerts_enabled(self) -> bool:
+ # Scope the flag to the alert's organization (via team scope), not the user's current
+ # organization — otherwise a user in multiple orgs could flip their current org to a
+ # flag-on org and create a SQL alert in a team where the flag is disabled. get_organization
+ # is always injected by TeamAndOrgViewSetMixin; access it unconditionally so the org-scoping
+ # invariant can't silently degrade to an unscoped check.
+ user = self.context["request"].user
+ org = self.context["get_organization"]()
+ return bool(
+ posthoganalytics.feature_enabled(
+ "hogql-insight-alerts",
+ str(user.distinct_id),
+ groups={"organization": str(org.id)},
+ )
+ )
+
def validate_subscribed_users(self, value):
for user in value:
if not user.teams.filter(pk=self.context["team_id"]).exists():
@@ -526,6 +581,7 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
insight = attrs.get("insight") or (self.instance.insight if self.instance else None)
if insight is None:
raise ValidationError({"insight": ["Insight is required."]})
+ self._enforce_alert_feature_flags(insight)
with upgrade_query(insight):
query = insight.query
if query is None:
@@ -640,6 +696,10 @@ class AlertSimulateSerializer(serializers.Serializer):
"If not provided, uses the detector's minimum required samples.",
)
+ def validate_insight(self, value):
+ _require_insight_viewer_access(self.context, value)
+ return value
+
def validate_detector_config(self, value):
if value is None:
raise ValidationError("detector_config is required.")
@@ -779,6 +839,17 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
queryset = self._apply_search(queryset, search)
+ # Gate on viewer access to the linked insight. Alert read/write access does not imply access
+ # to the insight's results (carried in AlertCheck.triggered_metadata / calculated_value), and
+ # "alert" isn't an access-control resource — so without this an alert leaks a restricted
+ # insight's data via check history, or via a PATCH that omits `insight` (skipping the
+ # create-time check). Filtering here covers list, retrieve, update, delete, and the embedded
+ # checks, since get_object() resolves detail routes from this queryset.
+ viewable_insights = self.user_access_control.filter_queryset_by_access_level(
+ Insight.objects.filter(team_id=self.team_id)
+ )
+ queryset = queryset.filter(insight_id__in=viewable_insights.values("id"))
+
latest_check = AlertCheck.objects.filter(alert_configuration=OuterRef("pk")).order_by("-created_at")
queryset = queryset.annotate(last_value=Subquery(latest_check.values("calculated_value")[:1]))
diff --git a/products/alerts/backend/api/test/test_alert.py b/products/alerts/backend/api/test/test_alert.py
index 6318d5c29bdf..7d61b1570451 100644
--- a/products/alerts/backend/api/test/test_alert.py
+++ b/products/alerts/backend/api/test/test_alert.py
@@ -93,6 +93,69 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
alerts = self.client.get(f"/api/projects/{self.team.id}/alerts")
assert len(alerts.json()["results"]) == 0
+ def test_alert_rejects_insight_without_viewer_access(self) -> None:
+ # Alert write access must not let a user reference an insight they can't view — otherwise
+ # they could exfiltrate a restricted insight's results via notifications / check history.
+ def deny_insight(obj=None, *args, **kwargs) -> bool:
+ return type(obj).__name__ != "Insight"
+
+ creation_request = {
+ "insight": self.insight["id"],
+ "subscribed_users": [self.user.id],
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "name": "alert name",
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},
+ "calculation_interval": "daily",
+ }
+ # An alert created while access is allowed, so we can test the insight-swap update vector.
+ alert_id = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()["id"]
+
+ with mock.patch(
+ "posthog.rbac.user_access_control.UserAccessControl.check_access_level_for_object",
+ side_effect=deny_insight,
+ ):
+ create = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request)
+ update = self.client.patch(
+ f"/api/projects/{self.team.id}/alerts/{alert_id}", {"insight": self.insight["id"]}
+ )
+ simulate = self.client.post(
+ f"/api/projects/{self.team.id}/alerts/simulate/",
+ {"insight": self.insight["id"], "detector_config": {"type": "zscore", "threshold": 0.9}},
+ )
+
+ for response in (create, update, simulate):
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "access to this insight" in str(response.json())
+
+ def test_existing_alert_hidden_when_insight_viewer_access_is_lost(self) -> None:
+ # An existing alert must not outlive viewer access to its linked insight: otherwise its
+ # check history (breaching rows / values) leaks on read, and a PATCH that omits `insight`
+ # bypasses the create-time check. The queryset gate hides it from list, retrieve, and update.
+ creation_request = {
+ "insight": self.insight["id"],
+ "subscribed_users": [self.user.id],
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "name": "alert name",
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},
+ "calculation_interval": "daily",
+ }
+ alert_id = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()["id"]
+
+ # Deny viewer access to every insight by emptying the viewable-insight queryset.
+ with mock.patch(
+ "posthog.rbac.user_access_control.UserAccessControl.filter_queryset_by_access_level",
+ side_effect=lambda queryset, *args, **kwargs: queryset.none(),
+ ):
+ retrieve = self.client.get(f"/api/projects/{self.team.id}/alerts/{alert_id}")
+ listed = self.client.get(f"/api/projects/{self.team.id}/alerts")
+ update = self.client.patch(f"/api/projects/{self.team.id}/alerts/{alert_id}", {"name": "renamed"})
+
+ assert retrieve.status_code == status.HTTP_404_NOT_FOUND, retrieve.content
+ assert update.status_code == status.HTTP_404_NOT_FOUND, update.content
+ assert [a["id"] for a in listed.json()["results"]] == []
+
def test_create_threshold_alert_rejects_empty_bounds(self) -> None:
creation_request = {
"insight": self.insight["id"],
@@ -420,6 +483,121 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
response = self.client.get(f"/api/projects/{self.team.id}/alerts/{alert['id']}")
assert response.status_code == status.HTTP_404_NOT_FOUND
+ def test_hogql_alert_survives_insight_update_and_is_listed_on_insight(self) -> None:
+ hogql_insight_data: dict[str, Any] = {
+ "query": {
+ "kind": "DataVisualizationNode",
+ "source": {"kind": "HogQLQuery", "query": "select count() from events"},
+ },
+ }
+ hogql_insight = self.client.post(f"/api/projects/{self.team.id}/insights", data=hogql_insight_data).json()
+
+ with mock.patch("products.alerts.backend.api.alert.posthoganalytics.feature_enabled", return_value=True):
+ alert = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ {
+ "insight": hogql_insight["id"],
+ "subscribed_users": [self.user.id],
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "HogQLAlertConfig", "evaluation": "last_row"},
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},
+ "name": "sql alert",
+ },
+ ).json()
+
+ # The insight response must list the alert inline — the UI trusts this list on reload.
+ insight_response = self.client.get(f"/api/projects/{self.team.id}/insights/{hogql_insight['id']}").json()
+ assert [a["id"] for a in insight_response["alerts"]] == [alert["id"]]
+
+ # Updating the insight while it stays SQL-backed must not cascade-delete the alert.
+ updated = deepcopy(hogql_insight_data)
+ updated["query"]["source"]["query"] = "select count() + 1 from events"
+ self.client.patch(f"/api/projects/{self.team.id}/insights/{hogql_insight['id']}", data=updated)
+ response = self.client.get(f"/api/projects/{self.team.id}/alerts/{alert['id']}")
+ assert response.status_code == status.HTTP_200_OK
+
+ # Changing to a kind that cannot carry alerts still cascades.
+ self.client.patch(
+ f"/api/projects/{self.team.id}/insights/{hogql_insight['id']}",
+ data={"query": {"kind": "FunnelsQuery", "series": []}},
+ )
+ response = self.client.get(f"/api/projects/{self.team.id}/alerts/{alert['id']}")
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def _create_hogql_insight(self) -> dict:
+ return self.client.post(
+ f"/api/projects/{self.team.id}/insights",
+ data={
+ "query": {
+ "kind": "DataVisualizationNode",
+ "source": {"kind": "HogQLQuery", "query": "select count() from events"},
+ }
+ },
+ ).json()
+
+ def test_hogql_flag_enforced_on_config_only_patch(self) -> None:
+ # A config-only PATCH (no `insight`) skips the field-level validate_insight, so the SQL-alert
+ # flag must be enforced in the object-level validate() — otherwise an existing SQL alert could
+ # be reconfigured in an account where the flag is no longer enabled.
+ hogql_insight = self._create_hogql_insight()
+ with mock.patch("products.alerts.backend.api.alert.posthoganalytics.feature_enabled", return_value=True):
+ alert = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ {
+ "insight": hogql_insight["id"],
+ "subscribed_users": [self.user.id],
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "HogQLAlertConfig", "evaluation": "last_row"},
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},
+ "name": "sql alert",
+ },
+ )
+ assert alert.status_code == status.HTTP_201_CREATED, alert.content
+ alert_id = alert.json()["id"]
+
+ config_patch = {"config": {"type": "HogQLAlertConfig", "evaluation": "first_row"}}
+ with mock.patch("products.alerts.backend.api.alert.posthoganalytics.feature_enabled", return_value=False):
+ blocked = self.client.patch(f"/api/projects/{self.team.id}/alerts/{alert_id}", config_patch)
+ assert blocked.status_code == status.HTTP_400_BAD_REQUEST, blocked.content
+ assert "SQL insight alerts are not enabled" in str(blocked.content)
+
+ with mock.patch("products.alerts.backend.api.alert.posthoganalytics.feature_enabled", return_value=True):
+ allowed = self.client.patch(f"/api/projects/{self.team.id}/alerts/{alert_id}", config_patch)
+ assert allowed.status_code == status.HTTP_200_OK, allowed.content
+
+ def test_alert_survives_switch_between_alertable_kinds(self) -> None:
+ # Switching the insight to a different alertable kind (trends -> SQL) leaves the alert's config
+ # mismatched, but the alert is NOT deleted: the check cycle re-validates against the current
+ # query and auto-disables + notifies on mismatch (covered by the validation/auto-disable tests),
+ # so the alert and its history survive the edit and the user can reconfigure it.
+ trends_insight = self.client.post(
+ f"/api/projects/{self.team.id}/insights", data=self.default_insight_data
+ ).json()
+ alert_id = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ {
+ "insight": trends_insight["id"],
+ "subscribed_users": [self.user.id],
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},
+ "name": "trends alert",
+ },
+ ).json()["id"]
+
+ # Switch the insight from trends to SQL — a different alertable kind.
+ with mock.patch("products.alerts.backend.api.alert.posthoganalytics.feature_enabled", return_value=True):
+ self.client.patch(
+ f"/api/projects/{self.team.id}/insights/{trends_insight['id']}",
+ data={
+ "query": {
+ "kind": "DataVisualizationNode",
+ "source": {"kind": "HogQLQuery", "query": "select count() from events"},
+ }
+ },
+ )
+ assert self.client.get(f"/api/projects/{self.team.id}/alerts/{alert_id}").status_code == status.HTTP_200_OK
+
def test_alert_is_deleted_on_insight_soft_delete(self) -> None:
another_insight = self.client.post(
f"/api/projects/{self.team.id}/insights", data=self.default_insight_data
@@ -1231,6 +1409,52 @@ class TestAlertEventProperties(APIBaseTest):
for key, value in expected_detector_fields.items():
assert props[key] == value, f"{key} expected {value}, got {props[key]}"
+ @parameterized.expand(
+ [
+ (
+ "trends_config",
+ {"type": "TrendsAlertConfig", "series_index": 1},
+ {
+ "config_type": "TrendsAlertConfig",
+ "trends_series_index": 1,
+ "hogql_evaluation": None,
+ "hogql_has_explicit_column": None,
+ "hogql_has_label_column": None,
+ },
+ ),
+ (
+ "hogql_default",
+ {"type": "HogQLAlertConfig", "evaluation": "last_row"},
+ {
+ "config_type": "HogQLAlertConfig",
+ "hogql_evaluation": "last_row",
+ "hogql_has_explicit_column": False,
+ "hogql_has_label_column": False,
+ },
+ ),
+ (
+ "hogql_any_row_with_columns",
+ {"type": "HogQLAlertConfig", "evaluation": "any_row", "column": "errors", "label_column": "country"},
+ {
+ "config_type": "HogQLAlertConfig",
+ "hogql_evaluation": "any_row",
+ "hogql_has_explicit_column": True,
+ "hogql_has_label_column": True,
+ },
+ ),
+ ]
+ )
+ def test_event_properties_capture_alert_config_adoption(self, _name: str, config: dict, expected: dict) -> None:
+ alert = AlertConfiguration(
+ name="test alert",
+ condition={"type": "absolute_value"},
+ config=config,
+ calculation_interval="daily",
+ )
+ props = alert._get_event_properties()
+ for key, value in expected.items():
+ assert props[key] == value, f"{key} expected {value}, got {props[key]}"
+
class TestTriggerAlertHogFunctions(APIBaseTest):
@parameterized.expand(
diff --git a/products/alerts/backend/evaluation/comparator.py b/products/alerts/backend/evaluation/comparator.py
index 08b5bdb3bd01..0b48227e7712 100644
--- a/products/alerts/backend/evaluation/comparator.py
+++ b/products/alerts/backend/evaluation/comparator.py
@@ -11,6 +11,10 @@ from posthog.tasks.alerts.utils import AlertEvaluationResult
from products.alerts.backend.evaluation.contract import ExtractionResult
+# Aggregated (any-row) breach lists are capped so a wide violation doesn't flood the notification.
+# The persisted structured detail uses the same cap.
+MAX_BREACH_MESSAGES = 5
+
def _breach_messages(
bounds: InsightsThresholdBounds,
@@ -20,6 +24,7 @@ def _breach_messages(
*,
subject: str,
framed: bool,
+ include_series: bool = False,
interval_type: IntervalType | None = None,
series: str | None = None,
is_current_interval: bool = False,
@@ -38,12 +43,14 @@ def _breach_messages(
raise ValueError(f"Unsupported alert condition type: {condition_type}")
# Framed (time-series trends): "(label) for current/previous interval". Unframed (e.g. SQL
- # insights): just the subject, since there is no series label or interval to reference.
- context = (
- f" ({series}) for {'current' if is_current_interval else 'previous'} {interval_type or 'interval'}"
- if framed
- else ""
- )
+ # insights): just the subject — plus the series label when several series are in play
+ # (any-row SQL alerts), since the reader needs to know which row breached.
+ if framed:
+ context = f" ({series}) for {'current' if is_current_interval else 'previous'} {interval_type or 'interval'}"
+ elif include_series and series is not None:
+ context = f" ({series})"
+ else:
+ context = ""
if bounds.lower is not None and calculated_value < bounds.lower:
lower_value = f"{bounds.lower:.2%}" if is_percentage else bounds.lower
@@ -99,6 +106,9 @@ def evaluate_threshold(
return AlertEvaluationResult(value=0, breaches=[])
calculated: float | None = None
+ all_breaches: list[str] = []
+ breaching_rows: list[dict] = []
+ first_breach_value: float | None = None
for s in result.series:
anchor = s.points[s.current_index].value
if anchor is None:
@@ -119,12 +129,35 @@ def evaluate_threshold(
condition.type,
subject=result.subject,
framed=result.framed,
+ include_series=result.is_breakdown,
interval_type=result.interval_type,
series=s.label,
is_current_interval=s.is_current_interval,
)
if breaches:
- return AlertEvaluationResult(value=calculated, breaches=breaches)
+ if not result.aggregate_breaches:
+ return AlertEvaluationResult(value=calculated, breaches=breaches)
+ if first_breach_value is None:
+ # Representative value = the first breaching row in result order; the full list
+ # of breaching rows is carried by ``breaches`` and ``triggered_metadata``.
+ first_breach_value = calculated
+ all_breaches.extend(breaches)
+ breaching_rows.append({"label": s.label, "value": calculated})
+
+ if all_breaches:
+ capped = all_breaches[:MAX_BREACH_MESSAGES]
+ if len(all_breaches) > MAX_BREACH_MESSAGES:
+ capped.append(f"...and {len(all_breaches) - MAX_BREACH_MESSAGES} more rows breach")
+ # Persist which rows breached on the check record — notifications are transient, and the
+ # row labels have no other durable source of truth.
+ return AlertEvaluationResult(
+ value=first_breach_value,
+ breaches=capped,
+ triggered_metadata={
+ "breaching_rows": breaching_rows[:MAX_BREACH_MESSAGES],
+ "breaching_row_count": len(breaching_rows),
+ },
+ )
# No breach: an empty query result reports 0 regardless of breakdown (the metric is genuinely
# zero — matching the original _is_empty_query_result); otherwise a non-breakdown query reports
diff --git a/products/alerts/backend/evaluation/contract.py b/products/alerts/backend/evaluation/contract.py
index 7862b4e192ad..4ca264987558 100644
--- a/products/alerts/backend/evaluation/contract.py
+++ b/products/alerts/backend/evaluation/contract.py
@@ -35,11 +35,25 @@ class ExtractionResult:
interval_type: IntervalType | None = None # breach-message interval framing (time-series trends only)
subject: str = "The insight value" # breach-message subject
framed: bool = True # include the "(label) for current/previous interval" framing
- # Detector path only: the query returned zero rows, so the metric is genuinely 0. An empty
- # ``series`` with this False instead means rows existed but none were long enough to score —
+ # Detector-path-only: True means the query returned zero rows, so the metric is genuinely 0. An
+ # empty ``series`` with this False instead means rows existed but none were long enough to score —
# the detector reports that as an uncomputed value (None). Threshold extractors never set this
# (they emit a zero sentinel series) and the comparator ignores it.
empty_query_result: bool = False
+ # When True, every breaching series is reported (capped) instead of stopping at the first —
+ # any-row SQL alerts use this so the notification names all violating rows. Trends breakdowns
+ # keep first-breach-only for parity with their historical messages.
+ aggregate_breaches: bool = False
+
+
+def zero_sentinel_series() -> ComparableSeries:
+ """The shared empty-result sentinel: two zero points so relative conditions compute
+ 0 - 0 = 0 rather than skipping for lack of a previous point; absolute reads 0 at the anchor."""
+ return ComparableSeries(
+ label="empty result",
+ points=[SeriesPoint(date=None, value=0.0), SeriesPoint(date=None, value=0.0)],
+ current_index=1,
+ )
class AlertExtractionError(Exception):
diff --git a/products/alerts/backend/evaluation/dispatcher.py b/products/alerts/backend/evaluation/dispatcher.py
index 0405f69933bd..19e6c14671a3 100644
--- a/products/alerts/backend/evaluation/dispatcher.py
+++ b/products/alerts/backend/evaluation/dispatcher.py
@@ -7,6 +7,7 @@ from posthog.utils import get_from_dict_or_attr
from products.alerts.backend.evaluation.comparator import evaluate_threshold
from products.alerts.backend.evaluation.contract import Extractor
from products.alerts.backend.evaluation.detector import TrendsDetectorExtractor, evaluate_with_detector
+from products.alerts.backend.evaluation.hogql import HogQLExtractor
from products.alerts.backend.evaluation.trends import TrendsExtractor
from products.alerts.backend.models.alert import AlertConfiguration
from products.product_analytics.backend.models.insight import Insight
@@ -14,6 +15,7 @@ from products.product_analytics.backend.models.insight import Insight
# Each insight kind that supports threshold alerts maps to one extractor. The comparator is shared.
EXTRACTORS: dict[NodeKind, Extractor] = {
NodeKind.TRENDS_QUERY: TrendsExtractor(),
+ NodeKind.HOG_QL_QUERY: HogQLExtractor(),
}
# The anomaly-detector path mirrors EXTRACTORS: one detector extractor per kind, scored by the shared
diff --git a/products/alerts/backend/evaluation/hogql.py b/products/alerts/backend/evaluation/hogql.py
new file mode 100644
index 000000000000..e9b65f0c157a
--- /dev/null
+++ b/products/alerts/backend/evaluation/hogql.py
@@ -0,0 +1,267 @@
+import math
+from decimal import Decimal
+from typing import Any
+
+from posthog.schema import AlertCondition, AlertConditionType, HogQLAlertConfig, HogQLAlertEvaluation
+
+from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS
+
+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,
+ zero_sentinel_series,
+)
+from products.alerts.backend.models.alert import AlertConfiguration
+from products.product_analytics.backend.models.insight import Insight
+
+_HOGQL_SUBJECT = "The SQL insight value"
+# Any-row alerts fail loud past this many rows: silently truncating could skip the breaching row
+# (a false negative), which is worse than asking the user to add a LIMIT or aggregate the query.
+# Deliberately conservative to start — easy to raise if users ask for more. Mirrored in the
+# frontend preview as ``HOGQL_ANY_ROW_MAX_ROWS`` (frontend/src/lib/components/Alerts/alertFormLogic.ts);
+# keep the two in sync.
+ANY_ROW_MAX_ROWS = 50
+# last_row reads the tail, so a result truncated at HogQL's hard cap can't be trusted (the real
+# last row may have been dropped). Fail loud rather than alert on a truncated tail. first_row reads
+# the head, which truncation never touches, so it has no such limit — use it (with a DESC ORDER BY)
+# for queries that would otherwise return too many rows.
+LAST_ROW_MAX_ROWS = MAX_SELECT_RETURNED_ROWS
+
+
+class HogQLExtractor:
+ """Normalize a HogQL/SQL-backed insight into ``ComparableSeries``.
+
+ The config picks which result column to evaluate (defaulting to the single numeric column)
+ and how to read the rows:
+ - ``last_row``: the query is ordered oldest->newest; the last row is the current value.
+ - ``first_row``: the query is ordered newest->oldest; the first row is the current value.
+ The head is unaffected by result truncation and pairs with a user ``LIMIT``, so this is
+ the mode for queries that would otherwise return very many rows.
+ - ``any_row``: every row is checked and fires if any value breaches, labeling each row.
+ The shared comparator interprets the resulting series either way.
+
+ PREVIEW MIRROR CONTRACT: the configure-time preview re-implements this extractor's decision
+ rules in TypeScript (``deriveHogQLAlertPreview`` in
+ frontend/src/lib/components/Alerts/alertFormLogic.ts) so the modal can preview instantly from
+ the already-loaded result. The mirror is advisory only — this extractor is the sole authority
+ at evaluation time — but if you change any of these rules, update the mirror to match:
+ 1. value-column resolution: explicit ``column`` -> single column -> single numeric column
+ 2. numeric classification: most recent non-None cell decides; bools are not numeric
+ 3. ``None`` cells evaluate as 0
+ 4. label-column resolution: explicit -> first non-evaluated column -> row number
+ 5. empty result evaluates as 0 (zero sentinel)
+ 6. any-row cap: ``ANY_ROW_MAX_ROWS`` (mirrored as ``HOGQL_ANY_ROW_MAX_ROWS``)
+ 7. anchor row: ``last_row`` reads the tail, ``first_row`` the head; both yield (previous, current)
+ """
+
+ def extract(self, alert: AlertConfiguration, insight: Insight, query: Any) -> ExtractionResult:
+ # ``query`` is unused (Protocol signature): the extractor recomputes via the insight.
+ condition = AlertCondition.model_validate(alert.condition)
+ config = HogQLAlertConfig.model_validate(alert.config or {"type": "HogQLAlertConfig", "evaluation": "last_row"})
+ evaluation = config.evaluation
+
+ calculation_result = calculate_for_query_based_insight(
+ insight,
+ team=alert.team,
+ execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
+ user=None,
+ analytics_props={"source": EventSource.ALERT},
+ )
+ rows = calculation_result.result
+ # ``None`` (vs an empty list) means the query layer swallowed an error — raise to avoid a
+ # misfire, matching the trends extractor's handling of a None result.
+ if rows is None:
+ raise RuntimeError(f"No results found for insight with alert id = {alert.id}")
+ if not isinstance(rows, list):
+ raise AlertExtractionError(f"SQL alert query returned an unexpected result shape ({type(rows).__name__}).")
+ if len(rows) == 0:
+ # No rows means the metric is genuinely 0 this check (matching trends), so a lower
+ # bound can still breach.
+ return ExtractionResult(
+ series=[zero_sentinel_series()],
+ is_breakdown=False,
+ subject=_HOGQL_SUBJECT,
+ framed=False,
+ empty_query_result=True,
+ )
+
+ # Row caps are checked before column resolution so an oversized result gets the clearer
+ # "too many rows" error rather than a column-resolution one. last_row reads the tail, which
+ # a truncated result destroys, so fail loud at the hard cap; first_row reads the head and is
+ # unaffected, so it has no cap.
+ if evaluation == HogQLAlertEvaluation.ANY_ROW and len(rows) > ANY_ROW_MAX_ROWS:
+ raise AlertExtractionError(
+ f"Any-row SQL alerts evaluate at most {ANY_ROW_MAX_ROWS} rows, but the query returned "
+ f"{len(rows)} — add a LIMIT or aggregate the query."
+ )
+ if evaluation == HogQLAlertEvaluation.LAST_ROW and len(rows) >= LAST_ROW_MAX_ROWS:
+ raise AlertExtractionError(
+ f"Last-row SQL alerts can't trust a result of {len(rows)}+ rows — it may be truncated, so "
+ "the last row might not be the real one. Add ORDER BY ... LIMIT, aggregate, or use first-row "
+ "evaluation with a newest-first ordering."
+ )
+
+ columns = calculation_result.columns if isinstance(calculation_result.columns, list) else None
+ column_names = [str(c) for c in columns] if columns else None
+ value_index = _resolve_value_column_index(config.column, column_names, rows)
+
+ if evaluation == HogQLAlertEvaluation.ANY_ROW:
+ # Rows are entities (e.g. one per country), not a time axis — relative change between
+ # unrelated rows is meaningless. validate_alert_config enforces this at configuration
+ # time; this is the evaluation-time backstop.
+ if condition.type != AlertConditionType.ABSOLUTE_VALUE:
+ raise AlertExtractionError("Any-row SQL alerts only support absolute value conditions.")
+ label_index = _resolve_label_column_index(config.label_column, column_names, value_index, rows)
+ series = []
+ for i, row in enumerate(rows):
+ value = _numeric_cell(row, value_index, position=f"row {i + 1}")
+ series.append(
+ ComparableSeries(
+ label=_label_for_row(row, i, label_index),
+ points=[SeriesPoint(date=None, value=value)],
+ current_index=0,
+ )
+ )
+ return ExtractionResult(
+ series=series, is_breakdown=True, subject=_HOGQL_SUBJECT, framed=False, aggregate_breaches=True
+ )
+
+ # last_row / first_row: read the (previous, current) pair from the tail or head respectively.
+ values = _anchor_values(rows, value_index, from_head=evaluation == HogQLAlertEvaluation.FIRST_ROW)
+ is_relative = condition.type in (AlertConditionType.RELATIVE_INCREASE, AlertConditionType.RELATIVE_DECREASE)
+ if is_relative and len(values) < 2:
+ raise AlertExtractionError("Relative alerts on SQL insights need at least two rows (current and previous).")
+
+ points = [SeriesPoint(date=None, value=v) for v in values]
+ series_label = column_names[value_index] if column_names and value_index < len(column_names) else "result"
+ single = ComparableSeries(label=series_label, points=points, current_index=len(points) - 1)
+ return ExtractionResult(series=[single], is_breakdown=False, subject=_HOGQL_SUBJECT, framed=False)
+
+
+def _resolve_value_column_index(configured: str | None, column_names: list[str] | None, rows: list) -> int:
+ """Pick the result column the alert evaluates.
+
+ An explicit column name wins; otherwise a single-column result is used as-is, and a wider
+ result falls back to the single numeric column — ambiguity (0 or 2+ numeric columns) is a
+ configuration error rather than a guess.
+ """
+ if configured is not None:
+ if not column_names:
+ raise AlertExtractionError(
+ f"SQL alert is configured to evaluate column '{configured}' but the result has no column metadata."
+ )
+ if configured not in column_names:
+ raise AlertExtractionError(
+ f"SQL alert column '{configured}' is not in the result columns ({', '.join(column_names)})."
+ )
+ return column_names.index(configured)
+
+ width = _row_width(rows)
+ if width == 1:
+ return 0
+
+ numeric_indexes = [i for i in range(width) if _column_is_numeric(rows, i)]
+ if len(numeric_indexes) == 1:
+ return numeric_indexes[0]
+ described = f" ({', '.join(column_names)})" if column_names else ""
+ raise AlertExtractionError(
+ f"SQL alert query returns {width} columns{described} and "
+ f"{'none' if not numeric_indexes else 'more than one'} of them is numeric — "
+ "pick the column to evaluate in the alert settings."
+ )
+
+
+def _resolve_label_column_index(
+ configured: str | None, column_names: list[str] | None, value_index: int, rows: list
+) -> int | None:
+ if configured is not None:
+ if not column_names or configured not in column_names:
+ described = f" ({', '.join(column_names)})" if column_names else ""
+ raise AlertExtractionError(
+ f"SQL alert label column '{configured}' is not in the result columns{described}."
+ )
+ return column_names.index(configured)
+ # Default: the first column that isn't being evaluated (e.g. the GROUP BY key).
+ width = _row_width(rows)
+ for i in range(width):
+ if i != value_index:
+ return i
+ return None
+
+
+def _label_for_row(row: Any, index: int, label_index: int | None) -> str:
+ if label_index is not None and isinstance(row, list | tuple) and label_index < len(row):
+ cell = row[label_index]
+ if cell is not None:
+ return str(cell)
+ return f"row {index + 1}"
+
+
+def _row_width(rows: list) -> int:
+ last = rows[-1]
+ if not isinstance(last, list | tuple):
+ raise AlertExtractionError(
+ f"SQL alert query must return rows as lists/tuples (got {type(last).__name__} for the last row)."
+ )
+ return len(last)
+
+
+def _column_is_numeric(rows: list, index: int) -> bool:
+ """Classify a column by its most recent non-None value (all-None columns don't count)."""
+ for row in reversed(rows):
+ if not isinstance(row, list | tuple) or index >= len(row):
+ return False
+ cell = row[index]
+ if cell is None:
+ continue
+ return not isinstance(cell, bool) and isinstance(cell, int | float | Decimal)
+ return False
+
+
+def _anchor_values(rows: list, value_index: int, *, from_head: bool) -> list[float]:
+ """Extract the (previous, current) values for last_row/first_row, current last.
+
+ Only the head or tail is inspected — these modes never read past the second row in from
+ the anchor end, so validating the rest would waste work on data we won't use. ``last_row``
+ takes the tail ``[..previous, current]``; ``first_row`` takes the head ``[current, previous..]``
+ (newest first) and reverses it to the same ``[..previous, current]`` shape, so the caller can
+ treat the last element as the anchor either way.
+ """
+ if from_head:
+ head = rows[:2]
+ positions = ["first row", "second row"][: len(head)]
+ cells = [_numeric_cell(row, value_index, position=position) for position, row in zip(positions, head)]
+ return list(reversed(cells))
+ tail = rows[-2:]
+ positions = ["second-to-last row", "last row"] if len(tail) == 2 else ["last row"]
+ return [_numeric_cell(row, value_index, position=position) for position, row in zip(positions, tail)]
+
+
+def _numeric_cell(row: Any, index: int, *, position: str) -> float:
+ """Coerce one result cell to a float. ``None`` buckets become 0 to match trends handling."""
+ if not isinstance(row, list | tuple):
+ raise AlertExtractionError(
+ f"SQL alert query must return rows as lists/tuples (got {type(row).__name__} for the {position})."
+ )
+ if index >= len(row):
+ raise AlertExtractionError(f"SQL alert query returned a {position} with too few columns.")
+ raw = row[index]
+ if raw is None:
+ return 0.0
+ # ClickHouse Decimal columns surface as decimal.Decimal; accept them alongside int/float.
+ if isinstance(raw, bool) or not isinstance(raw, int | float | Decimal):
+ raise AlertExtractionError(
+ f"SQL alert query must return a numeric value to evaluate (got {type(raw).__name__} for the {position})."
+ )
+ value = float(raw)
+ if not math.isfinite(value):
+ raise AlertExtractionError(
+ f"SQL alert query must return a finite numeric value (got {raw} for the {position})."
+ )
+ return value
diff --git a/products/alerts/backend/evaluation/test/test_hogql_extractor.py b/products/alerts/backend/evaluation/test/test_hogql_extractor.py
new file mode 100644
index 000000000000..193b5d232537
--- /dev/null
+++ b/products/alerts/backend/evaluation/test/test_hogql_extractor.py
@@ -0,0 +1,320 @@
+from decimal import Decimal
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import (
+ AlertCondition,
+ AlertConditionType,
+ InsightsThresholdBounds,
+ InsightThreshold,
+ InsightThresholdType,
+)
+
+from products.alerts.backend.evaluation.comparator import MAX_BREACH_MESSAGES, evaluate_threshold
+from products.alerts.backend.evaluation.contract import AlertExtractionError
+from products.alerts.backend.evaluation.hogql import (
+ ANY_ROW_MAX_ROWS,
+ LAST_ROW_MAX_ROWS,
+ HogQLExtractor,
+ _resolve_value_column_index,
+)
+
+CALC_PATH = "products.alerts.backend.evaluation.hogql.calculate_for_query_based_insight"
+
+ABSOLUTE = AlertCondition(type=AlertConditionType.ABSOLUTE_VALUE)
+
+
+def _alert(condition_type=AlertConditionType.ABSOLUTE_VALUE, config: dict | None = None):
+ alert = MagicMock()
+ alert.condition = {"type": condition_type}
+ # ``evaluation`` is required on the schema; default it to last_row unless a case overrides it,
+ # so individual tests only specify it when the mode is what's under test.
+ alert.config = {"type": "HogQLAlertConfig", "evaluation": "last_row", **(config or {})}
+ return alert
+
+
+def _threshold(type_=InsightThresholdType.ABSOLUTE, lower=None, upper=None):
+ return InsightThreshold(type=type_, bounds=InsightsThresholdBounds(lower=lower, upper=upper))
+
+
+def _extract(rows, *, columns=None, condition_type=AlertConditionType.ABSOLUTE_VALUE, config: dict | None = None):
+ with patch(CALC_PATH) as calc:
+ calc.return_value = MagicMock(result=rows, columns=columns)
+ return HogQLExtractor().extract(_alert(condition_type, config), MagicMock(), MagicMock())
+
+
+ "rows,exc,match",
+ [
+ # A None result means the query layer swallowed an error — raise (not AlertExtractionError)
+ # to avoid a misfire, matching the trends extractor.
+ (None, RuntimeError, "No results found"),
+ ({"not": "a list"}, AlertExtractionError, "unexpected result shape"),
+ ([{"a": 1}], AlertExtractionError, "rows as lists/tuples"),
+ ],
+)
+def test_bad_result_shape_raises(rows, exc, match):
+ with pytest.raises(exc, match=match):
+ _extract(rows)
+
+
+ "bad,match",
+ [
+ ("text", "numeric value"),
+ (True, "numeric value"),
+ (float("nan"), "finite numeric value"),
+ (float("inf"), "finite numeric value"),
+ (float("-inf"), "finite numeric value"),
+ ],
+)
+def test_non_numeric_or_non_finite_value_raises(bad, match):
+ with pytest.raises(AlertExtractionError, match=match):
+ _extract([[bad]])
+
+
+def test_none_bucket_becomes_zero():
+ result = _extract([[None]])
+ assert [p.value for p in result.series[0].points] == [0.0]
+
+
+def test_accepts_decimal_columns():
+ # ClickHouse Decimal columns surface as decimal.Decimal — they are valid numeric values.
+ result = _extract([[Decimal("41.5")], [Decimal("42.0")]])
+ assert [p.value for p in result.series[0].points] == [41.5, 42.0]
+
+
+ "condition_type",
+ [AlertConditionType.ABSOLUTE_VALUE, AlertConditionType.RELATIVE_INCREASE],
+)
+def test_empty_result_evaluates_as_zero_and_can_breach_lower_bound(condition_type):
+ result = _extract([], condition_type=condition_type)
+ assert result.empty_query_result is True
+ breach = evaluate_threshold(result, AlertCondition(type=condition_type), _threshold(lower=5))
+ assert breach.value == 0.0
+ assert breach.breaches is not None and len(breach.breaches) == 1
+ no_breach = evaluate_threshold(result, AlertCondition(type=condition_type), _threshold(lower=-5))
+ assert no_breach.value == 0.0
+ assert no_breach.breaches == []
+
+
+def test_evaluation_uses_saved_variable_values_not_session_overrides():
+ # The alert path passes no variables_override, so a variable-using SQL query evaluates with
+ # the values saved on the query (or each variable's default) — session-level UI overrides
+ # never reach evaluation. This is why the configure-time preview (which reads the user's
+ # possibly-overridden cached result) can disagree with what the alert actually evaluates.
+ with patch(CALC_PATH) as calc:
+ calc.return_value = MagicMock(result=[[5]], columns=["count"])
+ HogQLExtractor().extract(_alert(), MagicMock(), MagicMock())
+ assert "variables_override" not in calc.call_args.kwargs
+
+
+def test_single_column_needs_no_metadata():
+ result = _extract([[10], [42]])
+ assert [p.value for p in result.series[0].points] == [10.0, 42.0]
+ assert result.series[0].label == "result"
+
+
+def test_single_numeric_column_heuristic_skips_date_column():
+ # The common charted shape: SELECT day, value ORDER BY day — evaluate the numeric column.
+ rows = [["2024-01-01", 10], ["2024-01-02", 42]]
+ result = _extract(rows, columns=["day", "value"])
+ assert [p.value for p in result.series[0].points] == [10.0, 42.0]
+ assert result.series[0].label == "value"
+
+
+ "rows",
+ [
+ [[1, 2]], # two numeric columns — ambiguous
+ [["x", "y"]], # no numeric column
+ ],
+)
+def test_ambiguous_columns_require_explicit_pick(rows):
+ with pytest.raises(AlertExtractionError, match="pick the column"):
+ _extract(rows, columns=["a", "b"])
+
+
+def test_explicit_column_pick():
+ rows = [["2024-01-01", 1, 10], ["2024-01-02", 2, 42]]
+ result = _extract(rows, columns=["day", "errors", "total"], config={"type": "HogQLAlertConfig", "column": "total"})
+ assert [p.value for p in result.series[0].points] == [10.0, 42.0]
+ assert result.series[0].label == "total"
+
+
+def test_explicit_column_not_in_result_raises():
+ with pytest.raises(AlertExtractionError, match="not in the result columns"):
+ _extract([[1]], columns=["count"], config={"type": "HogQLAlertConfig", "column": "missing"})
+
+
+def test_explicit_column_without_metadata_raises():
+ with pytest.raises(AlertExtractionError, match="no column metadata"):
+ _extract([[1]], config={"type": "HogQLAlertConfig", "column": "count"})
+
+
+def test_heuristic_classifies_by_most_recent_non_none_value():
+ # A column whose latest value is None is classified by the most recent non-None one.
+ assert _resolve_value_column_index(None, ["a", "b"], [["x", 1], ["y", None]]) == 1
+
+
+def test_all_none_column_is_not_numeric():
+ # An all-None column can't be classified, so the other (numeric) column wins.
+ assert _resolve_value_column_index(None, ["a", "b"], [[None, 1], [None, 2]]) == 1
+
+
+def test_builds_unframed_single_series():
+ result = _extract([[10], [42]])
+ assert result.framed is False and result.is_breakdown is False
+ assert result.subject == "The SQL insight value"
+ assert result.series[0].current_index == 1 # last row is the anchor
+
+
+def test_absolute_alert_breaches_on_last_row():
+ result = _extract([[10], [200]])
+ evaluation = evaluate_threshold(result, ABSOLUTE, _threshold(upper=100))
+ assert evaluation.value == 200.0
+ assert evaluation.breaches is not None
+ assert evaluation.breaches[0] == "The SQL insight value (200.0) is more than upper threshold (100.0)"
+
+
+def test_relative_alert_needs_two_rows():
+ with pytest.raises(AlertExtractionError, match="at least two rows"):
+ _extract([[5]], condition_type=AlertConditionType.RELATIVE_INCREASE)
+
+
+def test_last_row_fails_loud_when_result_hits_the_cap():
+ # A result at the hard cap may be truncated, so the "last row" can't be trusted — fail loud.
+ rows = [[float(i)] for i in range(LAST_ROW_MAX_ROWS)]
+ with pytest.raises(AlertExtractionError, match="may be truncated"):
+ _extract(rows)
+
+
+def test_first_row_evaluates_the_head_newest_first():
+ # first_row reads the head: row 0 is the current (newest) value.
+ result = _extract([[200], [10]], config={"evaluation": "first_row"})
+ assert result.series[0].current_index == len(result.series[0].points) - 1
+ evaluation = evaluate_threshold(result, ABSOLUTE, _threshold(upper=100))
+ assert evaluation.value == 200.0 # the head row, not the tail
+
+
+def test_first_row_relative_compares_the_first_two_rows():
+ # Newest-first: row 0 is current, row 1 is previous → 200 vs 100 = +100%.
+ result = _extract(
+ [[200], [100]], condition_type=AlertConditionType.RELATIVE_INCREASE, config={"evaluation": "first_row"}
+ )
+ evaluation = evaluate_threshold(
+ result, AlertCondition(type=AlertConditionType.RELATIVE_INCREASE), _threshold(upper=50)
+ )
+ assert evaluation.value == 100.0 # (200 - 100) / 100 = +100%
+
+
+def test_first_row_has_no_cap():
+ # The head is unaffected by truncation, so first_row accepts a result past the last_row cap.
+ rows = [[float(i)] for i in range(LAST_ROW_MAX_ROWS)]
+ result = _extract(rows, config={"evaluation": "first_row"})
+ assert result.series[0].points[result.series[0].current_index].value == 0.0 # row 0
+
+
+def test_any_row_breaches_on_any_value_with_row_label():
+ rows = [["US", 0.1], ["DE", 0.4], ["FR", 0.2]]
+ result = _extract(
+ rows, columns=["country", "error_rate"], config={"type": "HogQLAlertConfig", "evaluation": "any_row"}
+ )
+ assert result.is_breakdown is True
+ assert [s.label for s in result.series] == ["US", "DE", "FR"]
+ evaluation = evaluate_threshold(result, ABSOLUTE, _threshold(upper=0.25))
+ assert evaluation.value == 0.4
+ assert evaluation.breaches is not None
+ assert evaluation.breaches[0] == "The SQL insight value (DE) (0.4) is more than upper threshold (0.25)"
+
+
+def test_any_row_no_breach_reports_no_value():
+ rows = [["US", 0.1], ["DE", 0.2]]
+ result = _extract(
+ rows, columns=["country", "error_rate"], config={"type": "HogQLAlertConfig", "evaluation": "any_row"}
+ )
+ evaluation = evaluate_threshold(result, ABSOLUTE, _threshold(upper=0.5))
+ assert evaluation.breaches == []
+ assert evaluation.value is None # several rows — no single representative value
+
+
+def test_any_row_explicit_label_column():
+ rows = [["US", "prod", 5], ["DE", "dev", 50]]
+ result = _extract(
+ rows,
+ columns=["country", "env", "errors"],
+ config={"type": "HogQLAlertConfig", "evaluation": "any_row", "column": "errors", "label_column": "env"},
+ )
+ assert [s.label for s in result.series] == ["prod", "dev"]
+
+
+def test_any_row_label_falls_back_to_row_number():
+ result = _extract([[5], [50]], config={"type": "HogQLAlertConfig", "evaluation": "any_row"})
+ assert [s.label for s in result.series] == ["row 1", "row 2"]
+
+
+def test_any_row_missing_label_column_raises():
+ with pytest.raises(AlertExtractionError, match="label column"):
+ _extract(
+ [[1]],
+ columns=["count"],
+ config={"type": "HogQLAlertConfig", "evaluation": "any_row", "label_column": "missing"},
+ )
+
+
+def test_any_row_reports_every_breaching_row():
+ rows = [["US", 0.1], ["DE", 0.4], ["FR", 0.3], ["BR", 0.5]]
+ result = _extract(
+ rows, columns=["country", "error_rate"], config={"type": "HogQLAlertConfig", "evaluation": "any_row"}
+ )
+ evaluation = evaluate_threshold(result, ABSOLUTE, _threshold(upper=0.25))
+ assert evaluation.value == 0.4 # the first breaching value
+ assert evaluation.breaches == [
+ "The SQL insight value (DE) (0.4) is more than upper threshold (0.25)",
+ "The SQL insight value (FR) (0.3) is more than upper threshold (0.25)",
+ "The SQL insight value (BR) (0.5) is more than upper threshold (0.25)",
+ ]
+ # Which rows breached is persisted on the check record — notifications are transient.
+ assert evaluation.triggered_metadata == {
+ "breaching_rows": [
+ {"label": "DE", "value": 0.4},
+ {"label": "FR", "value": 0.3},
+ {"label": "BR", "value": 0.5},
+ ],
+ "breaching_row_count": 3,
+ }
+
+
+def test_any_row_breach_list_is_capped():
+ overflow = 3
+ rows = [[f"r{i}", 10.0] for i in range(MAX_BREACH_MESSAGES + overflow)]
+ result = _extract(rows, columns=["name", "value"], config={"type": "HogQLAlertConfig", "evaluation": "any_row"})
+ evaluation = evaluate_threshold(result, ABSOLUTE, _threshold(upper=5))
+ assert (
+ evaluation.breaches is not None and len(evaluation.breaches) == MAX_BREACH_MESSAGES + 1
+ ) # rows + overflow note
+ assert evaluation.breaches[-1] == f"...and {overflow} more rows breach"
+
+
+def test_any_row_accepts_exactly_the_row_cap():
+ rows = [[float(i)] for i in range(ANY_ROW_MAX_ROWS)]
+ result = _extract(rows, config={"type": "HogQLAlertConfig", "evaluation": "any_row"})
+ assert len(result.series) == ANY_ROW_MAX_ROWS
+
+
+def test_any_row_rejects_too_many_rows():
+ rows = [[float(i)] for i in range(ANY_ROW_MAX_ROWS + 1)]
+ with pytest.raises(AlertExtractionError, match=f"at most {ANY_ROW_MAX_ROWS} rows"):
+ _extract(rows, config={"type": "HogQLAlertConfig", "evaluation": "any_row"})
+
+
+def test_any_row_rejects_relative_conditions():
+ with pytest.raises(AlertExtractionError, match="absolute value conditions"):
+ _extract(
+ [["US", 1]],
+ columns=["country", "count"],
+ condition_type=AlertConditionType.RELATIVE_INCREASE,
+ config={"type": "HogQLAlertConfig", "evaluation": "any_row"},
+ )
diff --git a/products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.py b/products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.py
new file mode 100644
index 000000000000..81b95290d15f
--- /dev/null
+++ b/products/alerts/backend/evaluation/test/test_hogql_extractor_clickhouse.py
@@ -0,0 +1,63 @@
+from freezegun import freeze_time
+from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events
+
+from products.alerts.backend.evaluation.hogql import HogQLExtractor
+from products.alerts.backend.models.alert import AlertConfiguration
+from products.product_analytics.backend.models.insight import Insight
+
+
+class TestHogQLExtractorFiltersPlaceholder(APIBaseTest, ClickhouseDestroyTablesMixin):
+ """Alert evaluation runs without any dashboard context, so a query using the ``{filters}``
+ placeholder must resolve from the filters saved on the query itself (or to a no-op when
+ none are saved) — never error. Pins that an alerted SQL insight using ``{filters}`` keeps
+ evaluating, and which rows it sees."""
+
+ def _evaluate(self, hogql_source: dict) -> float | None:
+ insight = Insight.objects.create(
+ team=self.team,
+ query={"kind": "DataVisualizationNode", "source": hogql_source},
+ )
+ alert = AlertConfiguration.objects.create(
+ team=self.team,
+ insight=insight,
+ name="filters placeholder alert",
+ condition={"type": "absolute_value"},
+ config={"type": "HogQLAlertConfig", "evaluation": "last_row"},
+ calculation_interval="daily",
+ )
+ result = HogQLExtractor().extract(alert, insight, hogql_source)
+ assert len(result.series) == 1
+ return result.series[0].points[result.series[0].current_index].value
+
+ def test_filters_placeholder_with_and_without_saved_filters(self) -> None:
+ with freeze_time("2026-06-12T12:00:00Z"):
+ for i in range(3):
+ _create_event(
+ team=self.team, event="signup", distinct_id=f"recent_{i}", timestamp="2026-06-11T12:00:00Z"
+ )
+ for i in range(2):
+ _create_event(team=self.team, event="signup", distinct_id=f"old_{i}", timestamp="2026-06-01T12:00:00Z")
+ flush_persons_and_events()
+
+ # Saved filters resolve the placeholder: only the 3 events within the date range count.
+ assert (
+ self._evaluate(
+ {
+ "kind": "HogQLQuery",
+ "query": "SELECT count() FROM events WHERE {filters}",
+ "filters": {"dateRange": {"date_from": "-7d"}},
+ }
+ )
+ == 3.0
+ )
+
+ # No saved filters: the placeholder resolves to a no-op and all rows count.
+ assert (
+ self._evaluate(
+ {
+ "kind": "HogQLQuery",
+ "query": "SELECT count() FROM events WHERE {filters}",
+ }
+ )
+ == 5.0
+ )
diff --git a/products/alerts/backend/evaluation/trends.py b/products/alerts/backend/evaluation/trends.py
index ebdc20805a72..44750f6ea484 100644
--- a/products/alerts/backend/evaluation/trends.py
+++ b/products/alerts/backend/evaluation/trends.py
@@ -28,12 +28,11 @@ from products.alerts.backend.evaluation.contract import (
ExtractionResult,
SeriesPoint,
lookback_intervals_for,
+ zero_sentinel_series,
)
from products.alerts.backend.models.alert import AlertConfiguration
from products.product_analytics.backend.models.insight import Insight
-EMPTY_RESULT_LABEL = "empty result"
-
class TrendsExtractor:
"""Execute a trends insight and normalize the result into ``ComparableSeries``.
@@ -146,21 +145,12 @@ class TrendsExtractor:
) -> ExtractionResult | None:
"""A ``None`` result means the query layer swallowed an error — raise to avoid a misfire.
An empty result means no data, treated as a 0 value compared against the threshold (this
- can fire a breach, e.g. a lower-bound alert).
-
- Two zero points (not one) so relative conditions compute 0 - 0 = 0 rather than skipping
- for lack of a previous point; absolute reads the same 0 at the anchor."""
+ can fire a breach, e.g. a lower-bound alert)."""
if calculation_result.result is None:
raise RuntimeError(f"No results found for insight with alert id = {alert.id}")
if not calculation_result.result:
- sentinel = ComparableSeries(
- label=EMPTY_RESULT_LABEL,
- points=[SeriesPoint(date=None, value=0.0), SeriesPoint(date=None, value=0.0)],
- current_index=1,
- is_current_interval=False,
- )
return ExtractionResult(
- series=[sentinel],
+ series=[zero_sentinel_series()],
is_breakdown=has_breakdown,
interval_type=interval_type,
empty_query_result=True,
diff --git a/products/alerts/backend/evaluation/validation.py b/products/alerts/backend/evaluation/validation.py
new file mode 100644
index 000000000000..52407cedec5d
--- /dev/null
+++ b/products/alerts/backend/evaluation/validation.py
@@ -0,0 +1,199 @@
+from collections.abc import Callable
+from dataclasses import dataclass
+
+from pydantic import ValidationError as PydanticValidationError
+
+from posthog.schema import (
+ AlertCalculationInterval,
+ AlertCondition,
+ AlertConditionType,
+ HogQLAlertConfig,
+ HogQLAlertEvaluation,
+ InsightThreshold,
+ InsightThresholdType,
+ NodeKind,
+ TrendsAlertConfig,
+ TrendsQuery,
+)
+
+from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, is_non_time_series_trend
+from posthog.utils import get_from_dict_or_attr
+
+from products.alerts.backend.evaluation.dispatcher import DETECTOR_EXTRACTORS
+
+THRESHOLD_BOUNDS_REQUIRED_MESSAGE = "At least one threshold bound (lower or upper) must be provided."
+
+
+@dataclass(frozen=True)
+class _AlertConfigValidationContext:
+ """Everything a per-config-type validator needs, after the common checks have run."""
+
+ config: dict
+ query: dict
+ query_kind: str | None
+ parsed_condition: AlertCondition
+ threshold_config: dict | None
+ require_threshold_bounds: bool
+ detector_config: dict | None
+
+
+def insight_threshold_has_bounds(threshold_config: dict | None) -> bool:
+ if threshold_config is None:
+ return False
+ try:
+ threshold = InsightThreshold.model_validate(threshold_config)
+ except PydanticValidationError:
+ return False
+ bounds = threshold.bounds
+ if bounds is None:
+ return False
+ return bounds.lower is not None or bounds.upper is not None
+
+
+def validate_threshold_bounds_required(threshold_config: dict | None) -> None:
+ if not insight_threshold_has_bounds(threshold_config):
+ raise ValueError(THRESHOLD_BOUNDS_REQUIRED_MESSAGE)
+
+
+def _validate_condition_threshold_compatibility(
+ parsed_condition: AlertCondition, threshold_config: dict | None
+) -> InsightThreshold | None:
+ """Parse the threshold and enforce condition/threshold compatibility shared by all insight kinds."""
+ if threshold_config is None:
+ return None
+ try:
+ threshold = InsightThreshold.model_validate(threshold_config)
+ except Exception:
+ raise ValueError(f"Alert has invalid threshold configuration: {threshold_config}")
+ if parsed_condition.type == AlertConditionType.ABSOLUTE_VALUE and threshold.type != InsightThresholdType.ABSOLUTE:
+ raise ValueError(
+ "Absolute value alerts require an absolute threshold, but a percentage threshold was configured"
+ )
+ return threshold
+
+
+def _validate_hogql_alert_config(ctx: _AlertConfigValidationContext) -> None:
+ # SQL insights own their time window; there is no series_index or ongoing-interval concept,
+ # so the query kind, evaluation mode, condition/threshold compatibility, and bounds are validated.
+ if ctx.query_kind != NodeKind.HOG_QL_QUERY:
+ raise ValueError(f"SQL alert config requires a HogQLQuery insight, got '{ctx.query_kind}'")
+ try:
+ parsed = HogQLAlertConfig.model_validate(ctx.config)
+ except Exception:
+ raise ValueError(f"Alert has invalid HogQLAlertConfig: {ctx.config}")
+ if parsed.evaluation == HogQLAlertEvaluation.ANY_ROW and ctx.parsed_condition.type != (
+ AlertConditionType.ABSOLUTE_VALUE
+ ):
+ # Rows are entities in any_row mode, not a time axis — relative change is meaningless.
+ raise ValueError("Any-row SQL alerts only support absolute value conditions")
+ _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)
+
+
+def _validate_trends_alert_config(ctx: _AlertConfigValidationContext) -> None:
+ try:
+ parsed_config = TrendsAlertConfig.model_validate(ctx.config)
+ except Exception:
+ raise ValueError(f"Alert has invalid TrendsAlertConfig: {ctx.config}")
+
+ if ctx.query_kind != NodeKind.TRENDS_QUERY:
+ raise ValueError(f"Alert's insight query kind '{ctx.query_kind}' is not supported (only TrendsQuery)")
+
+ try:
+ trends_query = TrendsQuery.model_validate(ctx.query)
+ except Exception as e:
+ raise ValueError(f"Alert's insight has an invalid TrendsQuery: {e}")
+
+ if ctx.parsed_condition.type in (
+ AlertConditionType.RELATIVE_INCREASE,
+ AlertConditionType.RELATIVE_DECREASE,
+ ) and is_non_time_series_trend(trends_query):
+ raise ValueError(
+ f"Relative alert condition '{ctx.parsed_condition.type}' is not compatible with non time series trends"
+ )
+
+ formula_nodes = trends_query.trendsFilter.formulaNodes if trends_query.trendsFilter else None
+ result_count = len(formula_nodes) if formula_nodes else len(trends_query.series)
+ if parsed_config.series_index >= result_count:
+ raise ValueError(f"series_index {parsed_config.series_index} is out of range (query has {result_count} series)")
+
+ threshold = _validate_condition_threshold_compatibility(ctx.parsed_condition, ctx.threshold_config)
+ if (
+ threshold is not None
+ and parsed_config.check_ongoing_interval
+ and ctx.parsed_condition.type
+ in (
+ AlertConditionType.ABSOLUTE_VALUE,
+ AlertConditionType.RELATIVE_INCREASE,
+ )
+ ):
+ if not threshold.bounds or threshold.bounds.upper is None:
+ raise ValueError(
+ f"check_ongoing_interval is only supported for alert condition {ctx.parsed_condition.type} when upper threshold is specified"
+ )
+
+ if ctx.require_threshold_bounds and ctx.detector_config is None:
+ validate_threshold_bounds_required(ctx.threshold_config)
+
+
+# Per-config-type validators, mirroring the extractor registry in dispatcher.py: one entry per
+# config type the threshold path supports. Adding a kind = adding an entry here and an extractor.
+_ALERT_CONFIG_VALIDATORS: dict[str, Callable[[_AlertConfigValidationContext], None]] = {
+ "HogQLAlertConfig": _validate_hogql_alert_config,
+ "TrendsAlertConfig": _validate_trends_alert_config,
+}
+
+
+def validate_alert_config(
+ query: dict,
+ condition: dict | None,
+ config: dict | None,
+ threshold_config: dict | None = None,
+ calculation_interval: str | None = None,
+ detector_config: dict | None = None,
+ require_threshold_bounds: bool = True,
+) -> None:
+ """Validate alert configuration dicts. Raises ValueError on failure.
+
+ Common checks run here; per-config-type rules live in ``_ALERT_CONFIG_VALIDATORS``.
+ """
+ if not calculation_interval or not isinstance(calculation_interval, str):
+ raise ValueError(f"Invalid calculation interval: {calculation_interval}")
+ try:
+ AlertCalculationInterval(calculation_interval)
+ except ValueError:
+ raise ValueError(f"Invalid calculation interval: {calculation_interval}")
+
+ try:
+ parsed_condition = AlertCondition.model_validate(condition)
+ except Exception:
+ raise ValueError(f"Alert has invalid condition: {condition}")
+
+ config_type = config.get("type") if isinstance(config, dict) else None
+
+ kind = get_from_dict_or_attr(query, "kind")
+ if kind in WRAPPER_NODE_KINDS:
+ query = get_from_dict_or_attr(query, "source")
+ kind = get_from_dict_or_attr(query, "kind")
+
+ # The detector path supports only the kinds with a detector extractor — a non-supported detector
+ # alert would raise at evaluation time, so reject it here at configuration time. Reading the
+ # dispatcher's registry directly keeps the config-time and evaluation-time views from drifting.
+ if detector_config is not None and kind not in DETECTOR_EXTRACTORS:
+ raise ValueError("Anomaly detection alerts are only supported for trends insights")
+
+ validator = _ALERT_CONFIG_VALIDATORS.get(config_type) if isinstance(config_type, str) else None
+ if validator is None:
+ raise ValueError(f"Unsupported alert config type: {config}")
+ validator(
+ _AlertConfigValidationContext(
+ config=config if isinstance(config, dict) else {},
+ query=query,
+ query_kind=kind,
+ parsed_condition=parsed_condition,
+ threshold_config=threshold_config,
+ require_threshold_bounds=require_threshold_bounds,
+ detector_config=detector_config,
+ )
+ )
diff --git a/products/alerts/backend/max_tools.py b/products/alerts/backend/max_tools.py
index ea443b01c434..5615659a3fd8 100644
--- a/products/alerts/backend/max_tools.py
+++ b/products/alerts/backend/max_tools.py
@@ -12,6 +12,7 @@ from posthog.schema import (
AlertConditionType,
InsightThresholdType,
InsightVizNode,
+ NodeKind,
QuerySchemaRoot,
)
@@ -21,8 +22,8 @@ from posthog.models.team import Team
from posthog.models.user import User
from posthog.rbac.user_access_control import AccessControlLevel
from posthog.scopes import APIScopeObject
-from posthog.tasks.alerts.utils import THRESHOLD_BOUNDS_REQUIRED_MESSAGE
+from products.alerts.backend.evaluation.validation import THRESHOLD_BOUNDS_REQUIRED_MESSAGE
from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold
from products.product_analytics.backend.models.insight import Insight
@@ -432,7 +433,9 @@ class UpsertAlertTool(MaxTool):
) -> tuple[Insight, bool]:
insight, was_auto_saved = await self._resolve_insight(insight_id)
await self.check_object_access(insight, "viewer", resource="insight", action=action_description)
- if not await sync_to_async(lambda: insight.are_alerts_supported)():
+ # Max's alert tooling only builds trends configs, so it accepts only trends — narrower
+ # than the model's alertable_query_kind (which also allows SQL).
+ if await sync_to_async(lambda: insight.alertable_query_kind)() != NodeKind.TRENDS_QUERY:
raise ValueError("Alerts are only supported for TrendsQuery insights. This insight type is not supported.")
return insight, was_auto_saved
diff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.py
index b80c4b3a8600..ba4bc373bc37 100644
--- a/products/alerts/backend/models/alert.py
+++ b/products/alerts/backend/models/alert.py
@@ -252,7 +252,8 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
has_lower_bound = threshold_bounds.get("lower") is not None if has_threshold else False
has_upper_bound = threshold_bounds.get("upper") is not None if has_threshold else False
- trends_config = self.config if isinstance(self.config, dict) else {}
+ alert_config = self.config if isinstance(self.config, dict) else {}
+ is_hogql_config = alert_config.get("type") == "HogQLAlertConfig"
subscribed_users_count: int | None = None
if self.pk is not None:
@@ -271,8 +272,12 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
"threshold_type": threshold_type,
"has_lower_bound": has_lower_bound,
"has_upper_bound": has_upper_bound,
- "trends_series_index": trends_config.get("series_index"),
- "trends_check_ongoing_interval": trends_config.get("check_ongoing_interval"),
+ "config_type": alert_config.get("type"),
+ "trends_series_index": alert_config.get("series_index"),
+ "trends_check_ongoing_interval": alert_config.get("check_ongoing_interval"),
+ "hogql_evaluation": (alert_config.get("evaluation") or "last_row") if is_hogql_config else None,
+ "hogql_has_explicit_column": bool(alert_config.get("column")) if is_hogql_config else None,
+ "hogql_has_label_column": bool(alert_config.get("label_column")) if is_hogql_config else None,
"subscribed_users_count": subscribed_users_count,
**derive_detector_event_fields(detector_config),
"ensemble_detector_types": ensemble_detector_types,
diff --git a/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx b/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx
index 6fe52c3a37b3..91544277d77c 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx
+++ b/products/alerts/frontend/components/editAlertModal/AlertAdvancedOptionsSection.tsx
@@ -4,6 +4,7 @@ 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 { LemonField } from 'lib/lemon-ui/LemonField'
import { AlertCalculationInterval } from '~/queries/schema/schema-general'
@@ -53,32 +54,34 @@ export function AlertAdvancedOptionsSection({
},
content: (
<div className="space-y-2">
- <Group name={['config']}>
- <div className="flex gap-1">
- <LemonField name="check_ongoing_interval">
- <LemonCheckbox
- checked={
- can_check_ongoing_interval &&
- alertForm?.config.check_ongoing_interval
- }
- 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.'
- }
- />
- </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}
- >
- <IconInfo />
- </Tooltip>
- </div>
- </Group>
+ {supportsOngoingInterval(alertForm?.config) && (
+ <Group name={['config']}>
+ <div className="flex gap-1">
+ <LemonField name="check_ongoing_interval">
+ <LemonCheckbox
+ checked={
+ can_check_ongoing_interval &&
+ alertForm.config.check_ongoing_interval
+ }
+ 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.'
+ }
+ />
+ </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}
+ >
+ <IconInfo />
+ </Tooltip>
+ </div>
+ </Group>
+ )}
<LemonField name="skip_weekend">
<LemonCheckbox
checked={
diff --git a/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx b/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx
new file mode 100644
index 000000000000..fb499338fe1f
--- /dev/null
+++ b/products/alerts/frontend/components/editAlertModal/AlertDefinitionFields.tsx
@@ -0,0 +1,160 @@
+import { Group } from 'kea-forms'
+
+import { IconInfo } from '@posthog/icons'
+import { LemonSelect, Tooltip } from '@posthog/lemon-ui'
+
+import { AlertFormType } from 'lib/components/Alerts/alertFormLogic'
+import { HogQLAlertPreview } from 'lib/components/Alerts/hogqlAlertPreview'
+import { isAnyRowHogQLConfig } from 'lib/components/Alerts/types'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { alphabet } from 'lib/utils/strings'
+
+import { AlertConditionType } from '~/queries/schema/schema-general'
+
+import { HogQLAlertPreviewBanner, HogQLAlertPreviewRowsTable } from './HogQLAlertPreview'
+
+const breakdownDisabledReason = (alertMode: 'detector' | 'threshold'): string =>
+ alertMode === 'detector'
+ ? 'For trends with breakdown, the detector will independently monitor each breakdown value (up to 25) and fire if any is anomalous.'
+ : 'For trends with breakdown, the alert will fire if any of the breakdown values breaches the threshold.'
+
+/** Trends: pick which series (or formula) to monitor. */
+export function TrendsDefinitionFields({
+ alertSeries,
+ formulaNodes,
+ isBreakdownValid,
+ alertMode,
+}: {
+ alertSeries: Array<{ custom_name?: string | null; name?: string | null; event?: string | null }> | null
+ formulaNodes: Array<{ formula: string; custom_name?: string | null }> | undefined
+ isBreakdownValid: boolean
+ alertMode: 'detector' | 'threshold'
+}): JSX.Element {
+ return (
+ <div className="flex gap-3 items-center">
+ <div>When</div>
+ <Group name={['config']}>
+ <LemonField name="series_index" className="flex-auto">
+ <LemonSelect
+ fullWidth
+ data-attr="alertForm-series-index"
+ options={
+ (formulaNodes?.length ?? 0) > 0
+ ? (formulaNodes ?? []).map(({ formula, custom_name }, index) => ({
+ label: `${custom_name ? custom_name : 'Formula'} (${formula})`,
+ value: index,
+ }))
+ : (alertSeries?.map(({ custom_name, name, event }, index) => ({
+ label: isBreakdownValid
+ ? 'any breakdown value'
+ : `${alphabet[index]} - ${custom_name ?? name ?? event}`,
+ value: isBreakdownValid ? 0 : index,
+ })) ?? [])
+ }
+ disabledReason={isBreakdownValid && breakdownDisabledReason(alertMode)}
+ />
+ </LemonField>
+ </Group>
+ </div>
+ )
+}
+
+/** SQL: pick the evaluation mode and (when the result is multi-column) the value/label columns,
+ * plus the live preview of what the alert would evaluate. */
+export function HogQLDefinitionFields({
+ alertForm,
+ hogqlPreview,
+ hogqlColumns,
+ hogqlValueColumnOptions,
+ hogqlLabelColumnOptions,
+ onSetAlertFormValue,
+}: {
+ alertForm: AlertFormType
+ hogqlPreview: HogQLAlertPreview | null
+ hogqlColumns: string[] | null
+ hogqlValueColumnOptions: { label: string; value: string }[]
+ hogqlLabelColumnOptions: { label: string; value: string }[]
+ onSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void
+}): JSX.Element {
+ const hasMultipleColumns = (hogqlColumns?.length ?? 0) > 1
+ const isAnyRow = isAnyRowHogQLConfig(alertForm.config)
+ return (
+ <>
+ <div className="flex gap-3 items-center">
+ <div>When</div>
+ <Group name={['config']}>
+ <LemonField name="evaluation" className="flex-auto">
+ {({ value, onChange }) => (
+ <LemonSelect
+ fullWidth
+ data-attr="alertForm-hogql-evaluation"
+ value={value ?? 'last_row'}
+ onChange={(newValue) => {
+ onChange(newValue)
+ // Any-row mode checks unrelated rows — a relative condition is meaningless.
+ if (newValue === 'any_row') {
+ onSetAlertFormValue('condition', { type: AlertConditionType.ABSOLUTE_VALUE })
+ }
+ }}
+ options={[
+ {
+ label: 'the last row',
+ value: 'last_row',
+ tooltip:
+ 'For queries ordered oldest→newest (the usual chart order): the last row is the current value.',
+ },
+ {
+ label: 'the first row',
+ value: 'first_row',
+ tooltip:
+ 'For queries ordered newest→oldest (e.g. ORDER BY ... DESC): the first row is the current value. Pairs with a LIMIT to bound the query.',
+ },
+ {
+ label: 'any row',
+ value: 'any_row',
+ tooltip:
+ 'Every row is checked and the alert fires if any value breaches the threshold — e.g. one row per country.',
+ },
+ ]}
+ />
+ )}
+ </LemonField>
+ {hasMultipleColumns && (
+ <LemonField name="column" className="flex-auto">
+ {/* Prefilled with the last numeric column by alertFormLogic; the
+ placeholder only shows when nothing numeric is detectable. */}
+ <LemonSelect
+ fullWidth
+ data-attr="alertForm-hogql-column"
+ placeholder="select column to evaluate"
+ options={hogqlValueColumnOptions}
+ />
+ </LemonField>
+ )}
+ </Group>
+ </div>
+ {isAnyRow && hasMultipleColumns && (
+ <div className="flex gap-3 items-center">
+ <Tooltip title="Names the breaching row in notifications and the check history.">
+ <div className="flex items-center gap-1">
+ Labeled by <IconInfo className="text-muted" />
+ </div>
+ </Tooltip>
+ <Group name={['config']}>
+ <LemonField name="label_column" className="flex-auto">
+ {/* Prefilled with the first non-evaluated column by alertFormLogic. */}
+ <LemonSelect
+ fullWidth
+ data-attr="alertForm-hogql-label-column"
+ placeholder="select label column"
+ options={hogqlLabelColumnOptions}
+ />
+ </LemonField>
+ </Group>
+ </div>
+ )}
+ <HogQLAlertPreviewBanner preview={hogqlPreview} conditionType={alertForm.condition?.type} />
+ {hogqlPreview?.status === 'ok' && <HogQLAlertPreviewRowsTable preview={hogqlPreview} />}
+ </>
+ )
+}
diff --git a/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx b/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
index e87053db9fee..efc356997983 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
+++ b/products/alerts/frontend/components/editAlertModal/AlertDefinitionSection.tsx
@@ -12,16 +12,17 @@ import {
} from '@posthog/lemon-ui'
import { AlertFormType } from 'lib/components/Alerts/alertFormLogic'
-import { AlertSimulationResult } from 'lib/components/Alerts/types'
+import { HogQLAlertPreview } from 'lib/components/Alerts/hogqlAlertPreview'
+import { AlertSimulationResult, isAnyRowHogQLConfig, isTrendsAlertConfig } from 'lib/components/Alerts/types'
import { DetectorSelector, getDefaultWindow } from 'lib/components/Alerts/views/DetectorSelector'
import { SimulationSummary } from 'lib/components/Alerts/views/SimulationSummary'
import { LemonField } from 'lib/lemon-ui/LemonField'
-import { alphabet } from 'lib/utils/strings'
import { AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'
import { getDefaultSimulationRange } from 'products/alerts/frontend/logic/alertIntervalHelpers'
+import { HogQLDefinitionFields, TrendsDefinitionFields } from './AlertDefinitionFields'
import { getSimulationRangeOptions } from './editAlertModalUtils'
export interface AlertDefinitionSectionProps {
@@ -32,6 +33,14 @@ export interface AlertDefinitionSectionProps {
isNonTimeSeriesDisplay: boolean
alertSeries: Array<{ custom_name?: string | null; name?: string | null; event?: string | null }> | null
formulaNodes: Array<{ formula: string; custom_name?: string | null }> | undefined
+ /** What a SQL alert would evaluate right now; null until the insight result loads. */
+ hogqlPreview: HogQLAlertPreview | null
+ /** Result column names of the SQL insight, for the column pickers. */
+ hogqlColumns: string[] | null
+ /** Options for the evaluated-column picker (numeric columns, with fallbacks). */
+ hogqlValueColumnOptions: { label: string; value: string }[]
+ /** Options for the label-column picker (every column except the evaluated one). */
+ hogqlLabelColumnOptions: { label: string; value: string }[]
anomalyDetectionEnabled: boolean
investigationAgentEnabled: boolean
simulationResult: AlertSimulationResult | null
@@ -44,6 +53,11 @@ export interface AlertDefinitionSectionProps {
onClearSimulationOverlay: () => void
}
+/** Whether the form's SQL alert config is in any-row mode (every row checked, not just the last). */
+function isHogQLAnyRow(alertForm: AlertFormType): boolean {
+ return isAnyRowHogQLConfig(alertForm.config)
+}
+
export function AlertDefinitionSection({
alertForm,
alertMode,
@@ -52,6 +66,10 @@ export function AlertDefinitionSection({
isNonTimeSeriesDisplay,
alertSeries,
formulaNodes,
+ hogqlPreview,
+ hogqlColumns,
+ hogqlValueColumnOptions,
+ hogqlLabelColumnOptions,
anomalyDetectionEnabled,
investigationAgentEnabled,
simulationResult,
@@ -63,6 +81,10 @@ export function AlertDefinitionSection({
onClearSimulation,
onClearSimulationOverlay,
}: AlertDefinitionSectionProps): JSX.Element {
+ const relativeConditionDisabledReason =
+ (isNonTimeSeriesDisplay && 'This condition is only supported for time series trends') ||
+ (isHogQLAnyRow(alertForm) &&
+ "Rows in any-row mode aren't a time series — switch to 'the latest value' for relative conditions")
return (
<>
{isBreakdownValid && (
@@ -72,36 +94,23 @@ export function AlertDefinitionSection({
: 'For trends with breakdown, the alert will fire if any of the breakdown values breaches the threshold.'}
</LemonBanner>
)}
- <div className="flex gap-3 items-center">
- <div>When</div>
- <Group name={['config']}>
- <LemonField name="series_index" className="flex-auto">
- <LemonSelect
- fullWidth
- data-attr="alertForm-series-index"
- options={
- (formulaNodes?.length ?? 0) > 0
- ? (formulaNodes ?? []).map(({ formula, custom_name }, index) => ({
- label: `${custom_name ? custom_name : 'Formula'} (${formula})`,
- value: index,
- }))
- : (alertSeries?.map(({ custom_name, name, event }, index) => ({
- label: isBreakdownValid
- ? 'any breakdown value'
- : `${alphabet[index]} - ${custom_name ?? name ?? event}`,
- value: isBreakdownValid ? 0 : index,
- })) ?? [])
- }
- disabledReason={
- isBreakdownValid &&
- (alertMode === 'detector'
- ? 'For trends with breakdown, the detector will independently monitor each breakdown value (up to 25) and fire if any is anomalous.'
- : 'For trends with breakdown, the alert will fire if any of the breakdown values breaches the threshold.')
- }
- />
- </LemonField>
- </Group>
- </div>
+ {isTrendsAlertConfig(alertForm.config) ? (
+ <TrendsDefinitionFields
+ alertSeries={alertSeries}
+ formulaNodes={formulaNodes}
+ isBreakdownValid={isBreakdownValid}
+ alertMode={alertMode}
+ />
+ ) : (
+ <HogQLDefinitionFields
+ alertForm={alertForm}
+ hogqlPreview={hogqlPreview}
+ hogqlColumns={hogqlColumns}
+ hogqlValueColumnOptions={hogqlValueColumnOptions}
+ hogqlLabelColumnOptions={hogqlLabelColumnOptions}
+ onSetAlertFormValue={onSetAlertFormValue}
+ />
+ )}
{anomalyDetectionEnabled && (
<LemonSegmentedButton
@@ -155,16 +164,12 @@ export function AlertDefinitionSection({
{
label: 'increases by',
value: AlertConditionType.RELATIVE_INCREASE,
- disabledReason:
- isNonTimeSeriesDisplay &&
- 'This condition is only supported for time series trends',
+ disabledReason: relativeConditionDisabledReason,
},
{
label: 'decreases by',
value: AlertConditionType.RELATIVE_DECREASE,
- disabledReason:
- isNonTimeSeriesDisplay &&
- 'This condition is only supported for time series trends',
+ disabledReason: relativeConditionDisabledReason,
},
]}
/>
diff --git a/products/alerts/frontend/components/editAlertModal/AlertIntervalRow.tsx b/products/alerts/frontend/components/editAlertModal/AlertIntervalRow.tsx
index e63c2c04054d..b8342ad0be7a 100644
--- a/products/alerts/frontend/components/editAlertModal/AlertIntervalRow.tsx
+++ b/products/alerts/frontend/components/editAlertModal/AlertIntervalRow.tsx
@@ -2,7 +2,7 @@ import { IconClock } from '@posthog/icons'
import { LemonSelect } from '@posthog/lemon-ui'
import { AlertFormType } from 'lib/components/Alerts/alertFormLogic'
-import { AlertType } from 'lib/components/Alerts/types'
+import { AlertType, isHogQLAlertConfig, isTrendsAlertConfig, supportsTimeWindow } from 'lib/components/Alerts/types'
import { TZLabel } from 'lib/components/TZLabel'
import type { GuardAvailableFeatureFn } from 'lib/components/UpgradeModal/upgradeModalLogic'
import { LemonField } from 'lib/lemon-ui/LemonField'
@@ -32,6 +32,13 @@ export function AlertIntervalRow({
guardAvailableFeature,
nextPlannedEvaluationStale,
}: AlertIntervalRowProps): JSX.Element {
+ const hogqlEvaluation = isHogQLAlertConfig(alertForm.config) ? alertForm.config.evaluation : null
+ const hogqlEvaluatedText =
+ hogqlEvaluation === 'any_row'
+ ? 'and check every row of the result'
+ : hogqlEvaluation === 'first_row'
+ ? "and evaluate the query's first (newest) row"
+ : "and evaluate the query's last (newest) row"
return (
<>
<div className="flex flex-wrap gap-x-3 gap-y-2 items-center">
@@ -57,25 +64,38 @@ export function AlertIntervalRow({
/>
)}
</LemonField>
- <div>and check {alertForm?.config.check_ongoing_interval ? 'current' : 'last'}</div>
- <LemonSelect
- fullWidth
- className="w-28"
- data-attr="alertForm-trend-interval"
- disabledReason={
- <>
- To change the interval being checked, edit and <b>save</b> the interval which the insight is
- 'grouped by'
- </>
- }
- value={trendInterval ?? 'day'}
- options={[
- {
- label: trendInterval ?? 'day',
- value: trendInterval ?? 'day',
- },
- ]}
- />
+ {!supportsTimeWindow(alertForm.config) ? (
+ // SQL queries own their time window — there is no insight interval to echo here,
+ // so state what is actually evaluated instead of a trends-style "check last day".
+ <div>{hogqlEvaluatedText}</div>
+ ) : (
+ <>
+ <div>
+ and check{' '}
+ {isTrendsAlertConfig(alertForm?.config) && alertForm.config.check_ongoing_interval
+ ? 'current'
+ : 'last'}
+ </div>
+ <LemonSelect
+ fullWidth
+ className="w-28"
+ data-attr="alertForm-trend-interval"
+ disabledReason={
+ <>
+ To change the interval being checked, edit and <b>save</b> the interval which the
+ insight is 'grouped by'
+ </>
+ }
+ value={trendInterval ?? 'day'}
+ options={[
+ {
+ label: trendInterval ?? 'day',
+ value: trendInterval ?? 'day',
+ },
+ ]}
+ />
+ </>
+ )}
</div>
{!creatingNewAlert && alert ? (
<div className="text-sm text-muted flex flex-wrap items-center gap-x-2 gap-y-0">
diff --git a/products/alerts/frontend/components/editAlertModal/HogQLAlertPreview.tsx b/products/alerts/frontend/components/editAlertModal/HogQLAlertPreview.tsx
new file mode 100644
index 000000000000..55dac67f332b
--- /dev/null
+++ b/products/alerts/frontend/components/editAlertModal/HogQLAlertPreview.tsx
@@ -0,0 +1,211 @@
+import { LemonBanner, LemonTable, LemonTag } from '@posthog/lemon-ui'
+
+import {
+ HOGQL_ANY_ROW_MAX_ROWS,
+ HogQLAlertPreview,
+ HogQLAlertPreviewRow,
+} from 'lib/components/Alerts/hogqlAlertPreview'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
+
+import { AlertConditionType } from '~/queries/schema/schema-general'
+
+const PREVIEW_TABLE_MAX_ROWS = 10
+
+/** Per-row view of what the alert would evaluate: breaching rows first (any-row) or the most
+ * recent rows (last-row), capped to keep the modal compact. Shown even before a threshold is set —
+ * seeing the rows is how users orient on what to alert on; the breach column appears once bounds exist. */
+export function HogQLAlertPreviewRowsTable({
+ preview,
+}: {
+ preview: Extract<HogQLAlertPreview, { status: 'ok' }>
+}): JSX.Element | null {
+ const isAnyRow = preview.mode === 'any_row'
+ const isFirstRow = preview.mode === 'first_row'
+ const rows = isAnyRow
+ ? [...preview.rows].sort((a, b) => Number(b.breaching) - Number(a.breaching)).slice(0, PREVIEW_TABLE_MAX_ROWS)
+ : isFirstRow
+ ? preview.rows.slice(0, PREVIEW_TABLE_MAX_ROWS) // newest first: the head
+ : preview.rows.slice(-PREVIEW_TABLE_MAX_ROWS) // newest last: the tail
+ const hiddenCount = preview.rows.length - rows.length
+ const showStatus = preview.breachingRows !== null
+ // Only the evaluated row is tagged in single-row modes (the banner carries the rest); any-row
+ // tags them all. first_row evaluates the top row, last_row the bottom.
+ const evaluatedIndex = isAnyRow ? null : isFirstRow ? 0 : rows.length - 1
+ // The trimmed rows are always the older ones — in last_row they sit before the visible window
+ // (note above), in first_row after it (note below); below would read as newer data otherwise.
+ const overflowNote =
+ hiddenCount > 0 ? (
+ <div className="text-muted text-xs">+{pluralize(hiddenCount, isAnyRow ? 'more row' : 'older row')}</div>
+ ) : null
+
+ return (
+ <div className="deprecated-space-y-1">
+ {!isFirstRow && overflowNote}
+ <LemonTable
+ size="small"
+ dataSource={rows}
+ columns={[
+ {
+ title: preview.labelColumnName ?? 'Row',
+ render: (_, row: HogQLAlertPreviewRow) => row.label,
+ },
+ {
+ title: preview.columnName ?? 'Value',
+ render: (_, row: HogQLAlertPreviewRow) =>
+ row.value !== null ? humanFriendlyNumber(row.value) : '—',
+ },
+ ...(showStatus
+ ? [
+ {
+ title: '',
+ render: (_: unknown, row: HogQLAlertPreviewRow, index: number) =>
+ index === evaluatedIndex || isAnyRow ? (
+ row.breaching ? (
+ <LemonTag type="warning">breach</LemonTag>
+ ) : (
+ <LemonTag type="success">ok</LemonTag>
+ )
+ ) : null,
+ },
+ ]
+ : []),
+ ]}
+ />
+ {isFirstRow && overflowNote}
+ </div>
+ )
+}
+
+/** Shows what the SQL alert would evaluate right now, surfacing shape problems before the first check. */
+export function HogQLAlertPreviewBanner({
+ preview,
+ conditionType,
+}: {
+ preview: HogQLAlertPreview | null
+ conditionType?: AlertConditionType
+}): JSX.Element {
+ if (preview === null) {
+ return (
+ <LemonBanner type="info">
+ This alert evaluates the SQL insight's result — load the insight to preview the value.
+ </LemonBanner>
+ )
+ }
+ switch (preview.status) {
+ case 'no-rows':
+ return (
+ <LemonBanner type="info">
+ The query currently returns no rows — the alert evaluates this as 0, so a lower bound can still
+ fire.
+ </LemonBanner>
+ )
+ case 'too-many-rows':
+ return (
+ <LemonBanner type="warning">
+ Any-row alerts evaluate at most {HOGQL_ANY_ROW_MAX_ROWS} rows, but the query returns{' '}
+ {preview.rowCount} — add a LIMIT or aggregate the query, or the alert will fail to evaluate.
+ </LemonBanner>
+ )
+ case 'last-row-truncated':
+ return (
+ <LemonBanner type="warning">
+ The query returns {preview.rowCount.toLocaleString()} rows and may be truncated, so the last row
+ isn't reliably the newest — add a LIMIT, aggregate the query, or switch to evaluating the first row
+ (newest-first ordering), or the alert will fail to evaluate.
+ </LemonBanner>
+ )
+ case 'bad-shape':
+ return (
+ <LemonBanner type="warning">
+ The query result isn't plain rows of values — the alert requires a query returning rows with a
+ numeric column.
+ </LemonBanner>
+ )
+ case 'ambiguous-columns':
+ return (
+ <LemonBanner type="warning">
+ The value column can't be inferred
+ {preview.columnNames ? ` (columns: ${preview.columnNames.join(', ')})` : ''} — pick the column to
+ evaluate above.
+ </LemonBanner>
+ )
+ case 'missing-column':
+ return (
+ <LemonBanner type="warning">
+ Column "{preview.column}" is no longer returned by the query
+ {preview.columnNames ? ` (columns: ${preview.columnNames.join(', ')})` : ''} — pick another column
+ to evaluate.
+ </LemonBanner>
+ )
+ case 'not-numeric':
+ return (
+ <LemonBanner type="warning">
+ The evaluated value ({preview.value}) isn't a number — pick a numeric column to evaluate.
+ </LemonBanner>
+ )
+ case 'ok': {
+ const isRelative =
+ conditionType === AlertConditionType.RELATIVE_INCREASE ||
+ conditionType === AlertConditionType.RELATIVE_DECREASE
+ const columnLabel = preview.columnName ? (
+ <>
+ the <strong>{preview.columnName}</strong> column
+ </>
+ ) : (
+ 'the result'
+ )
+ if (preview.mode === 'any_row') {
+ const breaching = preview.breachingRows
+ return (
+ <LemonBanner type={breaching ? 'warning' : 'info'}>
+ The alert checks every row of {columnLabel}
+ {breaching !== null ? (
+ <>
+ {' '}
+ — currently <strong>{breaching}</strong> of {preview.rowCount} rows breach the threshold
+ {breaching > 0 ? ', so the alert would fire on its next check' : ''}.
+ </>
+ ) : (
+ <>. Set a threshold to preview which rows would breach.</>
+ )}
+ </LemonBanner>
+ )
+ }
+ if (isRelative && preview.rowCount < 2) {
+ return (
+ <LemonBanner type="warning">
+ Relative conditions compare the two most recent rows, but the query currently returns only one
+ row.
+ </LemonBanner>
+ )
+ }
+ const isFirstRow = preview.mode === 'first_row'
+ const anchorRowLabel = isFirstRow ? 'first row' : 'last row'
+ const orderingHint = isFirstRow
+ ? 'Order the query newest→oldest (e.g. ORDER BY ... DESC) so the first row is the most recent value.'
+ : 'Order the query oldest→newest so the last row is the most recent value.'
+ return (
+ <LemonBanner type="info">
+ The alert evaluates the {anchorRowLabel} of {columnLabel} — currently{' '}
+ <strong>{humanFriendlyNumber(preview.currentValue)}</strong>
+ {isRelative && preview.previousValue !== null ? (
+ <>
+ {' '}
+ vs <strong>{humanFriendlyNumber(preview.previousValue)}</strong> in the previous row
+ </>
+ ) : null}
+ . {orderingHint}
+ {!isRelative && preview.breachingRows !== null ? (
+ <>
+ {' '}
+ Right now <strong>{preview.breachingRows}</strong> of its{' '}
+ {pluralize(preview.rowCount, 'row')} {preview.breachingRows === 1 ? 'is' : 'are'} outside
+ the threshold.
+ </>
+ ) : null}
+ </LemonBanner>
+ )
+ }
+ }
+}
diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.ts
index ef5181529597..9b6cb11454cb 100644
--- a/products/alerts/frontend/generated/api.schemas.ts
+++ b/products/alerts/frontend/generated/api.schemas.ts
@@ -175,14 +175,50 @@ export interface AlertCheckApi {
readonly notification_suppressed_by_agent: boolean
}
+export type TrendsAlertConfigApiType = (typeof TrendsAlertConfigApiType)[keyof typeof TrendsAlertConfigApiType]
+
+export const TrendsAlertConfigApiType = {
+ TrendsAlertConfig: 'TrendsAlertConfig',
+} as const
+
export interface TrendsAlertConfigApi {
/** When true, evaluate the current (still incomplete) time interval in addition to completed ones. */
check_ongoing_interval?: boolean | null
/** Zero-based index of the series in the insight's query to monitor. */
series_index: number
- type?: 'TrendsAlertConfig'
+ type: TrendsAlertConfigApiType
+}
+
+export type HogQLAlertEvaluationApi = (typeof HogQLAlertEvaluationApi)[keyof typeof HogQLAlertEvaluationApi]
+
+export const HogQLAlertEvaluationApi = {
+ LastRow: 'last_row',
+ FirstRow: 'first_row',
+ AnyRow: 'any_row',
+} as const
+
+export type HogQLAlertConfigApiType = (typeof HogQLAlertConfigApiType)[keyof typeof HogQLAlertConfigApiType]
+
+export const HogQLAlertConfigApiType = {
+ HogQLAlertConfig: 'HogQLAlertConfig',
+} as const
+
+export interface HogQLAlertConfigApi {
+ /** Name of the result column to evaluate. When unset, the single numeric column is used (an error if the result has more than one numeric column). */
+ column?: string | null
+ /** How to read the result rows — an explicit choice, no implicit default. */
+ evaluation: HogQLAlertEvaluationApi
+ /** In `any_row` mode, the column whose value labels each row in breach messages. When unset, the first non-evaluated column is used, falling back to the row number. */
+ label_column?: string | null
+ type: HogQLAlertConfigApiType
}
+/**
+ * Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the
+ * generated frontend types and MCP tool schemas) in sync with every kind alerts support.
+ */
+export type AlertConfigUnionApi = TrendsAlertConfigApi | HogQLAlertConfigApi
+
export interface PreprocessingConfigApi {
/** Order of differencing. 0 = raw values, 1 = first-order diffs (default: 0) */
diffs_n?: number | null
@@ -459,8 +495,8 @@ export interface AlertApi {
* @nullable
*/
readonly checks_total: number | null
- /** Trends-specific alert configuration. Includes series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). */
- config?: TrendsAlertConfigApi | 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 (labels rows in breach messages for any_row). */
+ config?: AlertConfigUnionApi | null
detector_config?: DetectorConfigApi | null
/** How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.
*
@@ -540,8 +576,8 @@ export interface PatchedAlertApi {
* @nullable
*/
readonly checks_total?: number | null
- /** Trends-specific alert configuration. Includes series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). */
- config?: TrendsAlertConfigApi | 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 (labels rows in breach messages for any_row). */
+ 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/mcp/tools.yaml b/products/alerts/mcp/tools.yaml
index 484870e51571..8aaada37b5d6 100644
--- a/products/alerts/mcp/tools.yaml
+++ b/products/alerts/mcp/tools.yaml
@@ -28,6 +28,16 @@ tools:
window size. Ensemble detectors combine 2+ sub-detectors with AND/OR logic. Requires an insight ID and at
least one subscribed user.
+ The 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 labels rows in breach messages). Label values appear in delivered notifications
+ — avoid label columns containing PII. Anomaly detection (detector_config) is only supported for trends
+ insights.
+
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
(cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.
@@ -97,9 +107,11 @@ tools:
description: >
Update an existing alert by ID. Can update name, threshold, condition, config, detector_config, subscribed
users, enabled state, calculation interval, and weekend skipping. Set detector_config to switch to anomaly
- detection, or set it to null to switch back to threshold mode (threshold mode requires at least one of lower
- or upper in threshold.configuration.bounds). To snooze an alert, set snoozed_until to a relative date string
- (e.g. '2h', '1d'). To unsnooze, set snoozed_until to null.
+ detection (trends insights only), or set it to null to switch back to threshold mode (threshold mode
+ requires at least one of lower or upper in threshold.configuration.bounds). For SQL-insight alerts the
+ config is HogQLAlertConfig (column, evaluation 'last_row'/'first_row'/'any_row', label_column). To snooze an
+ alert, set snoozed_until to a relative date string (e.g. '2h', '1d'). To unsnooze, set snoozed_until to
+ null.
Note: Slack/webhook/Discord delivery for this alert lives as a HogFunction. See the recipe on
cdp-functions-create for the dedupe-and-create flow; to change or remove an existing destination, find it
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index 59c2e0abdb16..d4839b5fa7af 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -719,7 +719,12 @@ class InsightSerializer(InsightBasicSerializer):
self._update_insight_dashboards(dashboards, instance)
updated_insight = super().update(instance, validated_data)
- if not updated_insight.are_alerts_supported:
+ # Delete linked alerts only when the insight can no longer carry any alert. A switch between
+ # alertable kinds (e.g. trends -> SQL) is left alone: the config type no longer matches, but
+ # the alert check cycle re-validates against the current query and auto-disables + notifies on
+ # mismatch (see validate_alert_config + disable_invalid_alert in the alerts temporal activity),
+ # so the alert and its history are preserved and the user can reconfigure rather than lose it.
+ if updated_insight.alertable_query_kind is None:
for alert in instance.alertconfiguration_set.all():
alert.delete()
@@ -936,7 +941,7 @@ class InsightSerializer(InsightBasicSerializer):
@extend_schema_field(serializers.ListField())
def get_alerts(self, insight: Insight):
- if not insight.are_alerts_supported:
+ if insight.alertable_query_kind is None:
return []
# Use prefetched alerts data
diff --git a/products/product_analytics/backend/models/insight.py b/products/product_analytics/backend/models/insight.py
index 3e9b0e3ed214..e67495d5e249 100644
--- a/products/product_analytics/backend/models/insight.py
+++ b/products/product_analytics/backend/models/insight.py
@@ -37,6 +37,8 @@ _ANALYTICS_INSIGHT_QUERY_KINDS = frozenset(
if TYPE_CHECKING:
+ from posthog.schema import NodeKind
+
from posthog.models.team import Team
from products.dashboards.backend.models.dashboard import Dashboard
@@ -400,19 +402,28 @@ class Insight(RootTeamMixin, FileSystemSyncMixin, models.Model):
except (AttributeError, TypeError, KeyError):
return False
- @property
- def are_alerts_supported(self) -> bool:
+ def _unwrapped_query_kind(self) -> str | None:
+ """Innermost query ``kind`` after unwrapping DataTable/DataVisualization/InsightVizNode
+ wrappers, or None if the insight has no query."""
from posthog.schema_migrations.upgrade_manager import upgrade_query
with upgrade_query(self):
query = self.query
if query is None:
- return False
+ return None
while query.get("source"):
query = query["source"]
- if query.get("kind") != "TrendsQuery":
- return False
- return True
+ return query.get("kind")
+
+ @property
+ def alertable_query_kind(self) -> "NodeKind | None":
+ """The insight's alert-capable query kind (trends or SQL today), or None if alerts aren't
+ supported. Pure kind check — feature-flag gating is the caller's responsibility, so existing
+ alerts keep displaying and survive insight edits regardless of the flag."""
+ from posthog.schema import NodeKind # noqa: PLC0415
+
+ kind = self._unwrapped_query_kind()
+ return NodeKind(kind) if kind in (NodeKind.TRENDS_QUERY, NodeKind.HOG_QL_QUERY) else None
def generate_query_metadata(self):
from posthog.hogql_queries.query_metadata import extract_query_metadata
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 0953e70da887..f7998015abc2 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -757,7 +757,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.\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 labels rows in breach messages). Label values appear in delivered notifications — avoid label columns containing PII. Anomaly detection (detector_config) is only supported for trends insights.\nNote: subscribed_users only controls email recipients. For Slack, HTTPS webhook, or Discord delivery, see the recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe (cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.",
"category": "Alerts",
"feature": "alerts",
"summary": "Create alert",
@@ -813,7 +813,7 @@
}
},
"alert-update": {
- "description": "Update an existing alert by ID. Can update name, threshold, condition, config, detector_config, subscribed users, enabled state, calculation interval, and weekend skipping. Set detector_config to switch to anomaly detection, or set it to null to switch back to threshold mode (threshold mode requires at least one of lower or upper in threshold.configuration.bounds). To snooze an alert, set snoozed_until to a relative date string (e.g. '2h', '1d'). To unsnooze, set snoozed_until to null.\nNote: Slack/webhook/Discord delivery for this alert lives as a HogFunction. See the recipe on cdp-functions-create for the dedupe-and-create flow; to change or remove an existing destination, find it via cdp-functions-list (type=internal_destination, limit=1000) by matching filters.properties value against this alert's id, then use cdp-functions-partial-update or cdp-functions-delete.",
+ "description": "Update an existing alert by ID. Can update name, threshold, condition, config, detector_config, subscribed users, enabled state, calculation interval, and weekend skipping. Set detector_config to switch to anomaly detection (trends insights only), or set it to null to switch back to threshold mode (threshold mode requires at least one of lower or upper in threshold.configuration.bounds). For SQL-insight alerts the config is HogQLAlertConfig (column, evaluation 'last_row'/'first_row'/'any_row', label_column). To snooze an alert, set snoozed_until to a relative date string (e.g. '2h', '1d'). To unsnooze, set snoozed_until to null.\nNote: Slack/webhook/Discord delivery for this alert lives as a HogFunction. See the recipe on cdp-functions-create for the dedupe-and-create flow; to change or remove an existing destination, find it via cdp-functions-list (type=internal_destination, limit=1000) by matching filters.properties value against this alert's id, then use cdp-functions-partial-update or cdp-functions-delete.",
"category": "Alerts",
"feature": "alerts",
"summary": "Update alert",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 811aa1d83110..527483aee0f9 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -787,7 +787,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.\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 labels rows in breach messages). Label values appear in delivered notifications — avoid label columns containing PII. Anomaly detection (detector_config) is only supported for trends insights.\nNote: subscribed_users only controls email recipients. For Slack, HTTPS webhook, or Discord delivery, see the recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe (cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.",
"category": "Alerts",
"feature": "alerts",
"summary": "Create alert",
@@ -843,7 +843,7 @@
}
},
"alert-update": {
- "description": "Update an existing alert by ID. Can update name, threshold, condition, config, detector_config, subscribed users, enabled state, calculation interval, and weekend skipping. Set detector_config to switch to anomaly detection, or set it to null to switch back to threshold mode (threshold mode requires at least one of lower or upper in threshold.configuration.bounds). To snooze an alert, set snoozed_until to a relative date string (e.g. '2h', '1d'). To unsnooze, set snoozed_until to null.\nNote: Slack/webhook/Discord delivery for this alert lives as a HogFunction. See the recipe on cdp-functions-create for the dedupe-and-create flow; to change or remove an existing destination, find it via cdp-functions-list (type=internal_destination, limit=1000) by matching filters.properties value against this alert's id, then use cdp-functions-partial-update or cdp-functions-delete.",
+ "description": "Update an existing alert by ID. Can update name, threshold, condition, config, detector_config, subscribed users, enabled state, calculation interval, and weekend skipping. Set detector_config to switch to anomaly detection (trends insights only), or set it to null to switch back to threshold mode (threshold mode requires at least one of lower or upper in threshold.configuration.bounds). For SQL-insight alerts the config is HogQLAlertConfig (column, evaluation 'last_row'/'first_row'/'any_row', label_column). To snooze an alert, set snoozed_until to a relative date string (e.g. '2h', '1d'). To unsnooze, set snoozed_until to null.\nNote: Slack/webhook/Discord delivery for this alert lives as a HogFunction. See the recipe on cdp-functions-create for the dedupe-and-create flow; to change or remove an existing destination, find it via cdp-functions-list (type=internal_destination, limit=1000) by matching filters.properties value against this alert's id, then use cdp-functions-partial-update or cdp-functions-delete.",
"category": "Alerts",
"feature": "alerts",
"summary": "Update alert",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2d38b33061c7..52fe5b0e882e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8621,14 +8621,53 @@ export namespace Schemas {
readonly notification_suppressed_by_agent: boolean;
}
+ export type TrendsAlertConfigType = typeof TrendsAlertConfigType[keyof typeof TrendsAlertConfigType];
+
+
+ export const TrendsAlertConfigType = {
+ TrendsAlertConfig: 'TrendsAlertConfig',
+ } as const;
+
export interface TrendsAlertConfig {
/** When true, evaluate the current (still incomplete) time interval in addition to completed ones. */
check_ongoing_interval?: boolean | null;
/** Zero-based index of the series in the insight's query to monitor. */
series_index: number;
- type?: 'TrendsAlertConfig';
+ type: TrendsAlertConfigType;
}
+ export type HogQLAlertEvaluation = typeof HogQLAlertEvaluation[keyof typeof HogQLAlertEvaluation];
+
+
+ export const HogQLAlertEvaluation = {
+ LastRow: 'last_row',
+ FirstRow: 'first_row',
+ AnyRow: 'any_row',
+ } as const;
+
+ export type HogQLAlertConfigType = typeof HogQLAlertConfigType[keyof typeof HogQLAlertConfigType];
+
+
+ export const HogQLAlertConfigType = {
+ HogQLAlertConfig: 'HogQLAlertConfig',
+ } as const;
+
+ export interface HogQLAlertConfig {
+ /** Name of the result column to evaluate. When unset, the single numeric column is used (an error if the result has more than one numeric column). */
+ column?: string | null;
+ /** How to read the result rows — an explicit choice, no implicit default. */
+ evaluation: HogQLAlertEvaluation;
+ /** In `any_row` mode, the column whose value labels each row in breach messages. When unset, the first non-evaluated column is used, falling back to the row number. */
+ label_column?: string | null;
+ type: HogQLAlertConfigType;
+ }
+
+ /**
+ * Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the
+ * generated frontend types and MCP tool schemas) in sync with every kind alerts support.
+ */
+ export type AlertConfigUnion = TrendsAlertConfig | HogQLAlertConfig;
+
export interface PreprocessingConfig {
/** Order of differencing. 0 = raw values, 1 = first-order diffs (default: 0) */
diffs_n?: number | null;
@@ -8875,8 +8914,8 @@ export namespace Schemas {
* @nullable
*/
readonly checks_total: number | null;
- /** Trends-specific alert configuration. Includes series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). */
- config?: TrendsAlertConfig | 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 (labels rows in breach messages for any_row). */
+ config?: AlertConfigUnion | null;
detector_config?: DetectorConfig | null;
/** How often the alert is checked: every 15 minutes (Boost+), hourly, daily, weekly, or monthly.
*
@@ -33724,8 +33763,8 @@ export namespace Schemas {
* @nullable
*/
readonly checks_total?: number | null;
- /** Trends-specific alert configuration. Includes series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). */
- config?: TrendsAlertConfig | 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 (labels rows in breach messages for any_row). */
+ 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 ece3f25f346e..8e07d2b0fd17 100644
--- a/services/mcp/src/generated/alerts/api.ts
+++ b/services/mcp/src/generated/alerts/api.ts
@@ -40,7 +40,8 @@ export const AlertsCreateParams = /* @__PURE__ */ zod.object({
),
})
-export const alertsCreateBodyConfigOneTypeDefault = `TrendsAlertConfig`
+export const alertsCreateBodyConfigOneOneTypeDefault = `TrendsAlertConfig`
+export const alertsCreateBodyConfigOneTwoTypeDefault = `HogQLAlertConfig`
export const alertsCreateBodyDetectorConfigOneOneDetectorsItemOneTypeDefault = `zscore`
export const alertsCreateBodyDetectorConfigOneOneDetectorsItemTwoTypeDefault = `mad`
export const alertsCreateBodyDetectorConfigOneOneDetectorsItemThreeTypeDefault = `iqr`
@@ -122,23 +123,47 @@ export const AlertsCreateBody = /* @__PURE__ */ zod.object({
enabled: zod.boolean().optional().describe('Whether the alert is actively being evaluated.'),
config: zod
.union([
- zod.object({
- check_ongoing_interval: zod
- .union([zod.boolean(), zod.null()])
- .optional()
- .describe(
- 'When true, evaluate the current (still incomplete) time interval in addition to completed ones.'
- ),
- series_index: zod
- .number()
- .describe("Zero-based index of the series in the insight's query to monitor."),
- type: zod.literal('TrendsAlertConfig').default(alertsCreateBodyConfigOneTypeDefault),
- }),
+ zod
+ .union([
+ zod.object({
+ check_ongoing_interval: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'When true, evaluate the current (still incomplete) time interval in addition to completed ones.'
+ ),
+ series_index: zod
+ .number()
+ .describe("Zero-based index of the series in the insight's query to monitor."),
+ type: zod.enum(['TrendsAlertConfig']).default(alertsCreateBodyConfigOneOneTypeDefault),
+ }),
+ zod.object({
+ column: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'Name of the result column to evaluate. When unset, the single numeric column is used (an error if the result has more than one numeric column).'
+ ),
+ evaluation: zod
+ .enum(['last_row', 'first_row', 'any_row'])
+ .describe('How to read the result rows — an explicit choice, no implicit default.'),
+ label_column: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'In `any_row` mode, the column whose value labels each row in breach messages. When unset, the first non-evaluated column is used, falling back to the row number.'
+ ),
+ type: zod.enum(['HogQLAlertConfig']).default(alertsCreateBodyConfigOneTwoTypeDefault),
+ }),
+ ])
+ .describe(
+ 'Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support.'
+ ),
zod.null(),
])
.optional()
.describe(
- 'Trends-specific alert configuration. Includes series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval).'
+ "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 (labels rows in breach messages for any_row)."
),
detector_config: zod
.union([
@@ -1288,7 +1313,8 @@ export const AlertsPartialUpdateParams = /* @__PURE__ */ zod.object({
),
})
-export const alertsPartialUpdateBodyConfigOneTypeDefault = `TrendsAlertConfig`
+export const alertsPartialUpdateBodyConfigOneOneTypeDefault = `TrendsAlertConfig`
+export const alertsPartialUpdateBodyConfigOneTwoTypeDefault = `HogQLAlertConfig`
export const alertsPartialUpdateBodyDetectorConfigOneOneDetectorsItemOneTypeDefault = `zscore`
export const alertsPartialUpdateBodyDetectorConfigOneOneDetectorsItemTwoTypeDefault = `mad`
export const alertsPartialUpdateBodyDetectorConfigOneOneDetectorsItemThreeTypeDefault = `iqr`
@@ -1373,23 +1399,47 @@ export const AlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
enabled: zod.boolean().optional().describe('Whether the alert is actively being evaluated.'),
config: zod
.union([
- zod.object({
- check_ongoing_interval: zod
- .union([zod.boolean(), zod.null()])
- .optional()
- .describe(
- 'When true, evaluate the current (still incomplete) time interval in addition to completed ones.'
- ),
- series_index: zod
- .number()
- .describe("Zero-based index of the series in the insight's query to monitor."),
- type: zod.literal('TrendsAlertConfig').default(alertsPartialUpdateBodyConfigOneTypeDefault),
- }),
+ zod
+ .union([
+ zod.object({
+ check_ongoing_interval: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ 'When true, evaluate the current (still incomplete) time interval in addition to completed ones.'
+ ),
+ series_index: zod
+ .number()
+ .describe("Zero-based index of the series in the insight's query to monitor."),
+ type: zod.enum(['TrendsAlertConfig']).default(alertsPartialUpdateBodyConfigOneOneTypeDefault),
+ }),
+ zod.object({
+ column: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'Name of the result column to evaluate. When unset, the single numeric column is used (an error if the result has more than one numeric column).'
+ ),
+ evaluation: zod
+ .enum(['last_row', 'first_row', 'any_row'])
+ .describe('How to read the result rows — an explicit choice, no implicit default.'),
+ label_column: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'In `any_row` mode, the column whose value labels each row in breach messages. When unset, the first non-evaluated column is used, falling back to the row number.'
+ ),
+ type: zod.enum(['HogQLAlertConfig']).default(alertsPartialUpdateBodyConfigOneTwoTypeDefault),
+ }),
+ ])
+ .describe(
+ 'Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support.'
+ ),
zod.null(),
])
.optional()
.describe(
- 'Trends-specific alert configuration. Includes series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval).'
+ "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 (labels rows in breach messages for any_row)."
),
detector_config: zod
.union([
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 cdf59e5ce2c0..862dc11a3017 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json
@@ -27,36 +27,79 @@
"config": {
"anyOf": [
{
- "properties": {
- "check_ongoing_interval": {
- "anyOf": [
- {
- "type": "boolean"
+ "anyOf": [
+ {
+ "properties": {
+ "check_ongoing_interval": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "When true, evaluate the current (still incomplete) time interval in addition to completed ones."
},
- {
- "type": "null"
+ "series_index": {
+ "description": "Zero-based index of the series in the insight's query to monitor.",
+ "type": "number"
+ },
+ "type": {
+ "default": "TrendsAlertConfig",
+ "enum": ["TrendsAlertConfig"],
+ "type": "string"
}
- ],
- "description": "When true, evaluate the current (still incomplete) time interval in addition to completed ones."
- },
- "series_index": {
- "description": "Zero-based index of the series in the insight's query to monitor.",
- "type": "number"
+ },
+ "required": ["series_index"],
+ "type": "object"
},
- "type": {
- "const": "TrendsAlertConfig",
- "default": "TrendsAlertConfig",
- "type": "string"
+ {
+ "properties": {
+ "column": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Name of the result column to evaluate. When unset, the single numeric column is used (an error if the result has more than one numeric column)."
+ },
+ "evaluation": {
+ "description": "How to read the result rows — an explicit choice, no implicit default.",
+ "enum": ["last_row", "first_row", "any_row"],
+ "type": "string"
+ },
+ "label_column": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "In `any_row` mode, the column whose value labels each row in breach messages. When unset, the first non-evaluated column is used, falling back to the row number."
+ },
+ "type": {
+ "default": "HogQLAlertConfig",
+ "enum": ["HogQLAlertConfig"],
+ "type": "string"
+ }
+ },
+ "required": ["evaluation"],
+ "type": "object"
}
- },
- "required": ["series_index"],
- "type": "object"
+ ],
+ "description": "Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support."
},
{
"type": "null"
}
],
- "description": "Trends-specific alert configuration. Includes series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval)."
+ "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 (labels rows in breach messages for any_row)."
},
"detector_config": {
"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 05b3130a77ae..9c4169351ab0 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json
@@ -27,36 +27,79 @@
"config": {
"anyOf": [
{
- "properties": {
- "check_ongoing_interval": {
- "anyOf": [
- {
- "type": "boolean"
+ "anyOf": [
+ {
+ "properties": {
+ "check_ongoing_interval": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "When true, evaluate the current (still incomplete) time interval in addition to completed ones."
},
- {
- "type": "null"
+ "series_index": {
+ "description": "Zero-based index of the series in the insight's query to monitor.",
+ "type": "number"
+ },
+ "type": {
+ "default": "TrendsAlertConfig",
+ "enum": ["TrendsAlertConfig"],
+ "type": "string"
}
- ],
- "description": "When true, evaluate the current (still incomplete) time interval in addition to completed ones."
- },
- "series_index": {
- "description": "Zero-based index of the series in the insight's query to monitor.",
- "type": "number"
+ },
+ "required": ["series_index"],
+ "type": "object"
},
- "type": {
- "const": "TrendsAlertConfig",
- "default": "TrendsAlertConfig",
- "type": "string"
+ {
+ "properties": {
+ "column": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Name of the result column to evaluate. When unset, the single numeric column is used (an error if the result has more than one numeric column)."
+ },
+ "evaluation": {
+ "description": "How to read the result rows — an explicit choice, no implicit default.",
+ "enum": ["last_row", "first_row", "any_row"],
+ "type": "string"
+ },
+ "label_column": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "In `any_row` mode, the column whose value labels each row in breach messages. When unset, the first non-evaluated column is used, falling back to the row number."
+ },
+ "type": {
+ "default": "HogQLAlertConfig",
+ "enum": ["HogQLAlertConfig"],
+ "type": "string"
+ }
+ },
+ "required": ["evaluation"],
+ "type": "object"
}
- },
- "required": ["series_index"],
- "type": "object"
+ ],
+ "description": "Per-insight-kind alert config, discriminated by ``type`` — keeps the OpenAPI (and the\ngenerated frontend types and MCP tool schemas) in sync with every kind alerts support."
},
{
"type": "null"
}
],
- "description": "Trends-specific alert configuration. Includes series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval)."
+ "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 (labels rows in breach messages for any_row)."
},
"detector_config": {
"anyOf": [