: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(notifications): dispatch pipeline_failure realtime notifications (#56156)
Yasene83cc3a813be
diff --git a/posthog/tasks/plugin_server.py b/posthog/tasks/plugin_server.pyindex 1a11d4dfd25c..522b7bd89184 100644--- a/posthog/tasks/plugin_server.py+++ b/posthog/tasks/plugin_server.py@@ -3,9 +3,20 @@ from typing import Optionalfrom celery import shared_taskfrom structlog import get_logger-from posthog.tasks.email import send_fatal_plugin_error+from posthog.models import PluginConfig+from posthog.tasks.email import get_members_to_notify_for_pipeline_error, send_fatal_plugin_errorfrom posthog.tasks.utils import CeleryQueue+from products.notifications.backend.facade.api import (+ NotificationData,+ NotificationType,+ Priority,+ TargetType,+ create_notification,+ has_been_dispatched,+)+from products.notifications.backend.facade.enums import NotificationOnlyResourceType+logger = get_logger(__name__)# IMPORTANT - Do not modify this without also modifying plugin-server/../celery.ts@@ -13,6 +24,69 @@ logger = get_logger(__name__)queue = CeleryQueue.DEFAULT.value+def _dispatch_plugin_disabled_realtime(+ plugin_config_id: int,+ plugin_config_updated_at: Optional[str],+ error: str,+) -> None:+ """Fire one realtime pipeline_failure notification per pipeline-error recipient.++ Per-recipient try/except so one bad write does not drop the rest. Never raises so+ a realtime failure cannot poison the email side-effect. Per-recipient idempotency keyed+ on plugin_config_updated_at matches the email path's MessagingRecord dedup, so the+ same disable event won't double-notify on Celery retries or racing workers.+ """+ try:+ plugin_config = PluginConfig.objects.select_related("plugin", "team").get(id=plugin_config_id)+ team = plugin_config.team+ if team is None:+ return+ # failure_rate=1.0 mirrors the email path (send_fatal_plugin_error) — a disabled plugin+ # is treated as 100% failure, so users are filtered only by their data_pipeline_error_threshold.+ memberships = get_members_to_notify_for_pipeline_error(team, failure_rate=1.0)+ if not memberships:+ return+ title = f"Plugin {plugin_config.plugin.name} disabled"[:100]+ body = error[:200]+ source_url = f"/project/{team.project_id}/pipeline/plugins/{plugin_config_id}"+ source_id = str(plugin_config_updated_at) if plugin_config_updated_at else ""+ for membership in memberships:+ target_id = str(membership.user_id)+ if has_been_dispatched(+ notification_type=NotificationType.PIPELINE_FAILURE,+ target_type=TargetType.USER,+ target_id=target_id,+ resource_id=str(plugin_config_id),+ source_id=source_id,+ ):+ continue+ try:+ create_notification(+ NotificationData(+ team_id=team.id,+ notification_type=NotificationType.PIPELINE_FAILURE,+ priority=Priority.NORMAL,+ title=title,+ body=body,+ target_type=TargetType.USER,+ target_id=target_id,+ resource_type=NotificationOnlyResourceType.PIPELINE,+ resource_id=str(plugin_config_id),+ source_url=source_url,+ source_id=source_id,+ )+ )+ except Exception as e:+ logger.exception(+ "fatal_plugin_error.realtime_failed",+ plugin_config_id=plugin_config_id,+ user_id=membership.user_id,+ error=str(e),+ )+ except Exception as e:+ logger.exception("fatal_plugin_error.realtime_setup_failed", plugin_config_id=plugin_config_id, error=str(e))++# Called from plugin-server/../lazy.ts@shared_task(ignore_result=True, queue=queue)def fatal_plugin_error(@@ -22,6 +96,7 @@ def fatal_plugin_error(is_system_error: bool,) -> None:send_fatal_plugin_error.delay(plugin_config_id, plugin_config_updated_at, error, is_system_error)+ _dispatch_plugin_disabled_realtime(plugin_config_id, plugin_config_updated_at, error)# Called from plugin-server/../hog-watcher.service.tsdiff --git a/posthog/tasks/test/test_plugin_server.py b/posthog/tasks/test/test_plugin_server.pynew file mode 100644index 000000000000..0dcbc67bc206--- /dev/null+++ b/posthog/tasks/test/test_plugin_server.py@@ -0,0 +1,61 @@+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from posthog.models import OrganizationMembership+from posthog.models.plugin import Plugin, PluginConfig+from posthog.tasks.plugin_server import _dispatch_plugin_disabled_realtime+++class TestDispatchPluginDisabledRealtime(BaseTest):+ @patch("posthog.tasks.plugin_server.create_notification")+ def test_dispatches_one_notification_per_membership(self, mock_create_notification: MagicMock) -> None:+ plugin = Plugin.objects.create(organization=self.organization, name="GeoIP")+ plugin_config = PluginConfig.objects.create(plugin=plugin, team=self.team, enabled=True, order=1)+ user2 = self._create_user("[email protected]")+ OrganizationMembership.objects.get_or_create(+ organization=self.organization,+ user=user2,+ defaults={"level": OrganizationMembership.Level.MEMBER},+ )++ _dispatch_plugin_disabled_realtime(plugin_config.id, "2026-01-01T00:00:00Z", "boom")++ assert mock_create_notification.call_count >= 1+ first = mock_create_notification.call_args_list[0].args[0]+ assert first.notification_type.value == "pipeline_failure"+ assert first.title == "Plugin GeoIP disabled"+ assert first.body == "boom"+ assert first.resource_id == str(plugin_config.id)+ assert first.source_id == "2026-01-01T00:00:00Z"+ assert first.source_url == f"/project/{self.team.project_id}/pipeline/plugins/{plugin_config.id}"++ @patch("posthog.tasks.plugin_server.create_notification", side_effect=RuntimeError("kafka"))+ def test_swallows_per_recipient_exceptions(self, mock_create: MagicMock) -> None:+ plugin = Plugin.objects.create(organization=self.organization, name="GeoIP")+ plugin_config = PluginConfig.objects.create(plugin=plugin, team=self.team, enabled=True, order=1)+ # Should not raise.+ _dispatch_plugin_disabled_realtime(plugin_config.id, "2026-01-01T00:00:00Z", "boom")+ # Confirms the function actually attempted the dispatch before swallowing,+ # so a silent early-return would not mask a regression here.+ assert mock_create.call_count >= 1++ @patch("posthog.tasks.plugin_server.create_notification")+ def test_swallows_missing_plugin_config(self, mock_create_notification: MagicMock) -> None:+ _dispatch_plugin_disabled_realtime(999_999_999, "2026-01-01T00:00:00Z", "boom")+ mock_create_notification.assert_not_called()++ @patch("posthog.tasks.plugin_server.create_notification")+ @patch("posthog.tasks.plugin_server.has_been_dispatched", return_value=True)+ def test_skips_dispatch_when_already_dispatched(+ self,+ _mock_has_been_dispatched: MagicMock,+ mock_create_notification: MagicMock,+ ) -> None:+ # Mirrors the email path's MessagingRecord dedup: re-running fatal_plugin_error+ # for the same plugin_config_updated_at must not double-notify.+ plugin = Plugin.objects.create(organization=self.organization, name="GeoIP")+ plugin_config = PluginConfig.objects.create(plugin=plugin, team=self.team, enabled=True, order=1)++ _dispatch_plugin_disabled_realtime(plugin_config.id, "2026-01-01T00:00:00Z", "boom")++ mock_create_notification.assert_not_called()diff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.pyindex 6fbd6c16c70c..cf68e8983f81 100644--- a/products/batch_exports/backend/temporal/batch_exports.py+++ b/products/batch_exports/backend/temporal/batch_exports.py@@ -18,8 +18,10 @@ from posthog.batch_exports.models import BatchExportRunfrom posthog.kafka_client.routing import async_producer_scopefrom posthog.kafka_client.topics import KAFKA_APP_METRICS2from posthog.models.team.team import Team+from posthog.models.utils import UUIDTfrom posthog.settings.base_variables import TESTfrom posthog.sync import database_sync_to_async+from posthog.tasks.email import get_members_to_notify_for_pipeline_error, send_batch_export_run_failurefrom posthog.temporal.common.clickhouse import ClickHouseClientfrom posthog.temporal.common.client import connectfrom posthog.temporal.common.logger import get_logger, get_write_only_logger@@ -45,6 +47,14 @@ from products.batch_exports.backend.temporal.sql import (SELECT_FROM_EVENTS_VIEW_RECENT,SELECT_FROM_EVENTS_VIEW_UNBOUNDED,)+from products.notifications.backend.facade.api import (+ NotificationData,+ NotificationType,+ Priority,+ TargetType,+ create_notification,+)+from products.notifications.backend.facade.enums import NotificationOnlyResourceTypefrom ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, list_limited_team_attributes@@ -58,6 +68,79 @@ AsyncBytesGenerator = collections.abc.AsyncGenerator[bytes, None]AsyncRecordsGenerator = collections.abc.AsyncGenerator[pa.RecordBatch, None]+def _notify_run_failure(batch_export_run_id: str | UUIDT) -> None:+ """Fan out failure notifications across every channel for a failed run.++ Both channels swallow their own exceptions, so this helper itself never raises.+ """+ email_sent = False+ try:+ send_batch_export_run_failure(batch_export_run_id)+ email_sent = True+ except Exception:+ LOGGER.exception(+ "send_batch_export_run_failure.email_failed",+ batch_export_run_id=str(batch_export_run_id),+ )++ _dispatch_batch_export_failure_realtime(batch_export_run_id)++ # Only emit the customer-visible success line when the email actually went out — the+ # realtime path is best-effort and not surfaced here. Matches the pre-refactor behaviour+ # where this log only ran in the else-branch of the email try/except.+ if email_sent:+ EXTERNAL_LOGGER.info("Failure notification email for run '%s' has been sent", batch_export_run_id)+++def _dispatch_batch_export_failure_realtime(batch_export_run_id: str | UUIDT) -> None:+ """Fire one realtime pipeline_failure notification per pipeline-error recipient.++ Per-recipient try/except so one bad write does not drop the rest. Never raises so+ a realtime failure cannot poison the email side-effect.+ """+ try:+ run = BatchExportRun.objects.select_related("batch_export__team").get(id=batch_export_run_id)+ team = run.batch_export.team+ # failure_rate=1.0 mirrors the email path (send_batch_export_run_failure default) — a fully+ # failed run is treated as 100%, so users are filtered only by their data_pipeline_error_threshold.+ memberships = get_members_to_notify_for_pipeline_error(team, failure_rate=1.0)+ if not memberships:+ return+ name = (run.batch_export.name or "")[:80]+ title = f"Batch export {name} failed"+ body = f"Last failure at {run.last_updated_at.strftime('%I:%M%p %Z on %B %d, %Y')}"+ source_url = f"/project/{team.project_id}/pipeline/batch-exports/{run.batch_export.id}"+ for membership in memberships:+ try:+ create_notification(+ NotificationData(+ team_id=team.id,+ notification_type=NotificationType.PIPELINE_FAILURE,+ priority=Priority.NORMAL,+ title=title,+ body=body,+ target_type=TargetType.USER,+ target_id=str(membership.user_id),+ resource_type=NotificationOnlyResourceType.PIPELINE,+ resource_id=str(run.batch_export.id),+ source_url=source_url,+ )+ )+ except Exception as e:+ LOGGER.exception(+ "batch_export_failure.realtime_failed",+ batch_export_run_id=str(batch_export_run_id),+ user_id=membership.user_id,+ error=str(e),+ )+ except Exception as e:+ LOGGER.exception(+ "batch_export_failure.realtime_setup_failed",+ batch_export_run_id=str(batch_export_run_id),+ error=str(e),+ )++def default_fields() -> list[BatchExportField]:"""Return list of default batch export Fields."""return [@@ -553,14 +636,7 @@ async def finish_batch_export_run(inputs: FinishBatchExportRunInputs) -> None:)elif batch_export_run.status == BatchExportRun.Status.FAILED:- from posthog.tasks.email import send_batch_export_run_failure-- try:- await database_sync_to_async(send_batch_export_run_failure)(inputs.id)- except Exception:- logger.exception("Failure email notification could not be sent")- else:- external_logger.info("Failure notification email for run '%s' has been sent", inputs.id)+ await database_sync_to_async(_notify_run_failure)(inputs.id)external_logger.error("Batch export for range %s - %s failed with a non-recoverable error: %s",diff --git a/products/batch_exports/backend/tests/temporal/test_realtime_failure_dispatch.py b/products/batch_exports/backend/tests/temporal/test_realtime_failure_dispatch.pynew file mode 100644index 000000000000..d9a489e53620--- /dev/null+++ b/products/batch_exports/backend/tests/temporal/test_realtime_failure_dispatch.py@@ -0,0 +1,61 @@+import datetime as dt++from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from posthog.batch_exports.models import BatchExport, BatchExportDestination, BatchExportRun+from posthog.models.utils import UUIDT++from products.batch_exports.backend.temporal.batch_exports import _dispatch_batch_export_failure_realtime+++class TestDispatchBatchExportFailureRealtime(BaseTest):+ @patch("products.batch_exports.backend.temporal.batch_exports.create_notification")+ def test_dispatches_for_failed_batch_export_run(self, mock_create_notification: MagicMock) -> None:+ destination = BatchExportDestination.objects.create(+ type=BatchExportDestination.Destination.S3, config={"bucket_name": "my_bucket"}+ )+ batch_export = BatchExport.objects.create(team=self.team, name="A batch export", destination=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,+ )++ _dispatch_batch_export_failure_realtime(batch_export_run.id)++ assert mock_create_notification.call_count >= 1+ first = mock_create_notification.call_args_list[0].args[0]+ assert first.notification_type.value == "pipeline_failure"+ assert "Batch export A batch export failed" in first.title+ assert first.resource_id == str(batch_export.id)+ assert first.source_url == f"/project/{self.team.project_id}/pipeline/batch-exports/{batch_export.id}"++ @patch(+ "products.batch_exports.backend.temporal.batch_exports.create_notification",+ side_effect=RuntimeError("kafka"),+ )+ def test_swallows_per_recipient_exceptions(self, mock_create: MagicMock) -> None:+ destination = BatchExportDestination.objects.create(+ type=BatchExportDestination.Destination.S3, config={"bucket_name": "my_bucket"}+ )+ batch_export = BatchExport.objects.create(team=self.team, name="A batch export", destination=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,+ )+ # Should not raise.+ _dispatch_batch_export_failure_realtime(batch_export_run.id)+ # Confirms the function actually attempted the dispatch before swallowing,+ # so a silent early-return would not mask a regression here.+ assert mock_create.call_count >= 1++ @patch("products.batch_exports.backend.temporal.batch_exports.create_notification")+ def test_swallows_missing_run(self, mock_create_notification: MagicMock) -> None:+ _dispatch_batch_export_failure_realtime(str(UUIDT()))+ mock_create_notification.assert_not_called()diff --git a/products/notifications/backend/facade/api.py b/products/notifications/backend/facade/api.pyindex 3616ef416e50..23ed44fe026a 100644--- a/products/notifications/backend/facade/api.py+++ b/products/notifications/backend/facade/api.py@@ -6,11 +6,12 @@ from products.notifications.backend.facade.enums import (SourceType,TargetType,)-from products.notifications.backend.logic import create_notification+from products.notifications.backend.logic import create_notification, has_been_dispatchedfrom products.notifications.backend.resolvers import RecipientsResolver__all__ = ["create_notification",+ "has_been_dispatched","NotificationData","NotificationResourceType","NotificationType",diff --git a/products/notifications/backend/facade/enums.py b/products/notifications/backend/facade/enums.pyindex 710823e6c8b8..9a550e7d29dc 100644--- a/products/notifications/backend/facade/enums.py+++ b/products/notifications/backend/facade/enums.py@@ -12,6 +12,7 @@ class NotificationType(str, Enum):APPROVAL_REQUESTED = "approval_requested"APPROVAL_RESOLVED = "approval_resolved"EXPERIMENT_CONCLUDED = "experiment_concluded"+ PIPELINE_FAILURE = "pipeline_failure"class Priority(str, Enum):diff --git a/products/notifications/backend/logic.py b/products/notifications/backend/logic.pyindex e0c91a7d0116..37e406053760 100644--- a/products/notifications/backend/logic.py+++ b/products/notifications/backend/logic.py@@ -13,6 +13,7 @@ from products.notifications.backend.facade.enums import (AC_RESOURCE_TYPES,NotificationOnlyResourceType,NotificationType,+ TargetType,)from products.notifications.backend.models import NotificationEventfrom products.notifications.backend.resolvers import RecipientsResolver@@ -65,6 +66,27 @@ def _filter_by_user_preferences(return [uid for uid, settings in rows if not _is_disabled(settings)]+def has_been_dispatched(+ *,+ notification_type: NotificationType,+ target_type: TargetType,+ target_id: str,+ resource_id: str,+ source_id: str | None = None,+) -> bool:+ """Idempotency check used by dispatchers whose trigger can fire multiple times for the+ same logical event (e.g. Celery at-least-once retries, racing workers). Returns True if+ a matching NotificationEvent already exists, so the caller can skip a duplicate write.+ """+ return NotificationEvent.objects.filter(+ notification_type=notification_type.value,+ target_type=target_type.value,+ target_id=target_id,+ resource_id=resource_id,+ source_id=source_id,+ ).exists()++def create_notification(data: NotificationData) -> NotificationEvent | None:try:team = Team.objects.select_related("organization").get(id=data.team_id)diff --git a/products/notifications/backend/migrations/0010_alter_notificationevent_notification_type.py b/products/notifications/backend/migrations/0010_alter_notificationevent_notification_type.pynew file mode 100644index 000000000000..f18a1ae6f5ae--- /dev/null+++ b/products/notifications/backend/migrations/0010_alter_notificationevent_notification_type.py@@ -0,0 +1,28 @@+# Generated by Django 5.2.13 on 2026-05-18 07:11++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("notifications", "0009_alter_notificationevent_notification_type"),+ ]++ operations = [+ migrations.AlterField(+ model_name="notificationevent",+ name="notification_type",+ field=models.CharField(+ choices=[+ ("comment_mention", "COMMENT_MENTION"),+ ("alert_firing", "ALERT_FIRING"),+ ("issue_assigned", "ISSUE_ASSIGNED"),+ ("approval_requested", "APPROVAL_REQUESTED"),+ ("approval_resolved", "APPROVAL_RESOLVED"),+ ("experiment_concluded", "EXPERIMENT_CONCLUDED"),+ ("pipeline_failure", "PIPELINE_FAILURE"),+ ],+ max_length=32,+ ),+ ),+ ]diff --git a/products/notifications/backend/migrations/max_migration.txt b/products/notifications/backend/migrations/max_migration.txtindex 8d979961e0da..ce6ef01bd688 100644--- a/products/notifications/backend/migrations/max_migration.txt+++ b/products/notifications/backend/migrations/max_migration.txt@@ -1 +1 @@-0009_alter_notificationevent_notification_type+0010_alter_notificationevent_notification_typediff --git a/tach.toml b/tach.tomlindex 0fc6454d6fde..f4b49984a234 100644--- a/tach.toml+++ b/tach.toml@@ -122,6 +122,7 @@ path = "products.batch_exports"depends_on = ["ee","posthog",+ "products.notifications",]layer = "modules"