: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): stop job starts queuing on the dag edge lock (#108918)
posthog[bot]af8805cc13b7
diff --git a/posthog/temporal/data_modeling/activities/create_data_modeling_job.py b/posthog/temporal/data_modeling/activities/create_data_modeling_job.pyindex 0ee084ca2b88..30a07157c9ce 100644--- a/posthog/temporal/data_modeling/activities/create_data_modeling_job.py+++ b/posthog/temporal/data_modeling/activities/create_data_modeling_job.py@@ -10,7 +10,7 @@ from temporalio import activityfrom posthog.sync import database_sync_to_async_poolfrom posthog.temporal.data_modeling.activities.utils import bind_data_modeling_log_context-from products.data_modeling.backend.facade.api import lock_dag+from products.data_modeling.backend.facade.api import lock_dag_placements_sharedfrom products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobEngine, NodeLOGGER = get_logger(__name__)@@ -60,13 +60,14 @@ def _create_data_modeling_job(inputs: CreateDataModelingJobInputs, workflow_id: str, workflow_run_id: str) -> CreatedDataModelingJob:with transaction.atomic():- # A move to another DAG refuses while a job of this query is Running, and holds this lock- # across that check. Taking it here, around the placement read and the insert both, is- # what stops a job from being created against a placement the move has already left. The- # rest of this materialization loads the node by team, node and DAG, so such a job would- # find nothing, and that includes the activity which records the failure, so the job row- # would stay Running with nothing left to close it.- lock_dag(inputs.team_id, uuid.UUID(inputs.dag_id))+ # A move to another DAG refuses while a job of this query is Running, and holds this DAG's+ # placement lock across that check. Taking it here, around the placement read and the+ # insert both, is what stops a job from being created against a placement the move has+ # already left. The rest of this materialization loads the node by team, node and DAG, so+ # such a job would find nothing, and that includes the activity which records the failure,+ # so the job row would stay Running with nothing left to close it. The lock is shared, so+ # job starts in one DAG do not queue behind each other.+ lock_dag_placements_shared(inputs.team_id, uuid.UUID(inputs.dag_id))node = Node.objects.prefetch_related("saved_query").get(id=inputs.node_id, team_id=inputs.team_id, dag_id=inputs.dag_id)diff --git a/posthog/temporal/tests/data_modeling/test_create_data_modeling_job_concurrency.py b/posthog/temporal/tests/data_modeling/test_create_data_modeling_job_concurrency.pyindex 590ab708698a..a9f4ace06ff3 100644--- a/posthog/temporal/tests/data_modeling/test_create_data_modeling_job_concurrency.py+++ b/posthog/temporal/tests/data_modeling/test_create_data_modeling_job_concurrency.py@@ -1,11 +1,12 @@import time+import asyncioimport threadingfrom typing import Anyimport pytestimport unittest.mock-from django.db import connection+from django.db import connection, transactionfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.data_modeling.activities.create_data_modeling_job import (@@ -13,7 +14,7 @@ from posthog.temporal.data_modeling.activities.create_data_modeling_job import (_create_data_modeling_job,)-from products.data_modeling.backend.facade.api import NodeMoveError, move_saved_query_to_dag+from products.data_modeling.backend.facade.api import NodeMoveError, lock_dag, move_saved_query_to_dagfrom products.data_modeling.backend.facade.models import DAG, DataModelingJob, DataModelingJobStatus, Nodepytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]@@ -83,3 +84,32 @@ async def test_a_move_cannot_land_between_a_job_reading_a_placement_and_insertinassert node.dag_id == adag.idjob = await database_sync_to_async(DataModelingJob.objects.get)(id=created.job_id)assert job.status == DataModelingJobStatus.RUNNING+++async def test_a_job_start_does_not_wait_behind_a_dag_edge_writer(ateam, adag, anode):+ held = threading.Event()+ release = threading.Event()++ def hold_the_dag_edge_lock_on_another_connection() -> None:+ try:+ with transaction.atomic():+ lock_dag(ateam.pk, adag.id)+ held.set()+ release.wait(timeout=BLOCKED_DEADLINE_SECONDS)+ finally:+ connection.close()++ writer = threading.Thread(target=hold_the_dag_edge_lock_on_another_connection)+ writer.start()+ try:+ assert held.wait(timeout=BLOCKED_DEADLINE_SECONDS)+ inputs = CreateDataModelingJobInputs(team_id=ateam.pk, node_id=str(anode.id), dag_id=str(adag.id))+ created = await asyncio.wait_for(+ _create_data_modeling_job(inputs, "test-workflow-id", "test-run-id"), timeout=BLOCKED_DEADLINE_SECONDS / 3+ )+ finally:+ release.set()+ writer.join(timeout=BLOCKED_DEADLINE_SECONDS)++ job = await database_sync_to_async(DataModelingJob.objects.get)(id=created.job_id)+ assert job.status == DataModelingJobStatus.RUNNINGdiff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.pyindex a045134c35c3..29c7e5666f65 100644--- a/products/data_modeling/backend/facade/api.py+++ b/products/data_modeling/backend/facade/api.py@@ -22,6 +22,7 @@ _LAZY = {"blocked_lineage_node_id": "logic.saved_query_dag_sync","delete_node_from_dag": "logic.saved_query_dag_sync","lock_dag": "logic.saved_query_dag_sync",+ "lock_dag_placements_shared": "logic.saved_query_dag_sync","move_saved_query_to_dag": "logic.saved_query_dag_sync","describe_dependents": "logic.saved_query_dag_sync","promote_view_nodes_to_matview": "logic.saved_query_dag_sync",diff --git a/products/data_modeling/backend/logic/saved_query_dag_sync.py b/products/data_modeling/backend/logic/saved_query_dag_sync.pyindex 8f80584e2b02..9b035f291636 100644--- a/products/data_modeling/backend/logic/saved_query_dag_sync.py+++ b/products/data_modeling/backend/logic/saved_query_dag_sync.py@@ -204,14 +204,31 @@ def lock_dag(team_id: int, dag_id: UUID) -> None:The same key `Edge._detect_cycles` takes, so an edge write and a node delete cannot interleave.Callers holding more than one DAG take them in a fixed order, so two of them cannot deadlock.-- Materialization takes it too, on the job-start side, so a job cannot be created against a- placement a move has already left behind."""with connection.cursor() as cursor:cursor.execute("SELECT pg_advisory_xact_lock(%s, hashtext(%s))", [team_id, str(dag_id)])+def _placement_lock_key(dag_id: UUID) -> str:+ return f"placement:{dag_id}"+++def lock_dag_placements(team_id: int, dag_id: UUID) -> None:+ """Hold off every job start in this DAG, so a job cannot be created against a placement a+ move has already left behind.++ A separate key from `lock_dag`, so a job start does not queue behind edge writes and syncs.+ """+ with connection.cursor() as cursor:+ cursor.execute("SELECT pg_advisory_xact_lock(%s, hashtext(%s))", [team_id, _placement_lock_key(dag_id)])+++def lock_dag_placements_shared(team_id: int, dag_id: UUID) -> None:+ """Taken by each job start. Job starts do not block each other, only a move out of this DAG."""+ with connection.cursor() as cursor:+ cursor.execute("SELECT pg_advisory_xact_lock_shared(%s, hashtext(%s))", [team_id, _placement_lock_key(dag_id)])++def replace_incoming_edges(target: Node,dependency_names: Iterable[str],@@ -551,7 +568,7 @@ def move_saved_query_to_dag(team_id: int, saved_query_id: UUID, dag_id: UUID) ->A move is refused while a materialization runs. Its activities load the node by team, nodeand DAG, so the move makes the remaining ones stop finding it -- including the activity thatrecords the failure, which leaves the job row Running with nothing to close it. Job creation- takes the same DAG lock and re-reads the node in its DAG, so a job that starts between the+ takes the DAG's placement lock and re-reads the node in its DAG, so a job that starts between thecheck and the move cannot slip past.The saved-query row lock is held too, because a query edit picks the DAG to sync into from its@@ -560,7 +577,7 @@ def move_saved_query_to_dag(team_id: int, saved_query_id: UUID, dag_id: UUID) ->That row lock is `FOR NO KEY UPDATE`, which is what makes it safe to hold alongside a DAGlock. `FOR UPDATE` conflicts with the `KEY SHARE` lock Postgres takes on this row for the- foreign key of every job and node insert, so a materialization holding the DAG lock and+ foreign key of every job and node insert, so a materialization holding the placement lock andinserting its job row would deadlock against this transaction waiting for that same DAG."""from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery@@ -574,6 +591,7 @@ def move_saved_query_to_dag(team_id: int, saved_query_id: UUID, dag_id: UUID) ->held = {dag.id} | {node.dag_id for node in placements if node.dag_id is not None}for held_dag_id in sorted(held, key=str):lock_dag(team_id, held_dag_id)+ lock_dag_placements(team_id, held_dag_id)nodes = list(placements.select_related("dag"))if len(nodes) > 1: