Skip to content

: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.

fix(data-modeling): stop clickhouse dag runs waiting on trino shadows (#114695)

Jovan Sakovic3d9e88b195e6
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.md
index 24d7f5f32504..e61d6d8b9769 100644
--- a/docs/internal/hogql-trino-compiler.md
+++ b/docs/internal/hogql-trino-compiler.md
@@ -227,9 +227,15 @@ Compilation failures fail the modeling job, without connecting to Trino or falli
Trino replaces the output table in the organization's catalog under `posthog_data_modeling_team_<team_id>`, using the sanitized model-path label or saved-query UUID.
The compiler and materializer share this naming policy, so each compiled query can read upstream model outputs directly.
The legacy Duckgres path retains `shadow_<team_id>_models` and normalized saved-query names.
-ClickHouse materialization and publication continue independently.
-The DAG waits for upstream Trino builds and skips dependent Trino builds when an upstream model fails or is ineligible for shadowing, even if ClickHouse succeeds.
-Skipped managed warehouse jobs record the upstream node IDs. Existing Temporal histories retain their previous dependency behavior.
+The shadow is a separate DAG run, so ClickHouse materialization and publication never wait for Trino.
+When an eligible organization's ClickHouse DAG run starts, it starts one `managed_warehouse_only` run of the same nodes as an abandoned child workflow, and does not wait for it.
+The shadow run has a fixed workflow id per DAG and cadence tier: `execute-dag-trino-{dag_id}:{tier}`, or `execute-dag-trino-{dag_id}` for runs outside a tier schedule.
+If the previous shadow run with that id is still running, the new one is skipped, so a slow Trino never builds a backlog.
+Shadow runs record their outcomes in managed warehouse job rows and metrics only: they run no data quality checks and send no failure notifications.
+Preemption is scoped to the run's engine, so the ClickHouse and Trino runs of a tier never cancel each other's jobs.
+A single-model materialization started outside a DAG run does not start a Trino shadow.
+Within the shadow run, the DAG waits for upstream Trino builds and skips dependent Trino builds when an upstream model fails or is ineligible for shadowing.
+Skipped managed warehouse jobs record the upstream node IDs. Existing Temporal histories retain their previous behavior, including the shadow inside the ClickHouse materialization.
Run upstream materialized models before their dependents when selecting a subset of the DAG.
Do not run the legacy DuckLake model-copy workflow against the same destinations while Trino owns their refreshes.
Publication uses the DuckLake connector's atomic `CREATE OR REPLACE TABLE` operation, so a failed write preserves the previous table.
diff --git a/posthog/temporal/data_modeling/__init__.py b/posthog/temporal/data_modeling/__init__.py
index d8eda1e47d78..589d1067bc7b 100644
--- a/posthog/temporal/data_modeling/__init__.py
+++ b/posthog/temporal/data_modeling/__init__.py
@@ -1,6 +1,7 @@
from posthog.temporal.data_modeling.activities import (
check_managed_warehouse_shadow_eligibility_activity,
check_managed_warehouse_shadow_enabled_activity,
+ check_team_managed_warehouse_shadow_eligibility_activity,
clear_cdp_staging_activity,
create_data_modeling_job_activity,
enrich_view_semantics_activity,
@@ -33,6 +34,7 @@ SEMANTIC_ENRICHMENT_ACTIVITIES = [enrich_view_semantics_activity]
ACTIVITIES = [
check_managed_warehouse_shadow_eligibility_activity,
check_managed_warehouse_shadow_enabled_activity,
+ check_team_managed_warehouse_shadow_eligibility_activity,
clear_cdp_staging_activity,
create_data_modeling_job_activity,
record_skipped_data_modeling_jobs_activity,
diff --git a/posthog/temporal/data_modeling/activities/__init__.py b/posthog/temporal/data_modeling/activities/__init__.py
index 19edeb81d5d9..6581d5b43f1f 100644
--- a/posthog/temporal/data_modeling/activities/__init__.py
+++ b/posthog/temporal/data_modeling/activities/__init__.py
@@ -22,6 +22,7 @@ from .materialize_view_managed_warehouse import (
ManagedWarehouseShadowResult,
check_managed_warehouse_shadow_eligibility_activity,
check_managed_warehouse_shadow_enabled_activity,
+ check_team_managed_warehouse_shadow_eligibility_activity,
materialize_view_managed_warehouse_activity,
)
from .notify_materialization_failure import (
@@ -70,6 +71,7 @@ __all__ = [
"SucceedMaterializationResult",
"check_managed_warehouse_shadow_eligibility_activity",
"check_managed_warehouse_shadow_enabled_activity",
+ "check_team_managed_warehouse_shadow_eligibility_activity",
"clear_cdp_staging_activity",
"create_data_modeling_job_activity",
"record_skipped_data_modeling_jobs_activity",
diff --git a/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py b/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py
index 09bc2b426f65..6251334e39b3 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py
@@ -188,6 +188,17 @@ async def check_managed_warehouse_shadow_enabled_activity(team_id: int) -> bool:
return await _check_managed_warehouse_shadow_enabled_activity(team_id)
+@database_sync_to_async_pool
+def _check_team_managed_warehouse_shadow_eligibility(team_id: int) -> bool:
+ return _is_managed_warehouse_shadow_enabled(Team.objects.get(id=team_id))
+
+
+async def check_team_managed_warehouse_shadow_eligibility_activity(team_id: int) -> bool:
+ """Check whether DAG runs of this team's organization should start a Trino shadow run."""
+ return await _check_team_managed_warehouse_shadow_eligibility(team_id)
+
+
@activity.defn
async def check_managed_warehouse_shadow_eligibility_activity(
inputs: ManagedWarehouseShadowEligibilityInputs,
@@ -220,9 +231,9 @@ async def _materialize_view_managed_warehouse(
) -> ManagedWarehouseShadowResult:
"""Shadow activity: execute a managed warehouse materialization and create a DuckLake table.
- This is a fire-and-forget companion to the main ClickHouse-based materialize_view_activity.
+ It runs in a managed_warehouse_only MaterializeViewWorkflow, which the Trino shadow DAG run
+ starts separately from the ClickHouse run, so its failures never affect ClickHouse.
The query result is materialized as a native DuckLake table (Parquet on S3 + Postgres catalog).
- Failures here never affect the parent workflow.
"""
bind_contextvars(team_id=inputs.team_id)
logger = LOGGER.bind()
diff --git a/posthog/temporal/data_modeling/activities/preempt_dag_run.py b/posthog/temporal/data_modeling/activities/preempt_dag_run.py
index f6c6e4dafbe7..fd7569f9ea42 100644
--- a/posthog/temporal/data_modeling/activities/preempt_dag_run.py
+++ b/posthog/temporal/data_modeling/activities/preempt_dag_run.py
@@ -10,7 +10,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.sync import database_sync_to_async_pool
from posthog.temporal.common.client import async_connect
-from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobStatus
+from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobEngine, DataModelingJobStatus
LOGGER = get_logger(__name__)
@@ -18,11 +18,13 @@ PREEMPTED_ERROR = "Preempted: a new DAG run started before this job completed"
ABANDONED_ERROR = "Abandoned: the materialization workflow is no longer running"
[email protected](frozen=False)
class PreemptDAGRunInputs:
team_id: int
dag_id: str
node_ids: list[str] | None = None
+ # Defaulted so inputs serialized before this field existed still decode.
+ engine: str = DataModelingJobEngine.CLICKHOUSE
def _node_id_from_workflow_id(workflow_id: str, dag_id: str) -> str | None:
@@ -37,16 +39,18 @@ def _node_id_from_workflow_id(workflow_id: str, dag_id: str) -> str | None:
@database_sync_to_async_pool
-def _get_running_jobs_for_dag(team_id: int, dag_id: str) -> list[DataModelingJob]:
- """Every RUNNING job belonging to this DAG, whether or not this run owns its node.
+def _get_running_jobs_for_dag(team_id: int, dag_id: str, engine: str) -> list[DataModelingJob]:
+ """Every RUNNING job of one engine in 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.
+ so we can match jobs by their workflow_id prefix. The ClickHouse and Trino runs of a DAG
+ materialize the same nodes at the same time, so each run only touches its own engine's jobs.
"""
return list(
DataModelingJob.objects.filter(
team_id=team_id,
status=DataModelingJobStatus.RUNNING,
+ engine=engine,
workflow_id__startswith=f"materialize-view-{dag_id}-",
)
)
@@ -137,7 +141,7 @@ async def preempt_dag_run_activity(inputs: PreemptDAGRunInputs) -> None:
bind_contextvars(team_id=inputs.team_id)
logger = LOGGER.bind()
- running_jobs = await _get_running_jobs_for_dag(inputs.team_id, inputs.dag_id)
+ running_jobs = await _get_running_jobs_for_dag(inputs.team_id, inputs.dag_id, inputs.engine)
partitioned = partition_running_jobs(running_jobs, inputs.dag_id, inputs.node_ids)
if not partitioned.owned and not partitioned.others:
await logger.adebug("No previous DAG run to preempt")
diff --git a/posthog/temporal/data_modeling/metrics.py b/posthog/temporal/data_modeling/metrics.py
index 91838470bd18..bfbc74f5d317 100644
--- a/posthog/temporal/data_modeling/metrics.py
+++ b/posthog/temporal/data_modeling/metrics.py
@@ -132,10 +132,10 @@ def get_clickhouse_materialization_duration_metric() -> MetricHistogramFloat:
# DAG-level metrics (v2 ExecuteDAGWorkflow)
-def get_dag_finished_metric(status: str) -> MetricCounter:
+def get_dag_finished_metric(status: str, engine: str) -> MetricCounter:
return (
workflow.metric_meter()
- .with_additional_attributes({"status": status})
+ .with_additional_attributes({"status": status, "engine": engine})
.create_counter(
"data_modeling_dag_finished",
"Number of DAG executions finished. Status is completed, partial_failure, skipped, or failed.",
@@ -143,18 +143,22 @@ def get_dag_finished_metric(status: str) -> MetricCounter:
)
-def get_dag_duration_metric() -> MetricHistogramFloat:
- return workflow.metric_meter().create_histogram_float(
- "data_modeling_dag_duration_seconds",
- "Total wall-clock duration of a DAG execution.",
- "s",
+def get_dag_duration_metric(engine: str) -> MetricHistogramFloat:
+ return (
+ workflow.metric_meter()
+ .with_additional_attributes({"engine": engine})
+ .create_histogram_float(
+ "data_modeling_dag_duration_seconds",
+ "Total wall-clock duration of a DAG execution.",
+ "s",
+ )
)
-def get_dag_node_count_metric(outcome: str) -> MetricHistogramFloat:
+def get_dag_node_count_metric(outcome: str, engine: str) -> MetricHistogramFloat:
return (
workflow.metric_meter()
- .with_additional_attributes({"outcome": outcome})
+ .with_additional_attributes({"outcome": outcome, "engine": engine})
.create_histogram_float(
"data_modeling_dag_node_count",
"Number of nodes per outcome (successful, failed, skipped) in a DAG execution.",
diff --git a/posthog/temporal/data_modeling/workflows/execute_dag.py b/posthog/temporal/data_modeling/workflows/execute_dag.py
index fb6325c9f54b..154ec2525720 100644
--- a/posthog/temporal/data_modeling/workflows/execute_dag.py
+++ b/posthog/temporal/data_modeling/workflows/execute_dag.py
@@ -7,6 +7,7 @@ from collections import defaultdict
import temporalio.common
import temporalio.workflow
import temporalio.exceptions
+from temporalio.exceptions import WorkflowAlreadyStartedError
from temporalio.workflow import ParentClosePolicy
from posthog.exceptions_capture import capture_exception
@@ -18,6 +19,7 @@ from posthog.temporal.data_modeling.activities import (
PreemptDAGRunInputs,
RecordSkippedDataModelingJobsInputs,
SkippedDataModelingNode,
+ check_team_managed_warehouse_shadow_eligibility_activity,
get_dag_structure_activity,
notify_dag_materialization_failures_activity,
preempt_dag_run_activity,
@@ -33,6 +35,7 @@ from posthog.temporal.data_modeling.workflows.materialize_view import (
MaterializeViewWorkflow,
MaterializeViewWorkflowInputs,
MaterializeViewWorkflowResult,
+ _is_cancellation,
)
from products.data_modeling.backend.facade.models import DataModelingJobEngine
@@ -41,6 +44,24 @@ from products.data_quality.backend.facade.enums import SuiteRunTrigger
MAX_CONCURRENT_CHILDREN = 10
+TRINO_SHADOW_DAG_RUN_PATCH = "data-modeling-trino-shadow-dag-run"
+TRINO_SHADOW_RUN_TIMEOUT = dt.timedelta(hours=12)
+
+
+def trino_shadow_workflow_id(workflow_id: str, dag_id: str) -> str:
+ """The fixed id of the Trino shadow run for the DAG run with this workflow id.
+
+ Tier schedule runs are `execute-dag-{dag_id}:{tier}-{timestamp}`, so each cadence tier gets
+ its own shadow id. Any other run shares one id per DAG. A fixed id lets Temporal refuse a
+ second shadow while the previous one is still running.
+ """
+ tier_prefix = f"execute-dag-{dag_id}:"
+ if workflow_id.startswith(tier_prefix):
+ tier = workflow_id[len(tier_prefix) :].split("-", 1)[0]
+ if tier:
+ return f"execute-dag-trino-{dag_id}:{tier}"
+ return f"execute-dag-trino-{dag_id}"
+
class EmptyDAGOrCycleError(Exception):
"""Raised when the DAG is empty or contains a cycle according to _dag_execution_levels."""
@@ -57,6 +78,8 @@ class ExecuteDAGInputs:
dag_id: the DAG to execute.
node_ids: optional list of specific node IDs to materialize. If not provided,
all materializable nodes in the DAG will be processed.
+ shadow: a Trino shadow of a ClickHouse run. Its failures stay in job rows and metrics,
+ so it runs no data quality checks and sends no failure notifications.
"""
team_id: int
@@ -66,6 +89,7 @@ class ExecuteDAGInputs:
dangerously_execute_raw_sql: bool = False
# Old workflow payloads contain this field, so removing it would prevent replay after deployment.
duckgres_only: bool = False
+ shadow: bool = False
@property
def properties_to_log(self) -> dict:
@@ -76,6 +100,13 @@ class ExecuteDAGInputs:
}
+def _serving_engine(inputs: ExecuteDAGInputs) -> str:
+ engine = (
+ DataModelingJobEngine.MANAGED_WAREHOUSE if inputs.managed_warehouse_only else DataModelingJobEngine.CLICKHOUSE
+ )
+ return engine.value
+
+
@dataclasses.dataclass(frozen=False)
class NodeResult:
"""Result for a single node materialization."""
@@ -217,6 +248,7 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
team_id=inputs.team_id,
dag_id=inputs.dag_id,
node_ids=inputs.node_ids,
+ engine=_serving_engine(inputs),
),
start_to_close_timeout=dt.timedelta(minutes=5),
retry_policy=temporalio.common.RetryPolicy(
@@ -265,6 +297,9 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
node_results=[],
)
+ if not inputs.managed_warehouse_only and temporalio.workflow.patched(TRINO_SHADOW_DAG_RUN_PATCH):
+ await self._maybe_start_trino_shadow(inputs)
+
edge_lookup = _get_edge_lookup(dag_structure.edges)
levels = _dag_execution_levels(inputs.team_id, inputs.dag_id, executable_nodes, edge_lookup)
@@ -283,9 +318,7 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
failed_node_set: set[str] = set()
quality_failed_node_set: set[str] = set()
managed_warehouse_only = inputs.managed_warehouse_only
- serving_engine = (
- DataModelingJobEngine.MANAGED_WAREHOUSE if managed_warehouse_only else DataModelingJobEngine.CLICKHOUSE
- ).value
+ serving_engine = _serving_engine(inputs)
suspended_node_set: set[str] = set(dag_structure.suspended_nodes.get(serving_engine, []))
downstreams = _get_downstream_lookup(edge_lookup)
skipped_jobs: list[SkippedDataModelingNode] = []
@@ -530,15 +563,17 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
dag_status = "failed"
else:
dag_status = "partial_failure"
- get_dag_finished_metric(dag_status).add(1)
- get_dag_duration_metric().record(duration_seconds)
- get_dag_node_count_metric("successful").record(successful_nodes)
- get_dag_node_count_metric("failed").record(failed_nodes)
- get_dag_node_count_metric("skipped").record(skipped_nodes)
+ engine = _serving_engine(inputs)
+ get_dag_finished_metric(dag_status, engine).add(1)
+ get_dag_duration_metric(engine).record(duration_seconds)
+ get_dag_node_count_metric("successful", engine).record(successful_nodes)
+ get_dag_node_count_metric("failed", engine).record(failed_nodes)
+ get_dag_node_count_metric("skipped", engine).record(skipped_nodes)
- await self._run_data_quality_checks(inputs, node_results)
+ if not inputs.shadow:
+ await self._run_data_quality_checks(inputs, node_results)
- if failed_nodes:
+ if failed_nodes and not inputs.shadow:
await temporalio.workflow.execute_activity(
notify_dag_materialization_failures_activity,
NotifyDAGMaterializationFailuresInputs(
@@ -561,6 +596,50 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
node_results=node_results,
)
+ async def _maybe_start_trino_shadow(self, inputs: ExecuteDAGInputs) -> None:
+ """Start a managed_warehouse_only run of the same nodes when the org shadows into Trino.
+
+ ABANDON and never awaited, so the Trino runtime can neither delay nor fail this run. When
+ the previous shadow of this tier is still running, this one is skipped rather than
+ restarting it, so a slow Trino never builds a backlog.
+ """
+ try:
+ eligible = await temporalio.workflow.execute_activity(
+ check_team_managed_warehouse_shadow_eligibility_activity,
+ inputs.team_id,
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),
+ )
+ if not eligible:
+ return
+ await temporalio.workflow.start_child_workflow(
+ ExecuteDAGWorkflow.run,
+ ExecuteDAGInputs(
+ team_id=inputs.team_id,
+ dag_id=inputs.dag_id,
+ node_ids=inputs.node_ids,
+ managed_warehouse_only=True,
+ dangerously_execute_raw_sql=inputs.dangerously_execute_raw_sql,
+ shadow=True,
+ ),
+ id=trino_shadow_workflow_id(temporalio.workflow.info().workflow_id, inputs.dag_id),
+ parent_close_policy=ParentClosePolicy.ABANDON,
+ # Later shadows of this tier are skipped while one runs, so a hung run must end.
+ execution_timeout=TRINO_SHADOW_RUN_TIMEOUT,
+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=1),
+ )
+ except WorkflowAlreadyStartedError:
+ temporalio.workflow.logger.info(
+ "Previous Trino shadow run is still running, skipping", extra=inputs.properties_to_log
+ )
+ except Exception as e:
+ if _is_cancellation(e):
+ raise
+ capture_exception(e)
+ temporalio.workflow.logger.warning(
+ "Could not start the Trino shadow run", extra={"error": str(e), **inputs.properties_to_log}
+ )
+
async def _run_data_quality_checks(self, inputs: ExecuteDAGInputs, node_results: list[NodeResult]) -> None:
"""Fire the check suite for the nodes this run refreshed but did not audit per-node.
diff --git a/posthog/temporal/data_modeling/workflows/materialize_view.py b/posthog/temporal/data_modeling/workflows/materialize_view.py
index 116d564d2dc0..23ce3c896c0e 100644
--- a/posthog/temporal/data_modeling/workflows/materialize_view.py
+++ b/posthog/temporal/data_modeling/workflows/materialize_view.py
@@ -87,6 +87,8 @@ NON_RETRYABLE_ERRORS = [
"UnstorableIntegerError",
]
+CLICKHOUSE_RUN_WITHOUT_TRINO_SHADOW_PATCH = "data-modeling-clickhouse-run-without-trino-shadow"
+
def _is_cancellation(error: BaseException) -> bool:
"""The SDK never re-delivers a cancel, so a handler that swallows one keeps issuing commands."""
@@ -140,6 +142,8 @@ class MaterializeViewWorkflowResult:
means no gated audit ran.
quality_audited: Whether a check suite covered this run, so the DAG's post-run sweep must
not run one again.
+ trino_materialized: Whether this run materialized the node in Trino. None means it made
+ no Trino attempt, as for every ClickHouse run.
"""
job_id: str
@@ -163,9 +167,9 @@ class MaterializeViewWorkflow(PostHogWorkflow):
This workflow handles the complete materialization of a single view/materialized view:
1. Creates a job record to track progress
- 2. Executes the HogQL query and writes results to a delta lake table
- 3. Copies the data to DuckLake (if enabled)
- 4. Updates the node and job with completion status
+ 2. Executes the HogQL query and writes results to a delta lake table, or, when
+ `managed_warehouse_only` is set, materializes it in the managed warehouse instead
+ 3. Updates the node and job with completion status
This workflow is designed to be called directly for ad hoc materialization of a single view
(i.e. a user clicks 'materialize now' or something to that effect), or as a child workflow
@@ -188,18 +192,22 @@ class MaterializeViewWorkflow(PostHogWorkflow):
managed_warehouse_job_id = None
managed_warehouse_only = inputs.managed_warehouse_only
- managed_warehouse_enabled = await temporalio.workflow.execute_activity(
- check_managed_warehouse_shadow_eligibility_activity,
- ManagedWarehouseShadowEligibilityInputs(
- team_id=inputs.team_id,
- dag_id=inputs.dag_id,
- node_id=inputs.node_id,
- ),
- start_to_close_timeout=dt.timedelta(minutes=5),
- retry_policy=temporalio.common.RetryPolicy(
- maximum_attempts=3,
- ),
- )
+ # Histories recorded without the patch marker replay the in-workflow shadow below.
+ if not managed_warehouse_only and temporalio.workflow.patched(CLICKHOUSE_RUN_WITHOUT_TRINO_SHADOW_PATCH):
+ managed_warehouse_enabled = False
+ else:
+ managed_warehouse_enabled = await temporalio.workflow.execute_activity(
+ check_managed_warehouse_shadow_eligibility_activity,
+ ManagedWarehouseShadowEligibilityInputs(
+ team_id=inputs.team_id,
+ dag_id=inputs.dag_id,
+ node_id=inputs.node_id,
+ ),
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ retry_policy=temporalio.common.RetryPolicy(
+ maximum_attempts=3,
+ ),
+ )
use_trino = managed_warehouse_enabled
trino_materialized: bool | None = False if use_trino else None
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.py
index 042cf89108d7..8ff55d22c950 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
@@ -19,6 +19,7 @@ from posthog.temporal.tests.data_modeling.test_execute_dag_workflow import (
_mock_workflow_should_block_on_quality,
_mock_workflow_should_fail,
_mock_workflow_should_self_audit,
+ stub_check_team_shadow_eligibility,
stub_notify_dag_materialization_failures,
stub_preempt_dag_run,
stub_record_skipped_data_modeling_jobs,
@@ -91,6 +92,7 @@ class TestPostMaterializationChecks:
workflows=workflows,
activities=[
stub_preempt_dag_run,
+ stub_check_team_shadow_eligibility,
stub_get_dag_structure,
stub_materialization_gate,
stub_record_skipped_data_modeling_jobs,
diff --git a/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py b/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py
index 50d82cb9c4d9..dfadaadceed7 100644
--- a/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py
+++ b/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py
@@ -12,15 +12,20 @@ from temporalio import (
activity as temporal_activity,
workflow as temporal_workflow,
)
+from temporalio.exceptions import WorkflowAlreadyStartedError
from temporalio.testing import WorkflowEnvironment
+from temporalio.workflow import ParentClosePolicy
+from posthog.dataclasses import frozen
from posthog.sync import database_sync_to_async
from posthog.temporal.data_modeling.activities import (
GetDAGStructureInputs,
NotifyDAGMaterializationFailuresInputs,
PreemptDAGRunInputs,
RecordSkippedDataModelingJobsInputs,
+ check_team_managed_warehouse_shadow_eligibility_activity,
get_dag_structure_activity,
+ preempt_dag_run_activity,
)
from posthog.temporal.data_modeling.activities.get_dag_structure import DAG as DAGPlan
from posthog.temporal.data_modeling.workflows.execute_dag import (
@@ -46,10 +51,18 @@ from products.data_modeling.backend.facade.models import (
Node,
NodeType,
)
+from products.data_quality.backend.facade.contracts import MATERIALIZATION_GATE_ACTIVITY_NAME
pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]
+@frozen(slots=False)
+class ShadowRunOutcome:
+ result: ExecuteDAGResult
+ start_child: AsyncMock
+ execute_activity: AsyncMock
+
+
class TestGetDagStructureActivity:
@pytest_asyncio.fixture
async def saved_queries(self, ateam, auser):
@@ -463,6 +476,11 @@ async def stub_preempt_dag_run(_: PreemptDAGRunInputs) -> None:
pass
+@temporal_activity.defn(name="check_team_managed_warehouse_shadow_eligibility_activity")
+async def stub_check_team_shadow_eligibility(_: int) -> bool:
+ return False
+
+
class TestExecuteDAGWorkflow:
async def test_handles_empty_dag(self, ateam):
"""Test that the workflow returns early with empty result when no executable nodes exist."""
@@ -478,6 +496,7 @@ class TestExecuteDAGWorkflow:
workflows=[ExecuteDAGWorkflow],
activities=[
stub_preempt_dag_run,
+ stub_check_team_shadow_eligibility,
stub_get_dag_structure,
stub_record_skipped_data_modeling_jobs,
stub_notify_dag_materialization_failures,
@@ -576,6 +595,7 @@ class TestExecuteDAGWorkflowWithMocks:
workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],
activities=[
stub_preempt_dag_run,
+ stub_check_team_shadow_eligibility,
stub_get_dag_structure,
stub_record_skipped_data_modeling_jobs,
stub_notify_dag_materialization_failures,
@@ -630,6 +650,7 @@ class TestExecuteDAGWorkflowWithMocks:
workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],
activities=[
stub_preempt_dag_run,
+ stub_check_team_shadow_eligibility,
stub_get_dag_structure,
stub_record_skipped_data_modeling_jobs,
stub_notify_dag_materialization_failures,
@@ -673,6 +694,7 @@ class TestExecuteDAGWorkflowWithMocks:
workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],
activities=[
stub_preempt_dag_run,
+ stub_check_team_shadow_eligibility,
stub_get_dag_structure,
stub_record_skipped_data_modeling_jobs,
stub_notify_dag_materialization_failures,
@@ -721,6 +743,7 @@ class TestExecuteDAGWorkflowWithMocks:
workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],
activities=[
stub_preempt_dag_run,
+ stub_check_team_shadow_eligibility,
stub_get_dag_structure,
stub_record_skipped_data_modeling_jobs,
stub_notify_dag_materialization_failures,
@@ -760,7 +783,12 @@ class TestExecuteDAGWorkflowWithMocks:
env.client,
task_queue="test-queue",
workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],
- activities=[stub_preempt_dag_run, stub_get_dag_structure, stub_notify_dag_materialization_failures],
+ activities=[
+ stub_preempt_dag_run,
+ stub_check_team_shadow_eligibility,
+ stub_get_dag_structure,
+ stub_notify_dag_materialization_failures,
+ ],
workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
):
result: ExecuteDAGResult = await env.client.execute_workflow(
@@ -801,6 +829,7 @@ class TestExecuteDAGWorkflowWithMocks:
workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],
activities=[
stub_preempt_dag_run,
+ stub_check_team_shadow_eligibility,
stub_get_dag_structure,
stub_record_skipped_data_modeling_jobs,
stub_notify_dag_materialization_failures,
@@ -846,7 +875,12 @@ class TestExecuteDAGWorkflowWithMocks:
env.client,
task_queue="test-queue",
workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],
- activities=[stub_preempt_dag_run, stub_get_dag_structure, stub_notify_dag_materialization_failures],
+ activities=[
+ stub_preempt_dag_run,
+ stub_check_team_shadow_eligibility,
+ stub_get_dag_structure,
+ stub_notify_dag_materialization_failures,
+ ],
workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
):
result: ExecuteDAGResult = await env.client.execute_workflow(
@@ -891,7 +925,12 @@ class TestExecuteDAGWorkflowWithMocks:
env.client,
task_queue="test-queue",
workflows=[ExecuteDAGWorkflow, MockMaterializeViewWorkflow],
- activities=[stub_preempt_dag_run, stub_get_dag_structure, stub_notify_dag_materialization_failures],
+ activities=[
+ stub_preempt_dag_run,
+ stub_check_team_shadow_eligibility,
+ stub_get_dag_structure,
+ stub_notify_dag_materialization_failures,
+ ],
workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
):
result: ExecuteDAGResult = await env.client.execute_workflow(
@@ -959,6 +998,7 @@ class TestTrinoDependencyOutcomes:
patch.object(temporal_workflow, "info", return_value=info),
patch.object(temporal_workflow, "metric_meter", return_value=MagicMock()),
patch.object(temporal_workflow, "logger"),
+ patch.object(temporal_workflow, "patched", return_value=False),
):
result = await ExecuteDAGWorkflow().run(ExecuteDAGInputs(team_id=7, dag_id="dag"))
@@ -976,3 +1016,188 @@ class TestTrinoDependencyOutcomes:
assert [n.node_id for n in skips[0].skipped_nodes] == ["b", "c"]
else:
assert not skips
+
+
+class TestTrinoShadowRun:
+ async def _run(
+ self,
+ inputs: ExecuteDAGInputs,
+ *,
+ workflow_id: str = "execute-dag-dag:3600-2026-01-01T00:00:00Z",
+ eligible: bool = True,
+ shadow_start_error: Exception | None = None,
+ failing_node_ids: frozenset[str] = frozenset(),
+ patched: bool = True,
+ ) -> ShadowRunOutcome:
+ plan = DAGPlan(nodes=["a", "b"], executable_nodes=["a", "b"], edges=[])
+
+ async def start_child(workflow: object, child_inputs: object, **kwargs: object) -> object:
+ if isinstance(child_inputs, ExecuteDAGInputs):
+ if shadow_start_error is not None:
+ raise shadow_start_error
+ return MagicMock()
+ assert isinstance(child_inputs, MaterializeViewWorkflowInputs)
+ future = asyncio.get_running_loop().create_future()
+ if child_inputs.node_id in failing_node_ids:
+ future.set_exception(RuntimeError(f"{child_inputs.node_id} failed"))
+ else:
+ future.set_result(
+ MaterializeViewWorkflowResult(
+ job_id=f"job-{child_inputs.node_id}",
+ node_id=child_inputs.node_id,
+ rows_materialized=10,
+ duration_seconds=1,
+ )
+ )
+ return future
+
+ async def execute_activity(fn: object, *args: object, **kwargs: object) -> object:
+ if fn == get_dag_structure_activity:
+ return plan
+ if fn == check_team_managed_warehouse_shadow_eligibility_activity:
+ return eligible
+ return None
+
+ info = MagicMock()
+ info.workflow_id = workflow_id
+ start_child_mock = AsyncMock(side_effect=start_child)
+ execute_activity_mock = AsyncMock(side_effect=execute_activity)
+ with (
+ patch.object(temporal_workflow, "execute_activity", new=execute_activity_mock),
+ patch.object(temporal_workflow, "start_child_workflow", new=start_child_mock),
+ patch.object(temporal_workflow, "now", return_value=dt.datetime(2026, 1, 1, tzinfo=dt.UTC)),
+ patch.object(temporal_workflow, "info", return_value=info),
+ patch.object(temporal_workflow, "metric_meter", return_value=MagicMock()),
+ patch.object(temporal_workflow, "logger"),
+ patch.object(temporal_workflow, "patched", return_value=patched),
+ patch("posthog.temporal.data_modeling.workflows.execute_dag.capture_exception"),
+ ):
+ result = await ExecuteDAGWorkflow().run(inputs)
+ return ShadowRunOutcome(result=result, start_child=start_child_mock, execute_activity=execute_activity_mock)
+
+ @staticmethod
+ def _shadow_starts(start_child: AsyncMock) -> list:
+ return [call for call in start_child.await_args_list if isinstance(call.args[1], ExecuteDAGInputs)]
+
+ @staticmethod
+ def _activity_names(execute_activity: AsyncMock) -> list[str]:
+ return [getattr(call.args[0], "__name__", call.args[0]) for call in execute_activity.await_args_list]
+
+ @pytest.mark.parametrize(
+ "workflow_id,expected_shadow_id",
+ [
+ pytest.param("execute-dag-dag:3600-2026-01-01T00:00:00Z", "execute-dag-trino-dag:3600", id="tier"),
+ pytest.param(
+ "execute-dag-dag:604800:180-2026-01-01T00:00:00Z",
+ "execute-dag-trino-dag:604800:180",
+ id="anchored_tier",
+ ),
+ pytest.param("execute-dag-0b0e2b8e-5c4f-4d47-9a51-3f4f0c1d2e3a", "execute-dag-trino-dag", id="ad_hoc"),
+ ],
+ )
+ async def test_a_clickhouse_run_starts_one_abandoned_trino_shadow_of_its_nodes(
+ self, workflow_id: str, expected_shadow_id: str
+ ) -> None:
+ outcome = await self._run(
+ ExecuteDAGInputs(team_id=7, dag_id="dag", node_ids=["a", "b"]), workflow_id=workflow_id
+ )
+
+ [shadow] = self._shadow_starts(outcome.start_child)
+ assert shadow.args[1] == ExecuteDAGInputs(
+ team_id=7, dag_id="dag", node_ids=["a", "b"], managed_warehouse_only=True, shadow=True
+ )
+ assert shadow.kwargs["id"] == expected_shadow_id
+ assert shadow.kwargs["parent_close_policy"] == ParentClosePolicy.ABANDON
+ assert shadow.kwargs["execution_timeout"] == dt.timedelta(hours=12)
+ assert outcome.result.successful_nodes == 2
+
+ @pytest.mark.parametrize(
+ "managed_warehouse_only,expected_engine",
+ [(False, "clickhouse"), (True, "managed_warehouse")],
+ )
+ async def test_dag_metrics_carry_the_runs_engine(self, managed_warehouse_only: bool, expected_engine: str) -> None:
+ # Production alerts on DAG failure ratio and duration exclude shadow runs by this label.
+ module = "posthog.temporal.data_modeling.workflows.execute_dag"
+ with (
+ patch(f"{module}.get_dag_finished_metric") as finished,
+ patch(f"{module}.get_dag_duration_metric") as duration,
+ patch(f"{module}.get_dag_node_count_metric") as node_count,
+ ):
+ await self._run(
+ ExecuteDAGInputs(team_id=7, dag_id="dag", managed_warehouse_only=managed_warehouse_only, shadow=True)
+ )
+
+ assert finished.call_args.args[1] == expected_engine
+ assert duration.call_args.args[0] == expected_engine
+ assert {call.args[1] for call in node_count.call_args_list} == {expected_engine}
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ pytest.param(
+ WorkflowAlreadyStartedError("execute-dag-trino-dag:3600", "data-modeling-execute-dag"),
+ id="previous_shadow_still_running",
+ ),
+ pytest.param(RuntimeError("task queue is gone"), id="start_failed"),
+ ],
+ )
+ async def test_a_shadow_that_cannot_start_does_not_fail_the_clickhouse_run(self, error: Exception) -> None:
+ outcome = await self._run(ExecuteDAGInputs(team_id=7, dag_id="dag"), shadow_start_error=error)
+
+ assert outcome.result.successful_nodes == 2
+ assert outcome.result.failed_nodes == 0
+
+ @pytest.mark.parametrize(
+ "inputs,eligible,patched",
+ [
+ pytest.param(ExecuteDAGInputs(team_id=7, dag_id="dag"), False, True, id="ineligible_org"),
+ pytest.param(
+ ExecuteDAGInputs(team_id=7, dag_id="dag", managed_warehouse_only=True),
+ True,
+ True,
+ id="managed_warehouse_only_run",
+ ),
+ pytest.param(
+ ExecuteDAGInputs(team_id=7, dag_id="dag", managed_warehouse_only=True, shadow=True),
+ True,
+ True,
+ id="shadow_run",
+ ),
+ pytest.param(ExecuteDAGInputs(team_id=7, dag_id="dag"), True, False, id="history_before_the_patch"),
+ ],
+ )
+ async def test_no_trino_shadow_starts(self, inputs: ExecuteDAGInputs, eligible: bool, patched: bool) -> None:
+ outcome = await self._run(inputs, eligible=eligible, patched=patched)
+
+ assert self._shadow_starts(outcome.start_child) == []
+ assert outcome.result.successful_nodes == 2
+
+ @pytest.mark.parametrize("shadow", [True, False])
+ async def test_a_shadow_run_neither_checks_quality_nor_notifies_failures(self, shadow: bool) -> None:
+ outcome = await self._run(
+ ExecuteDAGInputs(team_id=7, dag_id="dag", managed_warehouse_only=True, shadow=shadow),
+ failing_node_ids=frozenset({"b"}),
+ )
+
+ started = self._activity_names(outcome.execute_activity)
+ assert outcome.result.failed_nodes == 1
+ assert (MATERIALIZATION_GATE_ACTIVITY_NAME in started) is not shadow
+ assert ("notify_dag_materialization_failures_activity" in started) is not shadow
+
+ @pytest.mark.parametrize(
+ "managed_warehouse_only,engine",
+ [(False, DataModelingJobEngine.CLICKHOUSE), (True, DataModelingJobEngine.MANAGED_WAREHOUSE)],
+ )
+ async def test_preemption_is_scoped_to_the_runs_engine(
+ self, managed_warehouse_only: bool, engine: DataModelingJobEngine
+ ) -> None:
+ outcome = await self._run(
+ ExecuteDAGInputs(team_id=7, dag_id="dag", managed_warehouse_only=managed_warehouse_only), eligible=False
+ )
+
+ preempt_inputs = next(
+ call.args[1]
+ for call in outcome.execute_activity.await_args_list
+ if call.args[0] == preempt_dag_run_activity
+ )
+ assert preempt_inputs.engine == engine.value
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
index 550bafe77cd3..df250b7801df 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
@@ -11,7 +11,6 @@ from temporalio.exceptions import CancelledError, ChildWorkflowError, WorkflowAl
from posthog.temporal.data_modeling.activities import (
FailMaterializationInputs,
- ManagedWarehouseShadowEligibilityInputs,
ManagedWarehouseShadowResult,
MaterializeViewResult,
PrepareQueryableTableResult,
@@ -61,8 +60,10 @@ class TestQualityGateBranching:
shadow_handle: AsyncMock | None = None,
start_child: AsyncMock | None = None,
inputs: MaterializeViewWorkflowInputs | None = None,
+ execute_activity: AsyncMock | None = None,
+ patched: bool = True,
) -> tuple:
- execute_activity = AsyncMock(side_effect=activity_results)
+ execute_activity = execute_activity or AsyncMock(side_effect=activity_results)
child = (
AsyncMock(side_effect=child_result)
if isinstance(child_result, Exception)
@@ -79,6 +80,7 @@ class TestQualityGateBranching:
stack.enter_context(patch.object(temporalio.workflow, "info", return_value=info))
stack.enter_context(patch.object(temporalio.workflow, "now", return_value=dt.datetime(2026, 8, 1)))
stack.enter_context(patch.object(temporalio.workflow, "logger"))
+ stack.enter_context(patch.object(temporalio.workflow, "patched", return_value=patched))
stack.enter_context(patch(f"{WORKFLOW_MODULE}.capture_exception"))
if shadow_handle is not None:
stack.enter_context(patch.object(temporalio.workflow, "start_activity", return_value=shadow_handle))
@@ -101,7 +103,7 @@ class TestQualityGateBranching:
return result, execute_activity
@pytest.mark.parametrize("shadow_error,blocked", [(None, False), ("Upstream write failed", False), (None, True)])
- async def test_shadow_outcome_is_independent_of_clickhouse_success(
+ async def test_a_history_without_the_patch_replays_the_in_workflow_shadow(
self, shadow_error: str | None, blocked: bool
) -> None:
shadow = asyncio.get_running_loop().create_future()
@@ -126,7 +128,9 @@ class TestQualityGateBranching:
if blocked:
activity_results.pop(1)
with patch.object(temporalio.workflow, "start_activity", return_value=shadow) as start_shadow:
- result, _ = await self._run(activity_results, {}, inputs=dataclasses.replace(_inputs(), skip_trino=blocked))
+ result, _ = await self._run(
+ activity_results, {}, inputs=dataclasses.replace(_inputs(), skip_trino=blocked), patched=False
+ )
assert start_shadow.called is not blocked
assert result.job_id == "job-1"
assert result.rows_materialized == 10
@@ -157,9 +161,35 @@ class TestQualityGateBranching:
assert result.trino_materialized is True
assert result.job_id == "shadow-job"
+ async def test_a_clickhouse_run_does_not_wait_for_a_slow_trino_shadow(self) -> None:
+ results = {
+ "check_managed_warehouse_shadow_eligibility_activity": True,
+ "create_data_modeling_job_activity": "job-1",
+ "materialize_view_activity": _materialize_result("skip"),
+ "prepare_queryable_table_activity": PrepareQueryableTableResult(
+ storage_delta_mib=None, total_storage_mib=None
+ ),
+ }
+ never_finishes = asyncio.get_running_loop().create_future()
+
+ async def execute_activity(activity, *args, **kwargs):
+ return results.get(activity.__name__)
+
+ with patch.object(temporalio.workflow, "start_activity", return_value=never_finishes) as start_shadow:
+ result, executed = await asyncio.wait_for(
+ self._run([], {}, execute_activity=AsyncMock(side_effect=execute_activity)), timeout=5
+ )
+
+ assert result.job_id == "job-1"
+ assert result.rows_materialized == 10
+ assert result.trino_materialized is None
+ start_shadow.assert_not_called()
+ started = [call.args[0].__name__ for call in executed.await_args_list]
+ assert started.count("create_data_modeling_job_activity") == 1
+ assert "check_managed_warehouse_shadow_eligibility_activity" not in started
+
async def test_blocking_failures_stop_the_publish(self):
activity_results = [
- False, # managed warehouse shadow check
"job-1", # create job
_materialize_result("gate"),
StageQueryableFilesResult(staged_folder_path="staged_1"),
@@ -178,15 +208,6 @@ class TestQualityGateBranching:
assert "succeed_materialization_activity" not in started
block_inputs = execute_activity.await_args_list[-1].args[1]
assert block_inputs.suite_run_id == "suite-1"
- assert execute_activity.await_args_list[0].args[1] == ManagedWarehouseShadowEligibilityInputs(
- team_id=7,
- dag_id="dag-1",
- node_id="node-1",
- )
- assert (
- execute_activity.await_args_list[0].args[0].__name__
- == "check_managed_warehouse_shadow_eligibility_activity"
- )
async def test_account_staging_starts_an_isolated_child_workflow(self):
materialize_result = dataclasses.replace(
@@ -195,7 +216,6 @@ class TestQualityGateBranching:
delta_version=5,
)
activity_results = [
- False,
"job-1",
materialize_result,
PrepareQueryableTableResult(storage_delta_mib=None, total_storage_mib=None),
@@ -216,7 +236,6 @@ class TestQualityGateBranching:
async def test_a_passing_audit_publishes_and_succeeds(self):
activity_results = [
- False,
"job-1",
_materialize_result("gate"),
StageQueryableFilesResult(staged_folder_path="staged_1"),
@@ -235,7 +254,6 @@ class TestQualityGateBranching:
# Returning zero here would publish and also claim the node was audited, so the DAG's
# fallback sweep would skip the one node whose checks never ran.
activity_results = [
- False,
"job-1",
_materialize_result("gate"),
StageQueryableFilesResult(staged_folder_path="staged_1"),
@@ -262,7 +280,6 @@ class TestQualityGateBranching:
self, start_child, expected_audited
) -> None:
activity_results = [
- False,
"job-1",
_materialize_result("warn"),
PrepareQueryableTableResult(storage_delta_mib=None, total_storage_mib=None), # prepare
@@ -274,9 +291,9 @@ class TestQualityGateBranching:
assert result.quality_audited is expected_audited
assert result.quality_blocking_failures is None
- async def test_a_blocked_publish_still_settles_the_managed_warehouse_shadow(self):
- # The blocked branch returns early. Leaving the shadow activity unawaited holds the parent
- # DAG's concurrency slot and orphans the shadow job.
+ async def test_a_replayed_blocked_publish_still_settles_the_managed_warehouse_shadow(self):
+ # In a history recorded before the patch, the blocked branch returns early. Leaving the
+ # shadow activity unawaited there orphans the shadow job.
shadow_handle = AsyncMock()
shadow_handle.__await__ = lambda self=None: iter([])
activity_results = [
@@ -292,7 +309,7 @@ class TestQualityGateBranching:
patch.object(MaterializeViewWorkflow, "_collect_shadow_comparison", new=AsyncMock()) as collect,
patch.object(temporalio.workflow, "start_activity", return_value=shadow_handle) as start_shadow,
):
- result, execute_activity = await self._run(activity_results, {"checks_failed_blocking": 1})
+ result, execute_activity = await self._run(activity_results, {"checks_failed_blocking": 1}, patched=False)
assert result.quality_blocking_failures == 1
assert execute_activity.await_args_list[1].args[1].engine == DataModelingJobEngine.MANAGED_WAREHOUSE
@@ -580,7 +597,6 @@ class TestCDPProducerHandoff(TestQualityGateBranching):
async def test_the_producer_starts_after_a_successful_publish(self):
start_child = AsyncMock()
activity_results = [
- False,
"job-1",
self._result(should_trigger=True),
PrepareQueryableTableResult(storage_delta_mib=None, total_storage_mib=None),
@@ -595,7 +611,6 @@ class TestCDPProducerHandoff(TestQualityGateBranching):
async def test_no_producer_starts_when_nothing_subscribes(self):
start_child = AsyncMock()
activity_results = [
- False,
"job-1",
self._result(should_trigger=False),
PrepareQueryableTableResult(storage_delta_mib=None, total_storage_mib=None),
@@ -612,7 +627,6 @@ class TestCDPProducerHandoff(TestQualityGateBranching):
# clear reaches them.
start_child = AsyncMock(side_effect=RuntimeError("task queue is gone"))
activity_results = [
- False,
"job-1",
self._result(should_trigger=True),
PrepareQueryableTableResult(storage_delta_mib=None, total_storage_mib=None),
@@ -630,7 +644,6 @@ class TestCDPProducerHandoff(TestQualityGateBranching):
# clear will ever reach them.
start_child = AsyncMock()
activity_results = [
- False,
"job-1",
self._result(should_trigger=True, quality_audit="gate"),
StageQueryableFilesResult(staged_folder_path="staged_1"),
diff --git a/posthog/temporal/tests/data_modeling/test_preempt_dag_run.py b/posthog/temporal/tests/data_modeling/test_preempt_dag_run.py
index e16c8cbe2f8c..66c7374f05ec 100644
--- a/posthog/temporal/tests/data_modeling/test_preempt_dag_run.py
+++ b/posthog/temporal/tests/data_modeling/test_preempt_dag_run.py
@@ -16,7 +16,7 @@ from posthog.temporal.data_modeling.activities.preempt_dag_run import (
preempt_dag_run_activity,
)
-from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobStatus
+from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobEngine, DataModelingJobStatus
pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]
@@ -67,6 +67,7 @@ async def _run_activity(
team_id: int,
node_ids: list[str] | None,
workflow_status: dict[str, WorkflowExecutionStatus | Exception] | None = None,
+ engine: DataModelingJobEngine | None = None,
) -> list[str]:
"""Run the activity against a stubbed Temporal client, returning the workflows it cancelled.
@@ -103,11 +104,46 @@ async def _run_activity(
):
await ActivityEnvironment().run(
preempt_dag_run_activity,
- PreemptDAGRunInputs(team_id=team_id, dag_id=DAG_ID, node_ids=node_ids),
+ PreemptDAGRunInputs(
+ team_id=team_id,
+ dag_id=DAG_ID,
+ node_ids=node_ids,
+ **({"engine": engine} if engine is not None else {}),
+ ),
)
return cancelled
+ "preempting_engine,spared_engine",
+ [
+ (DataModelingJobEngine.MANAGED_WAREHOUSE, DataModelingJobEngine.CLICKHOUSE),
+ (DataModelingJobEngine.CLICKHOUSE, DataModelingJobEngine.MANAGED_WAREHOUSE),
+ ],
+)
+async def test_preempt_only_cancels_the_runs_own_engine(
+ preempting_engine: DataModelingJobEngine, spared_engine: DataModelingJobEngine, ateam
+) -> None:
+ jobs = {
+ engine: await database_sync_to_async(DataModelingJob.objects.create)(
+ team=ateam,
+ status=DataModelingJobStatus.RUNNING,
+ engine=engine,
+ workflow_id=f"materialize-view-{DAG_ID}-{NODE_HOURLY}-{engine}-2026-07-24T13:00:00",
+ parent_workflow_id=PARENT_HOURLY,
+ )
+ for engine in (DataModelingJobEngine.CLICKHOUSE, DataModelingJobEngine.MANAGED_WAREHOUSE)
+ }
+
+ cancelled = await _run_activity(ateam.pk, [NODE_HOURLY], engine=preempting_engine)
+
+ for job in jobs.values():
+ await database_sync_to_async(job.refresh_from_db)()
+ assert cancelled == [jobs[preempting_engine].workflow_id]
+ assert jobs[preempting_engine].status == DataModelingJobStatus.FAILED
+ assert jobs[spared_engine].status == DataModelingJobStatus.RUNNING
+
+
@pytest.mark.parametrize(
"node_ids,expected_preempted",
[
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 04a6874b199e..7371f549b82d 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -67,7 +67,6 @@
1 posthog/temporal/data_modeling/activities/enrich_view_semantics.py
1 posthog/temporal/data_modeling/activities/fail_materialization.py
1 posthog/temporal/data_modeling/activities/materialize_view.py
-1 posthog/temporal/data_modeling/activities/preempt_dag_run.py
1 posthog/temporal/exports/workflows.py
1 posthog/temporal/ingestion_acceptance_test/test_cases_discovery.py
1 posthog/temporal/mcp_analytics/intent_clustering/coordinator.py