: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
fix(data-modeling): send a manual run's failure toast only to its runner (#98275)
Jovan Sakovic80406079a06a
diff --git a/posthog/temporal/data_modeling/activities/create_data_modeling_job.py b/posthog/temporal/data_modeling/activities/create_data_modeling_job.pyindex fb5f4b0c974c..6ec2e2c93ef9 100644--- a/posthog/temporal/data_modeling/activities/create_data_modeling_job.py+++ b/posthog/temporal/data_modeling/activities/create_data_modeling_job.py@@ -12,13 +12,14 @@ from products.data_modeling.backend.facade.models import DataModelingJob, DataMoLOGGER = get_logger(__name__)[email protected](frozen=True, kw_only=True)class CreateDataModelingJobInputs:team_id: intnode_id: strdag_id: strengine: str = DataModelingJobEngine.CLICKHOUSEparent_workflow_id: str | None = None+ manually_triggered_by_id: int | None = None@dataclasses.dataclass(frozen=True, kw_only=True)@@ -66,6 +67,7 @@ def _create_data_modeling_job(workflow_run_id=workflow_run_id,parent_workflow_id=inputs.parent_workflow_id,created_by_id=node.saved_query.created_by_id if node.saved_query else None,+ manually_triggered_by_id=inputs.manually_triggered_by_id,)return CreatedDataModelingJob(job_id=str(job.id),diff --git a/posthog/temporal/data_modeling/activities/notify_materialization_failure.py b/posthog/temporal/data_modeling/activities/notify_materialization_failure.pyindex 73d9b6e8a191..4096f98a9fbf 100644--- a/posthog/temporal/data_modeling/activities/notify_materialization_failure.py+++ b/posthog/temporal/data_modeling/activities/notify_materialization_failure.py@@ -114,6 +114,12 @@ class _SavedQueryViewers(RecipientsResolver):# 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 []+ # The shared resolver applies this to a team target and returns a user target untouched, so+ # a member who has since lost the project would otherwise skip it.+ with_project_access = set(team.all_users_with_access().values_list("id", flat=True))+ user_ids = [user_id for user_id in user_ids if user_id in with_project_access]+ if not user_ids:+ return []return _viewers_of(_access_of(team, user_ids), self._saved_query)@@ -131,7 +137,7 @@ class _PrecomputedViewers(RecipientsResolver):def maybe_notify_materialization_failure(job: DataModelingJob, saved_query: DataWarehouseSavedQuery, team_id: int) -> bool:- """Email on the first failure of a streak; a run started by hand also notifies in-app every time."""+ """Email on the first failure of a streak; a run started by hand notifies its runner every time."""# An idempotent retry can land here with a job another path already completed or cancelled.if job.status != DataModelingJobStatus.FAILED:return False@@ -145,17 +151,20 @@ def maybe_notify_materialization_failure(# The DAG run this belongs to notifies for every view it broke, once, at the end.return False- # A run with no parent was started by hand, usually to check a fix, and the person who started- # it may have moved on. Silence mid-streak would read as success, so every failure is told.+ # A run with no parent was started outside a DAG, usually to check a fix. Silence mid-streak+ # would read as success, so every failure is told, not just the one that opened the streak.+ runner_id = job.manually_triggered_by_idcreate_notification(_failure_notification(team_id=team_id,views=[_FailedView(job=job, saved_query=saved_query)],resolver=_SavedQueryViewers(saved_query),source_id=str(job.id),- # Someone asked for this run and is waiting on its result, so it outranks the- # scheduled failures a person did not ask for.- priority=Priority.CRITICAL,+ recipient_id=runner_id,+ # A critical notification also raises a toast that does not close on its own, which is+ # right for the person waiting on this run. A run nobody asked for, such as a repair+ # triggered by read traffic, has no such person and stays at the scheduled volume.+ priority=Priority.CRITICAL if runner_id else Priority.NORMAL,))return True@@ -192,6 +201,7 @@ def _failure_notification(views: list[_FailedView],resolver: RecipientsResolver,source_id: str,+ recipient_id: int | None = None,priority: Priority = Priority.NORMAL,) -> NotificationData:title, body = _failure_copy(views)@@ -204,8 +214,8 @@ def _failure_notification(priority=priority,title=title[:255],body=body[:400],- target_type=TargetType.TEAM,- target_id=str(team_id),+ target_type=TargetType.USER if recipient_id else TargetType.TEAM,+ target_id=str(recipient_id) if recipient_id else str(team_id),# "warehouse_objects" (not "warehouse_view") is the AC resource — anything else# silently skips the access-control filter in create_notificationresource_type="warehouse_objects",diff --git a/posthog/temporal/data_modeling/workflows/materialize_view.py b/posthog/temporal/data_modeling/workflows/materialize_view.pyindex d0478dcb2b1b..45c5e6e56d4a 100644--- a/posthog/temporal/data_modeling/workflows/materialize_view.py+++ b/posthog/temporal/data_modeling/workflows/materialize_view.py@@ -111,7 +111,7 @@ def _is_cancellation(error: BaseException) -> bool:) and isinstance(error.cause, temporalio.exceptions.CancelledError)[email protected](frozen=True, kw_only=True)class MaterializeViewWorkflowInputs:"""Inputs for the MaterializeViewWorkflow.@@ -119,6 +119,7 @@ class MaterializeViewWorkflowInputs:team_id: The team ID that owns the node.dag_id: The DAG the node belongs to.node_id: The UUID of the Node to materialize.+ manually_triggered_by_id: The user who asked for this run, when a person did."""team_id: int@@ -126,6 +127,7 @@ class MaterializeViewWorkflowInputs:node_id: strduckgres_only: bool = Falsedangerously_execute_raw_sql: bool = False+ manually_triggered_by_id: int | None = None@propertydef properties_to_log(self) -> dict:@@ -222,6 +224,7 @@ class MaterializeViewWorkflow(PostHogWorkflow):dag_id=inputs.dag_id,engine=DataModelingJobEngine.DUCKGRES,parent_workflow_id=parent_workflow_id,+ manually_triggered_by_id=inputs.manually_triggered_by_id,),start_to_close_timeout=dt.timedelta(minutes=5),retry_policy=temporalio.common.RetryPolicy(@@ -254,6 +257,7 @@ class MaterializeViewWorkflow(PostHogWorkflow):node_id=inputs.node_id,dag_id=inputs.dag_id,parent_workflow_id=parent_workflow_id,+ manually_triggered_by_id=inputs.manually_triggered_by_id,),start_to_close_timeout=dt.timedelta(minutes=5),retry_policy=temporalio.common.RetryPolicy(diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex 8068704877ed..c81b91cf9ebc 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -75,7 +75,14 @@ pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]async def _make_job(- ateam, saved_query, status, *, engine=DataModelingJobEngine.CLICKHOUSE, error=None, parent_workflow_id=None+ ateam,+ saved_query,+ status,+ *,+ engine=DataModelingJobEngine.CLICKHOUSE,+ error=None,+ parent_workflow_id=None,+ manually_triggered_by=None,):return await database_sync_to_async(DataModelingJob.objects.create)(team=ateam,@@ -84,15 +91,24 @@ async def _make_job(engine=engine,error=error,parent_workflow_id=parent_workflow_id,+ manually_triggered_by=manually_triggered_by,)class TestCreateDataModelingJobActivity:- async def test_creates_job_with_running_status(self, activity_environment, ateam, auser, anode, asaved_query, adag):+ @pytest.mark.parametrize("with_runner", [True, False])+ async def test_creates_job_with_running_status(+ self, activity_environment, ateam, auser, anode, asaved_query, adag, aorganization, with_runner+ ):+ # These tests share a database, so the emails have to be unique per run.+ runner = await database_sync_to_async(User.objects.create_and_join)(+ aorganization, f"runner-{uuid4()}@posthog.com", None+ )inputs = CreateDataModelingJobInputs(team_id=ateam.pk,node_id=str(anode.id),dag_id=str(adag.id),+ manually_triggered_by_id=runner.pk if with_runner else None,)with unittest.mock.patch("temporalio.activity.info") as mock_info:mock_info.return_value.workflow_id = "test-workflow-id"@@ -106,7 +122,9 @@ class TestCreateDataModelingJobActivity:assert job.saved_query_id == asaved_query.idassert job.workflow_id == "test-workflow-id"assert job.workflow_run_id == "test-run-id"+ # The person who wrote the view is not the person who started this run.assert job.created_by_id == auser.id+ assert job.manually_triggered_by_id == (runner.pk if with_runner else None)class TestFailMaterializationActivity:@@ -201,23 +219,26 @@ class TestFailMaterializationActivity:assert is_node_suspended(anode, DataModelingJobEngine.CLICKHOUSE) is True@pytest.mark.parametrize(- "previous_status,parent_workflow_id,expect_email,expect_in_app",+ "previous_status,parent_workflow_id,with_runner,expect_email,expect_in_app",[- (None, None, True, True),- (DataModelingJob.Status.COMPLETED, None, True, True),- (DataModelingJob.Status.FAILED, None, False, True),- (DataModelingJob.Status.FAILED, "execute-dag-workflow", False, False),+ (None, None, True, True, True),+ (DataModelingJob.Status.COMPLETED, None, True, True, True),+ (DataModelingJob.Status.FAILED, None, True, False, True),+ (DataModelingJob.Status.FAILED, None, False, False, True),+ (DataModelingJob.Status.FAILED, "execute-dag-workflow", True, False, False),],)async def test_emails_at_streak_start_and_notifies_in_app_on_every_manual_run(self,activity_environment,ateam,+ auser,anode,asaved_query,adag,previous_status,parent_workflow_id,+ with_runner,expect_email,expect_in_app,):@@ -225,7 +246,11 @@ class TestFailMaterializationActivity:error = "boom" if previous_status == DataModelingJob.Status.FAILED else Noneawait _make_job(ateam, asaved_query, previous_status, error=error)current_job = await _make_job(- ateam, asaved_query, DataModelingJob.Status.RUNNING, parent_workflow_id=parent_workflow_id+ ateam,+ asaved_query,+ DataModelingJob.Status.RUNNING,+ parent_workflow_id=parent_workflow_id,+ manually_triggered_by=auser if with_runner else None,)inputs = FailMaterializationInputs(@@ -250,9 +275,15 @@ class TestFailMaterializationActivity:mock_create.assert_called_once()data = mock_create.call_args.args[0]assert data.notification_type == NotificationType.MATERIALIZATION_FAILURE- assert data.priority == Priority.CRITICAL- assert data.target_id == str(ateam.pk)assert data.resource_id == str(asaved_query.id)+ if with_runner:+ assert data.target_type == TargetType.USER+ assert data.target_id == str(auser.pk)+ assert data.priority == Priority.CRITICAL+ else:+ assert data.target_type == TargetType.TEAM+ assert data.target_id == str(ateam.pk)+ assert data.priority == Priority.NORMALelse:mock_create.assert_not_called()@@ -349,6 +380,36 @@ class TestFailMaterializationActivity:assert allowed.id in resolvedassert denied.id not in resolved+ async def test_notification_resolver_drops_a_named_user_who_left_the_project(+ self, activity_environment, ateam, asaved_query, aorganization+ ):+ # These tests share a database, so the emails have to be unique per run.+ member = await database_sync_to_async(User.objects.create_and_join)(+ aorganization, f"member-{uuid4()}@posthog.com", None+ )+ outsider = await database_sync_to_async(User.objects.create_user)(+ f"outsider-{uuid4()}@posthog.com", None, "Outsider"+ )++ class FakeAccess:+ def __init__(self, user, team):+ pass++ is_organization_admin = False++ def check_access_level_for_object(self, obj, required_level):+ return True++ with unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.notify_materialization_failure.UserAccessControl", FakeAccess+ ):+ resolve = database_sync_to_async(_SavedQueryViewers(asaved_query).resolve)+ kept = await resolve(TargetType.USER, str(member.pk), ateam.pk)+ dropped = await resolve(TargetType.USER, str(outsider.pk), ateam.pk)++ assert kept == [member.pk]+ assert dropped == []+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):diff --git a/products/data_modeling/backend/logic/node_materialization.py b/products/data_modeling/backend/logic/node_materialization.pyindex cf6be9002f27..f0b080181675 100644--- a/products/data_modeling/backend/logic/node_materialization.py+++ b/products/data_modeling/backend/logic/node_materialization.py@@ -19,7 +19,7 @@ from products.data_modeling.backend.schedule import get_v2_saved_query_idslogger = structlog.get_logger(__name__)-def start_node_materialization(node: Node, *, resume: bool = True) -> None:+def start_node_materialization(node: Node, *, resume: bool = True, triggered_by_id: int | None = None) -> None:"""Start a one-off materialization workflow for a single node.Shared by node `materialize` and saved-query `run`.@@ -27,6 +27,9 @@ def start_node_materialization(node: Node, *, resume: bool = True) -> None:`resume=False` is for automatic callers, such as a repair triggered by read traffic. The runstill starts, but a suspended node keeps its marker and its failure window, so request trafficcannot hold the circuit breaker open.++ `triggered_by_id` is the person who asked for this run, and only they are told if it fails.+ Callers with no person behind them leave it unset."""if resume:# An explicit run is a request to try again, so it gets a fresh failure window.@@ -35,6 +38,7 @@ def start_node_materialization(node: Node, *, resume: bool = True) -> None:team_id=node.team_id,dag_id=str(node.dag_id),node_id=str(node.id),+ manually_triggered_by_id=triggered_by_id,)temporal = sync_connect()@@ -86,7 +90,9 @@ def run_saved_query_materialization(team_id: int, saved_query_id: UUID | str) ->materialize_saved_query(saved_query)-def materialize_saved_query(saved_query: DataWarehouseSavedQuery, *, resume: bool = True) -> None:+def materialize_saved_query(+ saved_query: DataWarehouseSavedQuery, *, resume: bool = True, triggered_by_id: int | None = None+) -> None:"""Materialize the saved query's backing node via the v2 workflow.Fire a single materialization — don't fan out over duplicate-DAG nodes, or two workers race to@@ -98,4 +104,4 @@ def materialize_saved_query(saved_query: DataWarehouseSavedQuery, *, resume: boo# Raise rather than return: returning reports a materialization the caller can then find no# trace of, and there is no v1 schedule left to fall back to.raise MissingDagNodeError(f"Saved query {saved_query.id} has no DAG node to materialize")- start_node_materialization(node, resume=resume)+ start_node_materialization(node, resume=resume, triggered_by_id=triggered_by_id)diff --git a/products/data_modeling/backend/migrations/0039_datamodelingjob_manually_triggered_by.py b/products/data_modeling/backend/migrations/0039_datamodelingjob_manually_triggered_by.pynew file mode 100644index 000000000000..67997f603e39--- /dev/null+++ b/products/data_modeling/backend/migrations/0039_datamodelingjob_manually_triggered_by.py@@ -0,0 +1,27 @@+# Generated by Django 5.2.17 on 2026-09-10 12:22++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("data_modeling", "0038_datamodelingjob_full_refresh_reason"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.AddField(+ model_name="datamodelingjob",+ name="manually_triggered_by",+ field=models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ]diff --git a/products/data_modeling/backend/migrations/max_migration.txt b/products/data_modeling/backend/migrations/max_migration.txtindex ecd7b4a539d1..bf6bf762f4e6 100644--- a/products/data_modeling/backend/migrations/max_migration.txt+++ b/products/data_modeling/backend/migrations/max_migration.txt@@ -1 +1 @@-0038_datamodelingjob_full_refresh_reason+0039_datamodelingjob_manually_triggered_bydiff --git a/products/data_modeling/backend/models/data_modeling_job.py b/products/data_modeling/backend/models/data_modeling_job.pyindex 1f74539d94d8..4a6a60a8e86d 100644--- a/products/data_modeling/backend/models/data_modeling_job.py+++ b/products/data_modeling/backend/models/data_modeling_job.py@@ -39,6 +39,18 @@ class DataModelingJob(CreatedMetaFields, UpdatedMetaFields, UUIDTModel):workflow_id = models.CharField(max_length=400, null=True, blank=True)workflow_run_id = models.CharField(max_length=400, null=True, blank=True)parent_workflow_id = models.CharField(max_length=400, null=True, blank=True)+ # Distinct from `created_by`, which copies the saved query's author onto every run of it. Null+ # on a scheduled run and on one the product started for its own reasons, so a value here means+ # a person is waiting on this result.+ manually_triggered_by = models.ForeignKey(+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ related_name="+",+ # posthog_user is read on nearly every request, and a real constraint would lock it.+ db_constraint=False,+ )last_run_at = models.DateTimeField(default=timezone.now)rows_expected = models.IntegerField(null=True, blank=True, help_text="Total rows expected to be materialized")storage_delta_mib = models.FloatField(null=True, blank=True, default=0)diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.pyindex 1623540c2ca7..103c4733c2df 100644--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py@@ -1,6 +1,7 @@import reimport uuidfrom datetime import datetime, timedelta+from functools import partialfrom typing import TYPE_CHECKING, Any, Optional, Unionfrom urllib.parse import urlparse@@ -226,7 +227,9 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,else:DataWarehouseModelPath.objects.update_from_saved_query(self)- def schedule_materialization(self, reconcile: bool = True, trigger_immediate_run: bool = False):+ def schedule_materialization(+ self, reconcile: bool = True, trigger_immediate_run: bool = False, triggered_by_id: int | None = None+ ):"""Put this saved query on the schedule that will materialize it, at the frequency insync_frequency_interval.@@ -236,6 +239,9 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,Callers merely updating frequency must leave it False. The start is best effort, so afailure to start never disables materialization, because the tier still covers the query.+ triggered_by_id is the person who enabled materialization, and is who hears about it if+ that first run fails.+A rejected frequency propagates to the caller. Any other failure disablesmaterialization, because the alternative is a query that reports itself materializedwhile nothing is scheduled to materialize it.@@ -303,7 +309,7 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,if trigger_immediate_run:# Deferred to commit so the run sees the enable's writes (endpoints enable# runs inside an atomic block); immediate under autocommit.- transaction.on_commit(self._start_immediate_materialization)+ transaction.on_commit(partial(self._start_immediate_materialization, triggered_by_id))returnraise NoSchedulableDagError(f"Saved query {self.id} has no DAG that can schedule it")@@ -333,11 +339,11 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,self.is_materialized = Falseself.save(update_fields=["is_materialized"])- def _start_immediate_materialization(self) -> None:+ def _start_immediate_materialization(self, triggered_by_id: int | None = None) -> None:from products.data_modeling.backend.logic.node_materialization import materialize_saved_querytry:- materialize_saved_query(self)+ materialize_saved_query(self, triggered_by_id=triggered_by_id)except Exception as e:capture_exception(e, {"saved_query_id": self.id, "saved_query_name": self.name})logger.exception(diff --git a/products/data_modeling/backend/presentation/views/node.py b/products/data_modeling/backend/presentation/views/node.pyindex 1114e15448e2..f51754780638 100644--- a/products/data_modeling/backend/presentation/views/node.py+++ b/products/data_modeling/backend/presentation/views/node.py@@ -428,7 +428,7 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):if node.saved_query is not None:assert_user_can_read_query(node.saved_query.query, self.team_id, cast(User, req.user))- start_node_materialization(node)+ start_node_materialization(node, triggered_by_id=req.user.pk)return response.Response(status=status.HTTP_200_OK)diff --git a/products/data_warehouse/backend/presentation/views/saved_query.py b/products/data_warehouse/backend/presentation/views/saved_query.pyindex 6c10122d6c34..4c93aaa3f4ba 100644--- a/products/data_warehouse/backend/presentation/views/saved_query.py+++ b/products/data_warehouse/backend/presentation/views/saved_query.py@@ -1682,7 +1682,7 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSeclear_incremental_state(saved_query)try:- materialize_saved_query(saved_query)+ materialize_saved_query(saved_query, triggered_by_id=request.user.pk)except MissingDagNodeError:raise exceptions.ValidationError(detail="This view isn't fully set up to materialize. Save the query again, then try syncing."@@ -1857,7 +1857,7 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe# Enable materialization - this handles model path setup and schedule creation# If this fails, it will set is_materialized = Falsetry:- saved_query.schedule_materialization(trigger_immediate_run=True)+ saved_query.schedule_materialization(trigger_immediate_run=True, triggered_by_id=request.user.pk)except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError):# The check above already refused every cadence the lineage forbids, so reaching here# means the lineage moved mid-request. Say so plainly rather than forwarding a messagediff --git a/products/endpoints/backend/logic/materialization.py b/products/endpoints/backend/logic/materialization.pyindex fc2c7bc1c110..3dd1d31dcc1c 100644--- a/products/endpoints/backend/logic/materialization.py+++ b/products/endpoints/backend/logic/materialization.py@@ -272,7 +272,9 @@ class EndpointMaterializationService:# trigger_immediate_run mirrors that on v2: first run only for a newly created saved# query (deferred to on_commit, so it sees the version link above).try:- saved_query.schedule_materialization(trigger_immediate_run=newly_materialized)+ saved_query.schedule_materialization(+ trigger_immediate_run=newly_materialized, triggered_by_id=self.user.pk+ )except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:# The chosen data freshness can't be honored (e.g. finer than an upstream import# delivers) — a request problem, not a server one.