:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(alerts): stop the alert preview crashing on breakdown rows without data (#95995)
posthog[bot]686c7bab6b88
diff --git a/products/alerts/frontend/components/AlertPreviewCard.test.tsx b/products/alerts/frontend/components/AlertPreviewCard.test.tsxnew file mode 100644index 000000000000..aa32bcd469e0--- /dev/null+++ b/products/alerts/frontend/components/AlertPreviewCard.test.tsx@@ -0,0 +1,55 @@+import { render, within } from '@testing-library/react'++import { AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'++import { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'++import { AlertPreviewCard, AlertPreviewCardProps } from './AlertPreviewCard'++// Trend results declare `data` as a required array, but breakdown rows can arrive without it.+type BreakdownSeries = NonNullable<AlertPreviewCardProps['trendsBreakdownSeries']>+const seriesWithoutData = [{ key: 'chrome', label: 'Chrome' }] as BreakdownSeries+const seriesWithMissingAndPresentData = [+ { key: 'chrome', label: 'Chrome' },+ { key: 'safari', label: 'Safari', data: [10, 25, 60] },+] as BreakdownSeries++const EMPTY_BREAKDOWN_TEXT = 'No activity to preview across breakdown values.'++describe('AlertPreviewCard', () => {+ const alertForm = {+ name: 'Preview alert',+ enabled: true,+ config: { type: 'TrendsAlertConfig', series_index: 0 },+ condition: { type: AlertConditionType.ABSOLUTE_VALUE },+ threshold: { configuration: { type: InsightThresholdType.ABSOLUTE, bounds: { upper: 60, lower: 20 } } },+ } as AlertFormType++ // No labels are passed, because breakdown rows often have none. The chart then builds labels+ // from the first series' data, which is the path that crashed.+ function renderCard(trendsBreakdownSeries: BreakdownSeries): HTMLElement {+ const { container } = render(+ <AlertPreviewCard+ alertForm={alertForm}+ trendsValues={[20, 30, 40]}+ isBreakdown+ trendsBreakdownSeries={trendsBreakdownSeries}+ funnelPreview={null}+ hogqlPreview={null}+ />+ )+ return container+ }++ it('shows the empty state when every breakdown series has no data', () => {+ const container = renderCard(seriesWithoutData)++ expect(within(container).getByText(EMPTY_BREAKDOWN_TEXT)).toBeTruthy()+ })++ it('charts the breakdown series that do have data', () => {+ const container = renderCard(seriesWithMissingAndPresentData)++ expect(within(container).queryByText(EMPTY_BREAKDOWN_TEXT)).toBeNull()+ })+})diff --git a/products/alerts/frontend/components/AlertPreviewCard.tsx b/products/alerts/frontend/components/AlertPreviewCard.tsxindex 38d5bed3cd5a..26adf22e0a4b 100644--- a/products/alerts/frontend/components/AlertPreviewCard.tsx+++ b/products/alerts/frontend/components/AlertPreviewCard.tsx@@ -11,6 +11,7 @@ import { FunnelAlertPreview } from 'products/alerts/frontend/logic/funnelAlertPrimport { HogQLAlertPreview } from 'products/alerts/frontend/logic/hogqlAlertPreview'import {deriveTrendsAlertPreviewSeries,+ deriveTrendsBreakdownAlertPreview,TrendsAlertPreviewSeries,} from 'products/alerts/frontend/logic/trendsAlertPreview'import { isFunnelsAlertConfig, isHogQLAlertConfig, isTrendsAlertConfig } from 'products/alerts/frontend/types'@@ -46,7 +47,7 @@ function AlertPreviewChart({<div className="w-full h-24 flex flex-col"><LineChartseries={series}- labels={labels ?? series[0]?.data.map((_, index) => String(index)) ?? []}+ labels={labels ?? series[0]?.data?.map((_, index) => String(index)) ?? []}theme={theme}config={{hideXAxis: true,@@ -90,13 +91,10 @@ export function AlertPreviewCard({loading,}: AlertPreviewCardProps): JSX.Element {const config = alertForm.config+ const conditionType = alertForm.condition?.type ?? AlertConditionType.ABSOLUTE_VALUE+ const thresholdType = alertForm.threshold?.configuration?.type ?? InsightThresholdType.ABSOLUTEconst trendsPreview = trendsValues- ? deriveTrendsAlertPreviewSeries(- trendsValues,- trendsLabels ?? undefined,- alertForm.condition?.type ?? AlertConditionType.ABSOLUTE_VALUE,- alertForm.threshold?.configuration?.type ?? InsightThresholdType.ABSOLUTE- )+ ? deriveTrendsAlertPreviewSeries(trendsValues, trendsLabels ?? undefined, conditionType, thresholdType): nullconst isBreakdownPreview = isTrendsAlertConfig(config) && isBreakdownconst referenceLines = thresholdReferenceLines(alertForm)@@ -104,17 +102,15 @@ export function AlertPreviewCard({!isBreakdownPreview && trendsPreview && shouldUseLogScale(trendsPreview.values, referenceLines))const checkPreviewValues = checkPreview?.values- const trendsBreakdownPreviews = trendsBreakdownSeries?.map(({ key, label, data }) => ({- key,- label,- data: deriveTrendsAlertPreviewSeries(- data,- trendsLabels ?? undefined,- alertForm.condition?.type ?? AlertConditionType.ABSOLUTE_VALUE,- alertForm.threshold?.configuration?.type ?? InsightThresholdType.ABSOLUTE- ).values,- }))- const breakdownPreviewValues = trendsBreakdownPreviews?.flatMap((series) => series.data) ?? []+ const breakdownPreview = deriveTrendsBreakdownAlertPreview(+ trendsBreakdownSeries ?? undefined,+ trendsLabels ?? undefined,+ conditionType,+ thresholdType+ )+ // A row carries `NaN` on the intervals it has no comparison for, so count only drawable points.+ const breakdownPreviewValues =+ breakdownPreview?.rows.flatMap((row) => row.data).filter((value) => Number.isFinite(value)) ?? []const breakdownUseLogScale = shouldUseLogScale(breakdownPreviewValues, referenceLines)const isUnconfiguredAbsoluteThreshold =!alertForm.detector_config &&@@ -134,11 +130,11 @@ export function AlertPreviewCard({Set less than or more than to preview this alert.</div>)- } else if (isBreakdownPreview && trendsBreakdownPreviews && breakdownPreviewValues.length > 0) {+ } else if (isBreakdownPreview && breakdownPreview && breakdownPreviewValues.length > 0) {body = (<AlertPreviewChart- series={trendsBreakdownPreviews}- labels={trendsLabels ?? undefined}+ series={breakdownPreview.rows}+ labels={breakdownPreview.labels}referenceLines={referenceLines}relative={trendsPreview?.relative ?? false}useLogScale={breakdownUseLogScale}diff --git a/products/alerts/frontend/logic/trendsAlertPreview.test.ts b/products/alerts/frontend/logic/trendsAlertPreview.test.tsindex d4b3d384decf..67ffcbea42c2 100644--- a/products/alerts/frontend/logic/trendsAlertPreview.test.ts+++ b/products/alerts/frontend/logic/trendsAlertPreview.test.ts@@ -1,6 +1,10 @@import { AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'-import { deriveAlertCheckPreviewSeries, deriveTrendsAlertPreviewSeries } from './trendsAlertPreview'+import {+ deriveAlertCheckPreviewSeries,+ deriveTrendsAlertPreviewSeries,+ deriveTrendsBreakdownAlertPreview,+} from './trendsAlertPreview'describe('deriveTrendsAlertPreviewSeries', () => {it.each([@@ -17,6 +21,41 @@ describe('deriveTrendsAlertPreviewSeries', () => {})})+ it.each([+ [+ 'moves a relative breakdown onto the compared intervals and gaps the rows that cannot compare',+ AlertConditionType.RELATIVE_INCREASE,+ InsightThresholdType.PERCENTAGE,+ [+ { key: '0', label: 'Chrome', data: [NaN, 100] },+ { key: '1', label: 'Safari', data: [100, 100] },+ ],+ ['b', 'c'],+ ],+ [+ 'keeps an absolute breakdown on the raw intervals',+ AlertConditionType.ABSOLUTE_VALUE,+ InsightThresholdType.ABSOLUTE,+ [+ { key: '0', label: 'Chrome', data: [0, 4, 8] },+ { key: '1', label: 'Safari', data: [2, 4, 8] },+ ],+ ['a', 'b', 'c'],+ ],+ ])('%s', (_case, conditionType, thresholdType, rows, labels) => {+ expect(+ deriveTrendsBreakdownAlertPreview(+ [+ { key: '0', label: 'Chrome', data: [0, 4, 8] },+ { key: '1', label: 'Safari', data: [2, 4, 8] },+ ],+ ['a', 'b', 'c'],+ conditionType,+ thresholdType+ )+ ).toEqual({ rows, labels })+ })+it('returns an empty series when checks is undefined', () => {expect(deriveAlertCheckPreviewSeries(undefined, AlertConditionType.ABSOLUTE_VALUE, InsightThresholdType.ABSOLUTE)diff --git a/products/alerts/frontend/logic/trendsAlertPreview.ts b/products/alerts/frontend/logic/trendsAlertPreview.tsindex efb4ce72fe08..367a542ac2f0 100644--- a/products/alerts/frontend/logic/trendsAlertPreview.ts+++ b/products/alerts/frontend/logic/trendsAlertPreview.ts@@ -6,11 +6,27 @@ export interface TrendsAlertPreviewSeries {relative: boolean}+export interface TrendsBreakdownAlertPreviewRow {+ key: string+ label: string+ data: number[]+}++export interface TrendsBreakdownAlertPreview {+ rows: TrendsBreakdownAlertPreviewRow[]+ labels?: string[]+}+interface AlertCheckPreviewInput {calculated_value: number | nullcreated_at: string}+interface DerivedPoint {+ value: number | null+ index: number+}+export function deriveAlertCheckPreviewSeries(checks: AlertCheckPreviewInput[] | undefined,conditionType: AlertConditionType,@@ -32,17 +48,15 @@ export function deriveAlertCheckPreviewSeries(}}-export function deriveTrendsAlertPreviewSeries(+/** One point per interval transition, kept in raw interval order. `index` is the position of the+ * earlier interval. A `null` value marks a percentage change that has no meaning because the+ * earlier interval was zero. */+function deriveRelativePoints(values: number[],- labels: string[] | undefined,conditionType: AlertConditionType,thresholdType: InsightThresholdType-): TrendsAlertPreviewSeries {- if (conditionType === AlertConditionType.ABSOLUTE_VALUE) {- return { values, labels, relative: false }- }-- const derivedPoints = values.slice(1).map((current, index) => {+): DerivedPoint[] {+ return values.slice(1).map((current, index) => {const previous = values[index]const numerator =conditionType === AlertConditionType.RELATIVE_INCREASE ? current - previous : previous - current@@ -54,7 +68,19 @@ export function deriveTrendsAlertPreviewSeries(}return { value: (numerator / previous) * 100, index }})- const availablePoints = derivedPoints.filter(+}++export function deriveTrendsAlertPreviewSeries(+ values: number[],+ labels: string[] | undefined,+ conditionType: AlertConditionType,+ thresholdType: InsightThresholdType+): TrendsAlertPreviewSeries {+ if (conditionType === AlertConditionType.ABSOLUTE_VALUE) {+ return { values, labels, relative: false }+ }++ const availablePoints = deriveRelativePoints(values, conditionType, thresholdType).filter((point): point is { value: number; index: number } => point.value !== null)@@ -64,3 +90,35 @@ export function deriveTrendsAlertPreviewSeries(relative: true,}}++/** The breakdown rows and the one set of labels they all sit on. A relative point compares an+ * interval to the one before it, so it belongs to the later interval and the first raw label names+ * no point. A row without a usable comparison for an interval gets `NaN` there, which the chart+ * draws as a gap. Every row needs the same grid: if each row instead dropped its own unusable+ * comparisons, rows with different numbers of comparisons would put different intervals on the same+ * x position. */+export function deriveTrendsBreakdownAlertPreview(+ series: TrendsBreakdownAlertPreviewRow[] | undefined,+ labels: string[] | undefined,+ conditionType: AlertConditionType,+ thresholdType: InsightThresholdType+): TrendsBreakdownAlertPreview | null {+ if (!series) {+ return null+ }+ const relative = conditionType !== AlertConditionType.ABSOLUTE_VALUE++ return {+ // Trend results declare `data` as a required array, but breakdown rows can arrive without it.+ rows: series+ .filter(({ data }) => Array.isArray(data))+ .map(({ key, label, data }) => ({+ key,+ label,+ data: relative+ ? deriveRelativePoints(data, conditionType, thresholdType).map((point) => point.value ?? NaN)+ : data,+ })),+ labels: relative ? labels?.slice(1) : labels,+ }+}