: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(warehouse): heartbeat and stop cancelled view translations (#102542)
Eric Duongc3d6f8e9299a
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.mdindex 612bcc8105dd..8d86a25dc61d 100644--- a/docs/internal/hogql-trino-compiler.md+++ b/docs/internal/hogql-trino-compiler.md@@ -172,6 +172,12 @@ Response organization strings are limited to 128 characters; non-string values lCompilation is best effort per view. Unsupported HogQL records a failed result and processing continues. A definition changed after the snapshot records a stale result. The workflow stores generated SQL and named values directly from activities so large SQL strings do not cross the Temporal workflow payload boundary. It never executes the SQL, creates Trino relations, or updates `DataWarehouseSavedQuery.query`.+Each team compilation activity has a one-hour start-to-close timeout, a two-minute heartbeat timeout, and at most two attempts.+A background thread sends heartbeats during synchronous compilation, including while one view takes longer than the heartbeat interval.+Cancellation propagates as an activity cancellation instead of a per-view compilation failure.+Activities check cancellation and the job's running state before each view and before recording compilation outcomes; result updates also require a running job and a pending result.+An interrupted view remains pending for an activity retry, which resumes from pending results.+The result admin can retry selected failed or stale rows. A retry creates a new selected-view job linked to the source job, preserving the original job and results as an immutable audit record.The data modeling shadow path uses these results as an eligibility gate. It requires a ready Trino target and a non-empty compiled result whose source hash matches the saved query's current definition.diff --git a/products/managed_warehouse/backend/temporal/view_translation_workflow.py b/products/managed_warehouse/backend/temporal/view_translation_workflow.pyindex 1be313548c01..3e8b65f55863 100644--- a/products/managed_warehouse/backend/temporal/view_translation_workflow.py+++ b/products/managed_warehouse/backend/temporal/view_translation_workflow.py@@ -8,13 +8,14 @@ from django.utils import timezonefrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy-from temporalio.exceptions import ApplicationError+from temporalio.exceptions import ApplicationError, CancelledErrorfrom posthog.schema import HogQLQueryfrom posthog.dataclasses import frozenfrom posthog.models import Teamfrom posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.common.heartbeat_sync import HeartbeaterSyncfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.managed_warehouse.backend.facade.client import compile_hogql_to_trino_sql@@ -133,16 +134,27 @@ def prepare_managed_warehouse_view_translation_activity(job_id: str) -> ViewTranreturn ViewTranslationPreparation(team_ids=team_ids)-def compile_managed_warehouse_team_views_activity(job_id: str, team_id: int) -> None:+def _check_translation_running(job_id: str) -> None:+ if (+ activity.is_cancelled()+ or not ManagedWarehouseViewTranslationJob.objects.filter(+ id=job_id, status=ManagedWarehouseViewTranslationJob.Status.RUNNING+ ).exists()+ ):+ raise CancelledError("View translation activity stopped")+++def _compile_team_views(job_id: str, team_id: int) -> None:+ _check_translation_running(job_id)job = ManagedWarehouseViewTranslationJob.objects.get(id=job_id)team = Team.objects.get(id=team_id, organization_id=job.organization_id)results = list(- ManagedWarehouseViewTranslationResult.all_teams.filter(+ ManagedWarehouseViewTranslationResult.objects.for_team(team_id)+ .filter(job=job,- team_id=team_id,status=ManagedWarehouseViewTranslationResult.Status.PENDING,- ).order_by("saved_query_id")+ )+ .order_by("saved_query_id"))saved_queries = DataWarehouseSavedQuery.objects.filter(id__in=[result.saved_query_id for result in results],@@ -152,10 +164,16 @@ def compile_managed_warehouse_team_views_activity(job_id: str, team_id: int) ->saved_queries_by_id = {saved_query.id: saved_query for saved_query in saved_queries}for result in results:+ _check_translation_running(job_id)activity.heartbeat(str(result.saved_query_id))+ result_row = ManagedWarehouseViewTranslationResult.objects.for_team(team_id).filter(+ id=result.id,+ status=ManagedWarehouseViewTranslationResult.Status.PENDING,+ job__status=ManagedWarehouseViewTranslationJob.Status.RUNNING,+ )saved_query = saved_queries_by_id.get(result.saved_query_id)if saved_query is None or source_query_hash(saved_query.query) != result.source_query_hash:- ManagedWarehouseViewTranslationResult.all_teams.filter(id=result.id).update(+ result_row.update(status=ManagedWarehouseViewTranslationResult.Status.STALE,error_type="SavedQueryChanged",error_message="The saved query changed or was removed after this translation job started",@@ -175,8 +193,11 @@ def compile_managed_warehouse_team_views_activity(job_id: str, team_id: int) ->include_hogql=True,expansion_mode=TrinoExpansionMode.DJANGO,)+ except CancelledError:+ raiseexcept Exception as error:- ManagedWarehouseViewTranslationResult.all_teams.filter(id=result.id).update(+ _check_translation_running(job_id)+ result_row.update(status=ManagedWarehouseViewTranslationResult.Status.FAILED,error_type=type(error).__name__[:255],error_message=str(error)[:4000],@@ -184,7 +205,8 @@ def compile_managed_warehouse_team_views_activity(job_id: str, team_id: int) ->)continue- ManagedWarehouseViewTranslationResult.all_teams.filter(id=result.id).update(+ _check_translation_running(job_id)+ result_row.update(status=ManagedWarehouseViewTranslationResult.Status.COMPILED,trino_sql=compiled.sql,trino_values=compiled.values,@@ -195,6 +217,12 @@ def compile_managed_warehouse_team_views_activity(job_id: str, team_id: int) ->)+def compile_managed_warehouse_team_views_activity(job_id: str, team_id: int) -> None:+ with HeartbeaterSync(details=(job_id, team_id)):+ _compile_team_views(job_id, team_id)++@activity.defndef finalize_managed_warehouse_view_translation_activity(job_id: str) -> None:job = ManagedWarehouseViewTranslationJob.objects.get(id=job_id)diff --git a/products/managed_warehouse/backend/tests/temporal/test_view_translation_workflow.py b/products/managed_warehouse/backend/tests/temporal/test_view_translation_workflow.pyindex 8c84ed03f9e6..18259516c509 100644--- a/products/managed_warehouse/backend/tests/temporal/test_view_translation_workflow.py+++ b/products/managed_warehouse/backend/tests/temporal/test_view_translation_workflow.py@@ -1,8 +1,13 @@+import datetime as dt+import threading+from dataclasses import replace+import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import AsyncMock, MagicMock, patch-from temporalio.exceptions import ApplicationError+from parameterized import parameterized+from temporalio.exceptions import ApplicationError, CancelledErrorfrom temporalio.testing import ActivityEnvironmentfrom posthog.schema import HogQLQuery@@ -217,9 +222,16 @@ class TestManagedWarehouseViewTranslationActivities(BaseTest):changed.query = {"kind": "HogQLQuery", "query": "SELECT edited"}changed.save(update_fields=["query"])+ self.activity_environment.info = replace(+ self.activity_environment.info, heartbeat_timeout=dt.timedelta(milliseconds=120)+ )+ heartbeat_received = threading.Event()+ self.activity_environment.on_heartbeat = lambda *_: heartbeat_received.set()compile_kwargs: list[dict[str, object]] = []def compile_query(_team_id: int, query: HogQLQuery, **kwargs: object) -> TrinoCompiledQuery:+ heartbeat_received.clear()+ assert heartbeat_received.wait(timeout=5), "No heartbeat while compilation was blocked"compile_kwargs.append(kwargs)if query.query == "SELECT bad":raise ValueError("unsupported expression")@@ -256,6 +268,55 @@ class TestManagedWarehouseViewTranslationActivities(BaseTest):assert job.status == ManagedWarehouseViewTranslationJob.Status.COMPLETED_WITH_ERRORSassert (job.compiled_count, job.failed_count, job.stale_count) == (1, 1, 1)+ @parameterized.expand(["cancel_error", "cancel_requested", "failed_job", "failed_job_with_error"])+ def test_compile_stops_without_recording_results_after_cancellation(self, stop_reason: str) -> None:+ job = ManagedWarehouseViewTranslationJob.objects.create(+ organization=self.organization,+ status=ManagedWarehouseViewTranslationJob.Status.RUNNING,+ )+ for index in range(2):+ saved_query = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name=f"view_{index}",+ query={"kind": "HogQLQuery", "query": "SELECT 1"},+ )+ ManagedWarehouseViewTranslationResult.objects.for_team(self.team.id).create(+ job=job,+ team_id=self.team.id,+ saved_query_id=saved_query.id,+ saved_query_name=saved_query.name,+ source_query_hash=source_query_hash(saved_query.query),+ )++ def compile_query(*args: object, **kwargs: object) -> TrinoCompiledQuery:+ if stop_reason == "cancel_error":+ raise CancelledError()+ if stop_reason == "cancel_requested":+ self.activity_environment.cancel()+ else:+ ManagedWarehouseViewTranslationJob.objects.filter(id=job.id).update(+ status=ManagedWarehouseViewTranslationJob.Status.FAILED+ )+ if stop_reason == "failed_job_with_error":+ raise ValueError("Compilation interrupted")+ return TrinoCompiledQuery(sql="SELECT 1", values={}, hogql="SELECT 1")++ with (+ patch(+ "products.managed_warehouse.backend.temporal.view_translation_workflow.compile_hogql_to_trino_sql",+ side_effect=compile_query,+ ) as compile_mock,+ pytest.raises(CancelledError),+ ):+ self.activity_environment.run(compile_managed_warehouse_team_views_activity, str(job.id), self.team.id)++ assert compile_mock.call_count == 1+ results = ManagedWarehouseViewTranslationResult.objects.for_team(self.team.id).filter(job=job)+ assert list(results.values_list("status", "trino_sql", "error_message", "processed_at")) == [+ (ManagedWarehouseViewTranslationResult.Status.PENDING, None, None, None),+ (ManagedWarehouseViewTranslationResult.Status.PENDING, None, None, None),+ ]+class TestManagedWarehouseViewTranslationStarter(BaseTest):def test_start_records_the_temporal_workflow(self) -> None: