: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): let manual trino runs of different models run at once (#126466)
Jovan Sakovic4ba4b09d38a1
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.mdindex 94f470b1dacf..789b804a3046 100644--- a/docs/internal/hogql-trino-compiler.md+++ b/docs/internal/hogql-trino-compiler.md@@ -274,6 +274,8 @@ Shadow runs record their outcomes in managed warehouse job rows and metrics onlyPreemption is scoped to the run's engine, so the ClickHouse and Trino runs of a tier never cancel each other's jobs.A Trino run never cancels a running build, because cancelling a Trino build does not stop its SQL. It only reaps job rows whose workflow has ended.Each Trino build of a node has a fixed workflow id, so Temporal starts at most one build of that node at a time. A run that reaches a node another run is building skips it and its Trino dependents.+Each manual Trino run has its own workflow id, `execute-dag-trino-{dag_id}-manual-{uuid}`, so manual runs of different models can overlap.+Before it starts, a manual run checks the fixed build ids of its selected models, and it is refused with a 409 that names the models another run is building.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.diff --git a/posthog/temporal/data_modeling/workflows/execute_dag.py b/posthog/temporal/data_modeling/workflows/execute_dag.pyindex 9b95f3d9288b..ffc3581f0423 100644--- a/posthog/temporal/data_modeling/workflows/execute_dag.py+++ b/posthog/temporal/data_modeling/workflows/execute_dag.py@@ -1,4 +1,5 @@import json+import uuidimport asyncioimport datetime as dtimport dataclasses@@ -93,17 +94,14 @@ def trino_build_workflow_id(dag_id: str, node_id: str) -> str:def manual_trino_workflow_id(dag_id: str) -> str:- """The fixed id of a Trino run that a person starts by hand.+ """A new id for a Trino run that a person starts by hand.- It shares the `execute-dag-trino-{dag_id}` prefix with the scheduled shadows, so one- visibility query finds every Trino run of the DAG.+ Each manual run gets its own id, so manual runs of different models can overlap. The fixed+ build id of each node keeps two runs from building one model at once. The id shares the+ `execute-dag-trino-{dag_id}` prefix with the scheduled shadows, so one visibility query+ finds every Trino run of the DAG."""- return f"execute-dag-trino-{dag_id}-manual"---def trino_runs_of_dag_query(dag_id: str) -> str:- prefix = f"execute-dag-trino-{dag_id}"- return f'WorkflowId >= "{prefix}" AND WorkflowId < "{prefix}~" AND ExecutionStatus = "Running"'+ return f"execute-dag-trino-{dag_id}-manual-{uuid.uuid4()}"async def _kill_switch_child_limit(team_id: int) -> int:diff --git a/products/data_modeling/backend/logic/node_materialization.py b/products/data_modeling/backend/logic/node_materialization.pyindex 2bfcd9349ef8..9ffa73768179 100644--- a/products/data_modeling/backend/logic/node_materialization.py+++ b/products/data_modeling/backend/logic/node_materialization.py@@ -7,8 +7,9 @@ from django.conf import settingsfrom django.db import transactionimport structlog+from temporalio.client import Client, WorkflowExecutionStatusfrom temporalio.common import RetryPolicy, WorkflowIDConflictPolicy, WorkflowIDReusePolicy-from temporalio.exceptions import WorkflowAlreadyStartedError+from temporalio.service import RPCErrorfrom posthog.hogql.database.database import Database@@ -22,7 +23,7 @@ from posthog.temporal.data_modeling.workflows.execute_dag import (TRINO_SHADOW_RUN_TIMEOUT,ExecuteDAGInputs,manual_trino_workflow_id,- trino_runs_of_dag_query,+ trino_build_workflow_id,)from posthog.temporal.data_modeling.workflows.materialize_view import MaterializeViewWorkflowInputs@@ -48,9 +49,9 @@ RELATED_RUN_EDIT_ACCESS_REFUSAL = "You need edit access to every view in this ruMANAGED_WAREHOUSE_UNAVAILABLE_REFUSAL = "This organization has no managed warehouse set up."# Long enough for the state changes that follow the start to commit before the workflow first reads them.MANUAL_TRINO_RUN_START_DELAY = timedelta(seconds=5)-TRINO_RUN_ALREADY_RUNNING_REFUSAL = (- "A managed warehouse run is already in progress for this project's models. Try again once it finishes."-)+MAX_NAMED_BUILDING_MODELS = 5+BUILDING_LOOKUP_CONCURRENCY = 20+BUILDING_LOOKUP_TIMEOUT = timedelta(seconds=5)def start_node_materialization(node: Node, *, resume: bool = True, triggered_by_id: int | None = None) -> None:@@ -175,6 +176,38 @@ def run_related_node_materializations(return sorted(node_ids)+async def _nodes_building_on_trino(temporal: Client, dag_id: str, node_ids: list[str]) -> list[str]:+ """The nodes whose fixed Trino build id has a running workflow.++ This check only gives a clear error before the run starts. The fixed build id is the lock, so a node+ whose build cannot be read counts as free, and the run skips that node if another run holds it.+ Lookups are bounded in number and time, so a large selection cannot flood Temporal or stall the request.+ """++ limit = asyncio.Semaphore(BUILDING_LOOKUP_CONCURRENCY)++ async def is_building(node_id: str) -> bool:+ try:+ async with limit:+ description = await temporal.get_workflow_handle(trino_build_workflow_id(dag_id, node_id)).describe(+ rpc_timeout=BUILDING_LOOKUP_TIMEOUT+ )+ except RPCError:+ return False+ return description.status == WorkflowExecutionStatus.RUNNING++ building = await asyncio.gather(*(is_building(node_id) for node_id in node_ids))+ return [node_id for node_id, is_busy in zip(node_ids, building) if is_busy]+++def _models_building_refusal(team_id: int, node_ids: list[str]) -> str:+ names = sorted(Node.objects.filter(team_id=team_id, id__in=node_ids).values_list("name", flat=True))+ named = ", ".join(names[:MAX_NAMED_BUILDING_MODELS])+ if len(names) > MAX_NAMED_BUILDING_MODELS:+ named += f" and {len(names) - MAX_NAMED_BUILDING_MODELS} more"+ return f"Another managed warehouse run is building {named}. Try again once it finishes."++def run_trino_node_materializations(team_id: int,node_id: UUID | str,@@ -187,11 +220,12 @@ def run_trino_node_materializations("""Build the node, and optionally its upstreams or downstreams, on the managed warehouse only.Runs the same managed_warehouse_only DAG run as the scheduled Trino shadow, so ClickHouse is not- touched. Refuses while any Trino run of the DAG is in progress, because two runs would write the- same Trino tables at once.+ touched. Refuses while another run builds one of the selected models on Trino. Runs of other+ models can overlap, because the fixed build id of each node already stops two runs from writing+ one Trino table at once.- `full_refresh` drops the node's Trino watermark, and only after every refusal, including losing the- race for the run slot, so a refused run does not turn the next scheduled shadow into a full rebuild.+ `full_refresh` drops the node's Trino watermark, and only after every refusal, so a refused run+ does not turn the next scheduled shadow into a full rebuild.The run starts a few seconds late, so the state changes commit before the workflow reads them."""node = _get_node(team_id, node_id)@@ -214,30 +248,22 @@ def run_trino_node_materializations(shadow=True,manually_triggered_by_id=user.pk,)- # The scheduled shadow guards overlap only per tier, by its fixed id, so ask Temporal about every tier.- running = asyncio.run(temporal.count_workflows(query=trino_runs_of_dag_query(dag_id)))- if running.count > 0:- raise MaterializationAlreadyRunningError(TRINO_RUN_ALREADY_RUNNING_REFUSAL)+ building = asyncio.run(_nodes_building_on_trino(temporal, dag_id, sorted(node_ids)))+ if building:+ raise MaterializationAlreadyRunningError(_models_building_refusal(node.team_id, building))- # Take the run slot before changing any state, so a run that loses the race for it changes nothing. The- # start is delayed so that the changes below commit before the workflow reads them.- try:- handle = asyncio.run(- temporal.start_workflow(- "data-modeling-execute-dag",- asdict(inputs),- # A fixed id makes Temporal refuse a second manual run that slipped past the count above.- id=manual_trino_workflow_id(dag_id),- task_queue=str(settings.DATA_MODELING_TASK_QUEUE),- id_conflict_policy=WorkflowIDConflictPolicy.FAIL,- id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,- execution_timeout=TRINO_SHADOW_RUN_TIMEOUT,- retry_policy=RetryPolicy(maximum_attempts=1),- start_delay=MANUAL_TRINO_RUN_START_DELAY,- )+ # The start is delayed so that the changes below commit before the workflow reads them.+ handle = asyncio.run(+ temporal.start_workflow(+ "data-modeling-execute-dag",+ asdict(inputs),+ id=manual_trino_workflow_id(dag_id),+ task_queue=str(settings.DATA_MODELING_TASK_QUEUE),+ execution_timeout=TRINO_SHADOW_RUN_TIMEOUT,+ retry_policy=RetryPolicy(maximum_attempts=1),+ start_delay=MANUAL_TRINO_RUN_START_DELAY,)- except WorkflowAlreadyStartedError:- raise MaterializationAlreadyRunningError(TRINO_RUN_ALREADY_RUNNING_REFUSAL)+ )try:with transaction.atomic():diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.pyindex a74a6264c432..45e72540691d 100644--- a/products/data_warehouse/backend/tests/api/test_saved_query.py+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py@@ -18,7 +18,8 @@ from parameterized import parameterizedfrom rest_framework.parsers import JSONParserfrom rest_framework.request import Requestfrom rest_framework.test import APIRequestFactory-from temporalio.exceptions import WorkflowAlreadyStartedError+from temporalio.client import WorkflowExecutionStatus+from temporalio.service import RPCError, RPCStatusCodefrom posthog.hogql.errors import ExposedHogQLError@@ -2943,6 +2944,24 @@ class TestSavedQueryRun(APIBaseTest):)return saved_query, dag, node+ def _trino_client(+ self, running_workflow_ids: frozenset[str] = frozenset(), describe_fails: bool = False+ ) -> AsyncMock:+ client = AsyncMock()++ def handle_for(workflow_id: str) -> mock.Mock:+ handle = mock.Mock()+ if describe_fails:+ handle.describe = AsyncMock(side_effect=RPCError("unavailable", RPCStatusCode.UNAVAILABLE, b""))+ elif workflow_id in running_workflow_ids:+ handle.describe = AsyncMock(return_value=mock.Mock(status=WorkflowExecutionStatus.RUNNING))+ else:+ handle.describe = AsyncMock(side_effect=RPCError("not found", RPCStatusCode.NOT_FOUND, b""))+ return handle++ client.get_workflow_handle = mock.Mock(side_effect=handle_for)+ return client+@patch("products.data_modeling.backend.logic.node_materialization.sync_connect")def test_run_materializes_node(self, mock_sync_connect):saved_query, _dag, node = self._make_saved_query_with_node("v2_view")@@ -3006,8 +3025,7 @@ class TestSavedQueryRun(APIBaseTest):mark_node_suspended(node, engine=DataModelingJobEngine.MANAGED_WAREHOUSE, reason="boom", job_id="job-1")node.save()mock_eligible.return_value = True- mock_client = AsyncMock()- mock_client.count_workflows.return_value = mock.Mock(count=0)+ mock_client = self._trino_client()mock_sync_connect.return_value = mock_clientbody: dict[str, Any] = {"engine": "trino"}if direction:@@ -3028,9 +3046,8 @@ class TestSavedQueryRun(APIBaseTest):self.assertTrue(inputs["managed_warehouse_only"])self.assertTrue(inputs["shadow"])self.assertEqual(inputs["manually_triggered_by_id"], self.user.pk)- self.assertEqual(call.kwargs["id"], f"execute-dag-trino-{dag.id}-manual")+ self.assertTrue(call.kwargs["id"].startswith(f"execute-dag-trino-{dag.id}-manual-"))self.assertGreater(call.kwargs["start_delay"], timedelta(0))- self.assertIn(f"execute-dag-trino-{dag.id}", mock_client.count_workflows.call_args.kwargs["query"])node.refresh_from_db()self.assertNotIn(DataModelingJobEngine.MANAGED_WAREHOUSE, suspension_state(node))@@ -3054,8 +3071,7 @@ class TestSavedQueryRun(APIBaseTest):def test_run_on_trino_checks_access_to_the_single_view(self, mock_sync_connect, mock_eligible):saved_query, _dag, _node = self._make_saved_query_with_node("restricted_view")mock_eligible.return_value = True- mock_client = AsyncMock()- mock_client.count_workflows.return_value = mock.Mock(count=0)+ mock_client = self._trino_client()mock_sync_connect.return_value = mock_clientwith patch(@@ -3070,20 +3086,15 @@ class TestSavedQueryRun(APIBaseTest):self.assertEqual(response.status_code, 403, response.content)mock_client.start_workflow.assert_not_called()- @parameterized.expand([("another_run_listed", 1, False), ("start_races_a_manual_run", 0, True)])@patch("products.data_modeling.backend.logic.node_materialization.is_managed_warehouse_shadow_enabled")@patch("products.data_modeling.backend.logic.node_materialization.sync_connect")- def test_run_on_trino_while_a_trino_run_is_in_progress_conflicts(- self, _name, running_count, start_conflicts, mock_sync_connect, mock_eligible- ):- saved_query, _dag, node = self._make_saved_query_with_node("busy_view")+ def test_run_on_trino_while_a_selected_model_is_building_conflicts(self, mock_sync_connect, mock_eligible):+ saved_query, dag, node = self._make_saved_query_with_node("busy_view")mark_node_suspended(node, engine=DataModelingJobEngine.MANAGED_WAREHOUSE, reason="boom", job_id="job-1")node.save()mock_eligible.return_value = True- mock_client = AsyncMock()- mock_client.count_workflows.return_value = mock.Mock(count=running_count)- if start_conflicts:- mock_client.start_workflow.side_effect = WorkflowAlreadyStartedError("id", "data-modeling-execute-dag")+ mock_client = self._trino_client(frozenset({f"materialize-view-{dag.id}-{node.id}-trino"}))+ mock_client.count_workflows.return_value = mock.Mock(count=1)mock_sync_connect.return_value = mock_clientresponse = self.client.post(@@ -3092,11 +3103,62 @@ class TestSavedQueryRun(APIBaseTest):)self.assertEqual(response.status_code, 409, response.content)- self.assertEqual(mock_client.start_workflow.call_count, 1 if start_conflicts else 0)- # A refused run must leave the model as it found it, even when the refusal came after the changes.+ self.assertIn("busy_view", response.json()["detail"])+ mock_client.start_workflow.assert_not_called()node.refresh_from_db()self.assertIn(DataModelingJobEngine.MANAGED_WAREHOUSE, suspension_state(node))+ @parameterized.expand([("unrelated_model_building", False), ("build_state_unreadable", True)])+ @patch("products.data_modeling.backend.logic.node_materialization.is_managed_warehouse_shadow_enabled")+ @patch("products.data_modeling.backend.logic.node_materialization.sync_connect")+ def test_run_on_trino_starts_unless_a_selected_model_is_building(+ self, _name, describe_fails, mock_sync_connect, mock_eligible+ ):+ saved_query, dag, node = self._make_saved_query_with_node("free_view")+ unrelated_saved_query = DataWarehouseSavedQuery.objects.create(+ name="unrelated_view", team=self.team, query={"query": "SELECT 1", "kind": "HogQLQuery"}+ )+ unrelated_node = Node.objects.create(+ team=self.team, dag=dag, saved_query=unrelated_saved_query, type=NodeType.VIEW+ )+ mock_eligible.return_value = True+ mock_client = self._trino_client(+ frozenset({f"materialize-view-{dag.id}-{unrelated_node.id}-trino"}), describe_fails=describe_fails+ )+ mock_client.count_workflows.return_value = mock.Mock(count=1)+ mock_sync_connect.return_value = mock_client++ response = self.client.post(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query.id}/run/", {"engine": "trino"}+ )++ self.assertEqual(response.status_code, 200, response.content)+ self.assertEqual(response.json()["node_ids"], [str(node.id)])+ mock_client.start_workflow.assert_called_once()++ @patch("products.data_modeling.backend.logic.node_materialization.is_managed_warehouse_shadow_enabled")+ @patch("products.data_modeling.backend.logic.node_materialization.sync_connect")+ def test_manual_trino_runs_of_different_models_both_start(self, mock_sync_connect, mock_eligible):+ first_saved_query, dag, _first_node = self._make_saved_query_with_node("first_view")+ second_saved_query = DataWarehouseSavedQuery.objects.create(+ name="second_view", team=self.team, query={"query": "SELECT 1", "kind": "HogQLQuery"}+ )+ Node.objects.create(team=self.team, dag=dag, saved_query=second_saved_query, type=NodeType.VIEW)+ mock_eligible.return_value = True+ mock_client = self._trino_client()+ mock_sync_connect.return_value = mock_client++ for saved_query in (first_saved_query, second_saved_query):+ response = self.client.post(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query.id}/run/", {"engine": "trino"}+ )+ self.assertEqual(response.status_code, 200, response.content)++ workflow_ids = [call.kwargs["id"] for call in mock_client.start_workflow.call_args_list]+ self.assertEqual(len(set(workflow_ids)), 2)+ for workflow_id in workflow_ids:+ self.assertTrue(workflow_id.startswith(f"execute-dag-trino-{dag.id}-manual-"))+@patch("products.data_modeling.backend.logic.node_materialization.sync_connect")def test_run_with_dependencies_requires_edit_access_to_every_view(self, mock_sync_connect):saved_query, dag, node = self._make_saved_query_with_node("readable_view")