Skip to content

: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.

fix(data-modeling): build trino models and publish readable aliases (#102597)

Eric Duongc6c1eecd1d6d
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.md
index 12719ce7e5ed..daa59154ace6 100644
--- a/docs/internal/hogql-trino-compiler.md
+++ b/docs/internal/hogql-trino-compiler.md
@@ -192,7 +192,82 @@ An interrupted view remains pending for an activity retry, which resumes from pe
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.
+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.
+
+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 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.
+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.
+Publication uses the DuckLake connector's atomic `CREATE OR REPLACE TABLE` operation, so a failed write preserves the previous table.
+The shadow row count comes from Trino's write result; storage size metrics are unavailable and remain zero.
+
+### Execution limits and cancellation
+
+Trino enforces tenant capacity and query queueing.
+Model builds and alias passes submit work without application-level global or organization admission limits.
+Their synchronous client calls use a dedicated executor with Python's default pool size, separate from the general database thread pool.
+
+Build sessions set `query_max_run_time` to 15 minutes.
+The client also enforces a total execution deadline and sends cancellation through the active Trino cursor when the activity is canceled or its deadline expires.
+Activities heartbeat every second under a two-minute heartbeat timeout, and workflow cancellation waits for activity cleanup.
+Alias passes use a five-minute total deadline and cap each metadata statement at 30 seconds.
+
+### Readable model names
+
+After a successful Trino build, the activity starts or signals `managed-warehouse.reconcile-model-aliases` on the DuckLake task queue.
+One workflow per team (`managed-warehouse-model-aliases/<team_id>`) coalesces build signals for 30 seconds, then refreshes up to 100 requested models at a time.
+These passes load only the requested models and name conflicts, and fetch columns and ownership comments for their relations.
+Full audits handle renames, deletions, and missed signals, starting at a 30-minute interval and backing off to two hours when unchanged, with 20% jitter.
+Errors retry with backoff; pending model IDs survive retries and continuation.
+It continues as a new run after 100 passes to bound its history.
+Alias failures retry independently and do not fail a completed physical build or block downstream materialization.
+
+The workflow exposes each materialized saved query through an invoker-security view in `posthog_data_modeling_team_<team_id>`:
+
+```sql
+CREATE VIEW <catalog>.posthog_data_modeling_team_123.daily_revenue
+SECURITY INVOKER AS
+SELECT * FROM <catalog>.posthog_data_modeling_team_123.model_<saved_query_uuid>;
+```
+
+Physical destinations and compiled dependency references remain unchanged, including legacy physical table labels.
+Logical names use the saved-query name lowercased for Trino's case-insensitive identifiers.
+Dots, spaces, and quotes remain part of one quoted identifier, so a model named `reporting.orders` is queried as `<catalog>.<schema>."reporting.orders"`.
+If a legacy physical table already has its model's logical name, it needs no extra view.
+Names that collide after lowercasing, with another model's physical destination, or with an unmanaged relation are reported instead of overwritten.
+The `model_<32 hexadecimal characters>` namespace is reserved for physical destinations.
+
+Generated view comments record the team, saved-query ID, and a fingerprint of the destination and output columns.
+Reconciliation refreshes views when their destination or columns change and removes only marked views that are no longer desired.
+It leaves physical tables and unmarked relations intact.
+Renames and deletions are eventually reflected by the next successful full audit; alias cleanup does not delete backing data.
+The schema must be managed exclusively by this publisher for aliases; do not edit generated views or their ownership comments manually.
+
+The connector and DuckLake catalog must support views, view comments, and `CREATE OR REPLACE VIEW`.
+Unsupported catalogs retain working physical materializations while alias reconciliation reports failures.
+Inspect the workflow's `status` query and `trino_model_aliases_reconciled` worker logs for publication counts and errors (at most 50 collision messages per pass).
+The workflow stops when its team is missing or its shadow flag is disabled.
+An empty team gets one final owned-alias cleanup before the workflow stops.
+A subsequent build starts reconciliation again.
+If dispatch failed or the workflow was stopped, restart reconciliation without rebuilding any models from a Django shell:
+
+```python
+from asgiref.sync import async_to_sync
+from products.managed_warehouse.backend.facade.client import request_model_alias_reconciliation
+
+async_to_sync(request_model_alias_reconciliation)(123)
+```
+
+Existing Temporal histories retain their legacy execution path through a workflow patch.
+Explicit `managed_warehouse_only` runs without flag eligibility also retain the legacy path.
## Validation
diff --git a/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py b/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py
index af6383667367..da67476f0f63 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py
@@ -12,6 +12,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.models import Team
from posthog.ph_client import feature_enabled_or_false
from posthog.sync import database_sync_to_async_pool
+from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_logger
from products.data_modeling.backend.facade.models import (
@@ -24,11 +25,14 @@ from products.data_modeling.backend.facade.models import (
from products.endpoints.backend.facade.temporal import prepare_executable_query
from products.managed_warehouse.backend.facade.api import (
duckgres_data_modeling_schema,
+ ducklake_data_modeling_schema,
+ get_data_modeling_table_name,
has_provisioned_warehouse,
is_data_modeling_shadow_ready,
is_dev_mode,
)
from products.managed_warehouse.backend.facade.contracts import DuckLakeCompiledQuery, DuckLakeS3Secret
+from products.managed_warehouse.backend.facade.feature_flags import DATA_MODELING_SHADOW_FLAG
from ..metrics import get_node_suspended_metric
from .utils import (
@@ -40,7 +44,7 @@ from .utils import (
LOGGER = get_logger(__name__)
-FEATURE_FLAG = "managed-warehouse-data-modeling-shadow"
+FEATURE_FLAG = DATA_MODELING_SHADOW_FLAG
@frozen
@@ -57,6 +61,7 @@ class ManagedWarehouseShadowInputs:
node_id: str
job_id: str
dangerously_execute_raw_sql: bool = False
+ use_trino: bool = False
@property
def properties_to_log(self) -> dict[str, typing.Any]:
@@ -219,36 +224,54 @@ async def _materialize_view_managed_warehouse(
node = objects.node
saved_query = objects.saved_query
bind_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)
- table_name = saved_query.normalized_name
-
- await logger.ainfo(
- "Starting managed warehouse shadow materialization",
- node_name=node.name,
- schema_name=schema_name,
- table_name=table_name,
- )
+ schema_name = ducklake_data_modeling_schema(team.pk) if inputs.use_trino else duckgres_data_modeling_schema(team.pk)
+ table_name = "" if inputs.use_trino else saved_query.normalized_name
start_time = time.monotonic()
sql: str = ""
values: dict[str, object] = {}
s3_secrets: tuple[DuckLakeS3Secret, ...] = ()
try:
- if inputs.dangerously_execute_raw_sql:
- sql = hogql_query
- else:
- compiled = await database_sync_to_async_pool(_compile_hogql_for_ducklake)(hogql_query, team.pk)
- sql = compiled.sql
- values = compiled.values
- s3_secrets = compiled.s3_secrets
- await logger.adebug("Managed warehouse shadow SQL generated", sql=sql)
-
- from products.managed_warehouse.backend.facade.client import execute_ducklake_create_table
+ from products.managed_warehouse.backend.facade.client import execute_ducklake_create_table, execute_trino_model
- result = await database_sync_to_async_pool(execute_ducklake_create_table)(
- team.pk, sql, schema_name, table_name, values, s3_secrets=s3_secrets
+ if inputs.use_trino:
+ table_name = await database_sync_to_async_pool(get_data_modeling_table_name)(team.pk, saved_query.id)
+ await logger.ainfo(
+ "Starting managed warehouse shadow materialization",
+ node_name=node.name,
+ schema_name=schema_name,
+ table_name=table_name,
)
+ if inputs.use_trino:
+ result = await execute_trino_model(
+ organization_id=str(team.organization_id),
+ team_id=team.pk,
+ saved_query_id=saved_query.id,
+ source_query=saved_query.query,
+ )
+ from products.managed_warehouse.backend.facade.client import request_model_alias_reconciliation
+
+ try:
+ await request_model_alias_reconciliation(team.pk, str(saved_query.id))
+ except Exception as error:
+ capture_exception(error)
+ await logger.awarning(
+ "Could not schedule Trino model aliases; retry alias reconciliation without rebuilding the model",
+ team_id=team.pk,
+ )
+ else:
+ hogql_query = typing.cast(dict, saved_query.query)["query"]
+ if inputs.dangerously_execute_raw_sql:
+ sql = hogql_query
+ else:
+ compiled = await database_sync_to_async_pool(_compile_hogql_for_ducklake)(hogql_query, team.pk)
+ sql = compiled.sql
+ values = compiled.values
+ s3_secrets = compiled.s3_secrets
+ await logger.adebug("Managed warehouse shadow SQL generated", sql=sql)
+ result = await database_sync_to_async_pool(execute_ducklake_create_table)(
+ team.pk, sql, schema_name, table_name, values, s3_secrets=s3_secrets
+ )
duration = time.monotonic() - start_time
await logger.ainfo(
@@ -314,4 +337,7 @@ async def _materialize_view_managed_warehouse(
async def materialize_view_managed_warehouse_activity(
inputs: ManagedWarehouseShadowInputs,
) -> ManagedWarehouseShadowResult:
+ if inputs.use_trino:
+ async with Heartbeater():
+ return await _materialize_view_managed_warehouse(inputs)
return await _materialize_view_managed_warehouse(inputs)
diff --git a/posthog/temporal/data_modeling/workflows/execute_dag.py b/posthog/temporal/data_modeling/workflows/execute_dag.py
index 6a6c96bb0441..d290a881fb7d 100644
--- a/posthog/temporal/data_modeling/workflows/execute_dag.py
+++ b/posthog/temporal/data_modeling/workflows/execute_dag.py
@@ -41,6 +41,8 @@ from products.data_quality.backend.facade.enums import SuiteRunTrigger
MAX_CONCURRENT_CHILDREN = 10
+TRINO_DEPENDENCIES_PATCH = "trino-model-dependencies-2026-09"
+
NODE_AUDIT_PATCH = "data-quality-node-audit-2026-08"
@@ -91,6 +93,7 @@ class NodeResult:
skip_reason: str | None = None
quality_failed: bool = False
quality_audited: bool = False
+ trino_materialized: bool | None = None
@dataclasses.dataclass
@@ -290,6 +293,9 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
suspended_node_set: set[str] = set(dag_structure.suspended_nodes.get(serving_engine, []))
downstreams = _get_downstream_lookup(edge_lookup)
skipped_jobs: list[SkippedDataModelingNode] = []
+ track_trino_dependencies = temporalio.workflow.patched(TRINO_DEPENDENCIES_PATCH)
+ unavailable_trino_nodes: set[str] = set(dag_structure.suspended_nodes.get("managed_warehouse", []))
+ skipped_trino_jobs: list[SkippedDataModelingNode] = []
# execute child workflows with bounded concurrency using a sliding window;
# the semaphore limits how many child workflows run simultaneously across
# all levels to be a friendlier neighbor to managed warehouse and ClickHouse infrastructure
@@ -372,15 +378,40 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
async def _run_child(node_id: str) -> NodeResult:
async with semaphore:
+ blocked_trino_upstreams = (
+ sorted(upstream for upstream in unavailable_trino_nodes if node_id in downstreams[upstream])
+ if track_trino_dependencies
+ else []
+ )
+ child_inputs = MaterializeViewWorkflowInputs(
+ team_id=inputs.team_id,
+ dag_id=inputs.dag_id,
+ node_id=node_id,
+ managed_warehouse_only=managed_warehouse_only,
+ dangerously_execute_raw_sql=inputs.dangerously_execute_raw_sql,
+ skip_trino=bool(blocked_trino_upstreams),
+ )
+ trino_skip = (
+ SkippedDataModelingNode(
+ node_id=node_id,
+ failed_upstream_node_ids=blocked_trino_upstreams[:UPSTREAM_NAMES_IN_SKIP_REASON],
+ failed_upstream_total=len(blocked_trino_upstreams),
+ )
+ if blocked_trino_upstreams
+ else None
+ )
+ if trino_skip is not None and managed_warehouse_only:
+ skipped_trino_jobs.append(trino_skip)
+ return NodeResult(
+ node_id=node_id,
+ success=False,
+ skipped=True,
+ skip_reason="Upstream Trino materialization unavailable",
+ trino_materialized=False,
+ )
handle = await temporalio.workflow.start_child_workflow(
MaterializeViewWorkflow.run,
- MaterializeViewWorkflowInputs(
- team_id=inputs.team_id,
- dag_id=inputs.dag_id,
- node_id=node_id,
- managed_warehouse_only=managed_warehouse_only,
- dangerously_execute_raw_sql=inputs.dangerously_execute_raw_sql,
- ),
+ child_inputs,
id=f"materialize-view-{inputs.dag_id}-{node_id}-{start_time.isoformat()}",
parent_close_policy=ParentClosePolicy.REQUEST_CANCEL,
retry_policy=temporalio.common.RetryPolicy(
@@ -389,6 +420,8 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
)
try:
result: MaterializeViewWorkflowResult = await handle
+ if trino_skip is not None and result.trino_materialized is False:
+ skipped_trino_jobs.append(trino_skip)
if result.quality_blocking_failures is not None and result.quality_blocking_failures > 0:
temporalio.workflow.logger.warning(
f"Node {node_id} materialized but was not published: "
@@ -412,6 +445,7 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
rows_materialized=result.rows_materialized,
duration_seconds=result.duration_seconds,
quality_audited=result.quality_audited,
+ trino_materialized=result.trino_materialized,
)
except temporalio.exceptions.ChildWorkflowError as e:
error_message = str(e.cause) if e.cause else str(e)
@@ -440,6 +474,12 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
level_results = await asyncio.gather(*[_run_child(node_id) for node_id in execute_nodes])
for nr in level_results:
node_results.append(nr)
+ if nr.trino_materialized is True:
+ unavailable_trino_nodes.discard(nr.node_id)
+ if track_trino_dependencies and (
+ nr.trino_materialized is False or (not managed_warehouse_only and nr.trino_materialized is None)
+ ):
+ unavailable_trino_nodes.add(nr.node_id)
if not nr.success:
failed_node_set.add(nr.node_id)
if nr.quality_failed:
@@ -458,6 +498,19 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),
)
+ if skipped_trino_jobs:
+ await temporalio.workflow.execute_activity(
+ record_skipped_data_modeling_jobs_activity,
+ RecordSkippedDataModelingJobsInputs(
+ team_id=inputs.team_id,
+ dag_id=inputs.dag_id,
+ engine=DataModelingJobEngine.MANAGED_WAREHOUSE.value,
+ skipped_nodes=skipped_trino_jobs,
+ ),
+ start_to_close_timeout=dt.timedelta(minutes=5),
+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),
+ )
+
# compute summary
end_time = temporalio.workflow.now()
duration_seconds = (end_time - start_time).total_seconds()
diff --git a/posthog/temporal/data_modeling/workflows/materialize_view.py b/posthog/temporal/data_modeling/workflows/materialize_view.py
index dbfad7ddc54c..b5de955f0acb 100644
--- a/posthog/temporal/data_modeling/workflows/materialize_view.py
+++ b/posthog/temporal/data_modeling/workflows/materialize_view.py
@@ -91,6 +91,7 @@ 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"
+TRINO_SHADOW_EXECUTION_PATCH = "trino-shadow-execution-2026-09"
# these indicate problems with the query or data, not transient issues
NON_RETRYABLE_ERRORS = [
@@ -130,6 +131,7 @@ class MaterializeViewWorkflowInputs:
managed_warehouse_only: bool = False
dangerously_execute_raw_sql: bool = False
manually_triggered_by_id: int | None = None
+ skip_trino: bool = False
# Old workflow payloads contain this field, so removing it would prevent replay after deployment.
duckgres_only: bool = False
@@ -163,6 +165,7 @@ class MaterializeViewWorkflowResult:
duration_seconds: float
quality_blocking_failures: int | None = None
quality_audited: bool = False
+ trino_materialized: bool | None = None
@temporalio.workflow.defn(name="data-modeling-materialize-view")
@@ -219,8 +222,10 @@ class MaterializeViewWorkflow(PostHogWorkflow):
),
)
+ use_trino = managed_warehouse_enabled and temporalio.workflow.patched(TRINO_SHADOW_EXECUTION_PATCH)
+ trino_materialized: bool | None = False if use_trino else None
managed_warehouse_shadow_handle = None
- if managed_warehouse_enabled or managed_warehouse_only:
+ if (managed_warehouse_enabled or managed_warehouse_only) and not (use_trino and inputs.skip_trino):
managed_warehouse_job_id = await temporalio.workflow.execute_activity(
create_data_modeling_job_activity,
CreateDataModelingJobInputs(
@@ -245,8 +250,15 @@ class MaterializeViewWorkflow(PostHogWorkflow):
dag_id=inputs.dag_id,
job_id=managed_warehouse_job_id,
dangerously_execute_raw_sql=inputs.dangerously_execute_raw_sql,
+ use_trino=use_trino,
),
start_to_close_timeout=dt.timedelta(minutes=20),
+ heartbeat_timeout=dt.timedelta(minutes=2) if use_trino else None,
+ cancellation_type=(
+ temporalio.workflow.ActivityCancellationType.WAIT_CANCELLATION_COMPLETED
+ if use_trino
+ else temporalio.workflow.ActivityCancellationType.TRY_CANCEL
+ ),
retry_policy=temporalio.common.RetryPolicy(
maximum_attempts=3 if managed_warehouse_only else 1,
initial_interval=dt.timedelta(seconds=10),
@@ -343,13 +355,15 @@ class MaterializeViewWorkflow(PostHogWorkflow):
end_time = temporalio.workflow.now()
blocked_duration_seconds = (end_time - start_time).total_seconds()
if managed_warehouse_shadow_handle is not None:
- await self._collect_shadow_comparison(
+ shadow_succeeded = await self._collect_shadow_comparison(
managed_warehouse_shadow_handle,
managed_warehouse_job_id,
materialize_result.row_count,
blocked_duration_seconds,
inputs,
)
+ if use_trino:
+ trino_materialized = shadow_succeeded
return MaterializeViewWorkflowResult(
job_id=job_id,
node_id=inputs.node_id,
@@ -357,6 +371,7 @@ class MaterializeViewWorkflow(PostHogWorkflow):
duration_seconds=blocked_duration_seconds,
quality_blocking_failures=staged_verdict,
quality_audited=True,
+ trino_materialized=trino_materialized,
)
storage_result: PrepareQueryableTableResult = await temporalio.workflow.execute_activity(
publish_queryable_table_activity,
@@ -422,13 +437,15 @@ class MaterializeViewWorkflow(PostHogWorkflow):
# after the main workflow succeeds, collect shadow stats for comparison
if managed_warehouse_shadow_handle is not None:
- await self._collect_shadow_comparison(
+ shadow_succeeded = await self._collect_shadow_comparison(
managed_warehouse_shadow_handle,
managed_warehouse_job_id,
materialize_result.row_count,
duration_seconds,
inputs,
)
+ if use_trino:
+ trino_materialized = shadow_succeeded
temporalio.workflow.logger.info(
"MaterializeViewWorkflow completed successfully",
@@ -455,6 +472,7 @@ class MaterializeViewWorkflow(PostHogWorkflow):
duration_seconds=duration_seconds,
quality_blocking_failures=staged_verdict,
quality_audited=quality_audited,
+ trino_materialized=trino_materialized,
)
except Exception as e:
# handle failure
@@ -510,6 +528,12 @@ class MaterializeViewWorkflow(PostHogWorkflow):
extra=inputs.properties_to_log,
)
capture_exception(shadow_err)
+ if use_trino:
+ trino_materialized = result is not None and result.error is None
+ if not trino_materialized:
+ raise temporalio.exceptions.ApplicationError(
+ result.error if result and result.error else "Trino materialization did not complete"
+ )
# The managed warehouse job is the serving job when ClickHouse did not run.
if job_id is None:
if managed_warehouse_job_id is None:
@@ -520,6 +544,7 @@ class MaterializeViewWorkflow(PostHogWorkflow):
node_id=inputs.node_id,
rows_materialized=result.row_count if result else 0,
duration_seconds=result.duration_seconds if result else 0,
+ trino_materialized=trino_materialized,
)
async def _staged_audit_verdict(
@@ -843,7 +868,7 @@ class MaterializeViewWorkflow(PostHogWorkflow):
clickhouse_row_count: int,
clickhouse_duration_seconds: float,
inputs: MaterializeViewWorkflowInputs,
- ) -> None:
+ ) -> bool:
"""Await the managed warehouse shadow activity and emit comparison metrics.
The activity itself is responsible for updating its job to a terminal state.
@@ -884,6 +909,7 @@ class MaterializeViewWorkflow(PostHogWorkflow):
**inputs.properties_to_log,
},
)
+ return shadow_result.error is None
except Exception as shadow_err:
get_managed_warehouse_shadow_finished_metrics("error").add(1)
await self._finalize_orphaned_managed_warehouse_job(managed_warehouse_job_id, inputs, str(shadow_err))
@@ -892,6 +918,7 @@ class MaterializeViewWorkflow(PostHogWorkflow):
extra=inputs.properties_to_log,
)
capture_exception(shadow_err)
+ return False
async def _finalize_orphaned_managed_warehouse_job(
self,
diff --git a/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py b/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py
index cc211b29dcd1..3faa763c7091 100644
--- a/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py
+++ b/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py
@@ -1,7 +1,9 @@
import uuid
+import asyncio
import datetime as dt
import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest_asyncio
import temporalio.worker
@@ -912,3 +914,67 @@ class TestExecuteDAGWorkflowWithMocks:
ephemeral_result = next(r for r in result.node_results if r.node_id == ephemeral_view_id)
assert ephemeral_result.success is True
assert ephemeral_result.skipped is False
+
+
+class TestTrinoDependencyOutcomes:
+ @pytest.mark.parametrize(
+ "upstream_success,downstream_enabled", [(True, True), (False, True), (None, True), (None, False)]
+ )
+ @pytest.mark.parametrize("patched", [True, False])
+ async def test_downstream_trino_waits_for_upstream_success(
+ self, upstream_success: bool | None, downstream_enabled: bool, patched: bool
+ ) -> None:
+ plan = DAGPlan(nodes=["a", "b", "c"], executable_nodes=["a", "b", "c"], edges=[("a", "b"), ("b", "c")])
+ child_inputs: list[MaterializeViewWorkflowInputs] = []
+
+ async def start_child(
+ workflow: object, inputs: MaterializeViewWorkflowInputs, **kwargs: object
+ ) -> asyncio.Future[MaterializeViewWorkflowResult]:
+ child_inputs.append(inputs)
+ future = asyncio.get_running_loop().create_future()
+ future.set_result(
+ MaterializeViewWorkflowResult(
+ job_id=f"job-{inputs.node_id}",
+ node_id=inputs.node_id,
+ rows_materialized=10,
+ duration_seconds=1,
+ trino_materialized=upstream_success
+ if inputs.node_id == "a"
+ else (not inputs.skip_trino if downstream_enabled else None),
+ )
+ )
+ return future
+
+ async def execute_activity(fn: object, *args: object, **kwargs: object) -> DAGPlan | None:
+ if fn == get_dag_structure_activity:
+ return plan
+ return None
+
+ info = MagicMock()
+ with (
+ patch.object(
+ temporal_workflow, "execute_activity", new=AsyncMock(side_effect=execute_activity)
+ ) as activities,
+ patch.object(temporal_workflow, "start_child_workflow", new=AsyncMock(side_effect=start_child)),
+ patch.object(temporal_workflow, "patched", return_value=patched),
+ patch.object(temporal_workflow, "now", return_value=dt.datetime(2026, 1, 1, tzinfo=dt.UTC)),
+ patch.object(temporal_workflow, "info", return_value=info),
+ patch.object(temporal_workflow, "metric_meter", return_value=MagicMock()),
+ patch.object(temporal_workflow, "logger"),
+ ):
+ result = await ExecuteDAGWorkflow().run(ExecuteDAGInputs(team_id=7, dag_id="dag"))
+
+ assert result.successful_nodes == 3
+ assert [i.node_id for i in child_inputs] == ["a", "b", "c"]
+ blocked = patched and upstream_success is not True
+ assert [i.skip_trino for i in child_inputs] == [False, blocked, blocked]
+ skips = [
+ c.args[1]
+ for c in activities.await_args_list
+ if getattr(c.args[0], "__name__", "") == "record_skipped_data_modeling_jobs_activity"
+ ]
+ if blocked and downstream_enabled:
+ assert skips[0].engine == "managed_warehouse"
+ assert [n.node_id for n in skips[0].skipped_nodes] == ["b", "c"]
+ else:
+ assert not skips
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
index 5904cbefd0f7..9c77daa408c2 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -65,6 +65,7 @@ from products.data_modeling.backend.facade.models import (
NodeType,
)
from products.data_warehouse.backend.facade.api import CreateTableResult
+from products.managed_warehouse.backend.facade.contracts import DuckLakeTableResult
from products.notifications.backend.facade.api import NotificationType, Priority, TargetType
from products.warehouse_sources.backend.facade.hooks import (
AccountPropertySourceProjection,
@@ -102,6 +103,71 @@ async def _make_job(
class TestMaterializeViewManagedWarehouseActivity:
+ @pytest.mark.parametrize(
+ "stale,alias_dispatch_fails",
+ [(False, False), (True, False), (False, True)],
+ )
+ async def test_trino_shadow_records_result_without_recompiling(
+ self,
+ activity_environment,
+ ateam,
+ anode,
+ ajob,
+ adag,
+ asaved_query,
+ stale: bool,
+ alias_dispatch_fails: bool,
+ ) -> None:
+ inputs = ManagedWarehouseShadowInputs(
+ team_id=ateam.pk,
+ node_id=str(anode.id),
+ dag_id=str(adag.id),
+ job_id=str(ajob.id),
+ dangerously_execute_raw_sql=True,
+ use_trino=True,
+ )
+ asaved_query.origin = DataWarehouseSavedQuery.Origin.ENDPOINT
+ await database_sync_to_async(asaved_query.save)(update_fields=["origin"])
+ executable_query = {"kind": "HogQLQuery", "query": "SELECT 2"}
+ with (
+ unittest.mock.patch(
+ "products.managed_warehouse.backend.facade.client.request_model_alias_reconciliation",
+ side_effect=RuntimeError("Temporal unavailable") if alias_dispatch_fails else None,
+ ) as reconcile_aliases,
+ 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,
+ ) as execute,
+ unittest.mock.patch(
+ "products.managed_warehouse.backend.facade.client.execute_ducklake_create_table"
+ ) as legacy_execute,
+ unittest.mock.patch(
+ "posthog.temporal.data_modeling.activities.materialize_view_managed_warehouse.prepare_executable_query",
+ side_effect=lambda saved_query: setattr(saved_query, "query", executable_query),
+ ),
+ ):
+ result = await activity_environment.run(materialize_view_managed_warehouse_activity, inputs)
+
+ execute.assert_called_once_with(
+ organization_id=str(ateam.organization_id),
+ team_id=ateam.pk,
+ saved_query_id=asaved_query.id,
+ source_query=executable_query,
+ )
+ legacy_execute.assert_not_called()
+ await database_sync_to_async(ajob.refresh_from_db)()
+ if stale:
+ reconcile_aliases.assert_not_awaited()
+ assert result.error == "No current Trino conversion"
+ assert ajob.status == DataModelingJobStatus.FAILED
+ else:
+ reconcile_aliases.assert_awaited_once_with(ateam.pk, str(asaved_query.id))
+ assert result.row_count == 12
+ assert result.error is None
+ assert ajob.status == DataModelingJobStatus.COMPLETED
+ assert ajob.rows_materialized == 12
+
async def test_records_failure_against_the_job_engine(self, activity_environment, ateam, anode, ajob, adag):
ajob.engine = DataModelingJobEngine.LEGACY_DUCKGRES
await database_sync_to_async(ajob.save)(update_fields=["engine"])
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
index f04bff7f7101..fff433f52a02 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
@@ -1,3 +1,4 @@
+import asyncio
import datetime as dt
import dataclasses
from collections.abc import Callable
@@ -12,6 +13,7 @@ from temporalio.exceptions import CancelledError, ChildWorkflowError, WorkflowAl
from posthog.temporal.data_modeling.activities import (
FailMaterializationInputs,
ManagedWarehouseShadowEligibilityInputs,
+ ManagedWarehouseShadowResult,
MaterializeViewResult,
PrepareQueryableTableResult,
StageQueryableFilesResult,
@@ -22,6 +24,7 @@ from posthog.temporal.data_modeling.activities.enrich_view_semantics import Enri
from posthog.temporal.data_modeling.workflows.materialize_view import (
ACCOUNT_PROPERTY_S3_SYNC_PATCH,
ACCOUNT_PROPERTY_STAGING_WORKFLOW_PATCH,
+ TRINO_SHADOW_EXECUTION_PATCH,
MaterializeViewWorkflow,
MaterializeViewWorkflowInputs,
)
@@ -61,6 +64,7 @@ class TestQualityGateBranching:
patched: bool | Callable[[str], bool] = True,
shadow_handle: AsyncMock | None = None,
start_child: AsyncMock | None = None,
+ inputs: MaterializeViewWorkflowInputs | None = None,
) -> tuple:
execute_activity = AsyncMock(side_effect=activity_results)
child = (
@@ -103,9 +107,66 @@ class TestQualityGateBranching:
"get_managed_warehouse_shadow_storage_delta_mib_metrics",
):
stack.enter_context(patch(f"{WORKFLOW_MODULE}.{metric}"))
- result = await MaterializeViewWorkflow().run(_inputs())
+ result = await MaterializeViewWorkflow().run(inputs or _inputs())
return result, execute_activity
+ @pytest.mark.parametrize("shadow_error,blocked", [(None, False), ("Upstream write failed", False), (None, True)])
+ async def test_shadow_outcome_is_independent_of_clickhouse_success(
+ self, shadow_error: str | None, blocked: bool
+ ) -> None:
+ shadow = asyncio.get_running_loop().create_future()
+ shadow.set_result(
+ ManagedWarehouseShadowResult(
+ row_count=10,
+ duration_seconds=1,
+ schema_name="models",
+ table_name="orders",
+ error=shadow_error,
+ )
+ )
+ activity_results = [
+ True,
+ "shadow-job",
+ "job-1",
+ _materialize_result("skip"),
+ PrepareQueryableTableResult(storage_delta_mib=None, total_storage_mib=None),
+ None,
+ None,
+ ]
+ if blocked:
+ activity_results.pop(1)
+ with patch.object(temporalio.workflow, "start_activity", return_value=shadow) as start_shadow:
+ result, _ = await self._run(activity_results, {}, inputs=dataclasses.replace(_inputs(), skip_trino=blocked))
+ assert start_shadow.called is not blocked
+ assert result.job_id == "job-1"
+ assert result.rows_materialized == 10
+ assert result.trino_materialized is (not blocked and shadow_error is None)
+
+ @pytest.mark.parametrize("shadow_error", [None, "Trino write failed"])
+ async def test_trino_only_reports_materialization_failure(self, shadow_error: str | None) -> None:
+ shadow = asyncio.get_running_loop().create_future()
+ shadow.set_result(
+ ManagedWarehouseShadowResult(
+ row_count=10,
+ duration_seconds=1,
+ schema_name="models",
+ table_name="orders",
+ error=shadow_error,
+ )
+ )
+ with patch.object(temporalio.workflow, "start_activity", return_value=shadow):
+ if shadow_error:
+ with pytest.raises(temporalio.exceptions.ApplicationError, match="Trino write failed"):
+ await self._run(
+ [True, "shadow-job"], {}, inputs=dataclasses.replace(_inputs(), managed_warehouse_only=True)
+ )
+ else:
+ result, _ = await self._run(
+ [True, "shadow-job"], {}, inputs=dataclasses.replace(_inputs(), managed_warehouse_only=True)
+ )
+ assert result.trino_materialized is True
+ assert result.job_id == "shadow-job"
+
async def test_blocking_failures_stop_the_publish(self):
activity_results = [
False, # managed warehouse shadow check
@@ -308,7 +369,8 @@ class TestQualityGateBranching:
assert result.quality_audited is expected_audited
assert result.quality_blocking_failures is None
- async def test_a_blocked_publish_still_settles_the_managed_warehouse_shadow(self):
+ @pytest.mark.parametrize("trino_patch", [False, True])
+ async def test_a_blocked_publish_still_settles_the_managed_warehouse_shadow(self, trino_patch: bool):
# The blocked branch returns early. Leaving the shadow activity unawaited holds the parent
# DAG's concurrency slot and orphans the shadow job.
shadow_handle = AsyncMock()
@@ -322,14 +384,20 @@ class TestQualityGateBranching:
None, # quality_block_materialization
]
- with patch.object(MaterializeViewWorkflow, "_collect_shadow_comparison", new=AsyncMock()) as collect:
+ with (
+ patch.object(MaterializeViewWorkflow, "_collect_shadow_comparison", new=AsyncMock()) as collect,
+ patch.object(temporalio.workflow, "start_activity", return_value=shadow_handle) as start_shadow,
+ ):
result, execute_activity = await self._run(
- activity_results, {"checks_failed_blocking": 1}, shadow_handle=shadow_handle
+ activity_results,
+ {"checks_failed_blocking": 1},
+ patched=lambda name: trino_patch if name == TRINO_SHADOW_EXECUTION_PATCH else True,
)
assert result.quality_blocking_failures == 1
assert execute_activity.await_args_list[1].args[1].engine == DataModelingJobEngine.MANAGED_WAREHOUSE
collect.assert_awaited_once()
+ assert start_shadow.call_args.args[1].use_trino is trino_patch
def _cancelled_child_error() -> ChildWorkflowError:
diff --git a/products/managed_warehouse/backend/facade/api.py b/products/managed_warehouse/backend/facade/api.py
index de60c15b3401..fe66ca4dd5af 100644
--- a/products/managed_warehouse/backend/facade/api.py
+++ b/products/managed_warehouse/backend/facade/api.py
@@ -42,6 +42,8 @@ __all__ = [
"duckgres_data_imports_schema",
"duckgres_data_imports_table_name",
"duckgres_data_modeling_schema",
+ "ducklake_data_modeling_schema",
+ "get_data_modeling_table_name",
"get_catalog_connection_config",
"get_control_plane_bucket",
"get_duckgres_query_server_config",
@@ -242,6 +244,18 @@ def duckgres_data_modeling_schema(team_id: int) -> str:
return common.duckgres_data_modeling_schema(team_id)
+def ducklake_data_modeling_schema(team_id: int) -> str:
+ return common.ducklake_data_modeling_schema(team_id)
+
+
+def get_data_modeling_table_name(team_id: int, saved_query_id: UUID) -> str:
+ from products.managed_warehouse.backend.table_binding import (
+ get_data_modeling_table_names, # noqa: PLC0415 -- defer compiler dependencies until model resolution
+ )
+
+ return get_data_modeling_table_names(team_id, [saved_query_id])[saved_query_id]
+
+
def validate_schema_name(name: str | None) -> str | None:
return common.validate_schema_name(name)
diff --git a/products/managed_warehouse/backend/facade/client.py b/products/managed_warehouse/backend/facade/client.py
index 424b74249de4..54d09b2c1467 100644
--- a/products/managed_warehouse/backend/facade/client.py
+++ b/products/managed_warehouse/backend/facade/client.py
@@ -15,6 +15,7 @@ from __future__ import annotations
from collections.abc import Sequence
from contextlib import AbstractContextManager
from typing import TYPE_CHECKING
+from uuid import UUID
from products.managed_warehouse.backend import client
from products.managed_warehouse.backend.facade.contracts import (
@@ -50,6 +51,7 @@ if TYPE_CHECKING:
from products.managed_warehouse.backend.trino_compiler import PreparedTrinoCompiler
__all__ = [
+ "request_model_alias_reconciliation",
"ServiceCredential",
"ServiceCredentialUnavailable",
"ManagedWarehouseTrinoConnectionUnavailable",
@@ -58,6 +60,8 @@ __all__ = [
"connect_managed_warehouse_trino",
"execute_ducklake_create_table",
"execute_ducklake_query",
+ "execute_trino_shadow_materialization",
+ "execute_trino_model",
"make_duckgres_conninfo",
"mint_service_credential",
"prepare_hogql_to_trino_compiler",
@@ -82,6 +86,25 @@ def connect_managed_warehouse_trino(organization_id: str) -> AbstractContextMana
return _connect_managed_warehouse_trino(organization_id)
+def execute_trino_shadow_materialization(
+ *,
+ organization_id: str,
+ team_id: int,
+ saved_query_id: str | UUID,
+ source_query: object,
+) -> DuckLakeTableResult:
+ from products.managed_warehouse.backend.trino_materialization import ( # noqa: PLC0415 -- keeps the optional Trino driver off startup paths
+ execute_trino_shadow_materialization as execute_shadow,
+ )
+
+ return execute_shadow(
+ organization_id=organization_id,
+ team_id=team_id,
+ saved_query_id=saved_query_id,
+ source_query=source_query,
+ )
+
+
def compile_hogql_to_trino_sql(
team_id: int,
query: HogQLQuery,
@@ -198,3 +221,30 @@ def execute_ducklake_create_table(
organization_id=organization_id,
s3_secrets=s3_secrets,
)
+
+
+async def request_model_alias_reconciliation(team_id: int, saved_query_id: str | None = None) -> None:
+ from products.managed_warehouse.backend.model_alias_dispatch import request_model_alias_reconciliation as request
+
+ await request(team_id, saved_query_id)
+
+
+async def execute_trino_model(
+ *, organization_id: str, team_id: int, saved_query_id: str | UUID, source_query: object
+) -> DuckLakeTableResult:
+ from products.managed_warehouse.backend.trino_execution import ( # noqa: PLC0415 -- keeps executor creation off startup paths
+ run_trino_model,
+ )
+ from products.managed_warehouse.backend.trino_materialization import ( # noqa: PLC0415 -- keeps the optional Trino driver off startup paths
+ execute_trino_shadow_materialization,
+ )
+
+ return await run_trino_model(
+ lambda control: execute_trino_shadow_materialization(
+ organization_id=organization_id,
+ team_id=team_id,
+ saved_query_id=saved_query_id,
+ source_query=source_query,
+ control=control,
+ ),
+ )
diff --git a/products/managed_warehouse/backend/facade/feature_flags.py b/products/managed_warehouse/backend/facade/feature_flags.py
index 35f67af6f102..a9c75da10769 100644
--- a/products/managed_warehouse/backend/facade/feature_flags.py
+++ b/products/managed_warehouse/backend/facade/feature_flags.py
@@ -1 +1,2 @@
DATA_WAREHOUSE_SCENE_FLAG = "data-warehouse-scene"
+DATA_MODELING_SHADOW_FLAG = "managed-warehouse-data-modeling-shadow"
diff --git a/products/managed_warehouse/backend/model_alias_dispatch.py b/products/managed_warehouse/backend/model_alias_dispatch.py
new file mode 100644
index 000000000000..d944aced63b5
--- /dev/null
+++ b/products/managed_warehouse/backend/model_alias_dispatch.py
@@ -0,0 +1,18 @@
+from django.conf import settings
+
+from temporalio.common import WorkflowIDConflictPolicy
+
+from posthog.temporal.common.client import async_connect
+
+
+async def request_model_alias_reconciliation(team_id: int, saved_query_id: str | None = None) -> None:
+ temporal = await async_connect()
+ await temporal.start_workflow(
+ "managed-warehouse.reconcile-model-aliases",
+ {"team_id": team_id},
+ id=f"managed-warehouse-model-aliases/{team_id}",
+ task_queue=settings.DUCKLAKE_TASK_QUEUE,
+ id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,
+ start_signal="refresh",
+ start_signal_args=[saved_query_id],
+ )
diff --git a/products/managed_warehouse/backend/table_binding.py b/products/managed_warehouse/backend/table_binding.py
index 194c84bb0ab2..7e3b7442f362 100644
--- a/products/managed_warehouse/backend/table_binding.py
+++ b/products/managed_warehouse/backend/table_binding.py
@@ -1,7 +1,9 @@
from __future__ import annotations
import logging
+from collections.abc import Sequence
from typing import TYPE_CHECKING, Any
+from uuid import UUID
from posthog.hogql.database.trino_locator import TrinoTableLocator
@@ -36,6 +38,24 @@ def bind_tables_to_ducklake(database: Any, team_id: int) -> None:
_bind_source_tables(database, team_id)
+def get_data_modeling_table_names(team_id: int, saved_query_ids: Sequence[UUID]) -> dict[UUID, str]:
+ from products.data_modeling.backend.facade.modeling import DataWarehouseModelPath
+
+ labels = {
+ saved_query_id: path[-1]
+ for saved_query_id, path in DataWarehouseModelPath.objects.filter(
+ team_id=team_id, saved_query_id__in=saved_query_ids
+ ).values_list("saved_query_id", "path")
+ if path
+ }
+ return {
+ saved_query_id: ducklake_data_modeling_table_name(
+ labels.get(saved_query_id, saved_query_id.hex), saved_query_id.hex
+ )
+ for saved_query_id in saved_query_ids
+ }
+
+
def build_trino_table_locators(
database: Any,
team_id: int,
@@ -44,7 +64,6 @@ def build_trino_table_locators(
table_names: ManagedWarehouseTableNames,
) -> dict[str, TrinoTableLocator]:
"""Build explicit Trino targets from the relations managed warehouse provisions."""
- from products.data_modeling.backend.facade.modeling import DataWarehouseModelPath
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.managed_warehouse.backend.facade import team_state as team_state_facade
from products.warehouse_sources.backend.facade.ducklake import list_ducklake_imported_tables
@@ -60,21 +79,13 @@ def build_trino_table_locators(
deleted=True
)
)
- model_labels_by_saved_query_id = {
- saved_query_id: path[-1]
- for saved_query_id, path in DataWarehouseModelPath.objects.filter(
- team_id=team_id,
- saved_query_id__in=[saved_query.id for saved_query in materialized_models],
- ).values_list("saved_query_id", "path")
- if path
- }
+ model_table_names = get_data_modeling_table_names(team_id, [saved_query.id for saved_query in materialized_models])
for saved_query in materialized_models:
if database.has_table(saved_query.name):
- model_label = model_labels_by_saved_query_id.get(saved_query.id, saved_query.id.hex)
locators[saved_query.name] = (
catalog_name,
model_schema,
- ducklake_data_modeling_table_name(model_label, saved_query.normalized_name),
+ model_table_names[saved_query.id],
)
naming_version = team_state_facade.data_imports_table_naming_version(team_id)
diff --git a/products/managed_warehouse/backend/temporal/__init__.py b/products/managed_warehouse/backend/temporal/__init__.py
index 1922b332feb5..bb9505a5e980 100644
--- a/products/managed_warehouse/backend/temporal/__init__.py
+++ b/products/managed_warehouse/backend/temporal/__init__.py
@@ -25,6 +25,10 @@ from products.managed_warehouse.backend.temporal.ducklake_register_data_imports_
ducklake_register_data_imports_gate_activity,
prepare_ducklake_data_imports_registration_activity,
)
+from products.managed_warehouse.backend.temporal.model_alias_workflow import (
+ ReconcileModelAliasesWorkflow,
+ reconcile_trino_model_aliases_activity,
+)
from products.managed_warehouse.backend.temporal.source_job_state import record_managed_warehouse_source_job_activity
from products.managed_warehouse.backend.temporal.view_translation_workflow import (
ManagedWarehouseViewTranslationWorkflow,
@@ -35,6 +39,7 @@ from products.managed_warehouse.backend.temporal.view_translation_workflow impor
)
WORKFLOWS = [
+ ReconcileModelAliasesWorkflow,
DucklakeCompactionWorkflow,
DuckLakeCopyDataImportsWorkflow,
DuckLakeCopyDataModelingWorkflow,
@@ -42,6 +47,7 @@ WORKFLOWS = [
ManagedWarehouseViewTranslationWorkflow,
]
ACTIVITIES = [
+ reconcile_trino_model_aliases_activity,
cleanup_data_imports_staging_activity,
cleanup_data_modeling_staging_activity,
cleanup_ducklake_registration_tables_activity,
diff --git a/products/managed_warehouse/backend/temporal/model_alias_workflow.py b/products/managed_warehouse/backend/temporal/model_alias_workflow.py
new file mode 100644
index 000000000000..75ca1a4898ed
--- /dev/null
+++ b/products/managed_warehouse/backend/temporal/model_alias_workflow.py
@@ -0,0 +1,149 @@
+from __future__ import annotations
+
+import datetime as dt
+
+import structlog
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy
+from temporalio.exceptions import ActivityError, CancelledError
+
+from posthog.dataclasses import frozen
+from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.heartbeat import Heartbeater
+
+from products.managed_warehouse.backend.trino_model_aliases import (
+ ModelAliasReconciliation,
+ reconcile_trino_model_aliases,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+@frozen
+class ModelAliasInputs:
+ team_id: int
+ pending_ids: tuple[str, ...] = ()
+ full_audit: bool = False
+ next_audit_at: float = 0
+ audit_interval_seconds: float = 1800
+
+
+@frozen
+class ModelAliasBatch:
+ team_id: int
+ saved_query_ids: tuple[str, ...] | None = None
+
+
+def _checkpoint() -> None:
+ if activity.is_cancelled():
+ raise CancelledError()
+ if activity.is_worker_shutdown():
+ raise RuntimeError("Worker is shutting down")
+ activity.heartbeat()
+
+
+async def reconcile_trino_model_aliases_activity(inputs: ModelAliasBatch) -> ModelAliasReconciliation:
+ from products.managed_warehouse.backend.trino_execution import TrinoQueryControl, run_trino_model
+
+ def execute(control: TrinoQueryControl) -> ModelAliasReconciliation:
+ def checkpoint() -> None:
+ control.checkpoint()
+ _checkpoint()
+
+ return reconcile_trino_model_aliases(inputs.team_id, checkpoint, inputs.saved_query_ids, control)
+
+ async with Heartbeater(details=("model_aliases", inputs.team_id)):
+ result = await run_trino_model(execute, query_seconds=5 * 60)
+ log = logger.warning if result.errors else logger.info
+ log(
+ "trino_model_aliases_reconciled",
+ team_id=inputs.team_id,
+ published=result.published,
+ removed=result.removed,
+ unchanged=result.unchanged,
+ errors=result.errors,
+ )
+ return result
+
+
[email protected](name="managed-warehouse.reconcile-model-aliases")
+class ReconcileModelAliasesWorkflow(PostHogWorkflow):
+ inputs_cls = ModelAliasInputs
+
+ def __init__(self) -> None:
+ self.pending_ids: set[str] = set()
+ self.full_audit = False
+ self.last_result = ModelAliasReconciliation()
+
+ @workflow.signal
+ def refresh(self, saved_query_id: str | None = None) -> None:
+ if saved_query_id is None or len(self.pending_ids) >= 1000:
+ self.full_audit = True
+ self.pending_ids.clear()
+ elif not self.full_audit:
+ self.pending_ids.add(saved_query_id)
+
+ @workflow.query
+ def status(self) -> ModelAliasReconciliation:
+ return self.last_result
+
+ @workflow.run
+ async def run(self, inputs: ModelAliasInputs) -> None:
+ self.pending_ids.update(inputs.pending_ids)
+ self.full_audit |= inputs.full_audit
+ interval = inputs.audit_interval_seconds
+ next_audit = inputs.next_audit_at or (workflow.now().timestamp() + interval)
+ if not self.pending_ids and not inputs.next_audit_at:
+ self.full_audit = True
+ for _ in range(100):
+ if not self.pending_ids and not self.full_audit:
+ try:
+ await workflow.wait_condition(
+ lambda: bool(self.pending_ids) or self.full_audit,
+ timeout=dt.timedelta(seconds=max(0, next_audit - workflow.now().timestamp())),
+ )
+ except TimeoutError:
+ self.full_audit = True
+ # Batch bursts before snapshotting IDs; signals during the activity stay queued for the next pass.
+ await workflow.sleep(dt.timedelta(seconds=30))
+ audit = self.full_audit or workflow.now().timestamp() >= next_audit
+ batch = None if audit else tuple(sorted(self.pending_ids)[:100])
+ if audit:
+ self.pending_ids.clear()
+ self.full_audit = False
+ else:
+ self.pending_ids.difference_update(batch or ())
+ try:
+ self.last_result = await workflow.execute_activity(
+ reconcile_trino_model_aliases_activity,
+ ModelAliasBatch(team_id=inputs.team_id, saved_query_ids=batch),
+ start_to_close_timeout=dt.timedelta(minutes=10),
+ heartbeat_timeout=dt.timedelta(minutes=2),
+ cancellation_type=workflow.ActivityCancellationType.WAIT_CANCELLATION_COMPLETED,
+ retry_policy=RetryPolicy(maximum_attempts=3, initial_interval=dt.timedelta(seconds=10)),
+ )
+ if not self.last_result.active and not self.pending_ids and not self.full_audit:
+ return
+ except ActivityError as error:
+ if isinstance(error.cause, CancelledError):
+ raise error.cause
+ self.last_result = ModelAliasReconciliation(errors=(str(error.cause or error)[:1000],))
+ self.full_audit |= audit
+ self.pending_ids.update(batch or ())
+ workflow.logger.warning("Trino model alias reconciliation failed", extra={"team_id": inputs.team_id})
+ if audit:
+ unchanged = not (self.last_result.published or self.last_result.removed or self.last_result.errors)
+ interval = min(interval * 2, 7200) if unchanged else 1800
+ next_audit = workflow.now().timestamp() + interval * workflow.random().uniform(0.8, 1.2)
+ if self.last_result.errors:
+ await workflow.sleep(dt.timedelta(seconds=workflow.random().uniform(60, 120)))
+ workflow.continue_as_new(
+ ModelAliasInputs(
+ team_id=inputs.team_id,
+ pending_ids=tuple(sorted(self.pending_ids)),
+ full_audit=self.full_audit,
+ next_audit_at=next_audit,
+ audit_interval_seconds=interval,
+ )
+ )
diff --git a/products/managed_warehouse/backend/tests/temporal/test_model_alias_workflow.py b/products/managed_warehouse/backend/tests/temporal/test_model_alias_workflow.py
new file mode 100644
index 000000000000..df3a254a69c8
--- /dev/null
+++ b/products/managed_warehouse/backend/tests/temporal/test_model_alias_workflow.py
@@ -0,0 +1,117 @@
+import asyncio
+import datetime as dt
+from uuid import uuid4
+
+import pytest
+from unittest.mock import AsyncMock, patch
+
+from temporalio import activity
+from temporalio.exceptions import ApplicationError
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+
+from products.managed_warehouse.backend.model_alias_dispatch import request_model_alias_reconciliation
+from products.managed_warehouse.backend.temporal.model_alias_workflow import (
+ ModelAliasBatch,
+ ModelAliasInputs,
+ ReconcileModelAliasesWorkflow,
+)
+from products.managed_warehouse.backend.trino_model_aliases import ModelAliasReconciliation
+
+
+async def test_dispatch_coalesces_builds_into_one_team_workflow() -> None:
+ client = AsyncMock()
+ with patch("products.managed_warehouse.backend.model_alias_dispatch.async_connect", return_value=client):
+ await request_model_alias_reconciliation(42, "12345678-1234-5678-1234-567812345678")
+ args = client.start_workflow.call_args
+ assert args.args == ("managed-warehouse.reconcile-model-aliases", {"team_id": 42})
+ assert args.kwargs["id"] == "managed-warehouse-model-aliases/42"
+ assert args.kwargs["start_signal"] == "refresh"
+ assert args.kwargs["start_signal_args"] == ["12345678-1234-5678-1234-567812345678"]
+
+
[email protected]("first_pass_fails", [True, False])
+async def test_refresh_during_failed_or_empty_pass_is_processed_afterwards(first_pass_fails: bool) -> None:
+ entered: asyncio.Queue[int] = asyncio.Queue()
+ releases = [asyncio.Event(), asyncio.Event(), asyncio.Event()]
+ calls = 0
+
+ @activity.defn(name="reconcile_trino_model_aliases_activity")
+ async def reconcile(inputs: ModelAliasBatch) -> ModelAliasReconciliation:
+ nonlocal calls
+ attempt = calls
+ calls += 1
+ await entered.put(attempt)
+ await releases[attempt].wait()
+ if attempt == 0 and first_pass_fails:
+ raise ApplicationError("Catalog temporarily unavailable", non_retryable=True)
+ return ModelAliasReconciliation(published=1, active=attempt == 1)
+
+ async with await WorkflowEnvironment.start_time_skipping() as environment:
+ queue = f"model-alias-test-{uuid4()}"
+ async with Worker(
+ environment.client,
+ task_queue=queue,
+ workflows=[ReconcileModelAliasesWorkflow],
+ activities=[reconcile],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ handle = await environment.client.start_workflow(
+ ReconcileModelAliasesWorkflow.run,
+ ModelAliasInputs(team_id=42),
+ id=f"model-alias-{uuid4()}",
+ task_queue=queue,
+ execution_timeout=dt.timedelta(minutes=10),
+ )
+ result_task = asyncio.create_task(handle.result())
+ try:
+ assert await asyncio.wait_for(entered.get(), timeout=10) == 0
+ await handle.signal(ReconcileModelAliasesWorkflow.refresh)
+ assert calls == 1
+ releases[0].set()
+ assert await asyncio.wait_for(entered.get(), timeout=10) == 1
+ assert bool((await handle.query(ReconcileModelAliasesWorkflow.status)).errors) == first_pass_fails
+ await handle.signal(ReconcileModelAliasesWorkflow.refresh)
+ releases[1].set()
+ assert await asyncio.wait_for(entered.get(), timeout=10) == 2
+ assert await handle.query(ReconcileModelAliasesWorkflow.status) == ModelAliasReconciliation(published=1)
+ releases[2].set()
+ await asyncio.wait_for(result_task, timeout=10)
+ finally:
+ for release in releases:
+ release.set()
+ if not result_task.done():
+ await handle.cancel()
+ await asyncio.gather(result_task, return_exceptions=True)
+
+
+async def test_batches_large_refresh_and_stops_when_team_becomes_inactive() -> None:
+ batches: list[tuple[str, ...] | None] = []
+
+ @activity.defn(name="reconcile_trino_model_aliases_activity")
+ async def reconcile(inputs: ModelAliasBatch) -> ModelAliasReconciliation:
+ batches.append(inputs.saved_query_ids)
+ return ModelAliasReconciliation(active=len(batches) < 3)
+
+ ids = tuple(str(uuid4()) for _ in range(201))
+ async with await WorkflowEnvironment.start_time_skipping() as environment:
+ queue = f"model-alias-test-{uuid4()}"
+ async with Worker(
+ environment.client,
+ task_queue=queue,
+ workflows=[ReconcileModelAliasesWorkflow],
+ activities=[reconcile],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ await environment.client.execute_workflow(
+ ReconcileModelAliasesWorkflow.run,
+ ModelAliasInputs(team_id=42, pending_ids=ids),
+ id=f"model-alias-{uuid4()}",
+ task_queue=queue,
+ execution_timeout=dt.timedelta(minutes=10),
+ )
+ assert [len(batch or ()) for batch in batches] == [100, 100, 1]
+ assert sorted(item for batch in batches for item in batch or ()) == sorted(ids)
diff --git a/products/managed_warehouse/backend/tests/test_trino_execution.py b/products/managed_warehouse/backend/tests/test_trino_execution.py
new file mode 100644
index 000000000000..980917d7bbc8
--- /dev/null
+++ b/products/managed_warehouse/backend/tests/test_trino_execution.py
@@ -0,0 +1,58 @@
+import asyncio
+import threading
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from products.managed_warehouse.backend import trino_execution as execution
+
+
[email protected]("deadline_expired", [False, True])
+async def test_cancellation_reaches_cursor_and_waits_for_cleanup(deadline_expired: bool) -> None:
+ loop = asyncio.get_running_loop()
+ entered = asyncio.Event()
+ canceled = asyncio.Event()
+ stopped = threading.Event()
+ cleanup = threading.Event()
+ cursor = MagicMock()
+ timeout = asyncio.timeout(None)
+
+ def cancel() -> None:
+ stopped.set()
+ loop.call_soon_threadsafe(canceled.set)
+
+ cursor.cancel.side_effect = cancel
+
+ def execute(control: execution.TrinoQueryControl) -> int:
+ control.attach(cursor)
+ loop.call_soon_threadsafe(entered.set)
+ assert stopped.wait(10)
+ assert cleanup.wait(10)
+ return 1
+
+ with patch.object(execution.asyncio, "timeout", return_value=timeout):
+ task = asyncio.create_task(execution.run_trino_model(execute))
+ try:
+ await asyncio.wait_for(entered.wait(), timeout=10)
+ if deadline_expired:
+ timeout.reschedule(loop.time())
+ else:
+ task.cancel()
+ await asyncio.wait_for(canceled.wait(), timeout=10)
+ assert not task.done()
+ cleanup.set()
+ with pytest.raises(TimeoutError if deadline_expired else asyncio.CancelledError):
+ await task
+ cursor.cancel.assert_called()
+ finally:
+ stopped.set()
+ cleanup.set()
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+
+
+async def test_success_preserves_result() -> None:
+ assert await execution.run_trino_model(lambda control: 42) == 42
diff --git a/products/managed_warehouse/backend/tests/test_trino_materialization.py b/products/managed_warehouse/backend/tests/test_trino_materialization.py
new file mode 100644
index 000000000000..46a18c5bdc18
--- /dev/null
+++ b/products/managed_warehouse/backend/tests/test_trino_materialization.py
@@ -0,0 +1,150 @@
+from uuid import UUID, uuid4
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.models import Team
+
+from products.data_modeling.backend.facade.modeling import DataWarehouseModelPath
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from 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.models import (
+ ManagedWarehouseViewTranslationJob,
+ ManagedWarehouseViewTranslationResult,
+)
+from products.managed_warehouse.backend.table_binding import build_trino_table_locators
+from products.managed_warehouse.backend.view_translation_status import source_query_hash
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable
+
+
+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.connection = MagicMock(catalog='org_"catalog')
+ self.cursor = self.connection.cursor.return_value
+ self.cursor.rowcount = 12
+
+ def execute(self, *, team_id: int | None = None, organization_id: str | None = None) -> DuckLakeTableResult:
+ return execute_trino_shadow_materialization(
+ organization_id=organization_id or str(self.organization.pk),
+ team_id=team_id or self.team.pk,
+ saved_query_id=self.saved_query_id,
+ source_query=self.query,
+ )
+
+ @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,
+ )
+ 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:
+ connect.return_value.__enter__.return_value = self.connection
+ if fail_write:
+ with self.assertRaisesRegex(RuntimeError, "Trino write failed"):
+ self.execute()
+ else:
+ result = self.execute()
+ assert result.row_count == 12
+ assert result.schema_name == f"posthog_data_modeling_team_{self.team.pk}"
+ assert result.table_name == f"model_{self.saved_query_id.hex}"
+
+ connect.assert_called_once_with(str(self.organization.pk))
+ assert self.cursor.execute.call_args_list[1].args == (
+ f'CREATE SCHEMA IF NOT EXISTS "org_""catalog"."posthog_data_modeling_team_{self.team.pk}"',
+ )
+ assert self.cursor.execute.call_args_list[2].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',
+ ["example' OR 1=1 --"],
+ )
+ assert self.cursor.execute.call_args_list[0].args == ("SET SESSION query_max_run_time = '15m'",)
+ 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,
+ )
+ connect.assert_not_called()
+
+ @parameterized.expand([(None,), ("legacy_orders",)])
+ def test_materialized_dependency_matches_downstream_locator(self, model_label: str | None) -> None:
+
+ backing_table = DataWarehouseTable.objects.create(
+ team=self.team, name="orders", format="Parquet", url_pattern="https://example.com/orders/*.parquet"
+ )
+ saved_query = DataWarehouseSavedQuery.objects.create(
+ id=self.saved_query_id,
+ team=self.team,
+ name="orders",
+ query=self.query,
+ is_materialized=True,
+ table=backing_table,
+ )
+ 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:
+ connect.return_value.__enter__.return_value = self.connection
+ written = self.execute()
+ database = MagicMock()
+ with patch("products.managed_warehouse.backend.team_state.cp_teams.list_org_teams", return_value=[]):
+ locators = build_trino_table_locators(
+ database,
+ self.team.pk,
+ catalog_name=self.connection.catalog,
+ table_names=ManagedWarehouseTableNames(
+ events_table="events", persons_table="persons", data_imports_schema="imports"
+ ),
+ )
+ assert locators["orders"] == (self.connection.catalog, written.schema_name, written.table_name)
+ assert written.table_name == (model_label or f"model_{self.saved_query_id.hex}")
diff --git a/products/managed_warehouse/backend/tests/test_trino_model_aliases.py b/products/managed_warehouse/backend/tests/test_trino_model_aliases.py
new file mode 100644
index 000000000000..b8b251fad659
--- /dev/null
+++ b/products/managed_warehouse/backend/tests/test_trino_model_aliases.py
@@ -0,0 +1,196 @@
+import re
+from uuid import UUID
+
+import pytest
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from posthog.models import Team
+
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.managed_warehouse.backend.trino_model_aliases import (
+ ModelAlias,
+ ModelAliasPublisher,
+ ModelAliasReconciliation,
+ reconcile_trino_model_aliases,
+)
+
+MODEL_ID = UUID("12345678-1234-5678-1234-567812345678")
+OTHER_ID = UUID("abcdefab-1234-5678-1234-567812345678")
+TABLE = f"model_{MODEL_ID.hex}"
+SCHEMA = '"catalog"."posthog_data_modeling_team_42"'
+
+
+def reconcile(
+ models: list[ModelAlias],
+ *,
+ relations: list[tuple[str, str]] | None = None,
+ comments: list[tuple[str, str]] | None = None,
+ columns: list[tuple[str, str, str]] | None = None,
+) -> tuple[MagicMock, ModelAliasReconciliation]:
+ cursor = MagicMock()
+ cursor.fetchall.side_effect = [
+ relations if relations is not None else [(TABLE, "BASE TABLE")],
+ comments or [],
+ columns if columns is not None else [(TABLE, "amount", "bigint")],
+ *([[]] * 10),
+ ]
+ result = ModelAliasPublisher(cursor, "catalog", 42, lambda: None).reconcile(models)
+ return cursor, result
+
+
+def alias(name: str = "daily_revenue") -> ModelAlias:
+ return ModelAlias(saved_query_id=MODEL_ID, name=name, table_name=TABLE)
+
+
+def published_comment() -> str:
+ cursor, _ = reconcile([alias()])
+ match = re.search("COMMENT '([^']+)'", cursor.execute.call_args_list[-1].args[0])
+ assert match
+ return match.group(1)
+
+
[email protected]("name", ["daily_revenue", 'reporting.daily_"revenue', "select"])
+def test_publishes_quoted_invoker_view_without_rewriting_physical_tables(name: str) -> None:
+ cursor, result = reconcile([alias(name)])
+ sql = cursor.execute.call_args_list[-1].args[0]
+ escaped = name.replace('"', '""')
+ assert sql.startswith(f'CREATE VIEW {SCHEMA}."{escaped}" COMMENT ')
+ assert sql.endswith(f'SECURITY INVOKER AS SELECT * FROM {SCHEMA}."{TABLE}"')
+ assert result.published == 1
+ assert result.errors == ()
+
+
[email protected]("change", ["none", "columns", "rename", "delete", "missing_table"])
+def test_reconciles_published_alias_lifecycle(change: str) -> None:
+ models = [] if change == "delete" else [alias("daily_sales" if change == "rename" else "daily_revenue")]
+ relations = [(TABLE, "BASE TABLE"), ("daily_revenue", "VIEW")]
+ if change == "missing_table":
+ relations = [("daily_revenue", "VIEW")]
+ cursor, result = reconcile(
+ models,
+ relations=relations,
+ comments=[("daily_revenue", published_comment())],
+ columns=[(TABLE, "amount", "double" if change == "columns" else "bigint")],
+ )
+ statements = [call.args[0] for call in cursor.execute.call_args_list[3:]]
+ if change == "none":
+ assert statements == []
+ assert result.unchanged == 1
+ elif change == "columns":
+ assert len(statements) == 1
+ assert statements[0].startswith(f'CREATE OR REPLACE VIEW {SCHEMA}."daily_revenue" ')
+ else:
+ assert statements[0] == f'DROP VIEW IF EXISTS {SCHEMA}."daily_revenue"'
+ assert result.removed == 1
+ if change == "rename":
+ assert statements[1].startswith(f'CREATE VIEW {SCHEMA}."daily_sales" ')
+ else:
+ assert len(statements) == 1
+
+
[email protected]("conflict", ["table", "view", "other_team", "duplicate", "reserved_physical"])
+def test_does_not_overwrite_conflicting_relations(conflict: str) -> None:
+ models = [alias()]
+ relations = [(TABLE, "BASE TABLE")]
+ comments = []
+ if conflict in {"table", "view", "other_team"}:
+ relations.append(("daily_revenue", "BASE TABLE" if conflict == "table" else "VIEW"))
+ comments = [("daily_revenue", "posthog:model-alias:99:unrelated")]
+ else:
+ models.append(
+ ModelAlias(
+ saved_query_id=OTHER_ID,
+ name="daily_revenue" if conflict == "duplicate" else "other_model",
+ table_name="other_table" if conflict == "duplicate" else "daily_revenue",
+ )
+ )
+ cursor, result = reconcile(models, relations=relations, comments=comments)
+ assert len(cursor.execute.call_args_list) == 3
+ assert result.errors
+ assert result.published == 0
+
+
+def test_legacy_physical_name_already_serves_as_logical_name() -> None:
+ cursor, result = reconcile([alias(TABLE)])
+ assert len(cursor.execute.call_args_list) == 3
+ assert result.errors == ()
+
+
+class TestModelAliasScoping(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.enterContext(
+ patch("products.managed_warehouse.backend.trino_model_aliases.is_dev_mode", return_value=False)
+ )
+
+ def test_reconciles_only_live_materialized_models_for_the_requested_team(self) -> None:
+ other_team = Team.objects.create(organization=self.organization)
+ DataWarehouseSavedQuery.objects.create(
+ team=other_team, name="Reporting.Orders", query={"query": "SELECT 1"}, is_materialized=True
+ )
+ DataWarehouseSavedQuery.objects.create(
+ id=MODEL_ID, team=self.team, name="Reporting.Orders", query={"query": "SELECT 1"}, is_materialized=True
+ )
+ DataWarehouseSavedQuery.objects.create(
+ team=self.team, name="deleted", query={"query": "SELECT 1"}, is_materialized=True, deleted=True
+ )
+ DataWarehouseSavedQuery.objects.create(
+ team=self.team, name="ephemeral", query={"query": "SELECT 1"}, is_materialized=False
+ )
+ with (
+ patch("products.managed_warehouse.backend.trino_model_aliases.connect_managed_warehouse_trino") as connect,
+ patch.object(ModelAliasPublisher, "reconcile") as publish,
+ patch("posthog.ph_client.feature_enabled_or_false", return_value=True),
+ ):
+ reconcile_trino_model_aliases(self.team.pk, lambda: None)
+ connect.assert_called_once_with(str(self.organization.id))
+ publish.assert_called_once_with([alias("reporting.orders")], None)
+
+ def test_disabled_team_stops_before_connecting(self) -> None:
+ with (
+ patch("posthog.ph_client.feature_enabled_or_false", return_value=False),
+ patch("products.managed_warehouse.backend.trino_model_aliases.connect_managed_warehouse_trino") as connect,
+ ):
+ assert reconcile_trino_model_aliases(self.team.pk, lambda: None) == ModelAliasReconciliation(active=False)
+ connect.assert_not_called()
+
+ def test_empty_team_cleans_up_owned_aliases_then_stops(self) -> None:
+ with (
+ patch("posthog.ph_client.feature_enabled_or_false", return_value=True),
+ patch("products.managed_warehouse.backend.trino_model_aliases.connect_managed_warehouse_trino") as connect,
+ ):
+ cursor = connect.return_value.__enter__.return_value.cursor.return_value
+ cursor.fetchall.side_effect = [
+ [],
+ [("old_alias", "VIEW")],
+ [("old_alias", f"posthog:model-alias:{self.team.pk}:old")],
+ [],
+ [],
+ ]
+ assert reconcile_trino_model_aliases(self.team.pk, lambda: None) == ModelAliasReconciliation(
+ removed=1, active=False
+ )
+ assert cursor.execute.call_args_list[-1].args[0].endswith('."old_alias"')
+ assert cursor.execute.call_args_list[-1].args[0].startswith("DROP VIEW IF EXISTS ")
+
+
[email protected]("exists", [False, True])
+def test_targeted_refresh_reads_only_requested_metadata_and_leaves_other_aliases(exists: bool) -> None:
+ cursor = MagicMock()
+ cursor.fetchall.side_effect = [
+ [(TABLE, "BASE TABLE"), *(([("daily_revenue", "VIEW")]) if exists else [])],
+ *([[("daily_revenue", published_comment())]] if exists else []),
+ [("amount", "bigint", "", "")],
+ [],
+ ]
+ result = ModelAliasPublisher(cursor, "catalog", 42, lambda: None).reconcile(
+ [alias(), ModelAlias(saved_query_id=OTHER_ID, name="unrelated", table_name="other_table")], (str(MODEL_ID),)
+ )
+ statements = [call.args[0] for call in cursor.execute.call_args_list]
+ assert cursor.execute.call_args_list[0].args[1] == ["posthog_data_modeling_team_42", "daily_revenue", TABLE]
+ assert not any("information_schema.columns" in sql or "DROP VIEW" in sql for sql in statements)
+ assert f'SHOW COLUMNS FROM {SCHEMA}."{TABLE}"' in statements
+ assert (
+ result == ModelAliasReconciliation(unchanged=1) if exists else result == ModelAliasReconciliation(published=1)
+ )
diff --git a/products/managed_warehouse/backend/trino_execution.py b/products/managed_warehouse/backend/trino_execution.py
new file mode 100644
index 000000000000..5ba8235e387c
--- /dev/null
+++ b/products/managed_warehouse/backend/trino_execution.py
@@ -0,0 +1,71 @@
+from __future__ import annotations
+
+import asyncio
+import threading
+from concurrent.futures import ThreadPoolExecutor
+from time import monotonic
+from typing import TYPE_CHECKING, TypeVar
+
+from posthog.sync import database_sync_to_async_pool
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+ from trino.dbapi import Cursor
+
+_Result = TypeVar("_Result")
+
+TRINO_QUERY_SECONDS = 15 * 60
+_executor = ThreadPoolExecutor(thread_name_prefix="trino-model")
+
+
+class TrinoQueryControl:
+ def __init__(self, query_seconds: float = TRINO_QUERY_SECONDS) -> None:
+ self.cancelled = threading.Event()
+ self.finished = threading.Event()
+ self.cursor: Cursor | None = None
+ self.deadline = monotonic() + query_seconds
+
+ def checkpoint(self) -> None:
+ if self.cancelled.is_set() or monotonic() >= self.deadline:
+ raise TimeoutError("Trino model execution was canceled or exceeded its deadline")
+
+ def attach(self, cursor: Cursor) -> None:
+ self.cursor = cursor
+
+ def _cancel_until_finished(self) -> None:
+ # execute() can still be waiting for its first nextUri when cancellation arrives.
+ while not self.finished.is_set():
+ if self.cursor is not None:
+ try:
+ self.cursor.cancel()
+ except Exception:
+ pass
+ self.finished.wait(0.5)
+
+ def cancel(self) -> None:
+ if not self.cancelled.is_set():
+ self.cancelled.set()
+ threading.Thread(target=self._cancel_until_finished, name="trino-model-cancel", daemon=True).start()
+
+
+async def run_trino_model(
+ execute: Callable[[TrinoQueryControl], _Result], *, query_seconds: float = TRINO_QUERY_SECONDS
+) -> _Result:
+ control = TrinoQueryControl(query_seconds)
+ task = asyncio.create_task(database_sync_to_async_pool(execute, executor=_executor)(control))
+ try:
+ async with asyncio.timeout(query_seconds):
+ return await asyncio.shield(task)
+ except (asyncio.CancelledError, TimeoutError):
+ control.cancel()
+ while not task.done():
+ try:
+ await asyncio.shield(task)
+ except asyncio.CancelledError:
+ continue
+ except Exception:
+ break
+ raise
+ finally:
+ control.finished.set()
diff --git a/products/managed_warehouse/backend/trino_materialization.py b/products/managed_warehouse/backend/trino_materialization.py
new file mode 100644
index 000000000000..24ea815b562f
--- /dev/null
+++ b/products/managed_warehouse/backend/trino_materialization.py
@@ -0,0 +1,66 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+from uuid import UUID
+
+from posthog.hogql.escape_sql import escape_trino_identifier
+from posthog.hogql.trino_parameters import convert_pyformat_placeholders
+
+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.table_binding import get_data_modeling_table_names
+from products.managed_warehouse.backend.trino_connection import connect_managed_warehouse_trino
+from products.managed_warehouse.backend.view_translation_status import get_current_trino_translation
+
+if TYPE_CHECKING:
+ from products.managed_warehouse.backend.trino_execution import TrinoQueryControl
+
+
+def execute_trino_shadow_materialization(
+ *,
+ organization_id: str,
+ team_id: int,
+ saved_query_id: str | UUID,
+ 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 compiled is None:
+ raise ValueError("No current Trino conversion exists for this saved query. Run its translation again.")
+
+ sql, parameters = convert_pyformat_placeholders(compiled.sql, compiled.values)
+ schema_name = ducklake_data_modeling_schema(team_id)
+ query_id = UUID(str(saved_query_id))
+ table_name = get_data_modeling_table_names(team_id, [query_id])[query_id]
+ with connect_managed_warehouse_trino(organization_id) as connection:
+ schema = f"{escape_trino_identifier(connection.catalog)}.{escape_trino_identifier(schema_name)}"
+ table = f"{schema}.{escape_trino_identifier(table_name)}"
+ cursor = connection.cursor()
+ if control:
+ control.attach(cursor)
+ try:
+ if control:
+ control.checkpoint()
+ cursor.execute("SET SESSION query_max_run_time = '15m'")
+ cursor.fetchall()
+ if control:
+ control.checkpoint()
+ cursor.execute(f"CREATE SCHEMA IF NOT EXISTS {schema}")
+ cursor.fetchall()
+ if control:
+ control.checkpoint()
+ # The connector replaces the table atomically, so a failed write preserves the previous shadow.
+ cursor.execute(f"CREATE OR REPLACE TABLE {table} AS {sql}", parameters or None)
+ cursor.fetchall()
+ row_count = cursor.rowcount
+ if row_count < 0:
+ raise RuntimeError("Trino did not report the materialized row count")
+ finally:
+ cursor.close()
+
+ return DuckLakeTableResult(schema_name=schema_name, table_name=table_name, row_count=row_count)
diff --git a/products/managed_warehouse/backend/trino_model_aliases.py b/products/managed_warehouse/backend/trino_model_aliases.py
new file mode 100644
index 000000000000..7869cdc334e9
--- /dev/null
+++ b/products/managed_warehouse/backend/trino_model_aliases.py
@@ -0,0 +1,243 @@
+from __future__ import annotations
+
+import os
+import re
+import json
+import hashlib
+from collections import Counter
+from collections.abc import Callable
+from dataclasses import replace
+from typing import TYPE_CHECKING, cast
+from uuid import UUID
+
+from posthog.hogql.escape_sql import escape_trino_identifier
+
+from posthog.dataclasses import frozen
+
+from products.managed_warehouse.backend.common import ducklake_data_modeling_schema, is_dev_mode
+from products.managed_warehouse.backend.table_binding import get_data_modeling_table_names
+from products.managed_warehouse.backend.trino_connection import connect_managed_warehouse_trino
+
+if TYPE_CHECKING:
+ from trino.dbapi import Cursor
+
+ from products.managed_warehouse.backend.trino_execution import TrinoQueryControl
+
+
+@frozen
+class ModelAlias:
+ saved_query_id: UUID
+ name: str
+ table_name: str
+
+
+@frozen
+class ModelAliasReconciliation:
+ published: int = 0
+ removed: int = 0
+ unchanged: int = 0
+ errors: tuple[str, ...] = ()
+ active: bool = True
+
+
+def _load_models(team_id: int, saved_query_ids: tuple[str, ...] | None = None) -> list[ModelAlias]:
+ from django.db.models.functions import Lower
+
+ from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+
+ queryset = DataWarehouseSavedQuery.objects.filter(team_id=team_id, is_materialized=True).exclude(deleted=True)
+ if saved_query_ids is not None:
+ names = list(
+ queryset.filter(id__in=saved_query_ids)
+ .annotate(alias_name=Lower("name"))
+ .values_list("alias_name", flat=True)
+ )
+ queryset = queryset.annotate(alias_name=Lower("name")).filter(alias_name__in=names)
+ models = list(queryset.values_list("id", "name"))
+ tables = get_data_modeling_table_names(team_id, [query_id for query_id, _ in models])
+ return [
+ ModelAlias(saved_query_id=query_id, name=name.lower(), table_name=tables[query_id]) for query_id, name in models
+ ]
+
+
+class ModelAliasPublisher:
+ def __init__(self, cursor: Cursor, catalog: str, team_id: int, checkpoint: Callable[[], None]) -> None:
+ self.cursor = cursor
+ self.catalog = catalog
+ self.team_id = team_id
+ self.schema_name = ducklake_data_modeling_schema(team_id)
+ self.schema = f"{escape_trino_identifier(catalog)}.{escape_trino_identifier(self.schema_name)}"
+ self.owner_prefix = f"posthog:model-alias:{team_id}:"
+ self.checkpoint = checkpoint
+
+ def _execute(self, sql: str, parameters: list[str] | None = None) -> list[tuple[str, ...]]:
+ self.checkpoint()
+ self.cursor.execute(sql, parameters)
+ return cast(list[tuple[str, ...]], self.cursor.fetchall())
+
+ def _owned_views(self, names: set[str] | None) -> dict[str, str]:
+ owned: dict[str, str] = {}
+ if names is None:
+ return {
+ name: comment
+ for name, comment in self._execute(
+ "SELECT table_name, comment FROM system.metadata.table_comments WHERE catalog_name = ? AND schema_name = ?",
+ [self.catalog, self.schema_name],
+ )
+ if comment and comment.startswith(self.owner_prefix)
+ }
+ # Exact table predicates use Trino's point lookup; a schema-wide comments query loads every table's metadata.
+ for name in sorted(names):
+ for view_name, comment in self._execute(
+ "SELECT table_name, comment FROM system.metadata.table_comments "
+ "WHERE catalog_name = ? AND schema_name = ? AND table_name = ?",
+ [self.catalog, self.schema_name, name],
+ ):
+ if comment and comment.startswith(self.owner_prefix):
+ owned[view_name] = comment
+ return owned
+
+ def reconcile(
+ self, models: list[ModelAlias], saved_query_ids: tuple[str, ...] | None = None
+ ) -> ModelAliasReconciliation:
+ selected = (
+ models
+ if saved_query_ids is None
+ else [model for model in models if str(model.saved_query_id) in saved_query_ids]
+ )
+ target_names = {name for model in selected for name in (model.name, model.table_name)}
+ name_filter = (
+ "" if saved_query_ids is None else " AND table_name IN (" + ",".join("?" for _ in target_names) + ")"
+ )
+ if saved_query_ids is not None and not target_names:
+ return ModelAliasReconciliation()
+ relations = {
+ row[0]: row[1]
+ for row in self._execute(
+ f"SELECT table_name, table_type FROM {escape_trino_identifier(self.catalog)}.information_schema.tables "
+ f"WHERE table_schema = ?{name_filter}",
+ [self.schema_name, *sorted(target_names)] if saved_query_ids is not None else [self.schema_name],
+ )
+ }
+ if not relations:
+ return ModelAliasReconciliation()
+
+ owned = {
+ name: comment
+ for name, comment in self._owned_views(
+ None if saved_query_ids is None else {name for name, kind in relations.items() if kind == "VIEW"}
+ ).items()
+ if relations.get(name) == "VIEW"
+ }
+ columns: dict[str, list[tuple[str, str]]] = {}
+ if saved_query_ids is None:
+ for table, column, data_type in self._execute(
+ f"SELECT table_name, column_name, data_type FROM {escape_trino_identifier(self.catalog)}.information_schema.columns "
+ "WHERE table_schema = ? ORDER BY table_name, ordinal_position",
+ [self.schema_name],
+ ):
+ columns.setdefault(table, []).append((column, data_type))
+ else:
+ for model in selected:
+ if relations.get(model.table_name) != "BASE TABLE":
+ continue
+ columns[model.table_name] = [
+ (row[0], row[1])
+ for row in self._execute(
+ f"SHOW COLUMNS FROM {self.schema}.{escape_trino_identifier(model.table_name)}"
+ )
+ ]
+
+ counts = Counter(model.name for model in models)
+ physical_counts = Counter(model.table_name for model in models)
+ desired: dict[str, tuple[ModelAlias, str]] = {}
+ errors: list[str] = []
+ for model in selected:
+ if counts[model.name] > 1 or physical_counts[model.table_name] > 1:
+ errors.append(f"{model.saved_query_id}: model names collide; rename the conflicting model")
+ continue
+ if relations.get(model.table_name) != "BASE TABLE":
+ continue
+ if model.name == model.table_name:
+ continue
+ if (
+ re.fullmatch(r"model_[0-9a-f]{32}", model.name)
+ or model.name in physical_counts
+ or (model.name in relations and model.name not in owned)
+ ):
+ errors.append(f"{model.saved_query_id}: alias conflicts with an existing relation; choose another name")
+ continue
+ fingerprint = hashlib.sha256(
+ json.dumps([model.table_name, columns.get(model.table_name, [])]).encode()
+ ).hexdigest()
+ desired[model.name] = (model, f"{self.owner_prefix}{model.saved_query_id}:{fingerprint}")
+
+ removed = 0
+ stale = owned.keys() - desired.keys() if saved_query_ids is None else set()
+ for name in stale:
+ self._execute(f"DROP VIEW IF EXISTS {self.schema}.{escape_trino_identifier(name)}")
+ removed += 1
+
+ published = unchanged = 0
+ for name, (model, comment) in desired.items():
+ if owned.get(name) == comment:
+ unchanged += 1
+ continue
+ # The comment contains only generated IDs/hash; names are quoted as single identifiers.
+ replace = "OR REPLACE " if name in owned else ""
+ self._execute(
+ f"CREATE {replace}VIEW {self.schema}.{escape_trino_identifier(name)} "
+ f"COMMENT '{comment}' SECURITY INVOKER AS "
+ f"SELECT * FROM {self.schema}.{escape_trino_identifier(model.table_name)}"
+ )
+ published += 1
+
+ return ModelAliasReconciliation(
+ published=published, removed=removed, unchanged=unchanged, errors=tuple(errors[:50])
+ )
+
+
+def reconcile_trino_model_aliases(
+ team_id: int,
+ checkpoint: Callable[[], None],
+ saved_query_ids: tuple[str, ...] | None = None,
+ control: TrinoQueryControl | None = None,
+) -> ModelAliasReconciliation:
+ from posthog.models import Team
+ from posthog.ph_client import feature_enabled_or_false
+
+ from products.managed_warehouse.backend.facade.feature_flags import DATA_MODELING_SHADOW_FLAG
+
+ organization_id = Team.objects.filter(pk=team_id).values_list("organization_id", flat=True).first()
+ if organization_id is None:
+ return ModelAliasReconciliation(active=False)
+ enabled = (
+ (os.environ.get("MANAGED_WAREHOUSE_SHADOW_ENABLED", "").lower() in ("1", "true"))
+ if is_dev_mode()
+ else feature_enabled_or_false(
+ DATA_MODELING_SHADOW_FLAG,
+ str(team_id),
+ groups={"organization": str(organization_id), "project": str(team_id)},
+ group_properties={"organization": {"id": str(organization_id)}, "project": {"id": str(team_id)}},
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ )
+ if not enabled:
+ return ModelAliasReconciliation(active=False)
+ models = _load_models(team_id, saved_query_ids)
+ with connect_managed_warehouse_trino(str(organization_id)) as connection:
+ cursor = connection.cursor()
+ if control:
+ control.attach(cursor)
+ try:
+ checkpoint()
+ cursor.execute("SET SESSION query_max_run_time = '30s'")
+ cursor.fetchall()
+ publisher = ModelAliasPublisher(cursor, connection.catalog, team_id, checkpoint)
+ result = publisher.reconcile(models, saved_query_ids)
+ if saved_query_ids is None and not models:
+ return replace(result, active=False)
+ return result
+ finally:
+ cursor.close()
diff --git a/products/managed_warehouse/backend/view_translation_status.py b/products/managed_warehouse/backend/view_translation_status.py
index c6486a19cf2a..def21ec6d1f7 100644
--- a/products/managed_warehouse/backend/view_translation_status.py
+++ b/products/managed_warehouse/backend/view_translation_status.py
@@ -4,6 +4,9 @@ import json
import 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_name
@@ -13,16 +16,13 @@ def source_query_hash(query: object) -> str:
return hashlib.sha256(serialized.encode()).hexdigest()
-def is_data_modeling_shadow_ready(
+def _current_compiled_translations(
*,
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
-
+) -> QuerySet[ManagedWarehouseViewTranslationResult]:
return (
ManagedWarehouseViewTranslationResult.objects.for_team(team_id)
.filter(
@@ -33,5 +33,43 @@ def is_data_modeling_shadow_ready(
)
.exclude(trino_sql__isnull=True)
.exclude(trino_sql="")
- .exists()
)
+
+
+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()