: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(managed-warehouse): compile trino shadows for each job (#113748)
Eric Duong50fa04ef87a9
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.mdindex 0decc4d56793..24d7f5f32504 100644--- a/docs/internal/hogql-trino-compiler.md+++ b/docs/internal/hogql-trino-compiler.md@@ -172,7 +172,7 @@ Create a new compiler when the batch needs fresh control-plane placement or teamBoth managed compilation modes preserve the source query's limits and offsets in the generated SQL and diagnostic HogQL.They do not add an implicit row limit or cap an explicit limit at the interactive query maximum.For example, an unbounded query stays unbounded, and `LIMIT 75000` stays `LIMIT 75000`.-After deploying this behavior, rerun saved-view translation for queries compiled with the implicit cap; previously stored SQL is not rewritten automatically.+Previously stored diagnostic translations are not rewritten automatically; rerun the saved-view translation pass to refresh them. Shadow materialization compiles each run with the current compiler behavior.Pass `expansion_mode=TrinoExpansionMode.DJANGO` when a query requires actions, cohorts, saved queries, filters, variables, access-controlled warehouse discovery, or other Django-backed semantic expansion. This compatibility mode builds the full database and maps:@@ -218,16 +218,17 @@ An interrupted view remains pending for an activity retry, which resumes from peThe 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 `managed-warehouse-data-modeling-shadow` flag enables shadow materialization through Trino.-It requires a ready Trino target and a non-empty compiled result whose source hash matches the saved query's current definition.-The shadow activity executes the most recent matching conversion's stored `trino_sql` and `trino_values`, including its mapped table references.-It checks the source hash again when the activity runs and fails the shadow job if no current conversion exists; rerun translation after editing the saved query.-It does not recompile the query or fall back to DuckDB on failure.+It requires a provisioned managed warehouse and a ready Trino target.+Each dispatched shadow activity compiles the current saved query's HogQL in Django expansion mode and executes the generated Trino SQL with bound parameters.+Compilation uses current source bindings, saved-query dependencies, filters, and variables; endpoint queries are prepared before compilation.+Saved translation results remain diagnostic records and are not prerequisites or execution inputs for shadow jobs.+Compilation failures fail the modeling job, without connecting to Trino or falling back to DuckDB.Trino replaces the output table in the organization's catalog under `posthog_data_modeling_team_<team_id>`, using the sanitized model-path label or saved-query UUID.-The compiler and materializer share this naming policy, so stored translations can read upstream model outputs directly.+The compiler and materializer share this naming policy, so each compiled query can read upstream model outputs directly.The legacy Duckgres path retains `shadow_<team_id>_models` and normalized saved-query names.ClickHouse materialization and publication continue independently.-The DAG waits for upstream Trino builds and skips dependent Trino builds when an upstream model fails or has no eligible translation, even if ClickHouse succeeds.+The DAG waits for upstream Trino builds and skips dependent Trino builds when an upstream model fails or is ineligible for shadowing, even if ClickHouse succeeds.Skipped managed warehouse jobs record the upstream node IDs. Existing Temporal histories retain their previous dependency behavior.Run upstream materialized models before their dependents when selecting a subset of the DAG.Do not run the legacy DuckLake model-copy workflow against the same destinations while Trino owns their refreshes.diff --git a/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py b/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.pyindex da67476f0f63..c3f2277ad6dd 100644--- a/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py+++ b/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py@@ -117,15 +117,12 @@ def _is_managed_warehouse_shadow_flag_enabled(team: Team) -> bool:return False-def _is_managed_warehouse_shadow_enabled(team: Team, saved_query: DataWarehouseSavedQuery) -> bool:+def _is_managed_warehouse_shadow_enabled(team: Team) -> bool:if not _is_managed_warehouse_shadow_flag_enabled(team):return Falsereturn 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,)@@ -166,7 +163,7 @@ def _get_shadow_input_objects(inputs: ManagedWarehouseShadowInputs) -> _ManagedW@database_sync_to_async_pooldef _check_managed_warehouse_shadow_eligibility(inputs: ManagedWarehouseShadowEligibilityInputs) -> bool:objects = _load_shadow_objects(team_id=inputs.team_id, dag_id=inputs.dag_id, node_id=inputs.node_id)- return _is_managed_warehouse_shadow_enabled(objects.team, objects.saved_query)+ return _is_managed_warehouse_shadow_enabled(objects.team)async def _check_managed_warehouse_shadow_enabled_activity(team_id: int) -> bool:diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex 8580ee09b46d..f3d0fbe97dc7 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -50,7 +50,9 @@ from posthog.temporal.data_modeling.activities.materialize_view import (hogql_table,)from posthog.temporal.data_modeling.activities.materialize_view_managed_warehouse import (+ ManagedWarehouseShadowEligibilityInputs,ManagedWarehouseShadowInputs,+ check_managed_warehouse_shadow_eligibility_activity,materialize_view_managed_warehouse_activity,)from posthog.temporal.data_modeling.activities.notify_materialization_failure import _SavedQueryViewers@@ -115,11 +117,38 @@ async def _make_job(class TestMaterializeViewManagedWarehouseActivity:+ @pytest.mark.parametrize("flag_enabled,target_ready", [(False, True), (True, False), (True, True)])+ async def test_shadow_eligibility_does_not_require_translation(+ self, activity_environment, ateam, anode, adag, flag_enabled: bool, target_ready: bool+ ) -> None:+ inputs = ManagedWarehouseShadowEligibilityInputs(+ team_id=ateam.pk,+ node_id=str(anode.id),+ dag_id=str(adag.id),+ )+ with (+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.materialize_view_managed_warehouse._is_managed_warehouse_shadow_flag_enabled",+ return_value=flag_enabled,+ ),+ unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.materialize_view_managed_warehouse.is_data_modeling_shadow_ready",+ return_value=target_ready,+ ) as is_ready,+ ):+ assert await activity_environment.run(check_managed_warehouse_shadow_eligibility_activity, inputs) is (+ flag_enabled and target_ready+ )+ if flag_enabled:+ is_ready.assert_called_once_with(organization_id=ateam.organization_id)+ else:+ is_ready.assert_not_called()+@pytest.mark.parametrize(- "stale,alias_dispatch_fails",+ "compile_fails,alias_dispatch_fails",[(False, False), (True, False), (False, True)],)- async def test_trino_shadow_records_result_without_recompiling(+ async def test_trino_shadow_records_execution_or_compilation_result(self,activity_environment,ateam,@@ -127,7 +156,7 @@ class TestMaterializeViewManagedWarehouseActivity:ajob,adag,asaved_query,- stale: bool,+ compile_fails: bool,alias_dispatch_fails: bool,) -> None:inputs = ManagedWarehouseShadowInputs(@@ -149,7 +178,7 @@ class TestMaterializeViewManagedWarehouseActivity:unittest.mock.patch("products.managed_warehouse.backend.facade.client.execute_trino_model",return_value=DuckLakeTableResult(schema_name="shadow_models", table_name="test_model", row_count=12),- side_effect=ValueError("No current Trino conversion") if stale else None,+ side_effect=ValueError("Trino compilation failed") if compile_fails else None,) as execute,unittest.mock.patch("products.managed_warehouse.backend.facade.client.execute_ducklake_create_table"@@ -169,9 +198,9 @@ class TestMaterializeViewManagedWarehouseActivity:)legacy_execute.assert_not_called()await database_sync_to_async(ajob.refresh_from_db)()- if stale:+ if compile_fails:reconcile_aliases.assert_not_awaited()- assert result.error == "No current Trino conversion"+ assert result.error == "Trino compilation failed"assert ajob.status == DataModelingJobStatus.FAILEDelse:reconcile_aliases.assert_awaited_once_with(ateam.pk, str(asaved_query.id))diff --git a/products/managed_warehouse/backend/README.md b/products/managed_warehouse/backend/README.mdindex 0599dae130f4..d3c1fcb99fc6 100644--- a/products/managed_warehouse/backend/README.md+++ b/products/managed_warehouse/backend/README.md@@ -71,7 +71,7 @@ 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.+Data modeling shadow materialization starts when its feature flag is enabled, the managed warehouse is provisioned, and the organization has a ready Trino target. Each dispatched job compiles its current HogQL in Django expansion mode and executes the generated Trino SQL with bound parameters. Endpoint queries are prepared before compilation. The shadow path does not read stored translation results; the manual translation pass remains available for diagnostics. Compilation errors are recorded as failed modeling jobs.Trino shadow materialization has a six-hour execution deadline. Its Temporal activity allows six hours and five minutes so cancellation and cleanup can finish before the activity times out, and requires a heartbeat every two minutes. Deadline failures retain an explicit timeout message on the modeling job. Alias reconciliation keeps its separate five-minute execution deadline.diff --git a/products/managed_warehouse/backend/facade/api.py b/products/managed_warehouse/backend/facade/api.pyindex 4d315e1eb410..b2bd589df98e 100644--- a/products/managed_warehouse/backend/facade/api.py+++ b/products/managed_warehouse/backend/facade/api.py@@ -132,20 +132,12 @@ def has_provisioned_warehouse(organization_id: str | UUID) -> bool: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,+ from products.managed_warehouse.backend.trino_compiler import ( # noqa: PLC0415 -- keeps optional compiler imports off startup paths+ get_ready_trino_catalog_name,)- return check_shadow_readiness(- organization_id=organization_id,- team_id=team_id,- saved_query_id=saved_query_id,- source_query=source_query,- )+ return get_ready_trino_catalog_name(str(organization_id)) is not Nonedef get_duckgres_query_server_config(organization_id: str) -> DuckgresQueryServerConfig:diff --git a/products/managed_warehouse/backend/tests/test_api.py b/products/managed_warehouse/backend/tests/test_api.pyindex 5683419ebf5d..b3ff2eb4e85e 100644--- a/products/managed_warehouse/backend/tests/test_api.py+++ b/products/managed_warehouse/backend/tests/test_api.py@@ -1,22 +1,17 @@import pytest-from posthog.test.base import BaseTestfrom unittest.mock import patch+from django.test import SimpleTestCase+from posthog.models import Organization-from products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom 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,- ManagedWarehouseViewTranslationJob,- ManagedWarehouseViewTranslationResult,-)-from products.managed_warehouse.backend.view_translation_status import source_query_hash+from products.managed_warehouse.backend.models import DuckgresServerdef test_query_server_config_maps_legacy_environment_config_to_a_contract() -> None:@@ -71,46 +66,13 @@ def test_stored_warehouse_config_maps_connection_and_catalog_without_returning_tassert 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 False+class TestDataModelingShadowReadiness(SimpleTestCase):+ def test_requires_a_ready_trino_target_without_translation_records(self) -> None:+ for catalog in (None, "managed_catalog"):+ with self.subTest(catalog=catalog):+ with patch(+ "products.managed_warehouse.backend.trino_compiler.get_ready_trino_catalog_name",+ return_value=catalog,+ ) as get_catalog:+ assert is_data_modeling_shadow_ready(organization_id="organization-id") is (catalog is not None)+ get_catalog.assert_called_once_with("organization-id")diff --git a/products/managed_warehouse/backend/tests/test_trino_materialization.py b/products/managed_warehouse/backend/tests/test_trino_materialization.pyindex 9c0dab04d7b5..c1fd04a3f56d 100644--- a/products/managed_warehouse/backend/tests/test_trino_materialization.py+++ b/products/managed_warehouse/backend/tests/test_trino_materialization.py@@ -5,12 +5,20 @@ from unittest.mock import MagicMock, patchfrom parameterized import parameterized+from posthog.schema import HogQLQuery+from posthog.models import Teamfrom products.data_modeling.backend.facade.modeling import DataWarehouseModelPathfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.managed_warehouse.backend.facade.client import execute_trino_shadow_materialization-from products.managed_warehouse.backend.facade.contracts import DuckLakeTableResult, ManagedWarehouseTableNames+from products.managed_warehouse.backend.facade.contracts import (+ DuckLakeTableResult,+ ManagedWarehouseTableNames,+ ManagedWarehouseTeamMembership,+ TrinoCompiledQuery,+ TrinoExpansionMode,+)from products.managed_warehouse.backend.models import (ManagedWarehouseViewTranslationJob,ManagedWarehouseViewTranslationResult,@@ -24,19 +32,13 @@ class TestTrinoShadowMaterialization(BaseTest):def setUp(self) -> None:super().setUp()self.saved_query_id = UUID("12345678-1234-5678-1234-567812345678")- self.query = {"kind": "HogQLQuery", "query": "SELECT name FROM orders WHERE name = 'example'"}- self.job = ManagedWarehouseViewTranslationJob.objects.create(- organization=self.organization, status=ManagedWarehouseViewTranslationJob.Status.COMPLETED- )- self.translation = ManagedWarehouseViewTranslationResult.objects.for_team(self.team.pk).create(- team_id=self.team.pk,- job=self.job,- saved_query_id=self.saved_query_id,- saved_query_name="orders",- source_query_hash=source_query_hash(self.query),- status=ManagedWarehouseViewTranslationResult.Status.COMPILED,- trino_sql='SELECT name FROM "org_catalog"."imports"."orders" WHERE name = %(name)s',- trino_values={"name": "example' OR 1=1 --"},+ self.query: dict[str, object] = {+ "kind": "HogQLQuery",+ "query": "SELECT name FROM orders WHERE name = 'example'",+ }+ self.compiled = TrinoCompiledQuery(+ sql='SELECT name FROM "org_catalog"."imports"."orders" WHERE name = %(name)s',+ values={"name": "example' OR 1=1 --"},)self.connection = MagicMock(catalog='org_"catalog')self.cursor = self.connection.cursor.return_value@@ -51,24 +53,18 @@ class TestTrinoShadowMaterialization(BaseTest):)@parameterized.expand([(False,), (True,)])- def test_executes_latest_current_conversion_with_bound_values(self, fail_write: bool) -> None:- later_job = ManagedWarehouseViewTranslationJob.objects.create(organization=self.organization)- assert self.translation.trino_sql is not None- ManagedWarehouseViewTranslationResult.objects.for_team(self.team.pk).create(- team_id=self.team.pk,- job=later_job,- saved_query_id=self.saved_query_id,- saved_query_name="orders",- source_query_hash=self.translation.source_query_hash,- status=ManagedWarehouseViewTranslationResult.Status.COMPILED,- trino_sql=self.translation.trino_sql + " LIMIT 12",- trino_values=self.translation.trino_values,- )+ def test_compiles_and_executes_without_saved_translation(self, fail_write: bool) -> None:if fail_write:self.cursor.fetchall.side_effect = [[], RuntimeError("Trino write failed")]- with patch(- "products.managed_warehouse.backend.trino_materialization.connect_managed_warehouse_trino"- ) as connect:+ with (+ patch(+ "products.managed_warehouse.backend.trino_materialization.compile_hogql_to_trino_sql",+ return_value=self.compiled,+ ) as compile_query,+ patch(+ "products.managed_warehouse.backend.trino_materialization.connect_managed_warehouse_trino"+ ) as connect,+ ):connect.return_value.__enter__.return_value = self.connectionif fail_write:with self.assertRaisesRegex(RuntimeError, "Trino write failed"):@@ -79,6 +75,13 @@ class TestTrinoShadowMaterialization(BaseTest):assert result.schema_name == f"posthog_data_modeling_team_{self.team.pk}"assert result.table_name == f"model_{self.saved_query_id.hex}"+ compile_query.assert_called_once_with(+ self.team.pk,+ HogQLQuery.model_validate(self.query),+ team=self.team,+ bypass_warehouse_access_control=True,+ expansion_mode=TrinoExpansionMode.DJANGO,+ )connect.assert_called_once_with(str(self.organization.pk),principal=f"posthog:trino-materialization:team:{self.team.pk}:view:{self.saved_query_id}",@@ -88,33 +91,101 @@ class TestTrinoShadowMaterialization(BaseTest):)assert self.cursor.execute.call_args_list[1].args == (f'CREATE OR REPLACE TABLE "org_""catalog"."posthog_data_modeling_team_{self.team.pk}"."model_{self.saved_query_id.hex}" '- 'AS SELECT name FROM "org_catalog"."imports"."orders" WHERE name = ? LIMIT 12',+ 'AS SELECT name FROM "org_catalog"."imports"."orders" WHERE name = ?',["example' OR 1=1 --"],)self.cursor.close.assert_called_once()connect.return_value.__exit__.assert_called_once()- @parameterized.expand([("edited",), ("failed",), ("empty",), ("organization",), ("team",), ("saved_query",)])- def test_rejects_missing_current_conversion_before_connecting(self, reason: str) -> None:- if reason == "edited":- self.query["query"] = "SELECT 2"- elif reason == "failed":- self.translation.status = ManagedWarehouseViewTranslationResult.Status.FAILED- elif reason == "empty":- self.translation.trino_sql = ""- elif reason == "saved_query":- self.saved_query_id = uuid4()- self.translation.save()- other_team = Team.objects.create(organization=self.organization) if reason == "team" else None-- with patch(- "products.managed_warehouse.backend.trino_materialization.connect_managed_warehouse_trino"- ) as connect:- with self.assertRaisesRegex(ValueError, "No current Trino conversion"):- self.execute(- team_id=other_team.pk if other_team else None,- organization_id=str(uuid4()) if reason == "organization" else None,- )+ def test_recompiles_each_run_from_current_definition(self) -> None:+ self.query = {+ "kind": "HogQLQuery",+ "query": "SELECT event FROM events WHERE event = {event}",+ "values": {"event": "signup"},+ }+ job = ManagedWarehouseViewTranslationJob.objects.create(organization=self.organization)+ ManagedWarehouseViewTranslationResult.objects.for_team(self.team.pk).create(+ team_id=self.team.pk,+ job=job,+ saved_query_id=self.saved_query_id,+ saved_query_name="events_model",+ source_query_hash=source_query_hash(self.query),+ status=ManagedWarehouseViewTranslationResult.Status.COMPILED,+ trino_sql="SELECT 0",+ )+ membership = ManagedWarehouseTeamMembership(+ team_id=self.team.pk,+ organization_id=str(self.organization.pk),+ schema_name="production",+ enabled=True,+ backfill_enabled=True,+ table_names=ManagedWarehouseTableNames(+ events_table="events_current", persons_table="persons_current", data_imports_schema="imports"+ ),+ earliest_event_date=None,+ )+ with (+ patch("products.managed_warehouse.backend.cp_teams.list_org_teams", return_value=[]),+ patch(+ "products.managed_warehouse.backend.trino_compiler.get_ready_trino_catalog_name",+ return_value="org_catalog",+ ),+ patch(+ "products.managed_warehouse.backend.trino_compiler.get_org_team_membership",+ return_value=membership,+ ),+ patch(+ "products.managed_warehouse.backend.trino_materialization.connect_managed_warehouse_trino"+ ) as connect,+ ):+ connect.return_value.__enter__.return_value = self.connection+ self.execute()+ self.query = {+ "kind": "HogQLQuery",+ "query": "SELECT event FROM events WHERE event = {event} LIMIT 75000",+ "values": {"event": "purchase"},+ }+ self.execute()++ writes = [+ call.args for call in self.cursor.execute.call_args_list if call.args[0].startswith("CREATE OR REPLACE")+ ]+ assert len(writes) == 2+ for sql, _values in writes:+ assert 'FROM "org_catalog"."posthog"."events_current"' in sql+ assert "= ?)" in sql+ assert "SELECT 0" not in sql+ assert "LIMIT" not in writes[0][0]+ assert writes[0][1] == ["signup"]+ assert writes[1][0].endswith("LIMIT 75000")+ assert writes[1][1] == ["purchase"]++ def test_compilation_failure_does_not_connect_or_write(self) -> None:+ with (+ patch(+ "products.managed_warehouse.backend.trino_materialization.compile_hogql_to_trino_sql",+ side_effect=ValueError("Unsupported HogQL expression"),+ ),+ patch(+ "products.managed_warehouse.backend.trino_materialization.connect_managed_warehouse_trino"+ ) as connect,+ ):+ with self.assertRaisesRegex(ValueError, "Unsupported HogQL expression"):+ self.execute()+ connect.assert_not_called()++ def test_rejects_team_outside_organization_before_compilation(self) -> None:+ with (+ patch(+ "products.managed_warehouse.backend.trino_materialization.compile_hogql_to_trino_sql"+ ) as compile_query,+ patch(+ "products.managed_warehouse.backend.trino_materialization.connect_managed_warehouse_trino"+ ) as connect,+ ):+ with self.assertRaises(Team.DoesNotExist):+ self.execute(organization_id=str(uuid4()))+ compile_query.assert_not_called()connect.assert_not_called()@parameterized.expand([(None,), ("legacy_orders",)])@@ -133,9 +204,15 @@ class TestTrinoShadowMaterialization(BaseTest):)if model_label:DataWarehouseModelPath.objects.create(team=self.team, saved_query=saved_query, path=[model_label])- with patch(- "products.managed_warehouse.backend.trino_materialization.connect_managed_warehouse_trino"- ) as connect:+ with (+ patch(+ "products.managed_warehouse.backend.trino_materialization.compile_hogql_to_trino_sql",+ return_value=self.compiled,+ ),+ patch(+ "products.managed_warehouse.backend.trino_materialization.connect_managed_warehouse_trino"+ ) as connect,+ ):connect.return_value.__enter__.return_value = self.connectionwritten = self.execute()database = MagicMock()diff --git a/products/managed_warehouse/backend/trino_materialization.py b/products/managed_warehouse/backend/trino_materialization.pyindex 2997143c41ea..af96c1f07211 100644--- a/products/managed_warehouse/backend/trino_materialization.py+++ b/products/managed_warehouse/backend/trino_materialization.py@@ -3,14 +3,18 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGfrom uuid import UUID+from posthog.schema import HogQLQuery+from posthog.hogql.escape_sql import escape_trino_identifierfrom posthog.hogql.trino_parameters import convert_pyformat_placeholders+from posthog.models import Team+from products.managed_warehouse.backend.common import ducklake_data_modeling_schema-from products.managed_warehouse.backend.facade.contracts import DuckLakeTableResult+from products.managed_warehouse.backend.facade.contracts import DuckLakeTableResult, TrinoExpansionModefrom products.managed_warehouse.backend.table_binding import get_data_modeling_table_names+from products.managed_warehouse.backend.trino_compiler import compile_hogql_to_trino_sqlfrom products.managed_warehouse.backend.trino_connection import connect_managed_warehouse_trino-from products.managed_warehouse.backend.view_translation_status import get_current_trino_translationif TYPE_CHECKING:from products.managed_warehouse.backend.trino_execution import TrinoQueryControl@@ -24,14 +28,18 @@ def execute_trino_shadow_materialization(source_query: object,control: TrinoQueryControl | None = None,) -> DuckLakeTableResult:- compiled = get_current_trino_translation(- organization_id=organization_id,- team_id=team_id,- saved_query_id=saved_query_id,- source_query=source_query,+ if control:+ control.checkpoint()+ team = Team.objects.get(pk=team_id, organization_id=organization_id)+ compiled = compile_hogql_to_trino_sql(+ team_id,+ HogQLQuery.model_validate(source_query),+ team=team,+ bypass_warehouse_access_control=True,+ expansion_mode=TrinoExpansionMode.DJANGO,)- if compiled is None:- raise ValueError("No current Trino conversion exists for this saved query. Run its translation again.")+ if control:+ control.checkpoint()sql, parameters = convert_pyformat_placeholders(compiled.sql, compiled.values)schema_name = ducklake_data_modeling_schema(team_id)diff --git a/products/managed_warehouse/backend/view_translation_status.py b/products/managed_warehouse/backend/view_translation_status.pyindex def21ec6d1f7..5e8356a6d966 100644--- a/products/managed_warehouse/backend/view_translation_status.py+++ b/products/managed_warehouse/backend/view_translation_status.py@@ -2,74 +2,8 @@ from __future__ import annotationsimport jsonimport hashlib-from uuid import UUID--from django.db.models import QuerySet--from products.managed_warehouse.backend.facade.contracts import TrinoCompiledQuery-from products.managed_warehouse.backend.models import ManagedWarehouseViewTranslationResult-from products.managed_warehouse.backend.trino_compiler import get_ready_trino_catalog_namedef source_query_hash(query: object) -> str:serialized = json.dumps(query, sort_keys=True, separators=(",", ":"), ensure_ascii=True)return hashlib.sha256(serialized.encode()).hexdigest()---def _current_compiled_translations(- *,- organization_id: str | UUID,- team_id: int,- saved_query_id: str | UUID,- source_query: object,-) -> QuerySet[ManagedWarehouseViewTranslationResult]:- 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="")- )---def get_current_trino_translation(- *,- organization_id: str | UUID,- team_id: int,- saved_query_id: str | UUID,- source_query: object,-) -> TrinoCompiledQuery | None:- result = (- _current_compiled_translations(- organization_id=organization_id,- team_id=team_id,- saved_query_id=saved_query_id,- source_query=source_query,- )- .order_by("-processed_at", "-created_at", "-id")- .first()- )- if result is None or not result.trino_sql:- return None- return TrinoCompiledQuery(sql=result.trino_sql, values=result.trino_values, hogql=result.normalized_hogql)---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 _current_compiled_translations(- organization_id=organization_id,- team_id=team_id,- saved_query_id=saved_query_id,- source_query=source_query,- ).exists()