: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-modeling): notify when a materialized view starts failing (#80689)
Jovan Sakoviccd70c4e590e9
diff --git a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsxindex 179f027b980e..686c5aad3d96 100644--- a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx+++ b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx@@ -37,6 +37,10 @@ export const REALTIME_NOTIFICATION_TYPE_META: Record<string, { label: string; delabel: 'Pipeline failures',description: 'When a data pipeline or batch export fails',},+ materialization_failure: {+ label: 'Materialized view failures',+ description: 'When a materialized view in your project fails to refresh',+ },issue_assigned: {label: 'Issues assigned',description: 'When an error tracking issue is assigned to you',diff --git a/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx b/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsxindex af7d45f90091..c9392f36f8d4 100644--- a/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx+++ b/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx@@ -6,6 +6,7 @@ import {IconCheckCircle,IconClock,IconComment,+ IconDatabase,IconFlask,IconFolder,IconNotification,@@ -27,6 +28,7 @@ const NOTIFICATION_TYPE_ICONS: Record<string, { Icon: ComponentType<{ className?approval_requested: { Icon: IconCheckCircle, color: 'text-success' },approval_resolved: { Icon: IconCheckCircle, color: 'text-success' },pipeline_failure: { Icon: IconPlug, color: 'text-danger' },+ materialization_failure: { Icon: IconDatabase, color: 'text-danger' },issue_assigned: { Icon: IconBug, color: 'text-primary' },experiment_concluded: { Icon: IconFlask, color: 'text-primary' },project_created: { Icon: IconFolder, color: 'text-primary' },diff --git a/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx b/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsxindex 4326525d95b7..1edd9624b01c 100644--- a/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx+++ b/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx@@ -43,6 +43,8 @@ const NOTIFICATION_DEFAULTS: BooleanNotificationSettings = {all_weekly_digest_disabled: false,project_api_key_exposed: true,materialized_view_sync_failed: false,+ materialized_view_sync_failed_daily: true,+ materialized_view_sync_failed_immediate: false,web_analytics_weekly_digest: true,}@@ -509,13 +511,14 @@ export function UpdateEmailPreferences(): JSX.Element {</div>),[NotificationBlock.MaterializedViewSync]: (- <div className="border rounded p-4">+ <div className="border rounded p-4 space-y-3"><SimpleSwitchsetting="materialized_view_sync_failed"label="Materialized view sync failures"description="Get notified when a materialized view fails to sync"dataAttr="materialized_view_sync_failed_enabled"/>+ <MatviewFailureEmailOptions /></div>),}@@ -544,6 +547,31 @@ export function UpdateEmailPreferences(): JSX.Element {)}+const MatviewFailureEmailOptions = (): JSX.Element | null => {+ const { user } = useValues(userLogic)++ if (!user?.notification_settings?.materialized_view_sync_failed) {+ return null+ }++ return (+ <div className="pl-6 space-y-3">+ <SimpleSwitch+ setting="materialized_view_sync_failed_daily"+ label="Daily digest"+ description="One email a day listing every failing view."+ dataAttr="materialized_view_sync_failed_daily"+ />+ <SimpleSwitch+ setting="materialized_view_sync_failed_immediate"+ label="Right away"+ description="An email when a view starts failing. While it keeps failing, only the daily digest lists it."+ dataAttr="materialized_view_sync_failed_immediate"+ />+ </div>+ )+}+const SimpleSwitch = ({dataAttr,label,diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex bdf11802a2a0..8a713f02916a 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -450,6 +450,8 @@ export interface NotificationSettings {data_pipeline_error_threshold?: numberproject_api_key_exposed?: booleanmaterialized_view_sync_failed?: boolean+ materialized_view_sync_failed_daily?: boolean+ materialized_view_sync_failed_immediate?: booleanweb_analytics_weekly_digest: booleanweb_analytics_weekly_digest_project_enabled?: Record<string, boolean>organization_member_join_email_disabled?: Record<string, boolean>diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex d9540d4f1a89..4d8d63fefe01 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -2017,6 +2017,8 @@ class TestUserAPI(APIBaseTest):"data_pipeline_error_threshold": 0.1,"project_api_key_exposed": True,"materialized_view_sync_failed": True,+ "materialized_view_sync_failed_daily": True,+ "materialized_view_sync_failed_immediate": False,"web_analytics_weekly_digest": True,"organization_member_join_email_disabled": {},"realtime_notifications_disabled": {},@@ -2037,6 +2039,8 @@ class TestUserAPI(APIBaseTest):"data_pipeline_error_threshold": 0.1,"project_api_key_exposed": True,"materialized_view_sync_failed": True,+ "materialized_view_sync_failed_daily": True,+ "materialized_view_sync_failed_immediate": False,"web_analytics_weekly_digest": True,"organization_member_join_email_disabled": {},"realtime_notifications_disabled": {},@@ -2305,6 +2309,8 @@ class TestUserAPI(APIBaseTest):"data_pipeline_error_threshold": 0.01, # Default value"project_api_key_exposed": True, # Default value"materialized_view_sync_failed": False, # Default value+ "materialized_view_sync_failed_daily": True, # Default value+ "materialized_view_sync_failed_immediate": False, # Default value"web_analytics_weekly_digest": True, # Default value"organization_member_join_email_disabled": {}, # Default value"realtime_notifications_disabled": {}, # Default valuediff --git a/posthog/models/user.py b/posthog/models/user.pyindex 49dae2c946d1..b552b308868a 100644--- a/posthog/models/user.py+++ b/posthog/models/user.py@@ -47,6 +47,8 @@ class Notifications(TypedDict, total=False):)project_api_key_exposed: boolmaterialized_view_sync_failed: bool+ materialized_view_sync_failed_daily: bool # One digest a day covering every failing view+ materialized_view_sync_failed_immediate: bool # One email each time a view starts failingweb_analytics_weekly_digest: boolweb_analytics_weekly_digest_project_enabled: dict[str, bool]organization_member_join_email_disabled: dict[@@ -70,6 +72,8 @@ NOTIFICATION_DEFAULTS: Notifications = {"data_pipeline_error_threshold": 0.01, # Default: notify when failure rate exceeds 1%"project_api_key_exposed": True, # Private project API key (secure API key) exposure alerts enabled by default"materialized_view_sync_failed": False, # Materialized view failure disabled by default+ "materialized_view_sync_failed_daily": True, # Digest is the default delivery once failures are turned on+ "materialized_view_sync_failed_immediate": False,"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 defaultdiff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex ffab110fd470..f2226b64a0f7 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -39,6 +39,7 @@ from posthog.models.messaging import MessagingRecord, get_email_hashesfrom posthog.models.scoping import with_team_scopefrom posthog.models.utils import UUIDTfrom posthog.ph_client import feature_enabled_or_false, get_client, ph_scoped_capture+from posthog.rbac.user_access_control import UserAccessControlfrom posthog.scoping_audit import skip_team_scope_auditfrom posthog.user_permissions import UserPermissions@@ -46,6 +47,7 @@ from products.batch_exports.backend.models.batch_export import BatchExport, Batcfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cdp.backend.models.plugin import Plugin, PluginConfigfrom products.conversations.backend.models import Ticket+from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobEngine, DataWarehouseSavedQueryfrom products.error_tracking.backend.facade import api as error_tracking_apifrom products.tasks.backend.facade import api as tasks_facade@@ -60,6 +62,8 @@ class NotificationSetting(Enum):DISCUSSIONS_MENTIONED = "discussions_mentioned"PROJECT_API_KEY_EXPOSED = "project_api_key_exposed"MATERIALIZED_VIEW_SYNC_FAILED = "materialized_view_sync_failed"+ MATERIALIZED_VIEW_SYNC_FAILED_DAILY = "materialized_view_sync_failed_daily"+ MATERIALIZED_VIEW_SYNC_FAILED_IMMEDIATE = "materialized_view_sync_failed_immediate"WEB_ANALYTICS_WEEKLY_DIGEST = "web_analytics_weekly_digest"@@ -71,6 +75,8 @@ NotificationSettingType = Literal["discussions_mentioned","project_api_key_exposed","materialized_view_sync_failed",+ "materialized_view_sync_failed_daily",+ "materialized_view_sync_failed_immediate","web_analytics_weekly_digest",]@@ -102,6 +108,57 @@ def get_members_to_notify(team: Team, notification_setting: NotificationSettingTreturn memberships_to_email+def get_members_to_notify_of_matview_failure(+ team: Team, delivery: NotificationSettingType+) -> list[OrganizationMembership]:+ """Members who turned on materialization failure emails and this way of delivering them.++ Two settings gate these emails, so both are checked: the one that turns them on at all, and+ the one for the digest or the immediate email.+ """+ opted_into_delivery = {membership.id for membership in get_members_to_notify(team, delivery)}+ return [+ membership+ for membership in get_members_to_notify(team, NotificationSetting.MATERIALIZED_VIEW_SYNC_FAILED.value)+ if membership.id in opted_into_delivery+ ]+++def filter_members_by_warehouse_access(+ memberships: list[OrganizationMembership],+ team: Team,+ saved_query: Optional[DataWarehouseSavedQuery] = None,+) -> list[OrganizationMembership]:+ """Drop members who cannot view the warehouse objects an email would name.++ Two gates, because a deny can sit at either level. The resource gate covers members with+ no warehouse access at all. The object gate covers a deny on one view, which the resource+ gate cannot see, and repeats what `Database._is_warehouse_view_denied` does when the same+ member opens that view. Pass `saved_query` whenever the email names a single view.++ Falls back to the unfiltered list when access controls are unavailable: not being able to+ check must not silently stop every failure email.+ """+ if not memberships:+ return memberships++ def allowed(membership: OrganizationMembership) -> bool:+ access = UserAccessControl(membership.user, team)+ if not access.check_access_level_for_resource("warehouse_objects", "viewer"):+ return False+ if saved_query is None or access.is_organization_admin:+ return True+ return bool(access.check_access_level_for_object(saved_query, required_level="viewer"))++ try:+ if not UserAccessControl(memberships[0].user, team).access_controls_supported:+ return memberships+ return [membership for membership in memberships if allowed(membership)]+ except Exception:+ logger.exception("Warehouse access check failed, sending to all subscribed members", team_id=team.id)+ return memberships++def get_members_to_notify_for_pipeline_error(team: Team, failure_rate: float = 1.0, pipeline_id: Optional[str] = None) -> list[OrganizationMembership]:@@ -200,6 +257,13 @@ def should_send_notification(elif notification_type == NotificationSetting.MATERIALIZED_VIEW_SYNC_FAILED.value:return settings.get(notification_type, False)+ # Delivery modes for the setting above, so a member has to pass both it and one of these.+ elif notification_type == NotificationSetting.MATERIALIZED_VIEW_SYNC_FAILED_DAILY.value:+ return settings.get(notification_type, True)++ elif notification_type == NotificationSetting.MATERIALIZED_VIEW_SYNC_FAILED_IMMEDIATE.value:+ return settings.get(notification_type, False)+# The below typeerror is ignored because we're currently handling the notification# types above, so technically it's unreachable. However if another is added but# not handled in this function, we want this as a fallback.@@ -830,11 +894,6 @@ def send_external_data_failure_digest(team_id: int, schemas: list[dict[str, Any]@shared_task(ignore_result=True)@skip_team_scope_auditdef send_matview_failure_digest() -> None:- from products.data_modeling.backend.facade.models import (- DataModelingJob,- DataModelingJobEngine,- DataWarehouseSavedQuery,- )if not is_email_available(with_absolute_urls=True):logger.warning("Email service is not available for materialized view digest")@@ -882,11 +941,6 @@ def send_matview_failure_digest() -> None:@shared_task(**EMAIL_TASK_KWARGS)@skip_team_scope_auditdef send_team_matview_failure_digest(team_id: int, failed_query_ids: list[str], paused_query_ids: list[str]) -> None:- from products.data_modeling.backend.facade.models import (- DataModelingJob,- DataModelingJobEngine,- DataWarehouseSavedQuery,- )if not is_email_available(with_absolute_urls=True):return@@ -897,7 +951,10 @@ def send_team_matview_failure_digest(team_id: int, failed_query_ids: list[str],logger.warning("Team %d not found for matview failure digest", team_id)return- memberships_to_email = get_members_to_notify(team, NotificationSetting.MATERIALIZED_VIEW_SYNC_FAILED.value)+ memberships_to_email = filter_members_by_warehouse_access(+ get_members_to_notify_of_matview_failure(team, NotificationSetting.MATERIALIZED_VIEW_SYNC_FAILED_DAILY.value),+ team,+ )if not memberships_to_email:return@@ -971,6 +1028,61 @@ def send_team_matview_failure_digest(team_id: int, failed_query_ids: list[str],)+@shared_task(**EMAIL_TASK_KWARGS)+@skip_team_scope_audit+def send_matview_failure_immediate_email(team_id: int, saved_query_id: str, job_id: str) -> None:+ """Email members who asked for a materialization failure email as it happens.++ Dispatched on the first failure of a streak only; the job-scoped campaign key+ makes redelivery idempotent per recipient.+ """++ if not is_email_available(with_absolute_urls=True):+ return++ try:+ team = Team.objects.get(id=team_id)+ except Team.DoesNotExist:+ logger.warning("Team %d not found for matview failure email", team_id)+ return++ saved_query = (+ DataWarehouseSavedQuery.objects.filter(id=saved_query_id, team_id=team_id).exclude(deleted=True).first()+ )+ if saved_query is None:+ return++ memberships_to_email = filter_members_by_warehouse_access(+ get_members_to_notify_of_matview_failure(+ team, NotificationSetting.MATERIALIZED_VIEW_SYNC_FAILED_IMMEDIATE.value+ ),+ team,+ saved_query,+ )+ if not memberships_to_email:+ return++ message = EmailMessage(+ campaign_key=f"matview_failure_immediate_{saved_query_id}_{job_id}",+ subject=f"PostHog: Materialized view '{saved_query.name}' failed in {team.name}",+ template_name="saved_query_materialization_failure",+ template_context={+ "team": team,+ "saved_query_name": saved_query.name,+ "saved_query_id": str(saved_query.id),+ },+ )+ for membership in memberships_to_email:+ message.add_user_recipient(membership.user)+ message.send()++ logger.info(+ "Sent immediate materialized view failure email for team %d, saved query %s",+ team_id,+ saved_query_id,+ )++@shared_task(**EMAIL_TASK_KWARGS)def send_canary_email(user_email: str) -> None:message = EmailMessage(diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex 3936ef87cfb4..175f51fa9b02 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -47,6 +47,7 @@'posthog.tasks.email.send_integration_access_request','posthog.tasks.email.send_invite','posthog.tasks.email.send_matview_failure_digest',+ 'posthog.tasks.email.send_matview_failure_immediate_email','posthog.tasks.email.send_member_join','posthog.tasks.email.send_new_ticket_notification','posthog.tasks.email.send_oauth_token_exposed',diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.pyindex 32568617d225..c7b9b21f0250 100644--- a/posthog/tasks/test/test_email.py+++ b/posthog/tasks/test/test_email.py@@ -36,6 +36,7 @@ from posthog.tasks.email import (send_hog_functions_digest_email,send_invite,send_matview_failure_digest,+ send_matview_failure_immediate_email,send_member_join,send_new_ticket_notification,send_password_reset,@@ -51,6 +52,7 @@ from posthog.test.api_keys import create_project_secret_api_keyfrom products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRunfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cdp.backend.models.plugin import Plugin, PluginConfig+from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobEngine, DataWarehouseSavedQuerydef create_org_team_and_user(creation_date: str, email: str, ingested_event: bool = False) -> tuple[Organization, User]:@@ -2131,7 +2133,6 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):jobs: list[tuple[str, dt.timedelta, str | None]],expect_email: bool,) -> None:- from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuerymocked_email_messages = mock_email_messages(MockEmailMessage)@@ -2163,11 +2164,6 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):assert len(mocked_email_messages) == 0def test_send_matview_failure_digest_ignores_duckgres_shadow(self, MockEmailMessage: MagicMock) -> None:- from products.data_modeling.backend.facade.models import (- DataModelingJob,- DataModelingJobEngine,- DataWarehouseSavedQuery,- )mocked_email_messages = mock_email_messages(MockEmailMessage)@@ -2202,11 +2198,6 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):def test_send_matview_failure_digest_shows_clickhouse_error_not_newer_shadow(self, MockEmailMessage: MagicMock) -> None:- from products.data_modeling.backend.facade.models import (- DataModelingJob,- DataModelingJobEngine,- DataWarehouseSavedQuery,- )mocked_email_messages = mock_email_messages(MockEmailMessage)@@ -2242,7 +2233,6 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):assert "duckgres boom" not in mocked_email_messages[0].html_bodydef test_send_matview_failure_digest_not_sent_by_default(self, MockEmailMessage: MagicMock) -> None:- from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuerymocked_email_messages = mock_email_messages(MockEmailMessage)@@ -2265,7 +2255,6 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):assert len(mocked_email_messages) == 0def test_send_matview_failure_digest_kitchen_sink_snapshot(self, MockEmailMessage: MagicMock) -> None:- from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuerymocked_email_messages = mock_email_messages(MockEmailMessage)@@ -2342,7 +2331,6 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):def test_send_matview_failure_digest_truncates_long_errors(self, MockEmailMessage: MagicMock, name: str, error: str, expected_error: str) -> None:- from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuerymocked_email_messages = mock_email_messages(MockEmailMessage)@@ -2369,3 +2357,173 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):rendered_error = mocked_email_messages[0].properties["views"][0]["error"]assert rendered_error == expected_errorassert len(rendered_error) <= 255++ @parameterized.expand(+ [+ (+ "immediate_on",+ {"materialized_view_sync_failed": True, "materialized_view_sync_failed_immediate": True},+ True,+ ),+ (+ "immediate_off",+ {"materialized_view_sync_failed": True, "materialized_view_sync_failed_immediate": False},+ False,+ ),+ ("immediate_unset_defaults_off", {"materialized_view_sync_failed": True}, False),+ (+ "both_deliveries_on",+ {+ "materialized_view_sync_failed": True,+ "materialized_view_sync_failed_daily": True,+ "materialized_view_sync_failed_immediate": True,+ },+ True,+ ),+ (+ "master_off_wins",+ {"materialized_view_sync_failed": False, "materialized_view_sync_failed_immediate": True},+ False,+ ),+ ]+ )+ def test_send_matview_failure_immediate_email_respects_immediate_preference(+ self, MockEmailMessage: MagicMock, name: str, notification_settings: dict, expect_email: bool+ ) -> None:++ mocked_email_messages = mock_email_messages(MockEmailMessage)++ self.user.partial_notification_settings = notification_settings+ self.user.save()++ sq = DataWarehouseSavedQuery.objects.create(team=self.team, name="failing_view", query={"query": "SELECT 1"})+ job = DataModelingJob.objects.create(+ team=self.team,+ saved_query=sq,+ status=DataModelingJob.Status.FAILED,+ error="Some error",+ last_run_at=timezone.now(),+ )++ send_matview_failure_immediate_email(self.team.id, str(sq.id), str(job.id))++ if expect_email:+ assert len(mocked_email_messages) == 1+ assert mocked_email_messages[0].send.call_count == 1+ assert "failing_view" in mocked_email_messages[0].html_body+ else:+ assert len(mocked_email_messages) == 0++ @parameterized.expand(+ [+ ("warehouse_access_granted", True, True, True, True),+ ("warehouse_access_denied", True, False, True, False),+ ("this_view_denied", True, True, False, False),+ ("access_controls_unavailable_still_sends", False, False, False, True),+ ]+ )+ def test_send_matview_failure_immediate_email_respects_warehouse_access(+ self,+ MockEmailMessage: MagicMock,+ name: str,+ access_controls_supported: bool,+ has_warehouse_access: bool,+ has_view_access: bool,+ expect_email: bool,+ ) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)++ self.user.partial_notification_settings = {+ "materialized_view_sync_failed": True,+ "materialized_view_sync_failed_immediate": True,+ }+ self.user.save()++ sq = DataWarehouseSavedQuery.objects.create(team=self.team, name="failing_view", query={"query": "SELECT 1"})+ job = DataModelingJob.objects.create(+ team=self.team,+ saved_query=sq,+ status=DataModelingJob.Status.FAILED,+ error="Some error",+ last_run_at=timezone.now(),+ )++ class FakeUserAccessControl:+ def __init__(self, user: object, team: object) -> None:+ pass++ @property+ def access_controls_supported(self) -> bool:+ return access_controls_supported++ @property+ def is_organization_admin(self) -> bool:+ return False++ def check_access_level_for_resource(self, resource: str, level: str) -> bool:+ return has_warehouse_access++ def check_access_level_for_object(self, obj: object, required_level: str) -> bool:+ return has_view_access++ with patch("posthog.tasks.email.UserAccessControl", FakeUserAccessControl):+ send_matview_failure_immediate_email(self.team.id, str(sq.id), str(job.id))++ assert len(mocked_email_messages) == (1 if expect_email else 0)++ @parameterized.expand(+ [+ ("daily_on", {"materialized_view_sync_failed": True, "materialized_view_sync_failed_daily": True}, True),+ ("daily_off", {"materialized_view_sync_failed": True, "materialized_view_sync_failed_daily": False}, False),+ ("daily_unset_defaults_on", {"materialized_view_sync_failed": True}, True),+ (+ "both_deliveries_on",+ {+ "materialized_view_sync_failed": True,+ "materialized_view_sync_failed_daily": True,+ "materialized_view_sync_failed_immediate": True,+ },+ True,+ ),+ (+ "immediate_only_still_skips_digest",+ {+ "materialized_view_sync_failed": True,+ "materialized_view_sync_failed_daily": False,+ "materialized_view_sync_failed_immediate": True,+ },+ False,+ ),+ (+ "master_off_wins",+ {"materialized_view_sync_failed": False, "materialized_view_sync_failed_daily": True},+ False,+ ),+ ]+ )+ def test_send_matview_failure_digest_respects_daily_preference(+ self, MockEmailMessage: MagicMock, name: str, notification_settings: dict, expect_email: bool+ ) -> None:++ mocked_email_messages = mock_email_messages(MockEmailMessage)++ self.user.partial_notification_settings = notification_settings+ self.user.save()++ sq = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="failing_view",+ query={"query": "SELECT 1"},+ sync_frequency_interval=dt.timedelta(hours=1),+ )+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=sq,+ status=DataModelingJob.Status.FAILED,+ error="Some error",+ last_run_at=timezone.now() - dt.timedelta(hours=1),+ )++ send_matview_failure_digest()++ assert len(mocked_email_messages) == (1 if expect_email else 0)diff --git a/posthog/temporal/data_modeling/activities/fail_materialization.py b/posthog/temporal/data_modeling/activities/fail_materialization.pyindex a3376a7418a1..da6558fc3c02 100644--- a/posthog/temporal/data_modeling/activities/fail_materialization.py+++ b/posthog/temporal/data_modeling/activities/fail_materialization.py@@ -10,7 +10,10 @@ from structlog.contextvars import bind_contextvarsfrom temporalio import activityfrom posthog.exceptions_capture import capture_exception+from posthog.models import Team, User+from posthog.rbac.user_access_control import UserAccessControlfrom posthog.sync import database_sync_to_async_pool+from posthog.tasks.email import send_matview_failure_immediate_emailfrom products.data_modeling.backend.facade.models import (DataModelingJob,@@ -20,6 +23,15 @@ from products.data_modeling.backend.facade.models import (Node,)from products.data_warehouse.backend.facade.api import pause_saved_query_schedule+from products.notifications.backend.facade.api import (+ NotificationData,+ NotificationType,+ Priority,+ RecipientsResolver,+ TargetType,+ create_notification,+ has_been_dispatched,+)from ..metrics import get_node_suspended_metricfrom .utils import (@@ -38,16 +50,23 @@ LOGGER = get_logger(__name__)CONSECUTIVE_TIMEOUTS_TO_PAUSE = 5-def _get_previous_jobs(saved_query_id: UUID, current_job_id: UUID, count: int) -> "QuerySet[DataModelingJob]":+def _get_previous_jobs(+ saved_query_id: UUID, current_job_id: UUID, count: int, ignore_inconclusive: bool = False+) -> "QuerySet[DataModelingJob]":"""Get the most recent jobs for a saved query, excluding the current job."""- return (+ jobs = (DataModelingJob.objects.filter(saved_query_id=saved_query_id, engine=DataModelingJobEngine.CLICKHOUSE).exclude(id=current_job_id)# a skipped run never executed, so it is evidence of neither health nor failure. Leaving it# in lets one upstream outage clear a timeout streak that is about to pause the schedule..exclude(status=DataModelingJobStatus.SKIPPED)- .order_by("-created_at")[:count])+ if ignore_inconclusive:+ # Neither status says whether the query recovered: a cancel is our doing (preemption, a+ # deploy), and a run still marked running either is one, or was abandoned by a dead worker.+ # The timeout counter keeps treating both as a break, deliberately.+ jobs = jobs.exclude(status__in=(DataModelingJobStatus.CANCELLED, DataModelingJobStatus.RUNNING))+ return jobs.order_by("-created_at")[:count]def should_pause_schedule_for_timeout(saved_query_id: UUID, current_job_id: UUID) -> tuple[bool, int]:@@ -148,6 +167,84 @@ def _revert_materialization_on_unknown_table(job: DataModelingJob, saved_query:job.save(update_fields=["error"])+class _SavedQueryViewers(RecipientsResolver):+ """Narrow team recipients to the members allowed to open one specific view.++ `create_notification` gates on the parent `warehouse_objects` resource, which cannot see a+ deny placed on an individual view. This repeats the check `Database._is_warehouse_view_denied`+ makes when the same member opens that view, so a notification never names a view they would+ be refused. Both gates run: this one narrows, the shared one narrows again.+ """++ def __init__(self, saved_query: DataWarehouseSavedQuery) -> None:+ self._saved_query = saved_query++ def resolve(self, target_type: TargetType, target_id: str, team_id: int | None) -> list[int]:+ user_ids = super().resolve(target_type, target_id, team_id)+ if not user_ids or team_id is None:+ return user_ids+ team = Team.objects.filter(id=team_id).first()+ if team is None:+ return user_ids++ try:+ return [+ user.id+ for user in User.objects.filter(id__in=user_ids)+ if (access := UserAccessControl(user, team)).is_organization_admin+ or access.check_access_level_for_object(self._saved_query, required_level="viewer")+ ]+ except Exception:+ # Not being able to check must not stop every failure notification.+ capture_exception()+ return user_ids+++@database_sync_to_async_pool+def _maybe_notify_materialization_failure(+ job: DataModelingJob, saved_query: DataWarehouseSavedQuery, team_id: int+) -> bool:+ """Notify on the first failure of a streak; repeats of an ongoing streak stay quiet."""+ # An idempotent retry can land here with a job another path already completed or cancelled.+ if job.status != DataModelingJobStatus.FAILED:+ return False+ previous_job = _get_previous_jobs(saved_query.id, job.id, 1, ignore_inconclusive=True).first()+ if previous_job is not None and previous_job.status == DataModelingJobStatus.FAILED:+ return False++ # The email task dedupes per (recipient, job) via MessagingRecord, so an activity+ # retry that already sent the in-app notification still can't double-send email.+ send_matview_failure_immediate_email.delay(team_id, str(saved_query.id), str(job.id))++ if has_been_dispatched(+ notification_type=NotificationType.MATERIALIZATION_FAILURE,+ target_type=TargetType.TEAM,+ target_id=str(team_id),+ resource_id=str(saved_query.id),+ source_id=str(job.id),+ ):+ return False+ create_notification(+ NotificationData(+ team_id=team_id,+ notification_type=NotificationType.MATERIALIZATION_FAILURE,+ priority=Priority.NORMAL,+ title=f"{saved_query.name} failed to materialize"[:255],+ body=strip_hostname_from_error(job.error or "The latest materialization run failed.")[:400],+ target_type=TargetType.TEAM,+ target_id=str(team_id),+ # "warehouse_objects" (not "warehouse_view") is the AC resource — anything else+ # silently skips the access-control filter in create_notification+ resource_type="warehouse_objects",+ resource_id=str(saved_query.id),+ source_url=f"/project/{team_id}/sql?open_view={saved_query.id}",+ source_id=str(job.id),+ resolver=_SavedQueryViewers(saved_query),+ )+ )+ return True++@activity.defnasync def fail_materialization_activity(inputs: FailMaterializationInputs) -> None:"""Mark materialization as failed and update node properties."""@@ -168,6 +265,7 @@ async def fail_materialization_activity(inputs: FailMaterializationInputs) -> Noif not inputs.update_node:returnerror = inputs.error+ saved_query = Nonetry:saved_query = await _get_saved_query_for_job(job)if saved_query is None:@@ -203,8 +301,22 @@ async def fail_materialization_activity(inputs: FailMaterializationInputs) -> Noawait logger.ainfo(f"Suspended node {inputs.node_id} (clickhouse) after {CONSECUTIVE_FAILURES_TO_SUSPEND} consecutive failures",)+except Exception as e:capture_exception(e)await logger.aexception(f"Failed to run error-specific recovery for node {inputs.node_id}: {strip_hostname_from_error(str(e))}")++ # Kept out of the recovery block above: a failing pause or revert is exactly when someone most+ # needs telling, so it must not take the notification down with it.+ if saved_query is not None and not inputs.cancelled:+ try:+ notified = await _maybe_notify_materialization_failure(job, saved_query, inputs.team_id)+ if notified:+ await logger.ainfo(f"Sent materialization failure notification for node {inputs.node_id}")+ except Exception as e:+ capture_exception(e)+ await logger.aexception(+ f"Failed to notify materialization failure for node {inputs.node_id}: {strip_hostname_from_error(str(e))}"+ )diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex f3a6e8787ce9..2b83bb700015 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -3,6 +3,7 @@ import contextlibfrom collections.abc import AsyncIterator, Collection, Iterablefrom io import BytesIOfrom typing import Any, cast+from uuid import uuid4import pytestimport unittest.mock@@ -16,6 +17,7 @@ import pyarrow.parquet as pqfrom posthog.hogql.resolver import ResolverFactory+from posthog.models import Userfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.data_modeling.activities import (CreateDataModelingJobInputs,@@ -29,6 +31,7 @@ from posthog.temporal.data_modeling.activities import (prepare_queryable_table_activity,succeed_materialization_activity,)+from posthog.temporal.data_modeling.activities.fail_materialization import _SavedQueryViewersfrom posthog.temporal.data_modeling.activities.materialize_view import (LOGGER,InvalidNodeTypeException,@@ -48,6 +51,7 @@ from products.data_modeling.backend.facade.models import (NodeType,)from products.data_warehouse.backend.facade.api import CreateTableResult+from products.notifications.backend.facade.api import NotificationType, TargetTypefrom products.warehouse_sources.backend.facade.models import DataWarehouseTablepytestmark = [pytest.mark.asyncio, pytest.mark.django_db]@@ -162,6 +166,156 @@ class TestFailMaterializationActivity:await database_sync_to_async(anode.refresh_from_db)()assert is_node_suspended(anode, DataModelingJobEngine.CLICKHOUSE) is True+ @pytest.mark.parametrize(+ "previous_status,expect_notification",+ [+ (None, True),+ (DataModelingJob.Status.COMPLETED, True),+ (DataModelingJob.Status.FAILED, False),+ ],+ )+ async def test_notifies_only_on_first_failure_of_streak(+ self, activity_environment, ateam, anode, asaved_query, adag, previous_status, expect_notification+ ):+ if previous_status is not None:+ error = "boom" if previous_status == DataModelingJob.Status.FAILED else None+ await _make_job(ateam, asaved_query, previous_status, error=error)+ current_job = await _make_job(ateam, asaved_query, DataModelingJob.Status.RUNNING)++ inputs = FailMaterializationInputs(+ team_id=ateam.pk,+ node_id=str(anode.id),+ dag_id=str(adag.id),+ job_id=str(current_job.id),+ error="Some non-timeout error",+ )+ with unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.fail_materialization.create_notification"+ ) as mock_create:+ await activity_environment.run(fail_materialization_activity, inputs)++ if expect_notification:+ mock_create.assert_called_once()+ data = mock_create.call_args.args[0]+ assert data.notification_type == NotificationType.MATERIALIZATION_FAILURE+ assert data.target_id == str(ateam.pk)+ assert data.resource_id == str(asaved_query.id)+ else:+ mock_create.assert_not_called()++ @pytest.mark.parametrize("intervening_status", [DataModelingJob.Status.CANCELLED, DataModelingJob.Status.RUNNING])+ async def test_an_inconclusive_run_does_not_restart_the_streak(+ self, activity_environment, ateam, anode, asaved_query, adag, intervening_status+ ):+ await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="boom")+ await _make_job(ateam, asaved_query, intervening_status)+ current_job = await _make_job(ateam, asaved_query, DataModelingJob.Status.RUNNING)++ inputs = FailMaterializationInputs(+ team_id=ateam.pk,+ node_id=str(anode.id),+ dag_id=str(adag.id),+ job_id=str(current_job.id),+ error="Some non-timeout error",+ )+ with unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.fail_materialization.create_notification"+ ) as mock_create:+ await activity_environment.run(fail_materialization_activity, inputs)++ mock_create.assert_not_called()++ async def test_notifies_when_recovery_raises(self, activity_environment, ateam, anode, asaved_query, adag):+ current_job = await _make_job(ateam, asaved_query, DataModelingJob.Status.RUNNING)++ inputs = FailMaterializationInputs(+ team_id=ateam.pk,+ node_id=str(anode.id),+ dag_id=str(adag.id),+ job_id=str(current_job.id),+ error="Some non-timeout error",+ )+ with (+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.fail_materialization.maybe_suspend_node_for_engine",+ side_effect=Exception("suspension blew up"),+ ),+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.fail_materialization.create_notification"+ ) as mock_create,+ ):+ await activity_environment.run(fail_materialization_activity, inputs)++ mock_create.assert_called_once()++ async def test_does_not_notify_when_cancelled(self, activity_environment, ateam, anode, asaved_query, adag):+ current_job = await _make_job(ateam, asaved_query, DataModelingJob.Status.RUNNING)++ inputs = FailMaterializationInputs(+ team_id=ateam.pk,+ node_id=str(anode.id),+ dag_id=str(adag.id),+ job_id=str(current_job.id),+ error="Workflow was cancelled",+ cancelled=True,+ )+ with unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.fail_materialization.create_notification"+ ) as mock_create:+ await activity_environment.run(fail_materialization_activity, inputs)++ mock_create.assert_not_called()++ async def test_notification_resolver_drops_members_denied_on_the_view(+ self, activity_environment, ateam, anode, asaved_query, adag, aorganization+ ):+ # These tests share a database, so the emails have to be unique per run.+ allowed = await database_sync_to_async(User.objects.create_and_join)(+ aorganization, f"allowed-{uuid4()}@posthog.com", None+ )+ denied = await database_sync_to_async(User.objects.create_and_join)(+ aorganization, f"denied-{uuid4()}@posthog.com", None+ )++ class FakeAccess:+ def __init__(self, user, team):+ self._user = user++ is_organization_admin = False++ def check_access_level_for_object(self, obj, required_level):+ return self._user.id == allowed.id++ with unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.fail_materialization.UserAccessControl", FakeAccess+ ):+ resolved = await database_sync_to_async(_SavedQueryViewers(asaved_query).resolve)(+ TargetType.TEAM, str(ateam.pk), ateam.pk+ )++ assert allowed.id in resolved+ assert denied.id not in resolved++ async def test_notification_carries_the_per_view_resolver(+ self, activity_environment, ateam, anode, asaved_query, adag+ ):+ current_job = await _make_job(ateam, asaved_query, DataModelingJob.Status.RUNNING)+ inputs = FailMaterializationInputs(+ team_id=ateam.pk,+ node_id=str(anode.id),+ dag_id=str(adag.id),+ job_id=str(current_job.id),+ error="boom",+ )++ with unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.fail_materialization.create_notification"+ ) as mock_create:+ await activity_environment.run(fail_materialization_activity, inputs)++ resolver = mock_create.call_args.args[0].resolver+ assert isinstance(resolver, _SavedQueryViewers)+async def test_timeout_does_not_pause_schedule_with_fewer_than_5_previous_jobs(self, activity_environment, ateam, anode, asaved_query, adag):diff --git a/products/notifications/backend/facade/enums.py b/products/notifications/backend/facade/enums.pyindex 4b4576cd191f..a7f58850469d 100644--- a/products/notifications/backend/facade/enums.py+++ b/products/notifications/backend/facade/enums.py@@ -20,6 +20,7 @@ class NotificationType(str, Enum):ACHIEVEMENT_UNLOCKED = "achievement_unlocked"SUBSCRIPTION_NUDGE = "subscription_nudge"EMAIL_REPUTATION = "email_reputation"+ MATERIALIZATION_FAILURE = "materialization_failure"class Priority(str, Enum):diff --git a/products/notifications/backend/migrations/0021_alter_notificationevent_notification_type.py b/products/notifications/backend/migrations/0021_alter_notificationevent_notification_type.pynew file mode 100644index 000000000000..86f56afb4375--- /dev/null+++ b/products/notifications/backend/migrations/0021_alter_notificationevent_notification_type.py@@ -0,0 +1,34 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("notifications", "0020_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"),+ ("project_created", "PROJECT_CREATED"),+ ("usage_spike", "USAGE_SPIKE"),+ ("reminder", "REMINDER"),+ ("web_analytics_digest", "WEB_ANALYTICS_DIGEST"),+ ("achievement_unlocked", "ACHIEVEMENT_UNLOCKED"),+ ("subscription_nudge", "SUBSCRIPTION_NUDGE"),+ ("email_reputation", "EMAIL_REPUTATION"),+ ("materialization_failure", "MATERIALIZATION_FAILURE"),+ ],+ max_length=32,+ ),+ ),+ ]diff --git a/products/notifications/backend/migrations/max_migration.txt b/products/notifications/backend/migrations/max_migration.txtindex c0fcaac4b6fb..3e86d8e2fc48 100644--- a/products/notifications/backend/migrations/max_migration.txt+++ b/products/notifications/backend/migrations/max_migration.txt@@ -1 +1 @@-0020_alter_notificationevent_notification_type+0021_alter_notificationevent_notification_type