: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-warehouse): cancel the workflow the running job recorded (#82559)
Jovan Sakovicb61844f8f673
diff --git a/products/data_warehouse/backend/presentation/views/saved_query.py b/products/data_warehouse/backend/presentation/views/saved_query.pyindex ca628f9f22f6..0ffc574e64f9 100644--- a/products/data_warehouse/backend/presentation/views/saved_query.py+++ b/products/data_warehouse/backend/presentation/views/saved_query.py@@ -1,4 +1,5 @@import uuid+from dataclasses import dataclassfrom datetime import datetime, timedeltafrom typing import Any, cast@@ -15,7 +16,6 @@ from rest_framework import exceptions, filters, request, response, serializers,from rest_framework.decorators import actionfrom rest_framework.pagination import PageNumberPaginationfrom rest_framework.response import Response-from temporalio.client import ScheduleActionExecutionStartWorkflowfrom posthog.schema import DataWarehouseManagedViewsetKind@@ -77,6 +77,13 @@ from products.warehouse_sources.backend.facade.models import (logger = structlog.get_logger(__name__)++@dataclass(frozen=True, kw_only=True)+class _CancelTarget:+ workflow_id: str+ workflow_run_id: str | None++# A DataWarehouseSavedQuery's activity log also records materialization syncs and status# transitions (activity="sync_triggered", status changes) that advance the log without the query# being edited. Optimistic-concurrency ("modified by someone else") must key off the latest activity@@ -1454,54 +1461,45 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe"""Cancel a running saved query workflow."""saved_query = self.get_object()- if saved_query.status != DataWarehouseSavedQuery.Status.RUNNING:+ targets = {+ _CancelTarget(workflow_id=job.workflow_id, workflow_run_id=job.workflow_run_id)+ for job in DataModelingJob.objects.filter(+ team_id=self.team_id,+ saved_query=saved_query,+ status=DataModelingJob.Status.RUNNING,+ )+ if job.workflow_id+ }++ if not targets:return response.Response({"error": "Cannot cancel a query that is not running"}, status=status.HTTP_400_BAD_REQUEST)temporal = sync_connect()- workflow_id = f"data-modeling-run-{saved_query.id.hex}"-- try:- # Ad-hoc handling- try:- workflow_handle = temporal.get_workflow_handle(workflow_id)- if workflow_handle:- async_to_sync(workflow_handle.cancel)()- except Exception:- logger.info("No ad-hoc workflow to cancel", workflow_id=workflow_id)+ failed = False- # Schedule handling+ for target in sorted(targets, key=lambda target: target.workflow_id):try:- scheduled_workflow_handle = temporal.get_schedule_handle(str(saved_query.id))- desc = async_to_sync(scheduled_workflow_handle.describe)()- recent_actions = desc.info.running_actions- if len(recent_actions) > 0:- most_recent_action = recent_actions[-1]- if isinstance(most_recent_action, ScheduleActionExecutionStartWorkflow):- workflow_id_to_cancel = most_recent_action.workflow_id- else:- logger.warning(- "Unexpected action type in schedule",- action_type=type(most_recent_action).__name__,- )-- workflow_handle_to_cancel = temporal.get_workflow_handle(workflow_id_to_cancel)- if workflow_handle_to_cancel:- async_to_sync(workflow_handle_to_cancel.cancel)()- except Exception:- logger.info("No scheduled workflow to cancel", saved_query_id=str(saved_query.id))+ workflow_handle = temporal.get_workflow_handle(target.workflow_id, run_id=target.workflow_run_id)+ async_to_sync(workflow_handle.cancel)()+ except Exception as e:+ failed = True+ logger.exception(+ "Failed to cancel workflow",+ saved_query_id=str(saved_query.id),+ workflow_id=target.workflow_id,+ error=str(e),+ )- # Update saved query status, but not the data modeling job which occurs in the workflow- # This is because the saved_query is used by our UI to prevent multiple cancellations- saved_query.status = DataWarehouseSavedQuery.Status.CANCELLED- saved_query.save()- except Exception as e:- logger.exception("Failed to cancel workflow", workflow_id=workflow_id, error=str(e))+ if failed:return response.Response(- {"error": f"Failed to cancel workflow"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR+ {"error": "Failed to cancel workflow"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)+ saved_query.status = DataWarehouseSavedQuery.Status.CANCELLED+ saved_query.save()+log_activity(organization_id=self.team.organization_id,team_id=self.team_id,diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.pyindex 662bac0427e8..006dc6239d37 100644--- a/products/data_warehouse/backend/tests/api/test_saved_query.py+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py@@ -2285,6 +2285,89 @@ class TestSavedQueryRunV2Aware(APIBaseTest):self.assertEqual(response.status_code, 200, response.content)mock_trigger.assert_called_once()+ @parameterized.expand(+ [+ ("v1", "019c4fca-ee53-0000-e7e4-fd76c23d5157-2026-08-13T04:30:00Z"),+ ("v2", "materialize-view-019e4ccb-8369-71dd-9270-9bf570948062-2026-08-13T04:30:00Z"),+ ]+ )+ @patch("products.data_warehouse.backend.presentation.views.saved_query.sync_connect")+ def test_cancel_cancels_the_workflow_recorded_on_the_running_job(+ self, _name: str, workflow_id: str, mock_sync_connect+ ):+ saved_query, _dag, _node = self._make_saved_query_with_node(f"cancel_view_{_name}")+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=saved_query,+ status=DataModelingJob.Status.RUNNING,+ workflow_id=workflow_id,+ workflow_run_id="run-id-1",+ )+ mock_client = mock.MagicMock()+ mock_handle = AsyncMock()+ mock_client.get_workflow_handle.return_value = mock_handle+ mock_sync_connect.return_value = mock_client++ response = self.client.post(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query.id}/cancel/",+ )++ self.assertEqual(response.status_code, 200, response.content)+ mock_client.get_workflow_handle.assert_called_once_with(workflow_id, run_id="run-id-1")+ mock_handle.cancel.assert_awaited_once()+ saved_query.refresh_from_db()+ self.assertEqual(saved_query.status, DataWarehouseSavedQuery.Status.CANCELLED)++ @patch("products.data_warehouse.backend.presentation.views.saved_query.sync_connect")+ def test_cancel_is_rejected_when_no_job_is_running(self, mock_sync_connect):+ saved_query, _dag, _node = self._make_saved_query_with_node("idle_view")+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=saved_query,+ status=DataModelingJob.Status.COMPLETED,+ workflow_id="materialize-view-already-done",+ )++ response = self.client.post(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query.id}/cancel/",+ )++ self.assertEqual(response.status_code, 400, response.content)+ mock_sync_connect.assert_not_called()++ @patch("products.data_warehouse.backend.presentation.views.saved_query.sync_connect")+ def test_cancel_attempts_every_running_workflow_when_one_fails(self, mock_sync_connect):+ saved_query, _dag, _node = self._make_saved_query_with_node("partial_cancel_view")+ for workflow_id in ("materialize-view-1-unreachable", "materialize-view-2-healthy"):+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=saved_query,+ status=DataModelingJob.Status.RUNNING,+ workflow_id=workflow_id,+ workflow_run_id="run-id-1",+ )++ healthy_handle = AsyncMock()++ def handle_for(workflow_id, run_id=None):+ if workflow_id == "materialize-view-1-unreachable":+ raise RuntimeError("temporal refused the handle")+ return healthy_handle++ mock_client = mock.MagicMock()+ mock_client.get_workflow_handle.side_effect = handle_for+ mock_sync_connect.return_value = mock_client++ response = self.client.post(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query.id}/cancel/",+ )++ self.assertEqual(response.status_code, 500, response.content)+ self.assertEqual(mock_client.get_workflow_handle.call_count, 2)+ healthy_handle.cancel.assert_awaited_once()+ saved_query.refresh_from_db()+ self.assertNotEqual(saved_query.status, DataWarehouseSavedQuery.Status.CANCELLED)+class TestSavedQueryDescription(APIBaseTest):def _base(self) -> str: