: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
feat(data-warehouse): register sync alert sub-templates and wizard options (#114383)
Tom Owers6fea217ce58d
diff --git a/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.test.ts b/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.test.tsindex dea2f920b922..cac9980b34fa 100644--- a/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.test.ts+++ b/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.test.ts@@ -1,18 +1,34 @@import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'+import api from 'lib/api'import {HEALTH_ALERT_DESTINATIONS,HEALTH_ALERT_SUB_TEMPLATE_IDS,HEALTH_ALERT_TRIGGERS,} from 'scenes/health-alerts/healthAlertsWizardConfig'+import { HOG_FUNCTION_SUB_TEMPLATES } from 'scenes/hog-functions/sub-templates/sub-templates'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { CyclotronJobFiltersType, PropertyFilterType, PropertyOperator } from '~/types'+import {+ CyclotronJobFilterPropertyFilter,+ CyclotronJobFiltersType,+ PropertyFilterType,+ PropertyOperator,+} from '~/types'-import { alertWizardLogic, applyKindFilter, decorateAlertName, testInvocationFailureMessage } from './alertWizardLogic'+import {+ AlertWizardLogicProps,+ alertWizardLogic,+ applyKindFilter,+ applyPresetFilters,+ buildAlertHogFunctionConfiguration,+ decorateAlertName,+ testInvocationFailureMessage,+} from './alertWizardLogic'describe('alertWizardLogic', () => {describe('applyKindFilter', () => {@@ -76,6 +92,57 @@ describe('alertWizardLogic', () => {})})+ describe('applyPresetFilters', () => {+ const baseFilters: CyclotronJobFiltersType = {+ events: [{ id: '$data_warehouse_sync_failed', type: 'events' }],+ }+ const sourceFilter: CyclotronJobFilterPropertyFilter = {+ key: 'source_id',+ value: ['source-1'],+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+ }++ it.each([+ ['undefined', undefined],+ ['an empty array', [] as CyclotronJobFilterPropertyFilter[]],+ ])('matches applyKindFilter when presetPropertyFilters is %s', (_, preset) => {+ expect(applyPresetFilters(baseFilters, ['job_failed'], preset)).toEqual(+ applyKindFilter(baseFilters, ['job_failed'])+ )+ expect(applyPresetFilters(baseFilters, null, preset)).toBe(baseFilters)+ })++ it.each([+ ['no kinds', null, ['source_id']],+ ['kinds', ['job_failed'], ['kind', 'source_id']],+ ])('merges the preset filters beside %s', (_, kinds, expectedKeys) => {+ const result = applyPresetFilters(baseFilters, kinds, [sourceFilter])+ expect(result?.properties?.map((p) => ('key' in p ? p.key : null))).toEqual(expectedKeys)+ expect(result?.events).toEqual(baseFilters.events)+ })++ it('returns undefined when base filters are undefined', () => {+ expect(applyPresetFilters(undefined, null, [sourceFilter])).toBeUndefined()+ })+ })++ describe('buildAlertHogFunctionConfiguration', () => {+ const base = { templateId: 'template-slack', name: 'n', description: 'd', filters: null, inputs: {} }++ it.each([+ ['omitted', undefined, null],+ ['null', null, null],+ [+ 'set',+ { hash: '{event.properties.schema_id}', ttl: 3600, threshold: null },+ { hash: '{event.properties.schema_id}', ttl: 3600, threshold: null },+ ],+ ])('passes masking through when it is %s', (_, masking, expected) => {+ expect(buildAlertHogFunctionConfiguration({ ...base, masking }).masking).toEqual(expected)+ })+ })+describe('decorateAlertName', () => {const baseName = 'Email when a Health check fires'@@ -97,6 +164,13 @@ describe('alertWizardLogic', () => {)})+ it.each([+ ['without kinds', null, 'Email when a Health check fires for Stripe'],+ ['after the kinds', ['sdk_outdated'], 'Email when a Health check fires (SDK outdated) for Stripe'],+ ])('appends the name suffix %s', (_, kinds, expected) => {+ expect(decorateAlertName(baseName, kinds, 'for Stripe')).toBe(expected)+ })+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)'@@ -104,6 +178,110 @@ describe('alertWizardLogic', () => {})})+ describe('creating an alert', () => {+ const template = { id: 'template-slack', name: 'Slack', code: '', inputs_schema: [] }+ const sourceFilter: CyclotronJobFilterPropertyFilter = {+ key: 'source_id',+ value: ['source-1'],+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+ }+ const healthSlackName = HOG_FUNCTION_SUB_TEMPLATES['health-check-firing'].find(+ (t) => t.template_id === 'template-slack'+ )?.name+ const dwhTriggers = [+ {+ key: 'data-warehouse-sync-completed',+ name: 'Sync completed',+ description: 'A table finished syncing',+ },+ ] as const++ async function createAlert(+ logicProps: Partial<AlertWizardLogicProps>,+ triggerKey: 'health-check-firing' | 'data-warehouse-sync-completed'+ ): Promise<{ payload: Record<string, any>; captureSpy: jest.SpyInstance }> {+ const createSpy = jest.spyOn(api.hogFunctions, 'create').mockResolvedValue({} as any)+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined)+ jest.spyOn(lemonToast, 'success').mockReturnValue('toast-id')++ const logic = alertWizardLogic({+ logicKey: 'create-test',+ subTemplateIds: HEALTH_ALERT_SUB_TEMPLATE_IDS,+ triggers: HEALTH_ALERT_TRIGGERS,+ destinations: HEALTH_ALERT_DESTINATIONS,+ ...logicProps,+ })+ logic.mount()+ logic.actions.setDestinationKey('slack')+ logic.actions.setTriggerKey(triggerKey)+ await expectLogic(logic, () => logic.actions.loadTemplate('template-slack')).toDispatchActions([+ 'loadTemplateSuccess',+ ])+ await expectLogic(logic, () => logic.actions.submitConfiguration()).toDispatchActions([+ 'createAlertSuccess',+ ])+ return { payload: createSpy.mock.calls[0][0] as Record<string, any>, captureSpy }+ }++ beforeEach(() => {+ 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,+ },+ })+ initKeaTests()+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ it('keeps the payload and event name unchanged when no new props are set', async () => {+ const { payload, captureSpy } = await createAlert({ contextId: 'health-alerts' }, 'health-check-firing')++ expect(payload.masking).toBeNull()+ expect(payload.filters.properties).toBeUndefined()+ expect(payload.name).toBe(healthSlackName)+ expect(captureSpy).toHaveBeenCalledWith('error_tracking_alert_created', expect.any(Object))+ })++ it('applies the preset filters, name suffix and event name', async () => {+ const { payload, captureSpy } = await createAlert(+ {+ presetTriggerKinds: ['sdk_outdated'],+ presetPropertyFilters: [sourceFilter],+ nameSuffix: 'for Stripe',+ createdEventName: 'custom_alert_created',+ },+ 'health-check-firing'+ )++ expect(+ payload.filters.properties.map((p: CyclotronJobFilterPropertyFilter) => 'key' in p && p.key)+ ).toEqual(['kind', 'source_id'])+ expect(payload.name).toBe(`${healthSlackName} (SDK outdated) for Stripe`)+ expect(captureSpy).toHaveBeenCalledWith('custom_alert_created', expect.any(Object))+ expect(captureSpy).not.toHaveBeenCalledWith('error_tracking_alert_created', expect.any(Object))+ })++ it('passes the sub-template masking through', async () => {+ const { payload } = await createAlert(+ {+ subTemplateIds: ['data-warehouse-sync-completed'],+ triggers: [...dwhTriggers],+ },+ 'data-warehouse-sync-completed'+ )++ expect(payload.masking).toMatchObject({ ttl: 3600 })+ expect(payload.masking.hash).toContain('event.properties.schema_id')+ })+ })+describe('test invocation results', () => {const errorLog = { level: 'error', message: 'invalid_blocks' }const infoLog = { level: 'info', message: 'done' }diff --git a/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.ts b/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.tsindex ffb251e1da0c..faf308581a45 100644--- a/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.ts+++ b/frontend/src/lib/components/Alerting/AlertWizard/alertWizardLogic.ts@@ -14,6 +14,7 @@ import {} from 'scenes/hog-functions/sub-templates/sub-templates'import {+ CyclotronJobFilterPropertyFilter,CyclotronJobFiltersType,CyclotronJobInputType,CyclotronJobInvocationGlobals,@@ -69,6 +70,14 @@ export interface AlertWizardLogicProps {// to one or more health-check kinds. Pass an empty array to mean "all kinds"// explicitly; omit the prop to leave filters untouched.presetTriggerKinds?: string[]+ // Property filters merged into `filters.properties` of the created HogFunction,+ // after the `kind` filter from `presetTriggerKinds`. Used to scope an alert to+ // one record, for example `source_id = <id>`.+ presetPropertyFilters?: CyclotronJobFilterPropertyFilter[]+ // Text appended to the generated alert name, for example the name of a source.+ nameSuffix?: string+ // Event name sent when an alert is created.+ createdEventName?: string// When set, the "Test" button populates the test event via the matching// SAMPLE_GLOBALS_CONTEXTS loader (real product data) instead of a stub event.contextId?: HogFunctionConfigurationContextId@@ -151,6 +160,21 @@ export function applyKindFilter(}}+export function applyPresetFilters(+ baseFilters: CyclotronJobFiltersType | null | undefined,+ selectedKinds: string[] | null,+ presetPropertyFilters: CyclotronJobFilterPropertyFilter[] | null | undefined+): CyclotronJobFiltersType | null | undefined {+ const withKinds = applyKindFilter(baseFilters, selectedKinds)+ if (!withKinds || !presetPropertyFilters || presetPropertyFilters.length === 0) {+ return withKinds+ }+ return {+ ...withKinds,+ properties: [...(withKinds.properties ?? []), ...presetPropertyFilters],+ }+}+// Renders a selectedKinds list as a short, human-readable parenthetical suffix// (e.g. "(SDK outdated)" or "(SDK outdated, External data failures)") that can// be appended to a sub-template's generic name/description, so the created@@ -163,8 +187,12 @@ function formatKindsSuffix(selectedKinds: string[] | null | undefined): string {return ` (${labels.join(', ')})`}-export function decorateAlertName(baseName: string, selectedKinds: string[] | null | undefined): string {- return `${baseName}${formatKindsSuffix(selectedKinds)}`+export function decorateAlertName(+ baseName: string,+ selectedKinds: string[] | null | undefined,+ nameSuffix?: string+): string {+ return `${baseName}${formatKindsSuffix(selectedKinds)}${nameSuffix ? ` ${nameSuffix}` : ''}`}function lastErrorLogMessage(logs: readonly unknown[]): string | null {@@ -215,7 +243,7 @@ export interface AlertHogFunctionConfiguration {description: stringfilters: CyclotronJobFiltersType | null | undefinedenabled: true- masking: null+ masking: HogFunctionSubTemplateType['masking'] | nullinputs: Record<string, CyclotronJobInputType>}@@ -226,12 +254,14 @@ export function buildAlertHogFunctionConfiguration({description,filters,inputs,+ masking,}: {templateId: stringname: stringdescription: stringfilters: CyclotronJobFiltersType | null | undefinedinputs: Record<string, CyclotronJobInputType>+ masking?: HogFunctionSubTemplateType['masking'] | null}): AlertHogFunctionConfiguration {return {type: 'internal_destination',@@ -240,7 +270,7 @@ export function buildAlertHogFunctionConfiguration({description,filters,enabled: true,- masking: null,+ masking: masking ?? null,inputs,}}@@ -763,7 +793,7 @@ export const alertWizardLogic = kea<alertWizardLogicType>([template_id: destination.templateId,filters: subTemplate.filters,enabled: true,- masking: null,+ masking: subTemplate.masking ?? null,inputs: mergedInputs,inputs_schema: selectedTemplate.inputs_schema,hog: selectedTemplate.code,@@ -798,7 +828,7 @@ export const alertWizardLogic = kea<alertWizardLogicType>([try {globals = await sampleGlobalsLoader(globals,- applyKindFilter(subTemplate.filters, values.selectedKinds)+ applyPresetFilters(subTemplate.filters, values.selectedKinds, logicProps.presetPropertyFilters))} catch {// Fall back to the stub test event@@ -856,8 +886,12 @@ export const alertWizardLogic = kea<alertWizardLogicType>([values.inputValues)- const filters = applyKindFilter(subTemplate.filters, values.selectedKinds)- const name = decorateAlertName(subTemplate.name ?? '', values.selectedKinds)+ const filters = applyPresetFilters(+ subTemplate.filters,+ values.selectedKinds,+ logicProps.presetPropertyFilters+ )+ const name = decorateAlertName(subTemplate.name ?? '', values.selectedKinds, logicProps.nameSuffix)const description = decorateAlertName(subTemplate.description ?? '', values.selectedKinds)const configuration = buildAlertHogFunctionConfiguration({@@ -866,10 +900,12 @@ export const alertWizardLogic = kea<alertWizardLogicType>([description,filters,inputs: mergedInputs,+ masking: subTemplate.masking,})await api.hogFunctions.create(configuration)- posthog.capture('error_tracking_alert_created', {+ // pinned: analytics event name, renaming breaks dashboards+ posthog.capture(logicProps.createdEventName ?? 'error_tracking_alert_created', {ui_source: 'wizard',trigger_event: subTemplate.filters?.events?.[0]?.id ?? null,subtemplate_id: triggerKey,diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex f95ca93f4aff..58d74d7d4a22 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -327,6 +327,7 @@ export const FEATURE_FLAGS = {DROP_PERSON_LIST_ORDER_BY: 'drop-person-list-order-by', // owner: @arthurdedeus #team-customer-analyticsDWH_POSTGRES_CDC: 'dwh-postgres-cdc', // owner: #team-warehouse-sourcesDWH_SOURCE_METRICS: 'dwh-source-metrics', // owner: #team-warehouse-sources+ DWH_SYNC_ALERTS: 'dwh-sync-alerts', // owner: #team-warehouse-sources, gates the data warehouse sync alert sub-templatesEDITOR_DRAFTS: 'editor-drafts', // owner: @EDsCODE #team-data-toolsEMAIL_TEMPLATES_AI_FIRST_NEW: 'email-templates-ai-first-new', // owner: @mayteio #team-workflowsEMOJI_RELATED_SEARCH: 'emoji-related-search', // owner: @pauldambra, gates the model search in `emojiSuggestionsLogic.ts` when the emoji picker finds no matchdiff --git a/frontend/src/scenes/hog-functions/configuration/sampleGlobalsContexts.ts b/frontend/src/scenes/hog-functions/configuration/sampleGlobalsContexts.tsindex 74b118adb9bf..380d638748e9 100644--- a/frontend/src/scenes/hog-functions/configuration/sampleGlobalsContexts.ts+++ b/frontend/src/scenes/hog-functions/configuration/sampleGlobalsContexts.ts@@ -88,4 +88,29 @@ export const SAMPLE_GLOBALS_CONTEXTS: Partial<Record<HogFunctionConfigurationCon},},}),+ // The templates read these fields. An empty value renders an empty Slack block, and Slack rejects+ // the whole message.+ 'data-warehouse-alerts': async (exampleGlobals) => ({+ ...exampleGlobals,+ event: {+ ...exampleGlobals.event,+ properties: {+ source_id: '00000000-0000-4000-8000-000000000001',+ source_type: 'Stripe',+ source_prefix: 'stripe_',+ schema_id: '00000000-0000-4000-8000-000000000002',+ schema_name: 'charges',+ job_id: '00000000-0000-4000-8000-000000000003',+ status: 'Failed',+ kind: 'job_failed',+ error: 'This is a test alert from PostHog',+ rows_synced: 1200,+ paused: false,+ failed_runs_in_a_row: 1,+ source_url: 'https://example.com/data-warehouse/sources/00000000-0000-4000-8000-000000000001',+ schema_url: 'https://example.com/data-warehouse/sources/00000000-0000-4000-8000-000000000001/charges',+ finished_at: '2026-01-01T00:00:00.000Z',+ },+ },+ }),}diff --git a/frontend/src/scenes/hog-functions/filters/HogFunctionFiltersInternal.tsx b/frontend/src/scenes/hog-functions/filters/HogFunctionFiltersInternal.tsxindex 1d9f63aae55e..925f741d60ff 100644--- a/frontend/src/scenes/hog-functions/filters/HogFunctionFiltersInternal.tsx+++ b/frontend/src/scenes/hog-functions/filters/HogFunctionFiltersInternal.tsx@@ -40,10 +40,12 @@ const setSimpleFilterValue = (],}// Preserve properties bound by Logs alerting (alert_id) and batch export alerts- // (batch_export_id) — the trigger event id changes between the context's events, but the+ // (batch_export_id), and data warehouse alerts (source_id) — the trigger event id changes between the context's events, but the// binding to the parent resource must survive.if (- (contextId === 'logs-alerting' || contextId === 'batch-export-alerts') &&+ (contextId === 'logs-alerting' ||+ contextId === 'batch-export-alerts' ||+ contextId === 'data-warehouse-alerts') &&previous?.properties &&previous.properties.length > 0) {@@ -79,7 +81,7 @@ export function HogFunctionFiltersInternal(): JSX.Element {return [TaxonomicFilterGroupType.EventProperties]} else if (contextId === 'health-alerts') {return [TaxonomicFilterGroupType.EventProperties]- } else if (contextId === 'batch-export-alerts') {+ } else if (contextId === 'batch-export-alerts' || contextId === 'data-warehouse-alerts') {return [TaxonomicFilterGroupType.EventProperties]}return []diff --git a/frontend/src/scenes/hog-functions/filters/productEventFilterOptions.ts b/frontend/src/scenes/hog-functions/filters/productEventFilterOptions.tsindex 515757fa3363..9589443de010 100644--- a/frontend/src/scenes/hog-functions/filters/productEventFilterOptions.ts+++ b/frontend/src/scenes/hog-functions/filters/productEventFilterOptions.ts@@ -103,6 +103,13 @@ export const getProductEventFilterOptions = (contextId: HogFunctionConfigurationvalue: '$batch_export_run_failed',},]+ case 'data-warehouse-alerts':+ return [+ { label: 'Sync failed', value: '$data_warehouse_sync_failed' },+ { label: 'Sync recovered', value: '$data_warehouse_sync_recovered' },+ { label: 'Sync completed', value: '$data_warehouse_sync_completed' },+ { label: 'Billing limit reached', value: '$data_warehouse_billing_limit_reached' },+ ]default:return [{diff --git a/frontend/src/scenes/hog-functions/list/HogFunctionsList.tsx b/frontend/src/scenes/hog-functions/list/HogFunctionsList.tsxindex d4379550d3d1..2f49e8f3972c 100644--- a/frontend/src/scenes/hog-functions/list/HogFunctionsList.tsx+++ b/frontend/src/scenes/hog-functions/list/HogFunctionsList.tsx@@ -60,6 +60,7 @@ const INTERNAL_DESTINATION_CONTEXT: Partial<},'batch-export-alerts': { label: 'Batch export alerts' },'billing-alerts': { label: 'Billing alerts' },+ 'data-warehouse-alerts': { label: 'Data warehouse alerts', url: urls.sources() },'replay-vision-alerts': { label: 'Replay vision alerts' },}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 870d9c109251..f1df4bbc4593 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@@ -17,6 +17,10 @@ describe('sub-templates', () => {['$logs_alert_firing', 'logs-alerting'],['$health_check_issue_firing', 'health-alerts'],['$batch_export_run_failed', 'batch-export-alerts'],+ ['$data_warehouse_sync_failed', 'data-warehouse-alerts'],+ ['$data_warehouse_sync_recovered', 'data-warehouse-alerts'],+ ['$data_warehouse_sync_completed', 'data-warehouse-alerts'],+ ['$data_warehouse_billing_limit_reached', 'data-warehouse-alerts'],['$billing_alert_firing', 'billing-alerts'],['$replay_vision_alert_match', 'replay-vision-alerts'],['$pageview', 'standard'],@@ -27,10 +31,17 @@ describe('sub-templates', () => {// 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']!({+ it.each([+ ['health-alerts', 'health-check-firing'],+ ['health-alerts', 'health-check-resolved'],+ ['data-warehouse-alerts', 'data-warehouse-sync-failed'],+ ['data-warehouse-alerts', 'data-warehouse-sync-recovered'],+ ['data-warehouse-alerts', 'data-warehouse-sync-completed'],+ ['data-warehouse-alerts', 'data-warehouse-billing-limit-reached'],+ ] as const)(+ 'gives the %s sample event a value for every property the %s templates read',+ async (contextId, subTemplateId) => {+ const sample = await SAMPLE_GLOBALS_CONTEXTS[contextId]!({event: { properties: {} },} as CyclotronJobInvocationGlobals)const inputs = JSON.stringify(HOG_FUNCTION_SUB_TEMPLATES[subTemplateId].map((template) => template.inputs))diff --git a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.tsindex cc35c96071bd..66c15756374e 100644--- a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts+++ b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts@@ -80,6 +80,12 @@ const BATCH_EXPORT_ALERT_MASKING_TTL_SECONDS = 60 * 60const BATCH_EXPORT_ALERT_MASKING_HASH ="{event.properties.batch_export_id ? event.properties.batch_export_id : 'unknown-batch-export'}"+// A sync that runs every few minutes would post a message per run, so limit each table to one+// completed-sync message per hour. HogMaskerService skips masking on falsy hashes, so fall back+// defensively.+const DWH_SYNC_COMPLETED_MASKING_TTL_SECONDS = 60 * 60+const DWH_SYNC_COMPLETED_MASKING_HASH = "{event.properties.schema_id ? event.properties.schema_id : 'unknown-table'}"+// The page a rageclick happened on: $pathname when posthog-js set it, else the full URL.const PA_RAGECLICK_PAGE_EXPR = 'event.properties.$pathname ? event.properties.$pathname : event.properties.$current_url'@@ -254,6 +260,42 @@ export const HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES: Record<},flag: FEATURE_FLAGS.BATCH_EXPORT_ALERTS,},+ 'data-warehouse-sync-failed': {+ sub_template_id: 'data-warehouse-sync-failed',+ type: 'internal_destination',+ context_id: 'data-warehouse-alerts',+ filters: { source: 'internal-events', events: [{ id: '$data_warehouse_sync_failed', type: 'events' }] },+ flag: FEATURE_FLAGS.DWH_SYNC_ALERTS,+ },+ 'data-warehouse-sync-recovered': {+ sub_template_id: 'data-warehouse-sync-recovered',+ type: 'internal_destination',+ context_id: 'data-warehouse-alerts',+ filters: { source: 'internal-events', events: [{ id: '$data_warehouse_sync_recovered', type: 'events' }] },+ flag: FEATURE_FLAGS.DWH_SYNC_ALERTS,+ },+ 'data-warehouse-sync-completed': {+ sub_template_id: 'data-warehouse-sync-completed',+ type: 'internal_destination',+ context_id: 'data-warehouse-alerts',+ filters: { source: 'internal-events', events: [{ id: '$data_warehouse_sync_completed', type: 'events' }] },+ masking: {+ hash: DWH_SYNC_COMPLETED_MASKING_HASH,+ ttl: DWH_SYNC_COMPLETED_MASKING_TTL_SECONDS,+ threshold: null,+ },+ flag: FEATURE_FLAGS.DWH_SYNC_ALERTS,+ },+ 'data-warehouse-billing-limit-reached': {+ sub_template_id: 'data-warehouse-billing-limit-reached',+ type: 'internal_destination',+ context_id: 'data-warehouse-alerts',+ filters: {+ source: 'internal-events',+ events: [{ id: '$data_warehouse_billing_limit_reached', type: 'events' }],+ },+ flag: FEATURE_FLAGS.DWH_SYNC_ALERTS,+ },}const FLAG_ACTOR_NAME = "{event.properties.user.first_name ? event.properties.user.first_name : 'PostHog'}"@@ -629,6 +671,53 @@ function notificationVariants({const BATCH_EXPORT_NAME_SLACK = `{${slackEscapeExpr('event.properties.batch_export_name')}}`const BATCH_EXPORT_ERROR_SLACK = `{${slackEscapeExpr('event.properties.error', 1000)}}`+// source_type, schema_name and error come from the source system, so they get the same escaping and+// bounds as the other producer-controlled notification fields.+interface DwhMessageFields {+ sourceType: string+ table: string+ error: string+}++const DWH_SLACK_FIELDS: DwhMessageFields = {+ sourceType: `{${slackEscapeExpr('event.properties.source_type', 100)}}`,+ table: `{${slackEscapeExpr('event.properties.schema_name', 200)}}`,+ error: `{${slackEscapeExpr('event.properties.error', 1000)}}`,+}+const DWH_MARKDOWN_FIELDS: DwhMessageFields = {+ sourceType: `{${markdownEscapeExpr('event.properties.source_type', 100)}}`,+ table: `{${markdownEscapeExpr('event.properties.schema_name', 200)}}`,+ error: `{${markdownEscapeExpr('event.properties.error', 1000)}}`,+}++const DWH_TABLE_URL = '{event.properties.schema_url}'+const DWH_SOURCE_URL = '{event.properties.source_url}'+const DWH_MARKDOWN_TABLE_LINK = `[View table](${DWH_TABLE_URL})`+const DWH_MARKDOWN_SOURCE_LINK = `[View source](${DWH_SOURCE_URL})`++function dwhSyncFailedMessage(fields: DwhMessageFields, bold: string): string {+ return (+ `${bold}Sync failed${bold} for table ${bold}${fields.table}${bold} from ${fields.sourceType}.` ++ `{event.properties.paused ? ' The table is paused.' : ''}\n` ++ `${bold}Error:${bold} ${fields.error}`+ )+}++function dwhSyncRecoveredMessage(fields: DwhMessageFields, bold: string): string {+ return `Table ${bold}${fields.table}${bold} from ${fields.sourceType} is syncing again.`+}++function dwhSyncCompletedMessage(fields: DwhMessageFields, bold: string): string {+ return `Table ${bold}${fields.table}${bold} from ${fields.sourceType} finished a sync. Rows synced: {event.properties.rows_synced}.`+}++function dwhBillingLimitMessage(fields: DwhMessageFields, bold: string): string {+ return (+ `{event.properties.kind == 'too_low' ? 'The billing limit is too low to sync' : 'The billing limit was reached, so this sync did not run for'} ` ++ `table ${bold}${fields.table}${bold} from ${fields.sourceType}.`+ )+}+export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, HogFunctionSubTemplateType[]> = {'mcp-tool-error': notificationVariants({subTemplateId: 'mcp-tool-error',@@ -640,6 +729,46 @@ export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, HomarkdownMessage: `${MCP_TOOL_ERROR_MARKDOWN_MESSAGE}\n\n${MCP_TOOL_ERROR_LINK}`,slackButton: { url: MCP_TOOL_ERROR_LINK, label: MCP_NOTIFICATION_BUTTON_LABELS['mcp-tool-error'] },}),+ 'data-warehouse-sync-failed': notificationVariants({+ subTemplateId: 'data-warehouse-sync-failed',+ nameSuffix: 'when a table sync fails',+ description: 'Know when a table stops syncing and why',+ webhookDescription: 'Send failed table syncs to your own endpoint',+ slackMessage: dwhSyncFailedMessage(DWH_SLACK_FIELDS, '*'),+ slackFallbackText: 'A table sync failed',+ markdownMessage: `${dwhSyncFailedMessage(DWH_MARKDOWN_FIELDS, '**')}\n\n${DWH_MARKDOWN_TABLE_LINK}`,+ slackButton: { url: DWH_TABLE_URL, label: 'View table' },+ }),+ 'data-warehouse-sync-recovered': notificationVariants({+ subTemplateId: 'data-warehouse-sync-recovered',+ nameSuffix: 'when a table sync recovers',+ description: 'Know when a table that failed is syncing again',+ webhookDescription: 'Send recovered table syncs to your own endpoint',+ slackMessage: dwhSyncRecoveredMessage(DWH_SLACK_FIELDS, '*'),+ slackFallbackText: 'A table sync recovered',+ markdownMessage: `${dwhSyncRecoveredMessage(DWH_MARKDOWN_FIELDS, '**')}\n\n${DWH_MARKDOWN_TABLE_LINK}`,+ slackButton: { url: DWH_TABLE_URL, label: 'View table' },+ }),+ 'data-warehouse-sync-completed': notificationVariants({+ subTemplateId: 'data-warehouse-sync-completed',+ nameSuffix: 'when a table sync completes',+ description: 'Know when a table finishes syncing, at most once an hour for each table',+ webhookDescription: 'Send completed table syncs to your own endpoint',+ slackMessage: dwhSyncCompletedMessage(DWH_SLACK_FIELDS, '*'),+ slackFallbackText: 'A table sync completed',+ markdownMessage: `${dwhSyncCompletedMessage(DWH_MARKDOWN_FIELDS, '**')}\n\n${DWH_MARKDOWN_TABLE_LINK}`,+ slackButton: { url: DWH_TABLE_URL, label: 'View table' },+ }),+ 'data-warehouse-billing-limit-reached': notificationVariants({+ subTemplateId: 'data-warehouse-billing-limit-reached',+ nameSuffix: 'when the billing limit stops a sync',+ description: 'Know when the data warehouse billing limit stops a table from syncing',+ webhookDescription: 'Send billing limit events to your own endpoint',+ slackMessage: dwhBillingLimitMessage(DWH_SLACK_FIELDS, '*'),+ slackFallbackText: 'The billing limit stopped a table sync',+ markdownMessage: `${dwhBillingLimitMessage(DWH_MARKDOWN_FIELDS, '**')}\n\n${DWH_MARKDOWN_SOURCE_LINK}`,+ slackButton: { url: DWH_SOURCE_URL, label: 'View source' },+ }),'pa-rageclick': notificationVariants({subTemplateId: 'pa-rageclick',nameSuffix: 'when users rage click',@@ -1744,6 +1873,11 @@ export const eventToHogFunctionContextId = (event: string | undefined): HogFunctreturn 'health-alerts'case '$batch_export_run_failed':return 'batch-export-alerts'+ case '$data_warehouse_sync_failed':+ case '$data_warehouse_sync_recovered':+ case '$data_warehouse_sync_completed':+ case '$data_warehouse_billing_limit_reached':+ return 'data-warehouse-alerts'case '$billing_alert_firing':case '$billing_alert_resolved':case '$billing_alert_errored':diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 2a4cc8e58be9..b52e19d4088c 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -7519,6 +7519,7 @@ export type HogFunctionConfigurationContextId =| 'batch-export-alerts'| 'billing-alerts'| 'replay-vision-alerts'+ | 'data-warehouse-alerts'export type HogFunctionSubTemplateIdType =| 'early-access-feature-enrollment'@@ -7540,6 +7541,10 @@ export type HogFunctionSubTemplateIdType =| 'health-check-firing'| 'health-check-resolved'| 'batch-export-run-failed'+ | 'data-warehouse-sync-failed'+ | 'data-warehouse-sync-recovered'+ | 'data-warehouse-sync-completed'+ | 'data-warehouse-billing-limit-reached'export type HogFunctionConfigurationType = Omit<HogFunctionType,