: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): one failure notification per DAG run (#81956)
Jovan Sakovic59ef065a68e2
diff --git a/posthog/temporal/data_modeling/__init__.py b/posthog/temporal/data_modeling/__init__.pyindex 8dbdda449d5b..5cd3e7cda0e4 100644--- a/posthog/temporal/data_modeling/__init__.py+++ b/posthog/temporal/data_modeling/__init__.py@@ -6,6 +6,7 @@ from posthog.temporal.data_modeling.activities import (get_dag_structure_activity,materialize_view_activity,materialize_view_duckgres_activity,+ notify_dag_materialization_failures_activity,preempt_dag_run_activity,prepare_queryable_table_activity,record_skipped_data_modeling_jobs_activity,@@ -54,4 +55,5 @@ ACTIVITIES = [create_job_model_activity,cleanup_running_jobs_activity,preempt_dag_run_activity,+ notify_dag_materialization_failures_activity,]diff --git a/posthog/temporal/data_modeling/activities/__init__.py b/posthog/temporal/data_modeling/activities/__init__.pyindex fcc455e7e2e0..29d1807f13aa 100644--- a/posthog/temporal/data_modeling/activities/__init__.py+++ b/posthog/temporal/data_modeling/activities/__init__.py@@ -16,6 +16,10 @@ from .materialize_view_duckgres import (check_duckgres_shadow_enabled_activity,materialize_view_duckgres_activity,)+from .notify_materialization_failure import (+ NotifyDAGMaterializationFailuresInputs,+ notify_dag_materialization_failures_activity,+)from .preempt_dag_run import PreemptDAGRunInputs, preempt_dag_run_activityfrom .prepare_queryable_table import (PrepareQueryableTableInputs,@@ -38,6 +42,7 @@ __all__ = ["DuckgresShadowResult","GetDAGStructureInputs","FailMaterializationInputs",+ "NotifyDAGMaterializationFailuresInputs","MaterializeViewInputs","MaterializeViewResult","PreemptDAGRunInputs",@@ -50,6 +55,7 @@ __all__ = ["record_skipped_data_modeling_jobs_activity","enrich_view_semantics_activity","fail_materialization_activity",+ "notify_dag_materialization_failures_activity","materialize_view_activity","materialize_view_duckgres_activity","get_dag_structure_activity",diff --git a/posthog/temporal/data_modeling/activities/fail_materialization.py b/posthog/temporal/data_modeling/activities/fail_materialization.pyindex da6558fc3c02..55ce52f2a52e 100644--- a/posthog/temporal/data_modeling/activities/fail_materialization.py+++ b/posthog/temporal/data_modeling/activities/fail_materialization.py@@ -1,6 +1,5 @@import datetime as dtimport dataclasses-from typing import TYPE_CHECKINGfrom uuid import UUIDfrom django.db import transaction@@ -10,10 +9,7 @@ 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,@@ -23,60 +19,31 @@ 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_metric+from .notify_materialization_failure import maybe_notify_materialization_failurefrom .utils import (CONSECUTIVE_FAILURES_TO_SUSPEND,bind_data_modeling_log_context,+ get_previous_jobs,maybe_suspend_node_for_engine,strip_hostname_from_error,update_node_system_properties,)-if TYPE_CHECKING:- from django.db.models import QuerySet-LOGGER = get_logger(__name__)CONSECUTIVE_TIMEOUTS_TO_PAUSE = 5-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."""- 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)- )- 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]:+def should_pause_schedule_for_timeout(saved_query_id: UUID, current_job: DataModelingJob) -> tuple[bool, int]:"""Check if the schedule should be paused based on consecutive timeout failures.Returns True only if all of the previous CONSECUTIVE_TIMEOUTS_TO_PAUSE jobsfailed due to query timeouts. This prevents pausing schedules for transienttimeouts that can occur due to temporary ClickHouse load."""- previous_jobs = list(_get_previous_jobs(saved_query_id, current_job_id, CONSECUTIVE_TIMEOUTS_TO_PAUSE))+ previous_jobs = list(get_previous_jobs(saved_query_id, current_job, CONSECUTIVE_TIMEOUTS_TO_PAUSE))count = 0for job in previous_jobs:if job.status != DataModelingJobStatus.FAILED:@@ -145,7 +112,7 @@ def _maybe_pause_schedule_on_timeout(job: DataModelingJob, saved_query: DataWareReturns True if the schedule was paused, False otherwise. This prevents pausingschedules for transient timeouts that can occur due to temporary ClickHouse load."""- should_pause, _ = should_pause_schedule_for_timeout(saved_query.id, job.id)+ should_pause, _ = should_pause_schedule_for_timeout(saved_query.id, job)if not should_pause:return False@@ -167,84 +134,6 @@ 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."""@@ -312,7 +201,7 @@ async def fail_materialization_activity(inputs: FailMaterializationInputs) -> No# 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)+ 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:diff --git a/posthog/temporal/data_modeling/activities/notify_materialization_failure.py b/posthog/temporal/data_modeling/activities/notify_materialization_failure.pynew file mode 100644index 000000000000..a5e726867c43--- /dev/null+++ b/posthog/temporal/data_modeling/activities/notify_materialization_failure.py@@ -0,0 +1,300 @@+"""Telling people a materialized view broke.++Two shapes, because a failure arrives two ways:++- A view materialized on its own ("Sync now", a single-node schedule) notifies from its own+ failure path, in `maybe_notify_materialization_failure`.+- A view materialized inside a DAG run leaves the in-app notification to the run, which ends by+ posting one notification per audience covering every view it broke. A tier run that breaks many+ views is otherwise that many pings, a few seconds apart.++Email keeps the per-view shape in both cases: it dedupes per (recipient, job) in MessagingRecord,+and the digest already coalesces a day's worth.+"""++import hashlib+import dataclasses++from structlog import get_logger+from structlog.contextvars import bind_contextvars+from temporalio import activity++from posthog.exceptions_capture import capture_exception+from posthog.models import Team, User+from posthog.rbac.user_access_control import UserAccessControl+from posthog.sync import database_sync_to_async_pool+from posthog.tasks.email import send_matview_failure_immediate_email++from products.data_modeling.backend.facade.models import (+ DataModelingJob,+ DataModelingJobEngine,+ DataModelingJobStatus,+ DataWarehouseSavedQuery,+)+from products.notifications.backend.facade.api import (+ NotificationData,+ NotificationType,+ Priority,+ RecipientsResolver,+ TargetType,+ create_notification,+)++from .utils import starts_a_failure_streak, strip_hostname_from_error++LOGGER = get_logger(__name__)++# Beyond this the title's count carries the scale, and the body stays readable.+MAX_NAMED_VIEWS = 5++[email protected](frozen=True, kw_only=True)+class NotifyDAGMaterializationFailuresInputs:+ team_id: int+ dag_id: str+ parent_workflow_id: str+ # `start_time.isoformat()`, the same value the run put at the end of each child's workflow id.+ run_started_at: str++[email protected](frozen=True, kw_only=True)+class _FailedView:+ """A failed job with the view it was materializing.++ `DataModelingJob.saved_query` is nullable, and everything below needs both halves. Pairing them+ once, where the query already excluded the null ones, keeps the rest free of the impossible case.+ """++ job: DataModelingJob+ saved_query: DataWarehouseSavedQuery+++def _access_of(team: Team, user_ids: list[int]) -> list[tuple[int, UserAccessControl]]:+ """Build each member's access once, so a run that broke many views doesn't rebuild it per view."""+ return [(user.id, UserAccessControl(user, team)) for user in User.objects.filter(id__in=user_ids)]+++def _viewers_of(accesses: list[tuple[int, UserAccessControl]], saved_query: DataWarehouseSavedQuery) -> list[int]:+ """Keep only 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.+ """+ viewers = []+ for user_id, access in accesses:+ try:+ if access.is_organization_admin or access.check_access_level_for_object(+ saved_query, required_level="viewer"+ ):+ viewers.append(user_id)+ except Exception:+ # Dropping only the member whose check failed. Admitting them instead would name a view,+ # its error and its link to someone the same check may be about to deny.+ capture_exception()+ return viewers+++class _SavedQueryViewers(RecipientsResolver):+ """Narrow team recipients to the members allowed to open one specific view.++ Both gates run: this one narrows, the shared one in `create_notification` 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:+ return user_ids+ team = Team.objects.filter(id=team_id).first() if team_id is not None else None+ if team is None:+ # No team is no way to run the per-view check, so nobody is told, for the same reason+ # `_viewers_of` drops a member it could not check.+ return []+ return _viewers_of(_access_of(team, user_ids), self._saved_query)+++class _PrecomputedViewers(RecipientsResolver):+ """Recipients the coalescing activity already narrowed, per view, before grouping."""++ def __init__(self, allowed: frozenset[int]) -> None:+ self._allowed = allowed++ def resolve(self, target_type: TargetType, target_id: str, team_id: int | None) -> list[int]:+ return [user_id for user_id in super().resolve(target_type, target_id, team_id) if user_id in self._allowed]+++@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+ if not starts_a_failure_streak(saved_query.id, job):+ 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 job.parent_workflow_id:+ # The DAG run this belongs to notifies for every view it broke, once, at the end.+ return False++ create_notification(+ _failure_notification(+ team_id=team_id,+ views=[_FailedView(job=job, saved_query=saved_query)],+ resolver=_SavedQueryViewers(saved_query),+ source_id=str(job.id),+ )+ )+ return True+++def _failure_copy(views: list[_FailedView]) -> tuple[str, str]:+ names = [view.saved_query.name for view in views]+ if len(names) == 1:+ return (+ f"{names[0]} failed to materialize",+ strip_hostname_from_error(views[0].job.error or "The latest materialization run failed."),+ )+ body = ", ".join(names[:MAX_NAMED_VIEWS])+ if len(names) > MAX_NAMED_VIEWS:+ body = f"{body}, and {len(names) - MAX_NAMED_VIEWS} more"+ return f"{len(names)} views failed to materialize", body+++def _dedupe_key(views: list[_FailedView]) -> str:+ """Identity of one notification: this set of failed runs.++ Keyed on the runs rather than the views, so the same views breaking again in a later run notify+ again while a retry of this activity does not. Hashed to fit `idempotency_key`, which a unique+ constraint enforces — the check-then-create it replaces cannot, and this activity does run twice+ when a slow one hits its timeout.+ """+ runs = "|".join(sorted(str(view.job.id) for view in views))+ return f"matview-failure-{hashlib.sha256(runs.encode()).hexdigest()}"+++def _failure_notification(+ *, team_id: int, views: list[_FailedView], resolver: RecipientsResolver, source_id: str+) -> NotificationData:+ title, body = _failure_copy(views)+ source_url = f"/project/{team_id}/sql"+ if len(views) == 1:+ source_url = f"{source_url}?open_view={views[0].saved_query.id}"+ return NotificationData(+ team_id=team_id,+ notification_type=NotificationType.MATERIALIZATION_FAILURE,+ priority=Priority.NORMAL,+ title=title[:255],+ body=body[: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(views[0].saved_query.id),+ source_url=source_url,+ source_id=source_id,+ idempotency_key=_dedupe_key(views),+ resolver=resolver,+ )+++def _group_by_audience(+ team: Team, views: list[_FailedView], team_user_ids: list[int]+) -> list[tuple[frozenset[int], list[_FailedView]]]:+ """One notification per set of members who can see exactly the same failures.++ Views a member cannot open must not be named to them, so this groups by what each member sees+ rather than by who sees each view. Those are not the same: per-view viewer sets overlap wherever+ one view is denied and another is not — and every org admin sits in all of them — so a member in+ two would get two notifications for one run, each naming part of what broke. Grouping this way,+ every member appears in exactly one group. A team that denies nobody lands in a single group,+ which is the point of coalescing.+ """+ accesses = _access_of(team, team_user_ids)+ visible: dict[int, list[_FailedView]] = {}+ for view in views:+ for user_id in _viewers_of(accesses, view.saved_query):+ visible.setdefault(user_id, []).append(view)++ by_audience: dict[tuple[str, ...], tuple[list[int], list[_FailedView]]] = {}+ for user_id, seen in visible.items():+ # `views` is sorted and iterated in order above, so members seeing the same failures build+ # the same list, and the same key.+ audience, _ = by_audience.setdefault(tuple(str(view.job.id) for view in seen), ([], seen))+ audience.append(user_id)+ return [(frozenset(audience), seen) for audience, seen in by_audience.values()]+++@database_sync_to_async_pool+def _notify_dag_materialization_failures(inputs: NotifyDAGMaterializationFailuresInputs) -> int:+ team = Team.objects.filter(id=inputs.team_id).first()+ if team is None:+ return 0++ # A manually triggered run can reuse its workflow id, so matching the parent alone would sweep+ # in an earlier run's failures. Every child of this run ends its id with this run's start time,+ # which the run itself generated — no clock comparison, so no skew to get wrong.+ # `team_id` leads because neither workflow column is indexed, and the suffix match can only ever+ # be a post-filter; it puts the `(team, status)` index in front of a table that only grows.+ failed_jobs = DataModelingJob.objects.filter(+ team_id=inputs.team_id,+ parent_workflow_id=inputs.parent_workflow_id,+ workflow_id__endswith=f"-{inputs.run_started_at}",+ status=DataModelingJobStatus.FAILED,+ engine=DataModelingJobEngine.CLICKHOUSE,+ saved_query__isnull=False,+ ).select_related("saved_query")++ newly_failed = [+ _FailedView(job=job, saved_query=job.saved_query)+ for job in failed_jobs+ if job.saved_query is not None and starts_a_failure_streak(job.saved_query.id, job)+ ]+ if not newly_failed:+ return 0+ # The query above has no order of its own, and a retry has to rebuild the same groups under the+ # same keys to be recognised as one it already sent.+ newly_failed.sort(key=lambda view: str(view.job.id))++ team_user_ids = RecipientsResolver().resolve(TargetType.TEAM, str(inputs.team_id), inputs.team_id)++ sent = 0+ for viewers, views in _group_by_audience(team, newly_failed, team_user_ids):+ create_notification(+ _failure_notification(+ team_id=inputs.team_id,+ views=views,+ resolver=_PrecomputedViewers(viewers),+ source_id=str(views[0].job.id),+ )+ )+ sent += 1+ return sent+++async def notify_dag_materialization_failures_activity(inputs: NotifyDAGMaterializationFailuresInputs) -> int:+ """Post one notification per audience covering every view this DAG run broke."""+ bind_contextvars(team_id=inputs.team_id)+ logger = LOGGER.bind()+ try:+ sent = await _notify_dag_materialization_failures(inputs)+ except Exception as e:+ capture_exception(e)+ await logger.aexception(+ f"Failed to notify materialization failures for dag {inputs.dag_id}: {strip_hostname_from_error(str(e))}"+ )+ return 0+ if sent:+ await logger.ainfo(f"Sent {sent} coalesced materialization failure notification(s) for dag {inputs.dag_id}")+ return sentdiff --git a/posthog/temporal/data_modeling/activities/utils.py b/posthog/temporal/data_modeling/activities/utils.pyindex b880fee56a9b..074d01bf98c9 100644--- a/posthog/temporal/data_modeling/activities/utils.py+++ b/posthog/temporal/data_modeling/activities/utils.py@@ -1,5 +1,6 @@import reimport datetime as dt+from typing import TYPE_CHECKINGfrom uuid import UUIDfrom django.db import transaction@@ -35,15 +36,20 @@ __all__ = ["clear_node_suspension","clear_node_suspension_for_engine","count_leading_failures",+ "get_previous_jobs","is_externally_aborted","is_node_suspended","is_suspension_enforced","mark_node_suspended","maybe_suspend_node_for_engine",+ "starts_a_failure_streak","strip_hostname_from_error","update_node_system_properties",]+if TYPE_CHECKING:+ from django.db.models import QuerySet+LOGGER = get_logger(__name__)# Consecutive failed jobs (per engine) before a node is suspended from future DAG runs.@@ -51,6 +57,40 @@ CONSECUTIVE_FAILURES_TO_SUSPEND = 5SUSPENSION_ENFORCEMENT_FLAG = "data-modeling-suspend-failing-nodes"++def get_previous_jobs(+ saved_query_id: UUID, current_job: DataModelingJob, count: int, ignore_inconclusive: bool = False+) -> "QuerySet[DataModelingJob]":+ """Get the runs of a saved query that came before this one.++ Bounded by the current job's own timestamp rather than just excluding its id: a DAG run judges+ a failure once every sibling has finished, so a "Sync now" of the same view can land in between+ and would otherwise be read as what came before it.+ """+ jobs = (+ DataModelingJob.objects.filter(+ saved_query_id=saved_query_id,+ engine=DataModelingJobEngine.CLICKHOUSE,+ created_at__lt=current_job.created_at,+ )+ # 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)+ )+ 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 starts_a_failure_streak(saved_query_id: UUID, current_job: DataModelingJob) -> bool:+ """True when this failure is the edge into a streak, so repeats of an ongoing one stay quiet."""+ previous_job = get_previous_jobs(saved_query_id, current_job, 1, ignore_inconclusive=True).first()+ return previous_job is None or previous_job.status != DataModelingJobStatus.FAILED++# The test before adding a marker is "was the query denied the chance to fail on its own merits",# NOT "was this our fault" - a query that exhausts memory is one we do want suspended.EXTERNALLY_ABORTED_MARKERS = (diff --git a/posthog/temporal/data_modeling/run_workflow.py b/posthog/temporal/data_modeling/run_workflow.pyindex 0eb383a91787..7f589ae3ed78 100644--- a/posthog/temporal/data_modeling/run_workflow.py+++ b/posthog/temporal/data_modeling/run_workflow.py@@ -663,9 +663,7 @@ async def materialize_model(await logger.ainfo("Query exceeded timeout limit for model %s", model_label)await mark_job_as_failed(job, error_message, logger)- should_pause, count = await database_sync_to_async(should_pause_schedule_for_timeout)(- saved_query.id, job.id- )+ should_pause, count = await database_sync_to_async(should_pause_schedule_for_timeout)(saved_query.id, job)if should_pause:saved_query.sync_frequency_interval = Noneawait database_sync_to_async(saved_query.save)()diff --git a/posthog/temporal/data_modeling/workflows/execute_dag.py b/posthog/temporal/data_modeling/workflows/execute_dag.pyindex 566717daa6fb..58c964c6247b 100644--- a/posthog/temporal/data_modeling/workflows/execute_dag.py+++ b/posthog/temporal/data_modeling/workflows/execute_dag.py@@ -14,10 +14,12 @@ from posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.data_modeling.activities import (UPSTREAM_NAMES_IN_SKIP_REASON,GetDAGStructureInputs,+ NotifyDAGMaterializationFailuresInputs,PreemptDAGRunInputs,RecordSkippedDataModelingJobsInputs,SkippedDataModelingNode,get_dag_structure_activity,+ notify_dag_materialization_failures_activity,preempt_dag_run_activity,record_skipped_data_modeling_jobs_activity,)@@ -462,6 +464,19 @@ class ExecuteDAGWorkflow(PostHogWorkflow):await self._run_data_quality_checks(inputs, node_results)+ if failed_nodes:+ await temporalio.workflow.execute_activity(+ notify_dag_materialization_failures_activity,+ NotifyDAGMaterializationFailuresInputs(+ team_id=inputs.team_id,+ dag_id=inputs.dag_id,+ parent_workflow_id=temporalio.workflow.info().workflow_id,+ run_started_at=start_time.isoformat(),+ ),+ start_to_close_timeout=dt.timedelta(minutes=5),+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),+ )+return ExecuteDAGResult(dag_id=inputs.dag_id,scheduled_nodes=len(node_results),diff --git a/posthog/temporal/tests/data_modeling/test_execute_dag_data_quality.py b/posthog/temporal/tests/data_modeling/test_execute_dag_data_quality.pyindex 76919f0fc042..a44b1271eed1 100644--- a/posthog/temporal/tests/data_modeling/test_execute_dag_data_quality.py+++ b/posthog/temporal/tests/data_modeling/test_execute_dag_data_quality.py@@ -16,6 +16,7 @@ from posthog.temporal.data_modeling.workflows.execute_dag import ExecuteDAGInputfrom posthog.temporal.tests.data_modeling.test_execute_dag_workflow import (MockMaterializeViewWorkflow,_mock_workflow_should_fail,+ stub_notify_dag_materialization_failures,stub_preempt_dag_run,)@@ -76,7 +77,12 @@ class TestPostMaterializationChecks:env.client,task_queue="test-queue",workflows=workflows,- activities=[stub_preempt_dag_run, stub_get_dag_structure, stub_materialization_gate],+ activities=[+ stub_preempt_dag_run,+ stub_get_dag_structure,+ stub_materialization_gate,+ stub_notify_dag_materialization_failures,+ ],workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),):return await env.client.execute_workflow(diff --git a/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py b/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.pyindex eebd36fcff3b..39cd96b0d58f 100644--- a/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py+++ b/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py@@ -16,6 +16,7 @@ from temporalio.testing import WorkflowEnvironmentfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.data_modeling.activities import (GetDAGStructureInputs,+ NotifyDAGMaterializationFailuresInputs,PreemptDAGRunInputs,RecordSkippedDataModelingJobsInputs,get_dag_structure_activity,@@ -476,7 +477,12 @@ class TestExecuteDAGWorkflow:env.client,task_queue="test-queue",workflows=[ExecuteDAGWorkflow],- activities=[stub_preempt_dag_run, stub_get_dag_structure, stub_record_skipped_data_modeling_jobs],+ activities=[+ stub_preempt_dag_run,+ stub_get_dag_structure,+ stub_record_skipped_data_modeling_jobs,+ stub_notify_dag_materialization_failures,+ ],workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),):result: ExecuteDAGResult = await env.client.execute_workflow(@@ -496,6 +502,13 @@ class TestExecuteDAGWorkflow:_mock_workflow_calls: list[str] = []_mock_workflow_should_fail: set[str] = set()_recorded_skipped_nodes: list[RecordSkippedDataModelingJobsInputs] = []+_notified_dag_failures: list[NotifyDAGMaterializationFailuresInputs] = []+++@temporal_activity.defn(name="notify_dag_materialization_failures_activity")+async def stub_notify_dag_materialization_failures(inputs: NotifyDAGMaterializationFailuresInputs) -> int:+ _notified_dag_failures.append(inputs)+ return 1@temporal_activity.defn(name="record_skipped_data_modeling_jobs_activity")@@ -526,10 +539,12 @@ class TestExecuteDAGWorkflowWithMocks:_mock_workflow_calls.clear()_mock_workflow_should_fail.clear()_recorded_skipped_nodes.clear()+ _notified_dag_failures.clear()yield_mock_workflow_calls.clear()_mock_workflow_should_fail.clear()_recorded_skipped_nodes.clear()+ _notified_dag_failures.clear()async def test_skips_downstream_on_failure(self):"""Test that downstream nodes are skipped when an upstream node fails."""@@ -548,19 +563,25 @@ class TestExecuteDAGWorkflowWithMocks:# node a should fail_mock_workflow_should_fail.add(node_a_id)+ workflow_id = f"test-skip-downstream-{uuid.uuid4()}"async with await WorkflowEnvironment.start_time_skipping() as env:async with temporalio.worker.Worker(env.client,task_queue="test-queue",workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],- activities=[stub_preempt_dag_run, stub_get_dag_structure, stub_record_skipped_data_modeling_jobs],+ activities=[+ stub_preempt_dag_run,+ stub_get_dag_structure,+ stub_record_skipped_data_modeling_jobs,+ stub_notify_dag_materialization_failures,+ ],workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),):result: ExecuteDAGResult = await env.client.execute_workflow(ExecuteDAGWorkflow.run,ExecuteDAGInputs(team_id=1, dag_id=dag_id),- id=f"test-skip-downstream-{uuid.uuid4()}",+ id=workflow_id,task_queue="test-queue",execution_timeout=dt.timedelta(seconds=30),)@@ -576,6 +597,12 @@ class TestExecuteDAGWorkflowWithMocks:assert all(skipped.failed_upstream_node_ids == [node_a_id] for skipped in _recorded_skipped_nodes[0].skipped_nodes)+ assert len(_notified_dag_failures) == 1+ notified = _notified_dag_failures[0]+ assert (notified.team_id, notified.dag_id, notified.parent_workflow_id) == (1, dag_id, workflow_id)+ # The children stamp this same value on their own workflow ids, which is how the activity+ # tells this run's failures from an earlier run under the same parent.+ assert dt.datetime.fromisoformat(notified.run_started_at)async def test_records_every_failed_parent_on_one_skip_row(self):dag_id = "test-dag"@@ -597,7 +624,12 @@ class TestExecuteDAGWorkflowWithMocks:env.client,task_queue="test-queue",workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],- activities=[stub_preempt_dag_run, stub_get_dag_structure, stub_record_skipped_data_modeling_jobs],+ activities=[+ stub_preempt_dag_run,+ stub_get_dag_structure,+ stub_record_skipped_data_modeling_jobs,+ stub_notify_dag_materialization_failures,+ ],workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),):result: ExecuteDAGResult = await env.client.execute_workflow(@@ -635,7 +667,12 @@ class TestExecuteDAGWorkflowWithMocks:env.client,task_queue="test-queue",workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],- activities=[stub_preempt_dag_run, stub_get_dag_structure, stub_record_skipped_data_modeling_jobs],+ activities=[+ stub_preempt_dag_run,+ stub_get_dag_structure,+ stub_record_skipped_data_modeling_jobs,+ stub_notify_dag_materialization_failures,+ ],workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),):result: ExecuteDAGResult = await env.client.execute_workflow(@@ -674,7 +711,12 @@ class TestExecuteDAGWorkflowWithMocks:env.client,task_queue="test-queue",workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],- activities=[stub_preempt_dag_run, stub_get_dag_structure, stub_record_skipped_data_modeling_jobs],+ activities=[+ stub_preempt_dag_run,+ stub_get_dag_structure,+ stub_record_skipped_data_modeling_jobs,+ stub_notify_dag_materialization_failures,+ ],workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),):result: ExecuteDAGResult = await env.client.execute_workflow(@@ -710,7 +752,7 @@ class TestExecuteDAGWorkflowWithMocks:env.client,task_queue="test-queue",workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],- activities=[stub_preempt_dag_run, stub_get_dag_structure],+ activities=[stub_preempt_dag_run, stub_get_dag_structure, stub_notify_dag_materialization_failures],workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),):result: ExecuteDAGResult = await env.client.execute_workflow(@@ -749,7 +791,12 @@ class TestExecuteDAGWorkflowWithMocks:env.client,task_queue="test-queue",workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],- activities=[stub_preempt_dag_run, stub_get_dag_structure, stub_record_skipped_data_modeling_jobs],+ activities=[+ stub_preempt_dag_run,+ stub_get_dag_structure,+ stub_record_skipped_data_modeling_jobs,+ stub_notify_dag_materialization_failures,+ ],workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),):result: ExecuteDAGResult = await env.client.execute_workflow(@@ -791,7 +838,7 @@ class TestExecuteDAGWorkflowWithMocks:env.client,task_queue="test-queue",workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],- activities=[stub_preempt_dag_run, stub_get_dag_structure],+ activities=[stub_preempt_dag_run, stub_get_dag_structure, stub_notify_dag_materialization_failures],workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),):result: ExecuteDAGResult = await env.client.execute_workflow(@@ -812,6 +859,7 @@ class TestExecuteDAGWorkflowWithMocks:assert result.skipped_nodes == 0assert len(result.node_results) == 3assert all(r.success for r in result.node_results)+ assert _notified_dag_failures == []async def test_ephemeral_nodes_are_skipped(self):"""Test that ephemeral nodes are recorded as successful no-ops without starting child workflows."""@@ -835,7 +883,7 @@ class TestExecuteDAGWorkflowWithMocks:env.client,task_queue="test-queue",workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],- activities=[stub_preempt_dag_run, stub_get_dag_structure],+ activities=[stub_preempt_dag_run, stub_get_dag_structure, stub_notify_dag_materialization_failures],workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),):result: ExecuteDAGResult = await env.client.execute_workflow(diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex 2b83bb700015..437ef00d23e4 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -31,7 +31,6 @@ 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,@@ -39,6 +38,7 @@ from posthog.temporal.data_modeling.activities.materialize_view import (get_s3_client,hogql_table,)+from posthog.temporal.data_modeling.activities.notify_materialization_failure import _SavedQueryViewersfrom products.data_modeling.backend.facade.api import compute_enrichment_hashfrom products.data_modeling.backend.facade.modeling import bounded_resolver_factory_for_view@@ -57,9 +57,16 @@ from products.warehouse_sources.backend.facade.models import DataWarehouseTablepytestmark = [pytest.mark.asyncio, pytest.mark.django_db]-async def _make_job(ateam, saved_query, status, *, engine=DataModelingJobEngine.CLICKHOUSE, error=None):+async def _make_job(+ ateam, saved_query, status, *, engine=DataModelingJobEngine.CLICKHOUSE, error=None, parent_workflow_id=None+):return await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam, saved_query=saved_query, status=status, engine=engine, error=error+ team=ateam,+ saved_query=saved_query,+ status=status,+ engine=engine,+ error=error,+ parent_workflow_id=parent_workflow_id,)@@ -190,7 +197,7 @@ class TestFailMaterializationActivity:error="Some non-timeout error",)with unittest.mock.patch(- "posthog.temporal.data_modeling.activities.fail_materialization.create_notification"+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.create_notification") as mock_create:await activity_environment.run(fail_materialization_activity, inputs)@@ -219,7 +226,7 @@ class TestFailMaterializationActivity:error="Some non-timeout error",)with unittest.mock.patch(- "posthog.temporal.data_modeling.activities.fail_materialization.create_notification"+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.create_notification") as mock_create:await activity_environment.run(fail_materialization_activity, inputs)@@ -241,7 +248,7 @@ class TestFailMaterializationActivity:side_effect=Exception("suspension blew up"),),unittest.mock.patch(- "posthog.temporal.data_modeling.activities.fail_materialization.create_notification"+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.create_notification") as mock_create,):await activity_environment.run(fail_materialization_activity, inputs)@@ -260,7 +267,7 @@ class TestFailMaterializationActivity:cancelled=True,)with unittest.mock.patch(- "posthog.temporal.data_modeling.activities.fail_materialization.create_notification"+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.create_notification") as mock_create:await activity_environment.run(fail_materialization_activity, inputs)@@ -287,7 +294,7 @@ class TestFailMaterializationActivity:return self._user.id == allowed.idwith unittest.mock.patch(- "posthog.temporal.data_modeling.activities.fail_materialization.UserAccessControl", FakeAccess+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.UserAccessControl", FakeAccess):resolved = await database_sync_to_async(_SavedQueryViewers(asaved_query).resolve)(TargetType.TEAM, str(ateam.pk), ateam.pk@@ -296,6 +303,33 @@ class TestFailMaterializationActivity:assert allowed.id in resolvedassert denied.id not in resolved+ async def test_a_child_of_a_dag_run_leaves_the_in_app_notification_to_its_parent(+ self, activity_environment, ateam, anode, asaved_query, adag+ ):+ current_job = await _make_job(+ ateam, asaved_query, DataModelingJob.Status.RUNNING, parent_workflow_id="execute-dag-workflow"+ )+ 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.notify_materialization_failure.create_notification"+ ) as mock_create,+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.send_matview_failure_immediate_email"+ ) as mock_email,+ ):+ await activity_environment.run(fail_materialization_activity, inputs)++ mock_create.assert_not_called()+ mock_email.delay.assert_called_once()+async def test_notification_carries_the_per_view_resolver(self, activity_environment, ateam, anode, asaved_query, adag):@@ -309,7 +343,7 @@ class TestFailMaterializationActivity:)with unittest.mock.patch(- "posthog.temporal.data_modeling.activities.fail_materialization.create_notification"+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.create_notification") as mock_create:await activity_environment.run(fail_materialization_activity, inputs)@@ -508,7 +542,7 @@ class TestShouldPauseScheduleForTimeout:)should_pause, count = await database_sync_to_async(should_pause_schedule_for_timeout)(- asaved_query.id, current_job.id+ asaved_query.id, current_job)assert should_pause is Falseassert count == 3@@ -539,7 +573,7 @@ class TestShouldPauseScheduleForTimeout:)should_pause, count = await database_sync_to_async(should_pause_schedule_for_timeout)(- asaved_query.id, current_job.id+ asaved_query.id, current_job)assert should_pause is Trueassert count == 5@@ -579,7 +613,7 @@ class TestShouldPauseScheduleForTimeout:)should_pause, count = await database_sync_to_async(should_pause_schedule_for_timeout)(- asaved_query.id, current_job.id+ asaved_query.id, current_job)assert should_pause is Trueassert count == 5@@ -605,7 +639,7 @@ class TestShouldPauseScheduleForTimeout:jobs.append(current_job)should_pause, count = await database_sync_to_async(should_pause_schedule_for_timeout)(- asaved_query.id, current_job.id+ asaved_query.id, current_job)assert should_pause is Trueassert count == 5diff --git a/posthog/temporal/tests/data_modeling/test_notify_materialization_failure.py b/posthog/temporal/tests/data_modeling/test_notify_materialization_failure.pynew file mode 100644index 000000000000..e6292cb19045--- /dev/null+++ b/posthog/temporal/tests/data_modeling/test_notify_materialization_failure.py@@ -0,0 +1,288 @@+from types import SimpleNamespace+from uuid import uuid4++import pytest+import unittest.mock++from posthog.models import User+from posthog.sync import database_sync_to_async+from posthog.temporal.data_modeling.activities import (+ NotifyDAGMaterializationFailuresInputs,+ notify_dag_materialization_failures_activity,+)+from posthog.temporal.data_modeling.activities.notify_materialization_failure import _FailedView, _failure_copy++from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobEngine, DataWarehouseSavedQuery+from products.notifications.backend.facade.api import TargetType++RUN_STARTED_AT = "2026-08-12T10:00:00+00:00"+# The shape a tier schedule produces, rather than an arbitrary long string.+PARENT_WORKFLOW_ID = f"execute-dag-{uuid4()}:86400-{RUN_STARTED_AT}"+SOURCE_ID_MAX_LENGTH = 64+RESOURCE_ID_MAX_LENGTH = 64+IDEMPOTENCY_KEY_MAX_LENGTH = 128+++async def _saved_query(ateam, auser, name):+ return await database_sync_to_async(DataWarehouseSavedQuery.objects.create)(+ team=ateam, name=name, query={"query": "SELECT 1", "kind": "HogQLQuery"}, created_by=auser+ )+++async def _failed_job(ateam, saved_query, *, run_started_at=RUN_STARTED_AT, parent=PARENT_WORKFLOW_ID, error="boom"):+ return await database_sync_to_async(DataModelingJob.objects.create)(+ team=ateam,+ saved_query=saved_query,+ status=DataModelingJob.Status.FAILED,+ engine=DataModelingJobEngine.CLICKHOUSE,+ error=error,+ parent_workflow_id=parent,+ workflow_id=f"materialize-view-dag-{saved_query.name}-{run_started_at}",+ )+++def _access_allowing(allowed_by_view: dict[str, set[int]], *, raising_for: frozenset[int] = frozenset()):+ class FakeAccess:+ def __init__(self, user, team):+ self._user_id = user.id++ is_organization_admin = False++ def check_access_level_for_object(self, obj, required_level):+ if self._user_id in raising_for:+ raise RuntimeError("access check unavailable")+ return self._user_id in allowed_by_view.get(obj.name, set())++ return FakeAccess+++def _inputs(ateam, adag, *, run_started_at=RUN_STARTED_AT):+ return NotifyDAGMaterializationFailuresInputs(+ team_id=ateam.pk,+ dag_id=str(adag.id),+ parent_workflow_id=PARENT_WORKFLOW_ID,+ run_started_at=run_started_at,+ )+++class TestNotifyDAGMaterializationFailures:+ async def test_one_notification_names_every_view_the_run_broke(+ self, activity_environment, ateam, adag, auser, aorganization+ ):+ member = await database_sync_to_async(User.objects.create_and_join)(+ aorganization, f"member-{uuid4()}@posthog.com", None+ )+ names = ["alpha", "beta", "gamma"]+ for name in names:+ await _failed_job(ateam, await _saved_query(ateam, auser, name))++ with (+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.UserAccessControl",+ _access_allowing({name: {member.id} for name in names}),+ ),+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.create_notification"+ ) as mock_create,+ ):+ sent = await activity_environment.run(notify_dag_materialization_failures_activity, _inputs(ateam, adag))++ assert sent == 1+ mock_create.assert_called_once()+ data = mock_create.call_args.args[0]+ assert data.title == "3 views failed to materialize"+ assert data.body == "alpha, beta, gamma"++ async def test_an_earlier_run_under_the_same_workflow_id_is_left_out(+ self, activity_environment, ateam, adag, auser, aorganization+ ):+ member = await database_sync_to_async(User.objects.create_and_join)(+ aorganization, f"member-{uuid4()}@posthog.com", None+ )+ await _failed_job(+ ateam, await _saved_query(ateam, auser, "yesterday"), run_started_at="2026-08-11T10:00:00+00:00"+ )+ await _failed_job(ateam, await _saved_query(ateam, auser, "today"))++ with (+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.UserAccessControl",+ _access_allowing({"yesterday": {member.id}, "today": {member.id}}),+ ),+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.create_notification"+ ) as mock_create,+ ):+ await activity_environment.run(notify_dag_materialization_failures_activity, _inputs(ateam, adag))++ data = mock_create.call_args.args[0]+ assert data.title == "today failed to materialize"++ async def test_a_view_already_failing_is_not_named_again(+ self, activity_environment, ateam, adag, auser, aorganization+ ):+ member = await database_sync_to_async(User.objects.create_and_join)(+ aorganization, f"member-{uuid4()}@posthog.com", None+ )+ already_failing = await _saved_query(ateam, auser, "already_failing")+ await _failed_job(ateam, already_failing, run_started_at="2026-08-11T10:00:00+00:00")+ await _failed_job(ateam, already_failing)+ await _failed_job(ateam, await _saved_query(ateam, auser, "just_broke"))++ with (+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.UserAccessControl",+ _access_allowing({"already_failing": {member.id}, "just_broke": {member.id}}),+ ),+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.create_notification"+ ) as mock_create,+ ):+ await activity_environment.run(notify_dag_materialization_failures_activity, _inputs(ateam, adag))++ data = mock_create.call_args.args[0]+ assert data.title == "just_broke failed to materialize"++ async def test_the_dedupe_key_fits_the_column_a_long_workflow_id_would_overflow(+ self, activity_environment, ateam, adag, auser, aorganization+ ):+ member = await database_sync_to_async(User.objects.create_and_join)(+ aorganization, f"member-{uuid4()}@posthog.com", None+ )+ await _failed_job(ateam, await _saved_query(ateam, auser, "alpha"))++ with (+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.UserAccessControl",+ _access_allowing({"alpha": {member.id}}),+ ),+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.create_notification"+ ) as mock_create,+ ):+ await activity_environment.run(notify_dag_materialization_failures_activity, _inputs(ateam, adag))++ data = mock_create.call_args.args[0]+ assert len(PARENT_WORKFLOW_ID) > SOURCE_ID_MAX_LENGTH, "the id under test has to be one that would overflow"+ assert len(data.source_id) <= SOURCE_ID_MAX_LENGTH+ assert len(data.resource_id) <= RESOURCE_ID_MAX_LENGTH+ assert len(data.idempotency_key) <= IDEMPOTENCY_KEY_MAX_LENGTH++ async def test_a_retry_asks_for_the_same_notification_rather_than_a_second_one(+ self, activity_environment, ateam, adag, auser, aorganization+ ):+ member = await database_sync_to_async(User.objects.create_and_join)(+ aorganization, f"member-{uuid4()}@posthog.com", None+ )+ for name in ("alpha", "beta", "gamma"):+ await _failed_job(ateam, await _saved_query(ateam, auser, name))++ with (+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.UserAccessControl",+ _access_allowing({name: {member.id} for name in ("alpha", "beta", "gamma")}),+ ),+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.create_notification"+ ) as mock_create,+ ):+ await activity_environment.run(notify_dag_materialization_failures_activity, _inputs(ateam, adag))+ await activity_environment.run(notify_dag_materialization_failures_activity, _inputs(ateam, adag))++ # Equal keys are what lets the unique constraint recognise the retry; the activity cannot+ # tell it is one, since a timeout can hand it the same work with nothing written yet.+ first, second = (call.args[0].idempotency_key for call in mock_create.call_args_list)+ assert first == second++ async def test_each_member_hears_once_about_everything_they_can_see(+ self, activity_environment, ateam, adag, auser, aorganization+ ):+ finance = await database_sync_to_async(User.objects.create_and_join)(+ aorganization, f"finance-{uuid4()}@posthog.com", None+ )+ everyone_else = await database_sync_to_async(User.objects.create_and_join)(+ aorganization, f"other-{uuid4()}@posthog.com", None+ )+ await _failed_job(ateam, await _saved_query(ateam, auser, "salaries"))+ await _failed_job(ateam, await _saved_query(ateam, auser, "pageviews"))++ with (+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.UserAccessControl",+ _access_allowing(+ {"salaries": {finance.id}, "pageviews": {finance.id, everyone_else.id}},+ ),+ ),+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.create_notification"+ ) as mock_create,+ ):+ sent = await activity_environment.run(notify_dag_materialization_failures_activity, _inputs(ateam, adag))++ assert sent == 2+ told: dict[int, str] = {}+ for call in mock_create.call_args_list:+ data = call.args[0]+ recipients = await database_sync_to_async(data.resolver.resolve)(TargetType.TEAM, str(ateam.pk), ateam.pk)+ for user_id in recipients:+ assert user_id not in told, "one run must not produce two notifications for one member"+ told[user_id] = f"{data.title} :: {data.body}"++ # The member allowed both hears about both, in one notification.+ assert told[finance.id].startswith("2 views failed to materialize")+ assert "salaries" in told[finance.id] and "pageviews" in told[finance.id]+ # The restricted view is never named to the member who cannot open it.+ assert told[everyone_else.id].startswith("pageviews failed to materialize")+ assert "salaries" not in told[everyone_else.id]++ async def test_a_member_whose_access_check_raises_is_not_told(+ self, activity_environment, ateam, adag, auser, aorganization+ ):+ allowed = await database_sync_to_async(User.objects.create_and_join)(+ aorganization, f"allowed-{uuid4()}@posthog.com", None+ )+ unchecked = await database_sync_to_async(User.objects.create_and_join)(+ aorganization, f"unchecked-{uuid4()}@posthog.com", None+ )+ await _failed_job(ateam, await _saved_query(ateam, auser, "salaries"))++ with (+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.UserAccessControl",+ _access_allowing({"salaries": {allowed.id, unchecked.id}}, raising_for=frozenset({unchecked.id})),+ ),+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.capture_exception"+ ) as mock_capture,+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.create_notification"+ ) as mock_create,+ ):+ sent = await activity_environment.run(notify_dag_materialization_failures_activity, _inputs(ateam, adag))++ assert sent == 1+ data = mock_create.call_args.args[0]+ recipients = await database_sync_to_async(data.resolver.resolve)(TargetType.TEAM, str(ateam.pk), ateam.pk)+ assert allowed.id in recipients, "a member the check cleared still hears about it"+ assert unchecked.id not in recipients, "a failed check must not admit the member it could not clear"+ assert mock_capture.called+++class TestFailureCopy:+ @pytest.mark.parametrize(+ "names,expected_title,expected_body",+ [+ (["one"], "one failed to materialize", "it broke"),+ (["a", "b"], "2 views failed to materialize", "a, b"),+ (list("abcdefg"), "7 views failed to materialize", "a, b, c, d, e, and 2 more"),+ ],+ )+ def test_names_the_views_up_to_a_limit(self, names, expected_title, expected_body):+ views = [+ _FailedView(job=SimpleNamespace(error="it broke"), saved_query=SimpleNamespace(name=name)) # type: ignore[arg-type]+ for name in names+ ]++ assert _failure_copy(views) == (expected_title, expected_body)diff --git a/posthog/temporal/tests/data_modeling/test_run_workflow.py b/posthog/temporal/tests/data_modeling/test_run_workflow.pyindex 5df3c3854d14..bfa4f02ddde0 100644--- a/posthog/temporal/tests/data_modeling/test_run_workflow.py+++ b/posthog/temporal/tests/data_modeling/test_run_workflow.py@@ -1061,15 +1061,20 @@ async def test_run_workflow_timeout_pauses_schedule_after_5_consecutive_failures"""Timeout should pause the schedule when there are 5 consecutive timeout failures."""parent_query = saved_queries[0]- # Create 5 previous timeout failed jobs for this saved query+ # The run under test is frozen to test_time, so its own job row is stamped then, while these+ # are created at the wall clock that has already passed it. Dating them back makes them the+ # history the run counts, rather than rows it is entitled to ignore as newer than itself.for i in range(5):- await database_sync_to_async(DataModelingJob.objects.create)(+ job = await database_sync_to_async(DataModelingJob.objects.create)(team=ateam,saved_query=parent_query,status=DataModelingJob.Status.FAILED,error="Query exceeded timeout - we limit queries to a 10-minute timeout.",workflow_id=f"prev-workflow-{i}",)+ await database_sync_to_async(DataModelingJob.objects.filter(id=job.id).update)(+ created_at=test_time - dt.timedelta(minutes=5 - i)+ )workflow_id = str(uuid.uuid4())inputs = RunWorkflowInputs(team_id=ateam.pk)