: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): skip suspended nodes in DAG execution (#67160)
Jovan Sakovicd743f890a9b5
diff --git a/posthog/temporal/data_modeling/activities/get_dag_structure.py b/posthog/temporal/data_modeling/activities/get_dag_structure.pyindex 19a939de0591..69e0ca7e5738 100644--- a/posthog/temporal/data_modeling/activities/get_dag_structure.py+++ b/posthog/temporal/data_modeling/activities/get_dag_structure.py@@ -2,13 +2,35 @@ import dataclassesfrom temporalio import activity+from posthog.models import Team+from posthog.ph_client import feature_enabled_or_falsefrom posthog.sync import database_sync_to_async_poolfrom posthog.temporal.common.logger import get_logger-from products.data_modeling.backend.facade.models import Edge, Node, NodeType+from products.data_modeling.backend.facade.models import DataModelingJobEngine, Edge, Node, NodeType++from .utils import is_node_suspendedLOGGER = get_logger(__name__)+SUSPENSION_ENFORCEMENT_FLAG = "data-modeling-suspend-failing-nodes"+++def _is_suspension_enforced(team_id: int) -> bool:+ try:+ team = Team.objects.only("organization_id").get(id=team_id)+ return feature_enabled_or_false(+ SUSPENSION_ENFORCEMENT_FLAG,+ str(team_id),+ groups={"organization": str(team.organization_id), "project": str(team_id)},+ group_properties={"organization": {"id": str(team.organization_id)}, "project": {"id": str(team_id)}},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ except Exception:+ LOGGER.warning("Failed to evaluate suspension enforcement flag; treating as disabled", team_id=team_id)+ return False+@dataclasses.dataclassclass GetDAGStructureInputs:@@ -35,6 +57,7 @@ class DAG:executable_nodes: list[str]edges: list[tuple[str, str]]ephemeral_nodes: list[str] = dataclasses.field(default_factory=list)+ suspended_nodes: dict[str, list[str]] = dataclasses.field(default_factory=dict)@database_sync_to_async_pool@@ -48,12 +71,20 @@ def _get_dag_structure_async(team_id: int, dag_id: str) -> DAG:.filter(team_id=team_id, dag_id=dag_id).exclude(source__type=NodeType.TABLE))+ if _is_suspension_enforced(team_id):+ suspended_nodes = {+ engine.value: [str(n.id) for n in executable_nodes if is_node_suspended(n, engine)]+ for engine in DataModelingJobEngine+ }+ else:+ suspended_nodes = {engine.value: [] for engine in DataModelingJobEngine}# ids are uuid objects by default. primitives are probably betterreturn DAG(nodes=[str(n.id) for n in nodes],executable_nodes=[str(n.id) for n in executable_nodes],ephemeral_nodes=[str(n.id) for n in ephemeral_nodes],edges=[(str(e.source.id), str(e.target.id)) for e in edges],+ suspended_nodes=suspended_nodes,)diff --git a/posthog/temporal/data_modeling/workflows/execute_dag.py b/posthog/temporal/data_modeling/workflows/execute_dag.pyindex 7c0f09b1e179..a339800f410d 100644--- a/posthog/temporal/data_modeling/workflows/execute_dag.py+++ b/posthog/temporal/data_modeling/workflows/execute_dag.py@@ -29,6 +29,8 @@ from posthog.temporal.data_modeling.workflows.materialize_view import (MaterializeViewWorkflowResult,)+from products.data_modeling.backend.facade.models import DataModelingJobEngine+MAX_CONCURRENT_CHILDREN = 10@@ -265,6 +267,10 @@ class ExecuteDAGWorkflow(PostHogWorkflow):node_results: list[NodeResult] = []ephemeral_node_set = set(dag_structure.ephemeral_nodes)failed_node_set: set[str] = set()+ serving_engine = (+ DataModelingJobEngine.DUCKGRES if inputs.duckgres_only else DataModelingJobEngine.CLICKHOUSE+ ).value+ suspended_node_set: set[str] = set(dag_structure.suspended_nodes.get(serving_engine, []))downstreams = _get_downstream_lookup(edge_lookup)# execute child workflows with bounded concurrency using a sliding window;# the semaphore limits how many child workflows run simultaneously across@@ -278,14 +284,21 @@ class ExecuteDAGWorkflow(PostHogWorkflow):execute_nodes = []skip_nodes = []ephemeral_nodes = []+ # failed_node_set only grows between levels, so the blocked set is stable within one+ blocked_node_set = failed_node_set | suspended_node_setfor node_id in level:should_skip = Falseskip_reason = None- for failed_id in failed_node_set:- if node_id in downstreams[failed_id]:- should_skip = True- skip_reason = f"Upstream node {failed_id} failed"- break+ if node_id in suspended_node_set:+ should_skip = True+ skip_reason = "Node suspended after repeated materialization failures"+ else:+ for blocked_id in blocked_node_set:+ if node_id in downstreams[blocked_id]:+ should_skip = True+ verb = "suspended" if blocked_id in suspended_node_set else "failed"+ skip_reason = f"Upstream node {blocked_id} {verb}"+ breakif should_skip:skip_nodes.append((node_id, skip_reason))elif node_id in ephemeral_node_set:diff --git a/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py b/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.pyindex f385d6bbf813..6933819cadfd 100644--- a/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py+++ b/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py@@ -2,6 +2,7 @@ import uuidimport datetime as dtimport pytest+import unittest.mockimport pytest_asyncioimport temporalio.worker@@ -34,7 +35,14 @@ from posthog.temporal.data_modeling.workflows.materialize_view import (MaterializeViewWorkflowResult,)-from products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Edge, Node, NodeType+from products.data_modeling.backend.facade.models import (+ DAG,+ DataModelingJobEngine,+ DataWarehouseSavedQuery,+ Edge,+ Node,+ NodeType,+)pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]@@ -131,6 +139,24 @@ class TestGetDagStructureActivity:source_node = dag_nodes[0]assert str(source_node.id) not in dag.executable_nodes+ @pytest.mark.parametrize("enforced", [True, False])+ async def test_reports_suspended_nodes_only_when_enforced(+ self, activity_environment, ateam, dag_nodes, adag, enforced+ ):+ from posthog.temporal.data_modeling.activities import get_dag_structure as gds+ from posthog.temporal.data_modeling.activities.utils import mark_node_suspended++ suspended_node = dag_nodes[1]+ mark_node_suspended(suspended_node, engine=DataModelingJobEngine.CLICKHOUSE, reason="boom", job_id="j")+ await database_sync_to_async(suspended_node.save)()++ inputs = GetDAGStructureInputs(team_id=ateam.pk, dag_id=str(adag.id))+ with unittest.mock.patch.object(gds, "_is_suspension_enforced", return_value=enforced):+ dag = await activity_environment.run(get_dag_structure_activity, inputs)++ assert dag.suspended_nodes["clickhouse"] == ([str(suspended_node.id)] if enforced else [])+ assert dag.suspended_nodes["duckgres"] == []+@pytest.mark.usefixtures("dag_edges") # avoids type checking unused argasync def test_excludes_source_table_edges(self, activity_environment, ateam, adag):inputs = GetDAGStructureInputs(team_id=ateam.pk, dag_id=str(adag.id))@@ -512,6 +538,77 @@ class TestExecuteDAGWorkflowWithMocks:assert node_b_id not in _mock_workflow_callsassert node_c_id not in _mock_workflow_calls+ async def test_skips_suspended_node_and_downstream(self):+ dag_id = "test-dag"+ node_a_id = str(uuid.uuid4())+ node_b_id = str(uuid.uuid4())+ node_c_id = str(uuid.uuid4())++ @temporal_activity.defn(name="get_dag_structure_activity")+ async def stub_get_dag_structure(_: GetDAGStructureInputs) -> DAGPlan:+ return DAGPlan(+ nodes=[node_a_id, node_b_id, node_c_id],+ executable_nodes=[node_a_id, node_b_id, node_c_id],+ edges=[(node_a_id, node_b_id), (node_b_id, node_c_id)],+ suspended_nodes={"clickhouse": [node_a_id], "duckgres": []},+ )++ 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],+ 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-suspended-{uuid.uuid4()}",+ task_queue="test-queue",+ execution_timeout=dt.timedelta(seconds=30),+ )++ assert result.skipped_nodes == 3+ assert result.successful_nodes == 0+ assert result.failed_nodes == 0+ assert _mock_workflow_calls == []++ async def test_serving_engine_determines_suspension(self):+ dag_id = "test-dag"+ node_ch_id = str(uuid.uuid4())+ node_duck_id = str(uuid.uuid4())++ @temporal_activity.defn(name="get_dag_structure_activity")+ async def stub_get_dag_structure(_: GetDAGStructureInputs) -> DAGPlan:+ return DAGPlan(+ nodes=[node_ch_id, node_duck_id],+ executable_nodes=[node_ch_id, node_duck_id],+ edges=[],+ suspended_nodes={"clickhouse": [node_ch_id], "duckgres": [node_duck_id]},+ )++ 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],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ result: ExecuteDAGResult = await env.client.execute_workflow(+ ExecuteDAGWorkflow.run,+ ExecuteDAGInputs(team_id=1, dag_id=dag_id, duckgres_only=True),+ id=f"test-serving-engine-{uuid.uuid4()}",+ task_queue="test-queue",+ execution_timeout=dt.timedelta(seconds=30),+ )++ assert node_ch_id in _mock_workflow_calls+ assert node_duck_id not in _mock_workflow_calls+ assert result.successful_nodes == 1+ assert result.skipped_nodes == 1+async def test_filters_by_node_ids(self):"""Test that specifying node_ids filters which nodes are executed."""dag_id = "test-dag"