: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): scope DAG run preemption to the run's own nodes (#73567)
Jovan Sakovica774bbbea261
diff --git a/posthog/temporal/data_modeling/activities/preempt_dag_run.py b/posthog/temporal/data_modeling/activities/preempt_dag_run.pyindex dbb001619779..a177c70028d9 100644--- a/posthog/temporal/data_modeling/activities/preempt_dag_run.py+++ b/posthog/temporal/data_modeling/activities/preempt_dag_run.py@@ -3,6 +3,8 @@ import dataclassesfrom structlog import get_loggerfrom structlog.contextvars import bind_contextvarsfrom temporalio import activity+from temporalio.client import Client, WorkflowExecutionStatus+from temporalio.service import RPCError, RPCStatusCodefrom posthog.exceptions_capture import capture_exceptionfrom posthog.sync import database_sync_to_async_pool@@ -13,17 +15,30 @@ from products.data_modeling.backend.facade.models import DataModelingJob, DataMoLOGGER = get_logger(__name__)PREEMPTED_ERROR = "Preempted: a new DAG run started before this job completed"+ABANDONED_ERROR = "Abandoned: the materialization workflow is no longer running"@dataclasses.dataclassclass PreemptDAGRunInputs:team_id: intdag_id: str+ node_ids: list[str] | None = None+++def _node_id_from_workflow_id(workflow_id: str, dag_id: str) -> str | None:+ """Recover the node id from a child workflow id, or None if it doesn't belong to this DAG."""+ prefix = f"materialize-view-{dag_id}-"+ if not workflow_id.startswith(prefix):+ return None+ # The remainder is `{node_id}-{timestamp}`. Node ids are UUIDs, so take the first five+ # dash-separated groups rather than assuming a fixed overall length.+ groups = workflow_id[len(prefix) :].split("-")+ return "-".join(groups[:5]) if len(groups) >= 5 else None@database_sync_to_async_pooldef _get_running_jobs_for_dag(team_id: int, dag_id: str) -> list[DataModelingJob]:- """Find RUNNING DataModelingJob records belonging to a previous run of this DAG.+ """Every RUNNING job belonging to this DAG, whether or not this run owns its node.Child workflow IDs follow the pattern `materialize-view-{dag_id}-{node_id}-{timestamp}`,so we can match jobs by their workflow_id prefix.@@ -37,53 +52,133 @@ def _get_running_jobs_for_dag(team_id: int, dag_id: str) -> list[DataModelingJob)+def partition_running_jobs(+ jobs: list[DataModelingJob], dag_id: str, node_ids: list[str] | None+) -> tuple[list[DataModelingJob], list[DataModelingJob]]:+ """Split this DAG's running jobs into the nodes this run owns and everything else.++ Cadence tiers of one DAG hold disjoint node sets, so only the owned half may be preempted —+ preempting DAG-wide is what lets one tier cancel another tier's live work. An unset+ `node_ids` means a whole-DAG run (the legacy single v2 schedule), which owns every node.++ The rest are merely *candidates* for reaping: whether they are corpses is decided by asking+ Temporal, not by anything on the row.+ """+ owned = set(node_ids or [])+ ours: list[DataModelingJob] = []+ others: list[DataModelingJob] = []+ for job in jobs:+ # Empty node_ids means "every node", matching how ExecuteDAGWorkflow reads the same field.+ if not node_ids or _node_id_from_workflow_id(job.workflow_id or "", dag_id) in owned:+ ours.append(job)+ else:+ others.append(job)+ return ours, others+++async def _abandoned_jobs(temporal: Client, candidates: list[DataModelingJob]) -> list[DataModelingJob]:+ """Of these rows, the ones whose workflow is no longer running.++ A row saying Running while its workflow is closed (or gone from Temporal's retention) is a+ corpse: nothing will ever close it. Asking Temporal is the only way to tell a corpse from a+ slow run — a job's wall-clock age cannot, because nothing bounds it. Activity+ `start_to_close_timeout` caps one attempt, not queue wait, retries, or the workflow overall,+ and MaterializeViewWorkflow is started with no execution timeout.+ """+ abandoned: list[DataModelingJob] = []+ for job in candidates:+ if not job.workflow_id:+ continue+ try:+ description = await temporal.get_workflow_handle(job.workflow_id).describe()+ except RPCError as e:+ # NOT_FOUND is the only error that proves absence. Timeouts, unavailability and+ # permission errors say nothing about the workflow, and marking a live job Failed is+ # unrecoverable (succeed_materialization refuses to overwrite a terminal status), so+ # anything else leaves the row alone for a later run to judge.+ if e.status == RPCStatusCode.NOT_FOUND:+ abandoned.append(job)+ continue+ except Exception:+ continue+ if description.status != WorkflowExecutionStatus.RUNNING:+ abandoned.append(job)+ return abandoned++@database_sync_to_async_pool-def _mark_jobs_as_preempted(job_ids: list[str]) -> int:+def _mark_jobs_failed(job_ids: list[str], error: str) -> int:return DataModelingJob.objects.filter(id__in=job_ids, status=DataModelingJobStatus.RUNNING).update(status=DataModelingJobStatus.FAILED,rows_materialized=0,- error=PREEMPTED_ERROR,+ error=error,)@activity.defnasync def preempt_dag_run_activity(inputs: PreemptDAGRunInputs) -> None:- """Preempt a previous run of the same DAG by cancelling its parent workflow and marking jobs as failed.-- Cancelling the parent ExecuteDAGWorkflow cascades to all child MaterializeViewWorkflows- (via ParentClosePolicy.REQUEST_CANCEL), which avoids a race where new children could be- spawned after individual child cancellation.+ """Preempt in-flight materializations of the nodes this run is about to materialize, and+ reap rows anywhere in the DAG whose workflow died without closing them.++ Cancels each owned node's own MaterializeViewWorkflow rather than the parent+ ExecuteDAGWorkflow: parent cancellation cascades to every sibling child via+ ParentClosePolicy.REQUEST_CANCEL, so preempting one node that has since moved between+ cadence tiers would take down the whole run that still owns its siblings.+ A parent starts each of its nodes once, so there is no child to re-spawn behind us.++ Rows outside that node set are only reaped, and only once Temporal confirms their workflow+ is no longer running: they are marked, never cancelled, because there is nothing left to+ cancel and cancelling on another tier's behalf is exactly what this activity must not do."""bind_contextvars(team_id=inputs.team_id)logger = LOGGER.bind()running_jobs = await _get_running_jobs_for_dag(inputs.team_id, inputs.dag_id)- if not running_jobs:+ ours, others = partition_running_jobs(running_jobs, inputs.dag_id, inputs.node_ids)+ if not ours and not others:await logger.adebug("No previous DAG run to preempt")return- await logger.ainfo(- f"Preempting previous DAG run: found {len(running_jobs)} running jobs",- dag_id=inputs.dag_id,- )- # collect unique parent workflow IDs — cancelling the parent cascades to all children- parent_workflow_ids = {job.parent_workflow_id for job in running_jobs if job.parent_workflow_id}- job_ids = [str(job.id) for job in running_jobs]- # mark all running jobs as preempted- updated_count = await _mark_jobs_as_preempted(job_ids)- await logger.ainfo(f"Marked {updated_count} jobs as preempted", dag_id=inputs.dag_id)- # request cancellation of parent workflows — this cascades to all children- if parent_workflow_ids:- try:- temporal = await async_connect()- for workflow_id in parent_workflow_ids:- try:- handle = temporal.get_workflow_handle(workflow_id)- await handle.cancel()- await logger.ainfo(f"Requested cancellation of parent workflow {workflow_id}")- except Exception as e:- # workflow may have already completed — that's fine- await logger.awarning(f"Could not cancel parent workflow {workflow_id}: {str(e)}")- except Exception as e:- capture_exception(e)- await logger.aexception(f"Failed to connect to Temporal for workflow cancellation: {str(e)}")+ try:+ temporal = await async_connect()+ except Exception as e:+ # Nothing has been touched yet, and marking a row Failed without cancelling its workflow+ # is the corruption this activity exists to avoid. Leave everything Running and let the+ # activity's own retry (or the next run) handle it.+ capture_exception(e)+ await logger.aexception(f"Failed to connect to Temporal: {str(e)}")+ raise++ # Preempt first, and cancel before marking. Reaping below makes one RPC per candidate row and+ # can outrun the activity timeout; if that happens after the owned rows are already marked, a+ # retry no longer finds them as Running and their workflows would never be cancelled, leaving+ # the new run free to materialize the same node concurrently. Cancelling first also means a+ # crash between the two steps is recoverable: the rows are still Running, so the retry+ # re-finds them and cancellation is idempotent.+ if ours:+ await logger.ainfo(+ f"Preempting previous DAG run: found {len(ours)} running jobs",+ dag_id=inputs.dag_id,+ )+ for workflow_id in {job.workflow_id for job in ours if job.workflow_id}:+ try:+ await temporal.get_workflow_handle(workflow_id).cancel()+ await logger.ainfo(f"Requested cancellation of materialize workflow {workflow_id}")+ except Exception as e:+ # workflow may have already completed — that's fine+ await logger.awarning(f"Could not cancel materialize workflow {workflow_id}: {str(e)}")+ updated_count = await _mark_jobs_failed([str(job.id) for job in ours], PREEMPTED_ERROR)+ await logger.ainfo(f"Marked {updated_count} jobs as preempted", dag_id=inputs.dag_id)++ if not others:+ return++ # Best-effort cleanup: it must never undo or block the preemption above.+ try:+ abandoned = await _abandoned_jobs(temporal, others)+ if abandoned:+ reaped = await _mark_jobs_failed([str(job.id) for job in abandoned], ABANDONED_ERROR)+ await logger.ainfo(f"Reaped {reaped} abandoned jobs", dag_id=inputs.dag_id)+ except Exception as e:+ capture_exception(e)+ await logger.aexception(f"Failed to reap abandoned jobs: {str(e)}")diff --git a/posthog/temporal/data_modeling/workflows/execute_dag.py b/posthog/temporal/data_modeling/workflows/execute_dag.pyindex a339800f410d..a0a5491da09d 100644--- a/posthog/temporal/data_modeling/workflows/execute_dag.py+++ b/posthog/temporal/data_modeling/workflows/execute_dag.py@@ -203,6 +203,7 @@ class ExecuteDAGWorkflow(PostHogWorkflow):PreemptDAGRunInputs(team_id=inputs.team_id,dag_id=inputs.dag_id,+ node_ids=inputs.node_ids,),start_to_close_timeout=dt.timedelta(minutes=5),retry_policy=temporalio.common.RetryPolicy(diff --git a/posthog/temporal/tests/data_modeling/test_preempt_dag_run.py b/posthog/temporal/tests/data_modeling/test_preempt_dag_run.pynew file mode 100644index 000000000000..e16c8cbe2f8c--- /dev/null+++ b/posthog/temporal/tests/data_modeling/test_preempt_dag_run.py@@ -0,0 +1,221 @@+import uuid++import pytest+import unittest.mock++import pytest_asyncio+from temporalio.client import WorkflowExecutionStatus+from temporalio.service import RPCError, RPCStatusCode+from temporalio.testing import ActivityEnvironment++from posthog.sync import database_sync_to_async+from posthog.temporal.data_modeling.activities.preempt_dag_run import (+ ABANDONED_ERROR,+ PREEMPTED_ERROR,+ PreemptDAGRunInputs,+ preempt_dag_run_activity,+)++from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobStatus++pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]++DAG_ID = "019e4d6a-1d8a-7569-97f5-a78ab8467820"+NODE_HOURLY = "11111111-1111-1111-1111-111111111111"+NODE_QUARTER_HOURLY = "22222222-2222-2222-2222-222222222222"+# Ran under the hourly tier, but a reconcile has since moved it to the 15-minute tier, so the+# 15-minute run now owns a node whose in-flight job belongs to the hourly run.+NODE_MIGRATED = "33333333-3333-3333-3333-333333333333"+# In no tier at all, so no run ever owns it.+NODE_ORPHAN = "44444444-4444-4444-4444-444444444444"++# Mirrors execute_dag.py: child id is materialize-view-{dag_id}-{node_id}-{ts}, and the+# parent (tier) id is execute-dag-{dag_id}:{interval_seconds}-{ts}.+PARENT_HOURLY = f"execute-dag-{DAG_ID}:3600-2026-07-24T13:00:00"+PARENT_QUARTER_HOURLY = f"execute-dag-{DAG_ID}:900-2026-07-24T13:00:00"+++def _child_workflow_id(node_id: str) -> str:+ return f"materialize-view-{DAG_ID}-{node_id}-2026-07-24T13:00:00"+++@pytest_asyncio.fixture+async def tier_jobs(ateam):+ """One RUNNING job per cadence tier of the same DAG, on disjoint nodes."""++ async def make(node_id: str, parent_workflow_id: str) -> DataModelingJob:+ return await database_sync_to_async(DataModelingJob.objects.create)(+ team=ateam,+ status=DataModelingJobStatus.RUNNING,+ workflow_id=_child_workflow_id(node_id),+ parent_workflow_id=parent_workflow_id,+ )++ yield {+ NODE_HOURLY: await make(NODE_HOURLY, PARENT_HOURLY),+ NODE_QUARTER_HOURLY: await make(NODE_QUARTER_HOURLY, PARENT_QUARTER_HOURLY),+ # Shares the hourly run's parent with NODE_HOURLY.+ NODE_MIGRATED: await make(NODE_MIGRATED, PARENT_HOURLY),+ }+++NOT_FOUND = RPCError("workflow not found", RPCStatusCode.NOT_FOUND, b"")+UNAVAILABLE = RPCError("temporal unavailable", RPCStatusCode.UNAVAILABLE, b"")+++async def _run_activity(+ team_id: int,+ node_ids: list[str] | None,+ workflow_status: dict[str, WorkflowExecutionStatus | Exception] | None = None,+) -> list[str]:+ """Run the activity against a stubbed Temporal client, returning the workflows it cancelled.++ `workflow_status` maps a workflow id to what describe() does: a status to report, or an+ exception to raise. Anything unlisted is reported as still RUNNING.+ """+ cancelled: list[str] = []+ statuses: dict[str, WorkflowExecutionStatus | Exception] = workflow_status or {}++ def get_workflow_handle(workflow_id: str) -> unittest.mock.MagicMock:+ handle = unittest.mock.MagicMock()++ async def cancel() -> None:+ cancelled.append(workflow_id)++ async def describe() -> unittest.mock.MagicMock:+ outcome = statuses.get(workflow_id, WorkflowExecutionStatus.RUNNING)+ if isinstance(outcome, Exception):+ raise outcome+ description = unittest.mock.MagicMock()+ description.status = outcome+ return description++ handle.cancel = cancel+ handle.describe = describe+ return handle++ client = unittest.mock.MagicMock()+ client.get_workflow_handle = unittest.mock.MagicMock(side_effect=get_workflow_handle)++ with unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.preempt_dag_run.async_connect",+ unittest.mock.AsyncMock(return_value=client),+ ):+ await ActivityEnvironment().run(+ preempt_dag_run_activity,+ PreemptDAGRunInputs(team_id=team_id, dag_id=DAG_ID, node_ids=node_ids),+ )+ return cancelled+++ "node_ids,expected_preempted",+ [+ # The bug: the 15-minute tier must not touch the hourly tier's unrelated nodes.+ pytest.param([NODE_QUARTER_HOURLY], [NODE_QUARTER_HOURLY], id="scopes_to_own_tier"),+ # Claiming a node whose in-flight job belongs to another tier's run must not take that+ # run's siblings down with it — which cancelling the shared parent workflow would.+ pytest.param([NODE_MIGRATED], [NODE_MIGRATED], id="migrated_node_spares_its_old_runs_siblings"),+ # Legacy single whole-DAG schedule carries no node set and still preempts everything.+ pytest.param(None, [NODE_HOURLY, NODE_QUARTER_HOURLY, NODE_MIGRATED], id="no_node_ids_preempts_whole_dag"),+ # A tier whose nodes have no running jobs preempts nothing at all.+ pytest.param([str(uuid.uuid4())], [], id="unrelated_nodes_preempt_nothing"),+ ],+)+async def test_preempt_is_scoped_to_the_tiers_own_nodes(+ node_ids: list[str] | None,+ expected_preempted: list[str],+ ateam,+ tier_jobs,+) -> None:+ cancelled = await _run_activity(ateam.pk, node_ids)++ for node_id, job in tier_jobs.items():+ await database_sync_to_async(job.refresh_from_db)()+ if node_id in expected_preempted:+ assert job.status == DataModelingJobStatus.FAILED+ assert job.error == PREEMPTED_ERROR+ else:+ # Every other job's workflow reports RUNNING, so it is neither preempted nor reaped.+ assert job.status == DataModelingJobStatus.RUNNING+ assert job.error is None++ # Only the owned nodes' own materialize workflows are cancelled. Cancelling a parent+ # would cascade to its siblings via ParentClosePolicy.REQUEST_CANCEL, which is the+ # over-broad cancellation this scoping exists to prevent.+ assert sorted(cancelled) == sorted(_child_workflow_id(node_id) for node_id in expected_preempted)+ assert not {PARENT_HOURLY, PARENT_QUARTER_HOURLY} & set(cancelled)+++ "status,expect_reaped",+ [+ pytest.param(WorkflowExecutionStatus.COMPLETED, True, id="closed_workflow_is_reaped"),+ pytest.param(WorkflowExecutionStatus.TERMINATED, True, id="terminated_workflow_is_reaped"),+ pytest.param(NOT_FOUND, True, id="missing_workflow_is_reaped"),+ # The one that age could not tell apart: still running, just slow. Nothing bounds a+ # materialization's wall clock, so this must be decided by status, not elapsed time.+ pytest.param(WorkflowExecutionStatus.RUNNING, False, id="slow_live_workflow_is_left_alone"),+ # A transient RPC failure proves nothing about the workflow. Treating it as "gone" would+ # mark a live job Failed without cancelling it — the exact corruption this fix prevents,+ # and unrecoverable because succeed_materialization won't overwrite a terminal status.+ pytest.param(UNAVAILABLE, False, id="transient_rpc_error_leaves_row_alone"),+ ],+)+async def test_rows_we_do_not_own_are_reaped_only_when_their_workflow_is_gone(+ status: WorkflowExecutionStatus | Exception,+ expect_reaped: bool,+ ateam,+ tier_jobs,+) -> None:+ # A node in no tier: nothing ever owns it, so if ownership gated cleanup its row would stay+ # Running forever and the UI would show it perpetually materializing.+ orphan = await database_sync_to_async(DataModelingJob.objects.create)(+ team=ateam,+ status=DataModelingJobStatus.RUNNING,+ workflow_id=_child_workflow_id(NODE_ORPHAN),+ parent_workflow_id=PARENT_HOURLY,+ )++ cancelled = await _run_activity(+ ateam.pk,+ [NODE_QUARTER_HOURLY],+ workflow_status={_child_workflow_id(NODE_ORPHAN): status},+ )++ await database_sync_to_async(orphan.refresh_from_db)()+ if expect_reaped:+ assert orphan.status == DataModelingJobStatus.FAILED+ assert orphan.error == ABANDONED_ERROR+ else:+ assert orphan.status == DataModelingJobStatus.RUNNING+ assert orphan.error is None++ # Reaping only marks the row. There is no live workflow left to cancel, and cancelling on+ # another tier's behalf is precisely what this activity must not do.+ assert cancelled == [_child_workflow_id(NODE_QUARTER_HOURLY)]+++async def test_owned_workflows_are_cancelled_even_if_reaping_blows_up(ateam, tier_jobs) -> None:+ """Reaping makes one RPC per foreign row and can outrun the activity timeout. If that happened+ after the owned rows were marked Failed, a retry would no longer see them as Running and their+ workflows would never be cancelled — leaving the new run free to materialize the same node+ concurrently. Preemption must therefore complete before reaping is attempted at all."""+ await database_sync_to_async(DataModelingJob.objects.create)(+ team=ateam,+ status=DataModelingJobStatus.RUNNING,+ workflow_id=_child_workflow_id(NODE_ORPHAN),+ parent_workflow_id=PARENT_HOURLY,+ )++ with unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.preempt_dag_run._abandoned_jobs",+ unittest.mock.AsyncMock(side_effect=RuntimeError("reaping exploded")),+ ):+ cancelled = await _run_activity(ateam.pk, [NODE_QUARTER_HOURLY])++ owned = tier_jobs[NODE_QUARTER_HOURLY]+ await database_sync_to_async(owned.refresh_from_db)()+ assert owned.status == DataModelingJobStatus.FAILED+ assert owned.error == PREEMPTED_ERROR+ assert cancelled == [_child_workflow_id(NODE_QUARTER_HOURLY)]