: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
feat(data-modeling): gate shadow runs on Trino readiness (#93760)
Eric Duongf2c113c2eb38
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.mdindex b6a9dc59671d..1df2d1e77018 100644--- a/docs/internal/hogql-trino-compiler.md+++ b/docs/internal/hogql-trino-compiler.md@@ -79,6 +79,8 @@ Compilation is best effort per view. Unsupported HogQL records a failed result aThe 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.+## ValidationRun the Trino printer, semantic expansion, and parameter-helper tests. Run the existing printer/resolver and direct-adapter tests to check shared behavior, and the startup-import guards to check initialization. Do not regenerate existing dialect snapshots simply to make a regression pass.diff --git a/posthog/temporal/data_modeling/__init__.py b/posthog/temporal/data_modeling/__init__.pyindex 310a10763d6a..c39470807e22 100644--- a/posthog/temporal/data_modeling/__init__.py+++ b/posthog/temporal/data_modeling/__init__.py@@ -1,4 +1,5 @@from posthog.temporal.data_modeling.activities import (+ check_duckgres_shadow_eligibility_activity,check_duckgres_shadow_enabled_activity,clear_cdp_staging_activity,create_data_modeling_job_activity,@@ -30,6 +31,7 @@ WORKFLOWS = [MaterializeViewWorkflow, ExecuteDAGWorkflow]SEMANTIC_ENRICHMENT_WORKFLOWS = [EnrichViewSemanticsWorkflow]SEMANTIC_ENRICHMENT_ACTIVITIES = [enrich_view_semantics_activity]ACTIVITIES = [+ check_duckgres_shadow_eligibility_activity,check_duckgres_shadow_enabled_activity,clear_cdp_staging_activity,create_data_modeling_job_activity,diff --git a/posthog/temporal/data_modeling/activities/__init__.py b/posthog/temporal/data_modeling/activities/__init__.pyindex 4a2ca1ce92d0..14c895dafa14 100644--- a/posthog/temporal/data_modeling/activities/__init__.py+++ b/posthog/temporal/data_modeling/activities/__init__.py@@ -17,8 +17,10 @@ from .materialize_view import (materialize_view_activity,)from .materialize_view_duckgres import (+ DuckgresShadowEligibilityInputs,DuckgresShadowInputs,DuckgresShadowResult,+ check_duckgres_shadow_eligibility_activity,check_duckgres_shadow_enabled_activity,materialize_view_duckgres_activity,)@@ -50,6 +52,7 @@ __all__ = ["RecordSkippedDataModelingJobsInputs","SkippedDataModelingNode","EnrichViewSemanticsInputs",+ "DuckgresShadowEligibilityInputs","DuckgresShadowInputs","DuckgresShadowResult","GetDAGStructureInputs",@@ -65,6 +68,7 @@ __all__ = ["StageQueryableFilesResult","SucceedMaterializationInputs","SucceedMaterializationResult",+ "check_duckgres_shadow_eligibility_activity","check_duckgres_shadow_enabled_activity","clear_cdp_staging_activity","create_data_modeling_job_activity",diff --git a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.pyindex cd481ab54b88..6c6e24ff072b 100644--- a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py+++ b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py@@ -1,3 +1,4 @@+import osimport timeimport typingimport datetime as dt@@ -6,6 +7,7 @@ import dataclassesfrom structlog.contextvars import bind_contextvarsfrom temporalio import activity+from posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Teamfrom posthog.ph_client import feature_enabled_or_false@@ -24,6 +26,7 @@ from products.endpoints.backend.facade.temporal import prepare_executable_queryfrom products.managed_warehouse.backend.facade.api import (duckgres_data_modeling_schema,has_provisioned_warehouse,+ is_data_modeling_shadow_ready,is_dev_mode,)from products.managed_warehouse.backend.facade.contracts import DuckLakeCompiledQuery, DuckLakeS3Secret@@ -41,6 +44,13 @@ LOGGER = get_logger(__name__)FEATURE_FLAG = "duckgres-data-modeling-shadow"+@frozen+class DuckgresShadowEligibilityInputs:+ team_id: int+ dag_id: str+ node_id: str++@dataclasses.dataclassclass DuckgresShadowInputs:team_id: int@@ -70,10 +80,15 @@ class DuckgresShadowResult:file_size_delta_bytes: int = 0-def _is_duckgres_shadow_enabled(team: Team) -> bool:- if is_dev_mode():- import os+@frozen+class _DuckgresShadowObjects:+ team: Team+ node: Node+ saved_query: DataWarehouseSavedQuery++def _is_duckgres_shadow_flag_enabled(team: Team) -> bool:+ if is_dev_mode():return os.environ.get("DUCKGRES_SHADOW_ENABLED", "").lower() in ("1", "true")if not has_provisioned_warehouse(str(team.organization_id)):@@ -98,6 +113,18 @@ def _is_duckgres_shadow_enabled(team: Team) -> bool:return False+def _is_duckgres_shadow_enabled(team: Team, saved_query: DataWarehouseSavedQuery) -> bool:+ if not _is_duckgres_shadow_flag_enabled(team):+ return False++ return is_data_modeling_shadow_ready(+ organization_id=team.organization_id,+ team_id=team.id,+ saved_query_id=saved_query.id,+ source_query=saved_query.query,+ )++def _compile_hogql_for_ducklake(hogql_query: str, team_id: int) -> DuckLakeCompiledQuery:from posthog.schema import HogQLQuery@@ -112,30 +139,43 @@ def _compile_hogql_for_ducklake(hogql_query: str, team_id: int) -> DuckLakeCompi)-@database_sync_to_async_pool-def _get_shadow_input_objects(- inputs: DuckgresShadowInputs,-) -> tuple[Team, Node, DataWarehouseSavedQuery]:- team = Team.objects.get(id=inputs.team_id)- node = Node.objects.prefetch_related("saved_query").get(- id=inputs.node_id, team_id=inputs.team_id, dag_id=inputs.dag_id- )+def _load_shadow_objects(*, team_id: int, dag_id: str, node_id: str) -> _DuckgresShadowObjects:+ team = Team.objects.get(id=team_id)+ node = Node.objects.prefetch_related("saved_query").get(id=node_id, team_id=team_id, dag_id=dag_id)if node.type == NodeType.TABLE or node.saved_query is None:raise ValueError(f"Node {node.name} is not materializable")- saved_query = DataWarehouseSavedQuery.objects.exclude(deleted=True).get(- id=node.saved_query.id, team_id=inputs.team_id- )+ saved_query = DataWarehouseSavedQuery.objects.exclude(deleted=True).get(id=node.saved_query.id, team_id=team_id)++ return _DuckgresShadowObjects(team=team, node=node, saved_query=saved_query)+++@database_sync_to_async_pool+def _get_shadow_input_objects(inputs: DuckgresShadowInputs) -> _DuckgresShadowObjects:+ objects = _load_shadow_objects(team_id=inputs.team_id, dag_id=inputs.dag_id, node_id=inputs.node_id)+ saved_query = objects.saved_queryif saved_query.origin == DataWarehouseSavedQuery.Origin.ENDPOINT:prepare_executable_query(saved_query)- return (team, node, saved_query)+ return objects+++@database_sync_to_async_pool+def _check_duckgres_shadow_eligibility(inputs: DuckgresShadowEligibilityInputs) -> bool:+ objects = _load_shadow_objects(team_id=inputs.team_id, dag_id=inputs.dag_id, node_id=inputs.node_id)+ return _is_duckgres_shadow_enabled(objects.team, objects.saved_query)@activity.defnasync def check_duckgres_shadow_enabled_activity(team_id: int) -> bool:- """Check whether the duckgres shadow flag is enabled for a team."""+ """Check the legacy team-level shadow prerequisites."""team = await database_sync_to_async_pool(Team.objects.get)(id=team_id)- return await database_sync_to_async_pool(_is_duckgres_shadow_enabled)(team)+ return await database_sync_to_async_pool(_is_duckgres_shadow_flag_enabled)(team)+++async def check_duckgres_shadow_eligibility_activity(inputs: DuckgresShadowEligibilityInputs) -> bool:+ """Check whether the duckgres shadow path is eligible to run."""+ return await _check_duckgres_shadow_eligibility(inputs)@database_sync_to_async_pool@@ -167,7 +207,10 @@ async def materialize_view_duckgres_activity(inputs: DuckgresShadowInputs) -> Dubind_contextvars(team_id=inputs.team_id)logger = LOGGER.bind()- team, node, saved_query = await _get_shadow_input_objects(inputs)+ objects = await _get_shadow_input_objects(inputs)+ team = objects.team+ node = objects.node+ saved_query = objects.saved_querybind_data_modeling_log_context(inputs.team_id, saved_query.id)hogql_query = typing.cast(dict, saved_query.query)["query"]schema_name = duckgres_data_modeling_schema(team.pk)diff --git a/posthog/temporal/data_modeling/workflows/materialize_view.py b/posthog/temporal/data_modeling/workflows/materialize_view.pyindex 5c2f76086149..d0478dcb2b1b 100644--- a/posthog/temporal/data_modeling/workflows/materialize_view.py+++ b/posthog/temporal/data_modeling/workflows/materialize_view.py@@ -16,6 +16,7 @@ from posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.data_modeling.activities import (ClearCDPStagingInputs,CreateDataModelingJobInputs,+ DuckgresShadowEligibilityInputs,DuckgresShadowInputs,DuckgresShadowResult,FailMaterializationInputs,@@ -28,6 +29,7 @@ from posthog.temporal.data_modeling.activities import (StageQueryableFilesResult,SucceedMaterializationInputs,SucceedMaterializationResult,+ check_duckgres_shadow_eligibility_activity,check_duckgres_shadow_enabled_activity,clear_cdp_staging_activity,create_data_modeling_job_activity,@@ -87,6 +89,9 @@ ACCOUNT_PROPERTY_STAGING_WORKFLOW_PATCH = "account-property-staging-workflow-202# history recorded before this deploy has to keep taking the branch that issues neither.CDP_VIEW_TRIGGER_PATCH = "cdp-data-warehouse-view-trigger-2026-08"+# Histories recorded before this marker must keep passing only the team ID to the activity.+DUCKGRES_SHADOW_TRANSLATION_GATE_PATCH = "duckgres-shadow-translation-gate-2026-09"+# these indicate problems with the query or data, not transient issuesNON_RETRYABLE_ERRORS = ["CHQueryErrorMemoryLimitExceeded",@@ -184,15 +189,28 @@ class MaterializeViewWorkflow(PostHogWorkflow):job_id = Noneduckgres_job_id = None- # check whether duckgres shadow is enabled before creating the job- duckgres_enabled = await temporalio.workflow.execute_activity(- check_duckgres_shadow_enabled_activity,- inputs.team_id,- start_to_close_timeout=dt.timedelta(minutes=5),- retry_policy=temporalio.common.RetryPolicy(- maximum_attempts=3,- ),- )+ if temporalio.workflow.patched(DUCKGRES_SHADOW_TRANSLATION_GATE_PATCH):+ duckgres_enabled = await temporalio.workflow.execute_activity(+ check_duckgres_shadow_eligibility_activity,+ DuckgresShadowEligibilityInputs(+ 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,+ ),+ )+ else:+ duckgres_enabled = await temporalio.workflow.execute_activity(+ check_duckgres_shadow_enabled_activity,+ inputs.team_id,+ start_to_close_timeout=dt.timedelta(minutes=5),+ retry_policy=temporalio.common.RetryPolicy(+ maximum_attempts=3,+ ),+ )duckgres_shadow_handle = Noneif duckgres_enabled or inputs.duckgres_only:diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.pyindex 81b5bfe816ce..3545c9c70769 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py@@ -10,6 +10,7 @@ import temporalio.workflowfrom temporalio.exceptions import CancelledError, ChildWorkflowError, WorkflowAlreadyStartedErrorfrom posthog.temporal.data_modeling.activities import (+ DuckgresShadowEligibilityInputs,FailMaterializationInputs,MaterializeViewResult,PrepareQueryableTableResult,@@ -121,6 +122,12 @@ class TestQualityGateBranching:assert started[-2:] == ["stage_queryable_files_activity", "quality_block_materialization_activity"]assert "publish_queryable_table_activity" not in startedassert "succeed_materialization_activity" not in started+ assert execute_activity.await_args_list[0].args[1] == DuckgresShadowEligibilityInputs(+ team_id=7,+ dag_id="dag-1",+ node_id="node-1",+ )+ assert execute_activity.await_args_list[0].args[0].__name__ == "check_duckgres_shadow_eligibility_activity"async def test_account_staging_starts_an_isolated_child_workflow(self):materialize_result = dataclasses.replace(@@ -251,6 +258,8 @@ class TestQualityGateBranching:start_child.assert_not_awaited()assert result.quality_blocking_failures is Noneassert result.quality_audited is False+ assert execute_activity.await_args_list[0].args[1] == 7+ assert execute_activity.await_args_list[0].args[0].__name__ == "check_duckgres_shadow_enabled_activity"async def test_an_audit_that_reached_no_verdict_leaves_the_node_to_the_sweep(self):# Returning zero here would publish and also claim the node was audited, so the DAG'sdiff --git a/products/managed_warehouse/backend/README.md b/products/managed_warehouse/backend/README.mdindex c56adbc949eb..b42f6e3a29e9 100644--- a/products/managed_warehouse/backend/README.md+++ b/products/managed_warehouse/backend/README.md@@ -71,6 +71,8 @@ To retry specific failures, select failed or stale rows in `Managed warehouse viThe manual trigger is deliberately separate from provisioning. A future provisioning trigger should call the same job starter instead of adding compilation to the provisioning request path.+Data modeling shadow materialization starts only when its feature flag is enabled, the managed warehouse is provisioned, the organization has a ready Trino target, and the saved query has a compiled translation for its current definition. Missing, failed, stale, or empty translations keep the shadow path disabled.+## Environment variablesThe workflow obtains its DuckLake configuration from the following environment variables:diff --git a/products/managed_warehouse/backend/facade/api.py b/products/managed_warehouse/backend/facade/api.pyindex d7ca4ee0ceaa..de60c15b3401 100644--- a/products/managed_warehouse/backend/facade/api.py+++ b/products/managed_warehouse/backend/facade/api.py@@ -52,6 +52,7 @@ __all__ = ["get_team_backfill_state","get_warehouse_provision_status","has_provisioned_warehouse",+ "is_data_modeling_shadow_ready","is_dev_mode","organization_is_pending_deletion","persist_duckgres_server_for_org",@@ -125,6 +126,25 @@ def has_provisioned_warehouse(organization_id: str | UUID) -> bool:return DuckgresServer.objects.filter(organization_id=organization_id).exists()+def is_data_modeling_shadow_ready(+ *,+ organization_id: str | UUID,+ team_id: int,+ saved_query_id: str | UUID,+ source_query: object,+) -> bool:+ from products.managed_warehouse.backend.view_translation_status import ( # noqa: PLC0415 -- keeps ORM models off the facade import path+ is_data_modeling_shadow_ready as check_shadow_readiness,+ )++ return check_shadow_readiness(+ organization_id=organization_id,+ team_id=team_id,+ saved_query_id=saved_query_id,+ source_query=source_query,+ )++def get_duckgres_query_server_config(organization_id: str) -> DuckgresQueryServerConfig:config = common.get_duckgres_config_for_org(organization_id)return DuckgresQueryServerConfig(diff --git a/products/managed_warehouse/backend/temporal/view_translation_workflow.py b/products/managed_warehouse/backend/temporal/view_translation_workflow.pyindex f331ac235209..1be313548c01 100644--- a/products/managed_warehouse/backend/temporal/view_translation_workflow.py+++ b/products/managed_warehouse/backend/temporal/view_translation_workflow.py@@ -1,7 +1,5 @@from __future__ import annotations-import json-import hashlibimport datetime as dtfrom uuid import UUID@@ -28,6 +26,7 @@ from products.managed_warehouse.backend.models import (ManagedWarehouseViewTranslationResult,)from products.managed_warehouse.backend.trino_compiler import get_ready_trino_catalog_name+from products.managed_warehouse.backend.view_translation_status import source_query_hash@frozen@@ -35,11 +34,6 @@ class ViewTranslationPreparation:team_ids: tuple[int, ...]-def source_query_hash(query: object) -> str:- serialized = json.dumps(query, sort_keys=True, separators=(",", ":"), ensure_ascii=True)- return hashlib.sha256(serialized.encode()).hexdigest()--@activity.defndef prepare_managed_warehouse_view_translation_activity(job_id: str) -> ViewTranslationPreparation:job = ManagedWarehouseViewTranslationJob.objects.select_related("organization").get(id=job_id)diff --git a/products/managed_warehouse/backend/tests/test_api.py b/products/managed_warehouse/backend/tests/test_api.pyindex a10ad398bfb3..5683419ebf5d 100644--- a/products/managed_warehouse/backend/tests/test_api.py+++ b/products/managed_warehouse/backend/tests/test_api.py@@ -1,11 +1,22 @@import pytest+from posthog.test.base import BaseTestfrom unittest.mock import patchfrom posthog.models import Organization-from products.managed_warehouse.backend.facade.api import get_duckgres_query_server_config, get_stored_warehouse_config+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+from products.managed_warehouse.backend.facade.api import (+ get_duckgres_query_server_config,+ get_stored_warehouse_config,+ is_data_modeling_shadow_ready,+)from products.managed_warehouse.backend.facade.contracts import DuckgresStoredServerConfig-from products.managed_warehouse.backend.models import DuckgresServer+from products.managed_warehouse.backend.models import (+ DuckgresServer,+ ManagedWarehouseViewTranslationJob,+ ManagedWarehouseViewTranslationResult,+)+from products.managed_warehouse.backend.view_translation_status import source_query_hashdef test_query_server_config_maps_legacy_environment_config_to_a_contract() -> None:@@ -58,3 +69,48 @@ def test_stored_warehouse_config_maps_connection_and_catalog_without_returning_tassert stored.bucket is not Noneassert stored.bucket.bucket == "managed-warehouse-bucket"assert not hasattr(stored, "save")+++class TestDataModelingShadowReadiness(BaseTest):+ def test_requires_a_ready_trino_target_and_a_current_compiled_translation(self) -> None:+ query = {"kind": "HogQLQuery", "query": "SELECT 1"}+ saved_query = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="translated_view",+ query=query,+ )+ job = ManagedWarehouseViewTranslationJob.objects.create(organization=self.organization)+ result = ManagedWarehouseViewTranslationResult.all_teams.create(+ job=job,+ team=self.team,+ saved_query_id=saved_query.id,+ saved_query_name=saved_query.name,+ source_query_hash=source_query_hash(query),+ status=ManagedWarehouseViewTranslationResult.Status.COMPILED,+ trino_sql="SELECT 1",+ )++ def is_ready(source_query: object = query) -> bool:+ return is_data_modeling_shadow_ready(+ organization_id=self.organization.id,+ team_id=self.team.id,+ saved_query_id=saved_query.id,+ source_query=source_query,+ )++ readiness_target = "products.managed_warehouse.backend.view_translation_status.get_ready_trino_catalog_name"+ with patch(readiness_target, return_value=None):+ assert is_ready() is False++ with patch(readiness_target, return_value="managed_catalog"):+ assert is_ready() is True+ assert is_ready({"kind": "HogQLQuery", "query": "SELECT 2"}) is False++ result.trino_sql = ""+ result.save(update_fields=["trino_sql"])+ assert is_ready() is False++ result.trino_sql = "SELECT 1"+ result.status = ManagedWarehouseViewTranslationResult.Status.FAILED+ result.save(update_fields=["trino_sql", "status"])+ assert is_ready() is Falsediff --git a/products/managed_warehouse/backend/view_translation_status.py b/products/managed_warehouse/backend/view_translation_status.pynew file mode 100644index 000000000000..c6486a19cf2a--- /dev/null+++ b/products/managed_warehouse/backend/view_translation_status.py@@ -0,0 +1,37 @@+from __future__ import annotations++import json+import hashlib+from uuid import UUID++from products.managed_warehouse.backend.models import ManagedWarehouseViewTranslationResult+from products.managed_warehouse.backend.trino_compiler import get_ready_trino_catalog_name+++def source_query_hash(query: object) -> str:+ serialized = json.dumps(query, sort_keys=True, separators=(",", ":"), ensure_ascii=True)+ return hashlib.sha256(serialized.encode()).hexdigest()+++def is_data_modeling_shadow_ready(+ *,+ organization_id: str | UUID,+ team_id: int,+ saved_query_id: str | UUID,+ source_query: object,+) -> bool:+ if get_ready_trino_catalog_name(str(organization_id)) is None:+ return False++ return (+ ManagedWarehouseViewTranslationResult.objects.for_team(team_id)+ .filter(+ job__organization_id=organization_id,+ saved_query_id=saved_query_id,+ source_query_hash=source_query_hash(source_query),+ status=ManagedWarehouseViewTranslationResult.Status.COMPILED,+ )+ .exclude(trino_sql__isnull=True)+ .exclude(trino_sql="")+ .exists()+ )