: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(batch-exports): Add Slack notifications for batch exports (#82598)
Tomás Farías Santana85f01e2848ac
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex d5895389ba72..a7ec588ac9ce 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -187,6 +187,7 @@ export const FEATURE_FLAGS = {AI_OBSERVABILITY_SELF_DRIVING: 'ai-observability-daily-digest-scout', // owner: #team-ai-observability, gates the AI observability Self-driving tabAI_TRAINING: 'ai-training', // owner: @nicowaltz #team-replay #ai-research, gates the AI training opt-out UI and API enforcementAUDIT_LOGS_ACCESS: 'audit-logs-access', // owner: #team-platform-features, used to control access to audit logs+ BATCH_EXPORT_ALERTS: 'batch-export-alerts', // owner: #team-batch-exportsBATCH_EXPORT_EARLIEST_BACKFILL: 'batch-export-earliest-backfill', // owner: #team-batch-exports, allow backfilling from beginning of timeCONTROL_SUPPORT_LOGIN: 'control_support_login', // owner: #team-security, used to control whether users can opt out of support impersonationCUSTOM_CSS_THEMES: 'custom-css-themes', // owner: #team-growth, used to enable custom CSS for teams who want to have fundiff --git a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportNotifications.tsx b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportNotifications.tsxnew file mode 100644index 000000000000..91b1b5e3beba--- /dev/null+++ b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportNotifications.tsx@@ -0,0 +1,33 @@+import { LinkedHogFunctions, getFiltersFromSubTemplateId } from 'scenes/hog-functions/list/LinkedHogFunctions'+import { urls } from 'scenes/urls'++import { CyclotronJobFiltersType, PropertyFilterType, PropertyOperator } from '~/types'++export function BatchExportNotifications({ id }: { id: string }): JSX.Element {+ // The sub-template's own event filter plus a binding to this batch export, so the+ // list shows only notifications scoped to the export whose page we are on.+ const filterGroup: CyclotronJobFiltersType = {+ ...getFiltersFromSubTemplateId('batch-export-run-failed'),+ properties: [+ {+ key: 'batch_export_id',+ type: PropertyFilterType.Event,+ value: id,+ operator: PropertyOperator.Exact,+ },+ ],+ }++ return (+ <div className="deprecated-space-y-2">+ <p className="text-secondary mb-0">Get notified when this batch export fails.</p>+ <LinkedHogFunctions+ type="internal_destination"+ subTemplateIds={['batch-export-run-failed']}+ forceFilterGroups={[filterGroup]}+ emptyText="No notifications configured for this batch export."+ queryParams={{ returnTo: `${urls.batchExport(id)}?tab=notifications` }}+ />+ </div>+ )+}diff --git a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportScene.tsx b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportScene.tsxindex f54f70c02528..19f7e4c2ab8f 100644--- a/frontend/src/scenes/data-pipelines/batch-exports/BatchExportScene.tsx+++ b/frontend/src/scenes/data-pipelines/batch-exports/BatchExportScene.tsx@@ -18,6 +18,7 @@ import { LemonDivider, LemonSkeleton } from '@posthog/lemon-ui'import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'import { NotFound } from 'lib/components/NotFound'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { More } from 'lib/lemon-ui/LemonButton/More'import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'@@ -40,10 +41,19 @@ import {BatchExportConfigurationSaveButton,} from './BatchExportConfigurationButtons'import { RenderBatchExportIcon } from './BatchExportIcon'+import { BatchExportNotifications } from './BatchExportNotifications'import { BatchExportsMetrics } from './BatchExportsMetrics'import { humanizeBatchExportName, normalizeBatchExportService } from './utils'-const BATCH_EXPORT_SCENE_TABS = ['configuration', 'metrics', 'logs', 'runs', 'backfills', 'history'] as const+const BATCH_EXPORT_SCENE_TABS = [+ 'configuration',+ 'metrics',+ 'logs',+ 'runs',+ 'backfills',+ 'notifications',+ 'history',+] as constexport type BatchExportSceneTab = (typeof BATCH_EXPORT_SCENE_TABS)[number]// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -57,7 +67,7 @@ export interface batchExportSceneLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface batchExportSceneLogicActions {setCurrentTab: (tab: BatchExportSceneTab) => {- tab: 'backfills' | 'configuration' | 'history' | 'logs' | 'metrics' | 'runs'+ tab: 'backfills' | 'configuration' | 'history' | 'logs' | 'metrics' | 'notifications' | 'runs'}}@@ -246,6 +256,7 @@ function BatchExportSceneContentInner({service: BatchExportService['type'] | null}): JSX.Element {const { batchExportConfig, loading } = useValues(batchExportConfigFormLogic)+ const notificationsEnabled = useFeatureFlag('BATCH_EXPORT_ALERTS')if (loading && !batchExportConfig) {return (@@ -305,6 +316,13 @@ function BatchExportSceneContentInner({content: <BatchExportBackfills id={id} />,}: null,+ id && notificationsEnabled+ ? {+ label: 'Notifications',+ key: 'notifications',+ content: <BatchExportNotifications id={id} />,+ }+ : null,id? {label: 'History',diff --git a/frontend/src/scenes/data-pipelines/batch-exports/batchExportSceneLogic.test.ts b/frontend/src/scenes/data-pipelines/batch-exports/batchExportSceneLogic.test.tsindex 3b6f8bd344a3..920dabdbbbd8 100644--- a/frontend/src/scenes/data-pipelines/batch-exports/batchExportSceneLogic.test.ts+++ b/frontend/src/scenes/data-pipelines/batch-exports/batchExportSceneLogic.test.ts@@ -53,17 +53,23 @@ describe('batchExportSceneLogic', () => {expect(logic.values.currentTab).toBe('configuration')})- it.each(['runs', 'backfills', 'logs', 'metrics'] as const)('switches to %s tab via setCurrentTab', async (tab) => {- await initLogic()+ it.each(['runs', 'backfills', 'logs', 'metrics', 'notifications'] as const)(+ 'switches to %s tab via setCurrentTab',+ async (tab) => {+ await initLogic()- logic.actions.setCurrentTab(tab)- expect(logic.values.currentTab).toBe(tab)- })+ logic.actions.setCurrentTab(tab)+ expect(logic.values.currentTab).toBe(tab)+ }+ )- it.each(['runs', 'backfills', 'logs', 'metrics'] as const)('syncs %s tab to URL search params', async (tab) => {- await initLogic()+ it.each(['runs', 'backfills', 'logs', 'metrics', 'notifications'] as const)(+ 'syncs %s tab to URL search params',+ async (tab) => {+ await initLogic()- logic.actions.setCurrentTab(tab)- expect(router.values.searchParams).toEqual(expect.objectContaining({ tab }))- })+ logic.actions.setCurrentTab(tab)+ expect(router.values.searchParams).toEqual(expect.objectContaining({ tab }))+ }+ )})diff --git a/frontend/src/scenes/hog-functions/filters/HogFunctionFiltersInternal.tsx b/frontend/src/scenes/hog-functions/filters/HogFunctionFiltersInternal.tsxindex bf8b49d0f967..caf2cb14c66b 100644--- a/frontend/src/scenes/hog-functions/filters/HogFunctionFiltersInternal.tsx+++ b/frontend/src/scenes/hog-functions/filters/HogFunctionFiltersInternal.tsx@@ -85,6 +85,13 @@ export const getProductEventFilterOptions = (contextId: HogFunctionConfigurationvalue: '$health_check_issue_resolved',},]+ case 'batch-export-alerts':+ return [+ {+ label: 'Batch export run failed',+ value: '$batch_export_run_failed',+ },+ ]default:return [{@@ -182,9 +189,14 @@ const setSimpleFilterValue = (},],}- // Preserve properties bound by Logs alerting (alert_id) — the trigger event id changes between- // firing/resolved/auto-disabled/errored, but the binding to the parent alert must survive.- if (contextId === 'logs-alerting' && previous?.properties && previous.properties.length > 0) {+ // 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+ // binding to the parent resource must survive.+ if (+ (contextId === 'logs-alerting' || contextId === 'batch-export-alerts') &&+ previous?.properties &&+ previous.properties.length > 0+ ) {next.properties = previous.properties}return next@@ -217,6 +229,8 @@ export function HogFunctionFiltersInternal(): JSX.Element {return [TaxonomicFilterGroupType.EventProperties]} else if (contextId === 'health-alerts') {return [TaxonomicFilterGroupType.EventProperties]+ } else if (contextId === 'batch-export-alerts') {+ return [TaxonomicFilterGroupType.EventProperties]}return []}, [contextId])diff --git a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.tsindex 50c90afe416c..ddeba817b11b 100644--- a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts+++ b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts@@ -61,6 +61,15 @@ function mcpFailedToolCallEvent(errorType?: string): CyclotronJobFilterEvents {return { id: '$mcp_tool_call', type: 'events', properties }}+// A permanently broken batch export fails every run (as often as every 5 minutes), so dedupe+// per export: one message per broken export per hour. The auto-pause threshold bounds the tail.+const BATCH_EXPORT_ALERT_MASKING_TTL_SECONDS = 60 * 60++// Keyed per batch export so two exports breaking at once both alert. The producer always sets+// batch_export_id, but HogMaskerService skips masking on falsy hashes, so fall back defensively.+const BATCH_EXPORT_ALERT_MASKING_HASH =+ "{event.properties.batch_export_id ? event.properties.batch_export_id : 'unknown-batch-export'}"+// 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'@@ -226,6 +235,18 @@ export const HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES: Record<context_id: 'health-alerts',filters: { events: [{ id: '$health_check_issue_resolved', type: 'events' }] },},+ 'batch-export-run-failed': {+ sub_template_id: 'batch-export-run-failed',+ type: 'internal_destination',+ context_id: 'batch-export-alerts',+ filters: { events: [{ id: '$batch_export_run_failed', type: 'events' }] },+ masking: {+ hash: BATCH_EXPORT_ALERT_MASKING_HASH,+ ttl: BATCH_EXPORT_ALERT_MASKING_TTL_SECONDS,+ threshold: null,+ },+ flag: FEATURE_FLAGS.BATCH_EXPORT_ALERTS,+ },}const FLAG_ACTOR_NAME = "{event.properties.user.first_name ? event.properties.user.first_name : 'PostHog'}"@@ -594,6 +615,13 @@ function notificationVariants({]}+// batch_export_name is user-controlled and error can embed whatever the destination returned, so+// both get the same Slack escaping + bounds as the other producer-controlled notification fields+// (a raw value could smuggle <!channel> mentions or <url|text> masked links into the message).+// The error bound matches the backend's 1000-char truncation of the property.+const BATCH_EXPORT_NAME_SLACK = `{${slackEscapeExpr('event.properties.batch_export_name')}}`+const BATCH_EXPORT_ERROR_SLACK = `{${slackEscapeExpr('event.properties.error', 1000)}}`+export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, HogFunctionSubTemplateType[]> = {'mcp-tool-error': notificationVariants({subTemplateId: 'mcp-tool-error',@@ -1619,6 +1647,52 @@ export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, Ho},},],+ 'batch-export-run-failed': [+ {+ ...HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES['batch-export-run-failed'],+ template_id: 'template-slack',+ name: 'Post to Slack on batch export failure',+ description: 'Post to a Slack channel when a batch export run fails',+ inputs: {+ blocks: {+ value: [+ { type: 'header', text: { type: 'plain_text', text: 'Batch export failed' } },+ {+ type: 'section',+ text: {+ type: 'mrkdwn',+ // data_interval_start is null for backfill runs covering everything+ // up to the end date ("beginning of time" in the backfills UI)+ text: `*${BATCH_EXPORT_NAME_SLACK}* ({event.properties.destination_type}) failed to export data for {event.properties.data_interval_start ? event.properties.data_interval_start : 'the beginning of time'} – {event.properties.data_interval_end}.`,+ },+ },+ {+ type: 'section',+ text: { type: 'mrkdwn', text: `*Error:* ${BATCH_EXPORT_ERROR_SLACK}` },+ },+ {+ type: 'context',+ elements: [{ type: 'mrkdwn', text: 'Project: <{project.url}|{project.name}>' }],+ },+ { type: 'divider' },+ {+ type: 'actions',+ elements: [+ {+ url: '{project.url}/pipeline/batch-exports/{event.properties.batch_export_id}',+ text: { text: 'View batch export', type: 'plain_text' },+ type: 'button',+ },+ ],+ },+ ],+ },+ text: {+ value: `Batch export '${BATCH_EXPORT_NAME_SLACK}' failed: ${BATCH_EXPORT_ERROR_SLACK}`,+ },+ },+ },+ ],}export const getSubTemplate = (@@ -1650,6 +1724,8 @@ export const eventToHogFunctionContextId = (event: string | undefined): HogFunctcase '$health_check_issue_firing':case '$health_check_issue_resolved':return 'health-alerts'+ case '$batch_export_run_failed':+ return 'batch-export-alerts'default:return 'standard'}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex d422c2b1bacb..90da56fc41ac 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -7296,6 +7296,7 @@ export type HogFunctionConfigurationContextId =| 'experiment-alerts'| 'logs-alerting'| 'health-alerts'+ | 'batch-export-alerts'export type HogFunctionSubTemplateIdType =| 'early-access-feature-enrollment'@@ -7316,6 +7317,7 @@ export type HogFunctionSubTemplateIdType =| 'logs-alert-errored'| 'health-check-firing'| 'health-check-resolved'+ | 'batch-export-run-failed'export type HogFunctionConfigurationType = Omit<HogFunctionType,