: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: add per-pipeline notification settings for data pipeline errors (#54900)
posthog[bot]5b37991e22df
diff --git a/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx b/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsxindex d4555f2b1a5d..c6261cc48980 100644--- a/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx+++ b/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx@@ -3,13 +3,15 @@ import { router } from 'kea-router'import { useEffect, useRef, useState } from 'react'import { IconChevronDown, IconChevronRight } from '@posthog/icons'-import { LemonBanner, LemonButton, LemonCheckbox, LemonInput, LemonSwitch, LemonTag } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonCheckbox, LemonInput, LemonSwitch, LemonTag, Spinner } from '@posthog/lemon-ui'import { organizationLogic } from 'scenes/organizationLogic'import { userLogic } from 'scenes/userLogic'import { NotificationSettings, OrganizationBasicType, TeamBasicType } from '~/types'+import { PIPELINE_KIND_LABELS, pipelineNotificationsLogic } from './pipelineNotificationsLogic'+enum NotificationBlock {Security = 'security',WeeklyDigest = 'weekly-digest',@@ -203,6 +205,92 @@ function OrganizationMemberJoinSelector(): JSX.Element {)}+function PipelineNotificationSelector(): JSX.Element {+ const { userLoading } = useValues(userLogic)+ const { updatePipelineNotification, updatePipelineNotificationForAll } = useActions(userLogic)+ const { pipelines, pipelinesLoading, pipelinesByTeam, allPipelineIds, isPipelineDisabled } =+ useValues(pipelineNotificationsLogic)+ const [expanded, setExpanded] = useState(true)++ return (+ <div>+ <LemonButton+ icon={expanded ? <IconChevronDown /> : <IconChevronRight />}+ onClick={() => setExpanded(!expanded)}+ size="small"+ type="tertiary"+ className="p-0"+ >+ Select pipelines to receive notifications for+ </LemonButton>++ {expanded && (+ <div className="mt-3 ml-6 space-y-2">+ <p className="text-muted text-xs">+ All pipelines are enabled by default. Uncheck any pipeline you no longer want notifications for.+ </p>+ {pipelinesLoading ? (+ <div className="flex items-center gap-2 py-2">+ <Spinner className="text-lg" />+ <span className="text-muted text-sm">Loading pipelines...</span>+ </div>+ ) : pipelines.length === 0 ? (+ <p className="text-muted text-sm">No pipelines found in your projects.</p>+ ) : (+ <div className="flex flex-col gap-2">+ <div className="flex flex-row items-center gap-4">+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={() => updatePipelineNotificationForAll(allPipelineIds, true)}+ >+ Enable all notifications+ </LemonButton>+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={() => updatePipelineNotificationForAll(allPipelineIds, false)}+ >+ Mute all notifications+ </LemonButton>+ </div>++ {Object.entries(pipelinesByTeam).map(([key, { teamId, teamName, items }]) => (+ <div key={key} className="flex flex-col gap-2">+ <div className="flex items-center gap-2">+ <span className="font-medium">{teamName}</span>+ <LemonTag type="muted">id: {teamId}</LemonTag>+ </div>+ <div className="ml-4 flex flex-col gap-1">+ {items.map((pipeline) => (+ <LemonCheckbox+ key={pipeline.id}+ id={`pipeline-${pipeline.id}`}+ data-attr={`pipeline_notification_${pipeline.id}`}+ onChange={(checked) => updatePipelineNotification(pipeline.id, checked)}+ checked={!isPipelineDisabled(pipeline.id)}+ disabled={userLoading}+ label={+ <div className="flex items-center gap-2">+ <span>{pipeline.name}</span>+ <LemonTag type="default">+ {PIPELINE_KIND_LABELS[pipeline.kind]}+ </LemonTag>+ </div>+ }+ />+ ))}+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ )}+ </div>+ )+}+export function UpdateEmailPreferences(): JSX.Element {const { user, userLoading } = useValues(userLogic)const {@@ -327,6 +415,7 @@ export function UpdateEmailPreferences(): JSX.Element {</div></div>)}+ {user?.notification_settings?.plugin_disabled !== false && <PipelineNotificationSelector />}</div>),[NotificationBlock.IssueAssigned]: (diff --git a/frontend/src/scenes/settings/user/pipelineNotificationsLogic.ts b/frontend/src/scenes/settings/user/pipelineNotificationsLogic.tsnew file mode 100644index 000000000000..a8fec5cbd52c--- /dev/null+++ b/frontend/src/scenes/settings/user/pipelineNotificationsLogic.ts@@ -0,0 +1,185 @@+import { afterMount, connect, kea, path, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'++import api from 'lib/api'+import { organizationLogic } from 'scenes/organizationLogic'+import { userLogic } from 'scenes/userLogic'++import type { OrganizationType, UserType } from '~/types'++import { batchExportsList } from 'products/batch_exports/frontend/generated/api'+import type { BatchExportApi, PaginatedBatchExportListApi } from 'products/batch_exports/frontend/generated/api.schemas'+import { hogFunctionsList } from 'products/cdp/frontend/generated/api'+import type {+ HogFunctionMinimalApi,+ PaginatedHogFunctionMinimalListApi,+} from 'products/cdp/frontend/generated/api.schemas'++import type { pipelineNotificationsLogicType } from './pipelineNotificationsLogicType'++export type PipelineKind = 'destination' | 'transformation' | 'plugin' | 'batch_export'++export type PipelineItem = {+ id: string+ name: string+ kind: PipelineKind+ teamId: number+ teamName: string+}++export type PipelineTeamGroup = {+ teamId: number+ teamName: string+ items: PipelineItem[]+}++export const PIPELINE_KIND_ORDER: PipelineKind[] = ['destination', 'transformation', 'batch_export', 'plugin']++export const PIPELINE_KIND_LABELS: Record<PipelineKind, string> = {+ destination: 'Destinations',+ transformation: 'Transformations',+ batch_export: 'Batch exports',+ plugin: 'Plugin destinations (deprecated)',+}++type PluginDestinationConfig = { id: number; name?: string | null }++function displayName(name: string | null | undefined): string {+ return name?.trim() || '(unnamed)'+}++export const pipelineNotificationsLogic = kea<pipelineNotificationsLogicType>([+ path(['scenes', 'settings', 'user', 'pipelineNotificationsLogic']),+ connect(() => ({+ values: [organizationLogic, ['currentOrganization'], userLogic, ['user']],+ })),+ loaders(({ values }) => ({+ pipelines: [+ [] as PipelineItem[],+ {+ loadPipelines: async () => {+ const org: OrganizationType | null = values.currentOrganization+ if (!org?.teams?.length) {+ return []+ }++ const teamNamesById = new Map(org.teams.map((t) => [t.id, t.name]))++ const perTeamItems = await Promise.all(+ org.teams.map(async (team): Promise<PipelineItem[]> => {+ const items: PipelineItem[] = []+ try {+ const initial: PaginatedHogFunctionMinimalListApi = await hogFunctionsList(+ String(team.id),+ {+ type: ['destination', 'site_destination', 'transformation'],+ limit: 100,+ }+ )+ const hfs: HogFunctionMinimalApi[] = [+ ...initial.results,+ ...(await api.loadPaginatedResults<HogFunctionMinimalApi>(initial.next ?? null)),+ ]+ for (const hf of hfs) {+ items.push({+ id: `hog_function:${hf.id}`,+ name: displayName(hf.name),+ kind: hf.type === 'transformation' ? 'transformation' : 'destination',+ teamId: team.id,+ teamName: team.name,+ })+ }+ } catch (e) {+ console.warn(`Failed to load hog functions for team ${team.id}`, e)+ }+ try {+ const pcs = await api.loadPaginatedResults<PluginDestinationConfig>(+ `api/projects/${team.id}/pipeline_destination_configs/?limit=100`+ )+ for (const pc of pcs) {+ items.push({+ id: `plugin_config:${pc.id}`,+ name: displayName(pc.name),+ kind: 'plugin',+ teamId: team.id,+ teamName: team.name,+ })+ }+ } catch (e) {+ console.warn(`Failed to load plugin destinations for team ${team.id}`, e)+ }+ return items+ })+ )++ let batchExportItems: PipelineItem[] = []+ try {+ const initial: PaginatedBatchExportListApi = await batchExportsList(org.id, { limit: 100 })+ const bes: BatchExportApi[] = [+ ...initial.results,+ ...(await api.loadPaginatedResults<BatchExportApi>(initial.next ?? null)),+ ]+ batchExportItems = bes.map<PipelineItem>((be) => ({+ id: `batch_export:${be.id}`,+ name: displayName(be.name),+ kind: 'batch_export',+ teamId: be.team_id,+ teamName: teamNamesById.get(be.team_id) ?? '',+ }))+ } catch (e) {+ console.warn('Failed to load batch exports', e)+ }++ const items = [...perTeamItems.flat(), ...batchExportItems]+ return items.sort(+ (a, b) =>+ a.teamName.localeCompare(b.teamName) ||+ PIPELINE_KIND_ORDER.indexOf(a.kind) - PIPELINE_KIND_ORDER.indexOf(b.kind) ||+ a.name.localeCompare(b.name)+ )+ },+ },+ ],+ })),+ selectors({+ allPipelineIds: [(s) => [s.pipelines], (pipelines: PipelineItem[]): string[] => pipelines.map((p) => p.id)],+ pipelinesByTeam: [+ (s) => [s.pipelines],+ (pipelines: PipelineItem[]): Record<string, PipelineTeamGroup> =>+ pipelines.reduce(+ (acc, pipeline) => {+ const teamKey = `${pipeline.teamId}`+ if (!acc[teamKey]) {+ acc[teamKey] = {+ teamId: pipeline.teamId,+ teamName: pipeline.teamName,+ items: [],+ }+ }+ acc[teamKey].items.push(pipeline)+ return acc+ },+ {} as Record<string, PipelineTeamGroup>+ ),+ ],+ isPipelineDisabled: [+ (s) => [s.user],+ (user: UserType | null) =>+ (pipelineId: string): boolean =>+ !!user?.notification_settings?.pipeline_notifications_disabled?.[pipelineId],+ ],+ }),+ subscriptions(({ actions }) => ({+ currentOrganization: (curr: OrganizationType | null, prev: OrganizationType | null | undefined) => {+ if (curr?.id && curr.id !== prev?.id) {+ actions.loadPipelines()+ }+ },+ })),+ afterMount(({ actions, values }) => {+ if (values.currentOrganization?.teams?.length) {+ actions.loadPipelines()+ }+ }),+])diff --git a/frontend/src/scenes/userLogic.ts b/frontend/src/scenes/userLogic.tsindex b6700930835c..afca872d146c 100644--- a/frontend/src/scenes/userLogic.ts+++ b/frontend/src/scenes/userLogic.ts@@ -110,6 +110,8 @@ export const userLogic = kea<userLogicType>([types,enabled,}),+ updatePipelineNotification: (pipelineId: string, enabled: boolean) => ({ pipelineId, enabled }),+ updatePipelineNotificationForAll: (pipelineIds: string[], enabled: boolean) => ({ pipelineIds, enabled }),})),forms(({ actions }) => ({userDetails: {@@ -547,6 +549,40 @@ export const userLogic = kea<userLogicType>([},})},+ updatePipelineNotification: ({ pipelineId, enabled }) => {+ if (!values.user?.notification_settings) {+ return+ }++ actions.updateUser({+ notification_settings: {+ ...values.user.notification_settings,+ pipeline_notifications_disabled: {+ ...values.user.notification_settings.pipeline_notifications_disabled,+ [pipelineId]: !enabled,+ },+ },+ })+ },+ updatePipelineNotificationForAll: ({ pipelineIds, enabled }) => {+ if (!values.user?.notification_settings) {+ return+ }++ const pipelineNotificationsDisabled = {+ ...values.user.notification_settings.pipeline_notifications_disabled,+ }+ pipelineIds.forEach((id) => {+ pipelineNotificationsDisabled[id] = !enabled+ })++ actions.updateUser({+ notification_settings: {+ ...values.user.notification_settings,+ pipeline_notifications_disabled: pipelineNotificationsDisabled,+ },+ })+ },})),selectors({hasAvailableFeature: [diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 5559399c5f23..254a30141007 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -420,6 +420,7 @@ export interface NotificationSettings {web_analytics_weekly_digest_project_enabled?: Record<string, boolean>organization_member_join_email_disabled?: Record<string, boolean>realtime_notifications_disabled?: Record<string, Record<string, boolean>>+ pipeline_notifications_disabled?: Record<string, boolean>}export interface InAppNotification {diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex 6b8501acd342..1fd7df150fa0 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -1697,6 +1697,7 @@ class TestUserAPI(APIBaseTest):"web_analytics_weekly_digest": True,"organization_member_join_email_disabled": {},"realtime_notifications_disabled": {},+ "pipeline_notifications_disabled": {},},)@@ -1716,6 +1717,7 @@ class TestUserAPI(APIBaseTest):"web_analytics_weekly_digest": True,"organization_member_join_email_disabled": {},"realtime_notifications_disabled": {},+ "pipeline_notifications_disabled": {},},)@@ -1892,6 +1894,45 @@ class TestUserAPI(APIBaseTest):f"Patching {patched_key!r} clobbered {unrelated_key!r}")+ def test_pipeline_notifications_rejects_malformed_pipeline_ids(self):+ for bad_key in [+ "<script>alert(1)</script>",+ "random_garbage_key",+ "hog_function:",+ "hog_function:not a uuid",+ "unknown_type:abc",+ "",+ ]:+ response = self.client.patch(+ "/api/users/@me/",+ {"notification_settings": {"pipeline_notifications_disabled": {bad_key: True}}},+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, f"key {bad_key!r} was accepted")+ self.assertEqual(response.json()["code"], "invalid_input")++ def test_pipeline_notifications_accepts_valid_pipeline_ids(self):+ for good_key in [+ "hog_function:019dcf05-db1d-0000-682a-935c8e1ad2c9",+ "batch_export:019dcf05-dac4-0000-07d4-cf53026deba6",+ "plugin_config:42",+ ]:+ response = self.client.patch(+ "/api/users/@me/",+ {"notification_settings": {"pipeline_notifications_disabled": {good_key: True}}},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, f"key {good_key!r} was rejected")++ def test_pipeline_notifications_caps_total_entries(self):+ from posthog.api.user import MAX_PIPELINE_NOTIFICATIONS++ too_many = {f"hog_function:fake-{i}": True for i in range(MAX_PIPELINE_NOTIFICATIONS + 1)}+ response = self.client.patch(+ "/api/users/@me/",+ {"notification_settings": {"pipeline_notifications_disabled": too_many}},+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("more than", response.json()["detail"])+def test_invalid_notification_settings_returns_error(self):response = self.client.patch("/api/users/@me/", {"notification_settings": {"invalid_key": True}})self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)@@ -1944,6 +1985,7 @@ class TestUserAPI(APIBaseTest):"web_analytics_weekly_digest": True, # Default value"organization_member_join_email_disabled": {}, # Default value"realtime_notifications_disabled": {}, # Default value+ "pipeline_notifications_disabled": {}, # Default value},)diff --git a/posthog/api/user.py b/posthog/api/user.pyindex 9ab82d2f7e28..2db0376c8c11 100644--- a/posthog/api/user.py+++ b/posthog/api/user.py@@ -116,6 +116,24 @@ REDIRECT_TO_SITE_FAILED_COUNTER = Counter("posthog_redirect_to_site_failed", "ReNUM_2FA_BACKUP_CODES = 10+MAX_PIPELINE_NOTIFICATIONS = 1000+_PIPELINE_ID_PATTERN = re.compile(r"^(?:hog_function|batch_export|plugin_config):[0-9a-zA-Z-]{1,128}$")+++def _validate_pipeline_notifications(incoming: dict, merged: dict) -> None:+ for pipeline_id in incoming:+ if not isinstance(pipeline_id, str) or not _PIPELINE_ID_PATTERN.match(pipeline_id):+ raise serializers.ValidationError(+ f"Invalid pipeline id: {pipeline_id!r}",+ code="invalid_input",+ )+ if len(merged) > MAX_PIPELINE_NOTIFICATIONS:+ raise serializers.ValidationError(+ f"pipeline_notifications_disabled cannot have more than {MAX_PIPELINE_NOTIFICATIONS} entries",+ code="invalid_input",+ )++logger = structlog.get_logger(__name__)tracer = trace.get_tracer(__name__)@@ -492,6 +510,7 @@ class UserSerializer(serializers.ModelSerializer):"error_tracking_weekly_digest_project_enabled","web_analytics_weekly_digest_project_enabled","organization_member_join_email_disabled",+ "pipeline_notifications_disabled",)for key, value in notification_settings.items():@@ -515,7 +534,10 @@ class UserSerializer(serializers.ModelSerializer):f"Notification setting values must be boolean, got {type(disabled)} instead",code="invalid_input",)- current_settings[key] = {**current_settings.get(key, {}), **value}+ merged = {**current_settings.get(key, {}), **value}+ if key == "pipeline_notifications_disabled":+ _validate_pipeline_notifications(value, merged)+ current_settings[key] = mergedelif key == "realtime_notifications_disabled":if not isinstance(value, dict):raise serializers.ValidationError(@@ -540,10 +562,10 @@ class UserSerializer(serializers.ModelSerializer):code="invalid_input",)existing = current_settings.get("realtime_notifications_disabled", {}) or {}- merged: dict[str, dict[str, bool]] = {**existing}+ realtime_merged: dict[str, dict[str, bool]] = {**existing}for type_key, team_map in value.items():- merged[type_key] = {**(existing.get(type_key, {}) or {}), **team_map}- current_settings["realtime_notifications_disabled"] = merged+ realtime_merged[type_key] = {**(existing.get(type_key, {}) or {}), **team_map}+ current_settings["realtime_notifications_disabled"] = realtime_mergedelif key == "data_pipeline_error_threshold":if not isinstance(value, (int, float)):raise serializers.ValidationError(diff --git a/posthog/models/user.py b/posthog/models/user.pyindex 6d5ee9000e60..592035ccb568 100644--- a/posthog/models/user.py+++ b/posthog/models/user.py@@ -50,6 +50,9 @@ class Notifications(TypedDict, total=False):realtime_notifications_disabled: dict[str, dict[str, bool]] # Maps notification_type (str) to {team_id (str) -> disabled (True = muted)}. Absence = enabled (opt-out default).+ pipeline_notifications_disabled: dict[+ str, bool+ ] # Maps pipeline ID (e.g. "hog_function:<uuid>", "plugin_config:<id>", "batch_export:<uuid>") to disabled status (True = do not email for this pipeline)NOTIFICATION_DEFAULTS: Notifications = {@@ -65,6 +68,7 @@ NOTIFICATION_DEFAULTS: Notifications = {"web_analytics_weekly_digest": True, # Web analytics weekly digest enabled by default"organization_member_join_email_disabled": {}, # No per-org opt-out until user configures"realtime_notifications_disabled": {}, # No opt-outs by default+ "pipeline_notifications_disabled": {}, # No per-pipeline opt-out until user configures}# We don't need the following attributes in most cases, so we defer them by defaultdiff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex e41a58e9b39b..61254ebd4e74 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -98,13 +98,16 @@ def get_members_to_notify(team: Team, notification_setting: NotificationSettingTreturn memberships_to_email-def get_members_to_notify_for_pipeline_error(team: Team, failure_rate: float = 1.0) -> list[OrganizationMembership]:+def get_members_to_notify_for_pipeline_error(+ team: Team, failure_rate: float = 1.0, pipeline_id: Optional[str] = None+) -> list[OrganizationMembership]:"""- Get members to notify for a data pipeline error, respecting threshold.+ Get members to notify for a data pipeline error, respecting threshold and per-pipeline opt-out.Args:team: The team that owns the pipelinefailure_rate: The current failure rate (0.0 to 1.0). Defaults to 1.0 (100%) for single failures.+ pipeline_id: Optional pipeline identifier (e.g. "hog_function:<uuid>"). Used for per-pipeline opt-out.Returns:List of organization memberships to notify@@ -112,7 +115,9 @@ def get_members_to_notify_for_pipeline_error(team: Team, failure_rate: float = 1members_to_notify = get_members_to_notify(team, "plugin_disabled")return [- member for member in members_to_notify if should_send_pipeline_error_notification(member.user, failure_rate)+ member+ for member in members_to_notify+ if should_send_pipeline_error_notification(member.user, failure_rate, pipeline_id)]@@ -194,6 +199,7 @@ def should_send_notification(def should_send_pipeline_error_notification(user: User,failure_rate: float = 1.0,+ pipeline_id: Optional[str] = None,) -> bool:"""Determines if a data pipeline error notification should be sent to a user.@@ -201,12 +207,19 @@ def should_send_pipeline_error_notification(Args:user: The user to check settings forfailure_rate: The current failure rate (0.0 to 1.0) for this pipeline. Defaults to 1.0 (100%) for single failures.+ pipeline_id: Optional pipeline identifier (e.g. "hog_function:<uuid>"). If provided, checks per-pipeline opt-out.Returns:bool: True if the notification should be sent, False otherwise"""settings = user.notification_settings+ # Check per-pipeline opt-out+ if pipeline_id is not None:+ pipeline_disabled = settings.get("pipeline_notifications_disabled", {})+ if pipeline_disabled.get(pipeline_id, False):+ return False+# Check threshold - if threshold is 0.0, notify on any failurethreshold = settings.get("data_pipeline_error_threshold", 0.0)if threshold == 0.0:@@ -504,7 +517,8 @@ def send_fatal_plugin_error(if team is None:return- memberships_to_email = get_members_to_notify_for_pipeline_error(team, failure_rate=1.0)+ pipeline_id = f"plugin_config:{plugin_config_id}"+ memberships_to_email = get_members_to_notify_for_pipeline_error(team, failure_rate=1.0, pipeline_id=pipeline_id)if not memberships_to_email:return@@ -532,7 +546,8 @@ def send_hog_function_disabled(hog_function_id: str) -> None:hog_function: HogFunction = HogFunction.objects.prefetch_related("team").get(id=hog_function_id)team = hog_function.team- memberships_to_email = get_members_to_notify_for_pipeline_error(team, failure_rate=1.0)+ pipeline_id = f"hog_function:{hog_function_id}"+ memberships_to_email = get_members_to_notify_for_pipeline_error(team, failure_rate=1.0, pipeline_id=pipeline_id)if not memberships_to_email:return@@ -565,7 +580,8 @@ def send_batch_export_run_failure(batch_export = batch_export_run.parentteam: Team = batch_export.team- memberships_to_email = get_members_to_notify_for_pipeline_error(team, failure_rate)+ pipeline_id = f"batch_export:{batch_export.id}"+ memberships_to_email = get_members_to_notify_for_pipeline_error(team, failure_rate, pipeline_id=pipeline_id)if not memberships_to_email:return@@ -1184,12 +1200,16 @@ def send_hog_functions_digest_email(digest_data: dict, test_email_override: strfor membership in memberships_to_email:user = membership.user- # Filter functions based on user's threshold+ # Filter functions based on user's threshold and per-pipeline opt-out# failure_rate is stored as a percentage (e.g., 15.5 for 15.5%), convert to decimal for threshold checkuser_functions = [ffor f in all_functions- if should_send_pipeline_error_notification(user, float(f.get("failure_rate", 0) or 0) / 100)+ if should_send_pipeline_error_notification(+ user,+ float(f.get("failure_rate", 0) or 0) / 100,+ pipeline_id=f"hog_function:{f['id']}" if f.get("id") else None,+ )]# Skip this user if no functions exceed their thresholddiff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.pyindex 83161de24691..cf03ee0c0664 100644--- a/posthog/tasks/test/test_email.py+++ b/posthog/tasks/test/test_email.py@@ -31,6 +31,7 @@ from posthog.tasks.email import (send_email_change_emails,send_email_verification,send_fatal_plugin_error,+ send_hog_function_disabled,send_hog_functions_daily_digest,send_hog_functions_digest_email,send_invite,@@ -624,6 +625,122 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):assert len(memberships) == 1assert memberships[0].user.email == user2.email+ def test_should_send_pipeline_error_notification_per_pipeline_opt_out(self, MockEmailMessage: MagicMock) -> None:+ self.user.partial_notification_settings = {+ "plugin_disabled": True,+ "pipeline_notifications_disabled": {+ "hog_function:abc-123": True,+ "batch_export:def-456": True,+ },+ }+ self.user.save()++ assert (+ should_send_pipeline_error_notification(self.user, failure_rate=1.0, pipeline_id="hog_function:abc-123")+ is False+ )+ assert (+ should_send_pipeline_error_notification(self.user, failure_rate=1.0, pipeline_id="batch_export:def-456")+ is False+ )+ assert (+ should_send_pipeline_error_notification(self.user, failure_rate=1.0, pipeline_id="hog_function:other-id")+ is True+ )+ assert should_send_pipeline_error_notification(self.user, failure_rate=1.0, pipeline_id=None) is True++ def test_get_members_to_notify_for_pipeline_error_per_pipeline_opt_out(self, MockEmailMessage: MagicMock) -> None:+ user2 = self._create_user("[email protected]")++ pipeline_id = "hog_function:test-function-id"++ self.user.partial_notification_settings = {+ "plugin_disabled": True,+ "pipeline_notifications_disabled": {pipeline_id: True},+ }+ self.user.save()+ user2.partial_notification_settings = {"plugin_disabled": True}+ user2.save()++ memberships = get_members_to_notify_for_pipeline_error(+ cast(Team, self.user.team), failure_rate=1.0, pipeline_id=pipeline_id+ )+ assert len(memberships) == 1+ assert memberships[0].user.email == user2.email++ memberships = get_members_to_notify_for_pipeline_error(+ cast(Team, self.user.team), failure_rate=1.0, pipeline_id="hog_function:other-id"+ )+ assert len(memberships) == 2++ def test_send_fatal_plugin_error_per_pipeline_opt_out(self, MockEmailMessage: MagicMock) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ plugin = Plugin.objects.create(organization=self.organization)+ plugin_config = PluginConfig.objects.create(plugin=plugin, team=self.team, enabled=True, order=1)+ user2 = self._create_user("[email protected]")++ self.user.partial_notification_settings = {+ "plugin_disabled": True,+ "pipeline_notifications_disabled": {f"plugin_config:{plugin_config.id}": True},+ }+ self.user.save()++ send_fatal_plugin_error(plugin_config.id, "20222-01-01", error="It exploded!", is_system_error=False)++ assert mocked_email_messages[0].to == [+ {"recipient": "[email protected]", "raw_email": "[email protected]", "distinct_id": str(user2.distinct_id)}+ ]++ def test_send_hog_function_disabled_per_pipeline_opt_out(self, MockEmailMessage: MagicMock) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ hog_function = HogFunction.objects.create(+ team=self.team,+ name="Test Hog Function",+ enabled=True,+ )+ user2 = self._create_user("[email protected]")++ self.user.partial_notification_settings = {+ "plugin_disabled": True,+ "pipeline_notifications_disabled": {f"hog_function:{hog_function.id}": True},+ }+ self.user.save()++ send_hog_function_disabled(str(hog_function.id))++ assert mocked_email_messages[0].to == [+ {"recipient": "[email protected]", "raw_email": "[email protected]", "distinct_id": str(user2.distinct_id)}+ ]++ def test_send_batch_export_run_failure_per_pipeline_opt_out(self, MockEmailMessage: MagicMock) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ batch_export_destination = BatchExportDestination.objects.create(+ type=BatchExportDestination.Destination.S3, config={"bucket_name": "my_production_s3_bucket"}+ )+ batch_export = BatchExport.objects.create( # type: ignore+ team=self.user.team, name="A batch export", destination=batch_export_destination+ )+ now = dt.datetime.now()+ batch_export_run = BatchExportRun.objects.create(+ batch_export=batch_export,+ status=BatchExportRun.Status.FAILED,+ data_interval_start=now - dt.timedelta(hours=1),+ data_interval_end=now,+ )+ user2 = self._create_user("[email protected]")++ self.user.partial_notification_settings = {+ "plugin_disabled": True,+ "pipeline_notifications_disabled": {f"batch_export:{batch_export.id}": True},+ }+ self.user.save()++ send_batch_export_run_failure(batch_export_run.id)++ assert mocked_email_messages[0].to == [+ {"recipient": "[email protected]", "raw_email": "[email protected]", "distinct_id": str(user2.distinct_id)}+ ]+def test_send_canary_email(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_email_messages(MockEmailMessage)send_canary_email("[email protected]")