: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): report failed test alerts and send health sample data (#111807)
Daniel RC66b3fbb8bf68
diff --git a/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.test.ts b/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.test.tsindex d2f260d44286..dea2f920b922 100644--- a/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.test.ts+++ b/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.test.ts@@ -1,92 +1,184 @@-import { CyclotronJobFiltersType, PropertyFilterType, PropertyOperator } from '~/types'+import { expectLogic } from 'kea-test-utils'-import { applyKindFilter, decorateAlertName } from './alertWizardLogic'+import { lemonToast } from '@posthog/lemon-ui'-describe('applyKindFilter', () => {- const baseFilters: CyclotronJobFiltersType = {- events: [{ id: '$health_check_issue_firing', type: 'events' }],- }+import {+ HEALTH_ALERT_DESTINATIONS,+ HEALTH_ALERT_SUB_TEMPLATE_IDS,+ HEALTH_ALERT_TRIGGERS,+} from 'scenes/health-alerts/healthAlertsWizardConfig'- it.each([- ['null', null],- ['an empty array', [] as string[]],- ])('returns filters unchanged when selectedKinds is %s', (_, kinds) => {- expect(applyKindFilter(baseFilters, kinds)).toBe(baseFilters)- })+import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { CyclotronJobFiltersType, PropertyFilterType, PropertyOperator } from '~/types'- it('returns undefined when base filters are undefined', () => {- expect(applyKindFilter(undefined, ['sdk_outdated'])).toBeUndefined()- })+import { alertWizardLogic, applyKindFilter, decorateAlertName, testInvocationFailureMessage } from './alertWizardLogic'++describe('alertWizardLogic', () => {+ describe('applyKindFilter', () => {+ const baseFilters: CyclotronJobFiltersType = {+ events: [{ id: '$health_check_issue_firing', type: 'events' }],+ }- it('adds a top-level kind IN (...) property filter', () => {- const result = applyKindFilter(baseFilters, ['sdk_outdated', 'ingestion_warning'])- expect(result?.events?.[0]).toEqual({- id: '$health_check_issue_firing',- type: 'events',+ it.each([+ ['null', null],+ ['an empty array', [] as string[]],+ ])('returns filters unchanged when selectedKinds is %s', (_, kinds) => {+ expect(applyKindFilter(baseFilters, kinds)).toBe(baseFilters)})- expect(result?.properties).toEqual([- {- key: 'kind',- value: ['sdk_outdated', 'ingestion_warning'],- operator: PropertyOperator.Exact,- type: PropertyFilterType.Event,- },- ])- })- it('replaces any existing top-level properties', () => {- const withProps: CyclotronJobFiltersType = {- ...baseFilters,- properties: [+ it('returns undefined when base filters are undefined', () => {+ expect(applyKindFilter(undefined, ['sdk_outdated'])).toBeUndefined()+ })++ it('adds a top-level kind IN (...) property filter', () => {+ const result = applyKindFilter(baseFilters, ['sdk_outdated', 'ingestion_warning'])+ expect(result?.events?.[0]).toEqual({+ id: '$health_check_issue_firing',+ type: 'events',+ })+ expect(result?.properties).toEqual([{- key: 'some_other',- value: 'x',+ key: 'kind',+ value: ['sdk_outdated', 'ingestion_warning'],operator: PropertyOperator.Exact,type: PropertyFilterType.Event,},- ],- }- const result = applyKindFilter(withProps, ['sdk_outdated'])- expect(result?.properties).toHaveLength(1)- expect(result?.properties?.[0].key).toBe('kind')- })+ ])+ })- it('leaves events untouched', () => {- const twoEvents: CyclotronJobFiltersType = {- events: [- { id: '$health_check_issue_firing', type: 'events' },- { id: '$other_event', type: 'events' },- ],- }- const result = applyKindFilter(twoEvents, ['sdk_outdated'])- expect(result?.events).toEqual(twoEvents.events)+ it('replaces any existing top-level properties', () => {+ const withProps: CyclotronJobFiltersType = {+ ...baseFilters,+ properties: [+ {+ key: 'some_other',+ value: 'x',+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+ },+ ],+ }+ const result = applyKindFilter(withProps, ['sdk_outdated'])+ expect(result?.properties).toHaveLength(1)+ expect(result?.properties?.[0].key).toBe('kind')+ })++ it('leaves events untouched', () => {+ const twoEvents: CyclotronJobFiltersType = {+ events: [+ { id: '$health_check_issue_firing', type: 'events' },+ { id: '$other_event', type: 'events' },+ ],+ }+ const result = applyKindFilter(twoEvents, ['sdk_outdated'])+ expect(result?.events).toEqual(twoEvents.events)+ })})-})-describe('decorateAlertName', () => {- const baseName = 'Email when a Health check fires'+ describe('decorateAlertName', () => {+ const baseName = 'Email when a Health check fires'- it.each([- ['null', null],- ['undefined', undefined],- ['an empty array', [] as string[]],- ])('returns the base name unchanged when selectedKinds is %s', (_, kinds) => {- expect(decorateAlertName(baseName, kinds)).toBe(baseName)- })+ it.each([+ ['null', null],+ ['undefined', undefined],+ ['an empty array', [] as string[]],+ ])('returns the base name unchanged when selectedKinds is %s', (_, kinds) => {+ expect(decorateAlertName(baseName, kinds)).toBe(baseName)+ })- it('appends a single kind label in parens', () => {- expect(decorateAlertName(baseName, ['sdk_outdated'])).toBe('Email when a Health check fires (SDK outdated)')- })+ it('appends a single kind label in parens', () => {+ expect(decorateAlertName(baseName, ['sdk_outdated'])).toBe('Email when a Health check fires (SDK outdated)')+ })++ it('joins multiple kind labels with commas', () => {+ expect(decorateAlertName(baseName, ['external_data_failure', 'materialized_view_failure'])).toBe(+ 'Email when a Health check fires (External data failures, Materialized view failure)'+ )+ })- it('joins multiple kind labels with commas', () => {- expect(decorateAlertName(baseName, ['external_data_failure', 'materialized_view_failure'])).toBe(- 'Email when a Health check fires (External data failures, Materialized view failure)'- )+ it('falls back to the raw kind when no label is registered', () => {+ expect(decorateAlertName(baseName, ['some_future_kind'])).toBe(+ 'Email when a Health check fires (some_future_kind)'+ )+ })})- it('falls back to the raw kind when no label is registered', () => {- expect(decorateAlertName(baseName, ['some_future_kind'])).toBe(- 'Email when a Health check fires (some_future_kind)'- )+ describe('test invocation results', () => {+ const errorLog = { level: 'error', message: 'invalid_blocks' }+ const infoLog = { level: 'info', message: 'done' }++ it.each([+ ['a delivered test', { status: 'success', logs: [infoLog] }, null],+ ['a rejected test', { status: 'error', logs: [errorLog, infoLog] }, 'Test failed: invalid_blocks'],+ [+ 'a rejected test with no error log',+ { status: 'error', logs: [infoLog] },+ 'Test failed. Check the destination settings and try again.',+ ],+ [+ 'a test whose inputs failed to build',+ { status: 'skipped', logs: [errorLog] },+ 'Test failed: invalid_blocks',+ ],+ [+ 'a filtered-out test event',+ { status: 'skipped', logs: [infoLog] },+ "Test not sent. The test event didn't match this alert's filters.",+ ],+ ])('reads %s', (_, result, expected) => {+ expect(testInvocationFailureMessage(result)).toBe(expected)+ })++ it.each([+ [+ 'an error toast for a rejected test',+ { status: 'error', logs: [errorLog] },+ 'error',+ 'Test failed: invalid_blocks',+ ],+ [+ 'a success toast for a delivered test',+ { status: 'success', logs: [] },+ 'success',+ 'Test invocation sent',+ ],+ ] as const)('shows %s', async (_, result, toast, message) => {+ const template = { id: 'template-slack', name: 'Slack', code: '', inputs_schema: [] }+ useMocks({+ get: {+ '/api/environments/:team_id/hog_functions/': { count: 0, results: [] },+ '/api/projects/:team_id/hog_functions/': { count: 0, results: [] },+ '/api/environments/:team_id/hog_function_templates/template-slack/': template,+ '/api/projects/:team_id/hog_function_templates/template-slack/': template,+ },+ post: {+ '/api/projects/:team_id/hog_functions/new/invocations/': result,+ '/api/environments/:team_id/hog_functions/new/invocations/': result,+ },+ })+ initKeaTests()+ const toastSpy = jest.spyOn(lemonToast, toast).mockReturnValue('toast-id')++ const logic = alertWizardLogic({+ logicKey: 'test',+ subTemplateIds: HEALTH_ALERT_SUB_TEMPLATE_IDS,+ triggers: HEALTH_ALERT_TRIGGERS,+ destinations: HEALTH_ALERT_DESTINATIONS,+ contextId: 'health-alerts',+ })+ logic.mount()+ logic.actions.setDestinationKey('slack')+ logic.actions.setTriggerKey('health-check-firing')+ await expectLogic(logic, () => logic.actions.loadTemplate('template-slack')).toDispatchActions([+ 'loadTemplateSuccess',+ ])+ await expectLogic(logic, () => logic.actions.testConfiguration()).toDispatchActions([+ 'testConfigurationComplete',+ ])++ expect(toastSpy).toHaveBeenCalledWith(message)+ toastSpy.mockRestore()+ })})})diff --git a/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.ts b/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.tsindex b2caa3459e8d..ffb251e1da0c 100644--- a/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.ts+++ b/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.ts@@ -5,7 +5,7 @@ import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'-import api from 'lib/api'+import api, { ApiConfig } from 'lib/api'import { HealthIssueKind, KIND_LABELS } from 'scenes/health/healthCategories'import { SAMPLE_GLOBALS_CONTEXTS } from 'scenes/hog-functions/configuration/sampleGlobalsContexts'import {@@ -25,6 +25,9 @@ import {PropertyOperator,} from '~/types'+import { hogFunctionsInvocationsCreate } from 'products/cdp/frontend/generated/api'+import type { HogFunctionApi, HogFunctionInvocationApi } from 'products/cdp/frontend/generated/api.schemas'+import type { CyclotronJobInputSchemaType, HogFunctionSubTemplateType } from '../../../../types'export enum WizardStep {@@ -164,6 +167,33 @@ export function decorateAlertName(baseName: string, selectedKinds: string[] | nureturn `${baseName}${formatKindsSuffix(selectedKinds)}`}+function lastErrorLogMessage(logs: readonly unknown[]): string | null {+ for (const entry of [...logs].reverse()) {+ const { level, message } = (entry ?? {}) as { level?: unknown; message?: unknown }+ if (typeof level === 'string' && level.toLowerCase() === 'error' && typeof message === 'string') {+ return message+ }+ }+ return null+}++// The test endpoint answers HTTP 200 when the destination rejects the message, and reports the+// rejection in the logs. Returns the message to show, or null when the test went through.+// A skipped result covers two cases: the filters excluded the event, or the inputs failed to+// build. Only the second case writes an error log.+export function testInvocationFailureMessage(result: Pick<HogFunctionInvocationApi, 'status' | 'logs'>): string | null {+ if (result.status === 'success') {+ return null+ }+ const reason = lastErrorLogMessage(result.logs)+ if (reason) {+ return `Test failed: ${reason}`+ }+ return result.status === 'skipped'+ ? "Test not sent. The test event didn't match this alert's filters."+ : 'Test failed. Check the destination settings and try again.'+}+export function buildAlertInputs(inputsSchema: CyclotronJobInputSchemaType[] | null | undefined,subTemplateInputs: Record<string, CyclotronJobInputType> | null | undefined,@@ -766,20 +796,28 @@ export const alertWizardLogic = kea<alertWizardLogicType>([const sampleGlobalsLoader = logicProps.contextId ? SAMPLE_GLOBALS_CONTEXTS[logicProps.contextId] : undefinedif (sampleGlobalsLoader) {try {- globals = await sampleGlobalsLoader(globals)+ globals = await sampleGlobalsLoader(+ globals,+ applyKindFilter(subTemplate.filters, values.selectedKinds)+ )} catch {// Fall back to the stub test event}}try {- await api.hogFunctions.createTestInvocation('new', {- configuration,+ const result = await hogFunctionsInvocationsCreate(String(ApiConfig.getCurrentTeamId()), 'new', {+ configuration: configuration as HogFunctionApi,globals,mock_async_functions: false,})breakpoint()- lemonToast.success('Test invocation sent')+ const failure = testInvocationFailureMessage(result)+ if (failure) {+ lemonToast.error(failure)+ } else {+ lemonToast.success('Test invocation sent')+ }} catch (e: any) {breakpoint()lemonToast.error(e.detail || 'Test invocation failed')diff --git a/frontend/src/scenes/health-alerts/HealthAlertsEntryPoint.tsx b/frontend/src/scenes/health-alerts/HealthAlertsEntryPoint.tsxindex df6eee3924ef..aa030b85851e 100644--- a/frontend/src/scenes/health-alerts/HealthAlertsEntryPoint.tsx+++ b/frontend/src/scenes/health-alerts/HealthAlertsEntryPoint.tsx@@ -48,6 +48,7 @@ export function HealthAlertsEntryPoint({triggers: HEALTH_ALERT_TRIGGERS,destinations: HEALTH_ALERT_DESTINATIONS,presetTriggerKinds: presetKinds,+ contextId: 'health-alerts',}return (diff --git a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsxindex 2f40f57e29c6..3b2bb13f556f 100644--- a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx+++ b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx@@ -1144,7 +1144,10 @@ export const hogFunctionConfigurationLogic = kea<hogFunctionConfigurationLogicTyconst sampleGlobalsLoader = SAMPLE_GLOBALS_CONTEXTS[values.contextId]if (sampleGlobalsLoader) {try {- const globals = await sampleGlobalsLoader(values.exampleInvocationGlobals)+ const globals = await sampleGlobalsLoader(+ values.exampleInvocationGlobals,+ values.configuration?.filters+ )breakpoint()return globals} catch (e: any) {diff --git a/frontend/src/scenes/hog-functions/configuration/sampleGlobalsContexts.ts b/frontend/src/scenes/hog-functions/configuration/sampleGlobalsContexts.tsindex 2cd500d6caac..74b118adb9bf 100644--- a/frontend/src/scenes/hog-functions/configuration/sampleGlobalsContexts.ts+++ b/frontend/src/scenes/hog-functions/configuration/sampleGlobalsContexts.ts@@ -1,6 +1,11 @@import { ApiConfig } from 'lib/api'-import { CyclotronJobInvocationGlobals, HogFunctionConfigurationContextId } from '~/types'+import {+ CyclotronJobFiltersType,+ CyclotronJobInvocationGlobals,+ HogFunctionConfigurationContextId,+ PropertyOperator,+} from '~/types'import {errorTrackingFingerprintsList,@@ -8,9 +13,26 @@ import {} from 'products/error_tracking/frontend/generated/api'export type SampleGlobalsLoader = (- exampleGlobals: CyclotronJobInvocationGlobals+ exampleGlobals: CyclotronJobInvocationGlobals,+ filters?: CyclotronJobFiltersType | null) => Promise<CyclotronJobInvocationGlobals>+// An alert scoped to some health check kinds skips an event of any other kind, so the sample+// takes a kind the filters accept. Only an exact-match filter names an accepted kind. Any other+// operator, such as "is not", names kinds the alert excludes.+function sampleHealthCheckKind(filters?: CyclotronJobFiltersType | null): string {+ const kindFilter = filters?.properties?.find(+ (property) =>+ 'key' in property &&+ property.key === 'kind' &&+ 'operator' in property &&+ property.operator === PropertyOperator.Exact+ )+ const value = kindFilter && 'value' in kindFilter ? kindFilter.value : null+ const kind = Array.isArray(value) ? value[0] : value+ return typeof kind === 'string' && kind ? kind : 'test'+}+/*** Per-context overrides for the "load sample globals" flow in the hog function test panel.* Contexts without an entry load the last event matching the configured filters.@@ -48,4 +70,22 @@ export const SAMPLE_GLOBALS_CONTEXTS: Partial<Record<HogFunctionConfigurationCon},}},+ // Health alert templates read only this envelope. An empty title or summary renders an empty+ // Slack block, and Slack rejects the whole message.+ 'health-alerts': async (exampleGlobals, filters) => ({+ ...exampleGlobals,+ event: {+ ...exampleGlobals.event,+ properties: {+ kind: sampleHealthCheckKind(filters),+ severity: 'warning',+ issue_id: 'test-issue-id',+ title: 'Test health check',+ summary: 'This is a test alert from PostHog',+ link: '/health',+ remediation: null,+ payload: {},+ },+ },+ }),}diff --git a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.test.ts b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.test.tsindex 787e39f3d45d..870d9c109251 100644--- a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.test.ts+++ b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.test.ts@@ -1,4 +1,8 @@-import { eventToHogFunctionContextId } from './sub-templates'+import { SAMPLE_GLOBALS_CONTEXTS } from 'scenes/hog-functions/configuration/sampleGlobalsContexts'++import { CyclotronJobInvocationGlobals, PropertyFilterType, PropertyOperator } from '~/types'++import { HOG_FUNCTION_SUB_TEMPLATES, eventToHogFunctionContextId } from './sub-templates'describe('sub-templates', () => {// One event per product that creates internal destinations. An id missing from the switch@@ -20,4 +24,47 @@ describe('sub-templates', () => {])('reads %s as the %s context', (event, expected) => {expect(eventToHogFunctionContextId(event)).toBe(expected)})++ // A placeholder the sample event leaves empty renders an empty Slack block. Slack then rejects+ // the whole test message.+ it.each(['health-check-firing', 'health-check-resolved'] as const)(+ 'gives the %s templates a sample value for every event property they read',+ async (subTemplateId) => {+ const sample = await SAMPLE_GLOBALS_CONTEXTS['health-alerts']!({+ event: { properties: {} },+ } as CyclotronJobInvocationGlobals)+ const inputs = JSON.stringify(HOG_FUNCTION_SUB_TEMPLATES[subTemplateId].map((template) => template.inputs))+ const readProperties = new Set([...inputs.matchAll(/event\.properties\.(\w+)/g)].map((match) => match[1]))++ expect(readProperties.size).toBeGreaterThan(0)+ for (const property of readProperties) {+ expect([property, sample.event.properties[property] ?? '']).not.toEqual([property, ''])+ }+ }+ )++ // An alert scoped to some kinds skips a sample event of any other kind, so its test sends nothing.+ it.each([+ ['the first kind of an exact kind filter', PropertyOperator.Exact, 'external_data_failure'],+ ['a placeholder kind for a filter that excludes kinds', PropertyOperator.IsNot, 'test'],+ ['a placeholder kind with no kind filter', null, 'test'],+ ])('gives the health sample event %s', async (_, operator, expected) => {+ const sample = await SAMPLE_GLOBALS_CONTEXTS['health-alerts']!(+ { event: { properties: {} } } as CyclotronJobInvocationGlobals,+ {+ events: [{ id: '$health_check_issue_firing', type: 'events' }],+ properties: operator+ ? [+ {+ key: 'kind',+ value: ['external_data_failure', 'sdk_outdated'],+ operator,+ type: PropertyFilterType.Event,+ },+ ]+ : [],+ }+ )+ expect(sample.event.properties.kind).toBe(expected)+ })})