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.

feat(hogql): populate managed warehouse trino locators (#92080)

Bill Guowei Yang70632e774972
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.md
index 0f0a4bb0d42c..74b2e79e542c 100644
--- a/docs/internal/hogql-trino-compiler.md
+++ b/docs/internal/hogql-trino-compiler.md
@@ -33,9 +33,23 @@ Trino table rendering stays in Trino-specific modules. Neither the built-in numb
After deployment, Django shell can call the same compilation API. Construct the context with the intended team, user, effective modifiers, and `Database.create_for(...)`, then supply explicit Trino locators. No new HTTP endpoint or scheduled job is required.
+For managed DuckLake data, call `compile_hogql_to_trino_sql(...)` through the managed-warehouse client facade. This explicit entry point reads the organization's ready Trino catalog from the control plane and combines it with the project's authoritative team row. It maps:
+
+- `events` and `persons` to the project's provisioned tables in the `posthog` schema;
+- materialized saved queries to their `posthog_data_modeling_team_<team_id>` DuckLake copies;
+- copied warehouse sources to their provisioned data-import schema and table names.
+
+The control-plane read accepts both `trino_catalog_name` and the earlier `catalog` field during a rolling deployment. A disabled or non-ready Trino target, an organization mismatch, a missing team row, or an unmapped relation fails compilation before SQL submission. The helper only compiles; deploying it does not change query routing or execute Trino SQL.
+
+Trino compilation currently requires `personsOnEventsMode=person_id_override_properties_on_events`. The compiler rejects unset, disabled, V1, and joined modes before semantic lowering so it cannot silently apply V2 person attribution to a query that requested different behavior.
+
+Trino compilation fails when the caller has any effective property-level access restrictions. This applies to the entire query, including queries that do not reference a restricted property directly. The compiler must not return SQL until Trino supports equivalent masking for explicit property reads, whole property blobs, and wildcard projections.
+
+The provisioned persons relation stores one row per distinct ID and can retain person snapshots from more than one export partition. Trino lowering groups direct `persons` reads by person ID and selects values from the latest person version. For V2 event queries, it reads person properties from the exported event row and resolves `person_id` through the latest exported distinct-ID mapping, falling back to the event's physical `person_id`. Managed warehouse persons exports do not include `last_seen_at`, so the compiler rejects that field instead of emitting SQL for a missing column. The DuckLake export contract, rather than the SQL printer, defines deletion behavior.
+
Source metadata describes what HogQL means. Target mappings describe where the corresponding Trino data exists. Missing mappings and unsupported constructs fail compilation; the compiler must not invent physical relations or assume a ClickHouse materialized view exists in Trino.
-`test_trino_semantics.py` exercises action expansion, cohort expansion, and lazy person joins through the compilation API without using the execution adapter. A batch export script is a separate operational tool, not part of this release.
+`test_trino_semantics.py` exercises action expansion, cohort expansion, V2 person attribution, and unsupported-mode rejection through the compilation API without using the execution adapter. A batch export script is a separate operational tool, not part of this release.
## Validation
diff --git a/posthog/hogql/database/trino_locator.py b/posthog/hogql/database/trino_locator.py
index e572c2ca22b2..36d974d43c6a 100644
--- a/posthog/hogql/database/trino_locator.py
+++ b/posthog/hogql/database/trino_locator.py
@@ -20,5 +20,5 @@ def resolve_trino_table_locator(table: Table, context: HogQLContext) -> TrinoTab
if not value.strip():
raise QueryError(f"Direct Trino tables require a {label}.")
return locator
- logical_name = table.name or table.to_printed_hogql()
+ logical_name = getattr(table, "trino_locator_name", None) or table.name or table.to_printed_hogql()
return context.trino_table_locators.get(logical_name)
diff --git a/posthog/hogql/printer/test/test_trino_printer.py b/posthog/hogql/printer/test/test_trino_printer.py
index 39b6d868fd23..51e6060a9692 100644
--- a/posthog/hogql/printer/test/test_trino_printer.py
+++ b/posthog/hogql/printer/test/test_trino_printer.py
@@ -3,6 +3,8 @@ from contextlib import closing
import pytest
+from posthog.schema import HogQLQueryModifiers
+
from posthog.hogql import ast
from posthog.hogql.constants import HogQLQuerySettings
from posthog.hogql.context import HogQLContext
@@ -16,6 +18,12 @@ from posthog.hogql.printer import prepare_and_print_ast, print_prepared_ast
from posthog.hogql.transforms.trino.errors import TrinoLoweringError
from posthog.hogql.trino_parameters import convert_pyformat_placeholders
+from posthog.schema_enums import PersonsOnEventsMode
+
+
+def _trino_modifiers() -> HogQLQueryModifiers:
+ return HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS)
+
def _context_with_trino_table() -> HogQLContext:
database = Database(include_posthog_tables=False)
@@ -39,6 +47,7 @@ def _context_with_trino_table() -> HogQLContext:
)
return HogQLContext(
database=database,
+ modifiers=_trino_modifiers(),
enable_select_queries=True,
limit_top_select=False,
restricted_properties=set(),
@@ -80,6 +89,7 @@ def test_uses_trino_arbitrary_value_aggregate_for_any_variants() -> None:
def test_rejects_table_without_trino_locator() -> None:
context = HogQLContext(
database=Database(include_posthog_tables=True),
+ modifiers=_trino_modifiers(),
enable_select_queries=True,
limit_top_select=False,
restricted_properties=set(),
@@ -223,6 +233,7 @@ def test_prints_json_paths_as_bound_values() -> None:
def test_lowers_event_property_backed_fields_to_the_physical_json_column() -> None:
context = HogQLContext(
database=Database(include_posthog_tables=True),
+ modifiers=_trino_modifiers(),
enable_select_queries=True,
trino_table_locators={"events": ("tenant", "posthog", "events")},
)
@@ -246,6 +257,7 @@ def test_lowers_event_property_backed_fields_to_the_physical_json_column() -> No
def test_lowers_event_element_materializations_to_the_physical_chain() -> None:
context = HogQLContext(
database=Database(include_posthog_tables=True),
+ modifiers=_trino_modifiers(),
enable_select_queries=True,
trino_table_locators={"events": ("tenant", "posthog", "events")},
)
@@ -366,6 +378,7 @@ def test_rejects_function_argument_shapes_with_stable_error() -> None:
def test_lowers_numbers_to_bounded_unnest(source: str, expected: str) -> None:
context = HogQLContext(
database=Database(include_posthog_tables=True),
+ modifiers=_trino_modifiers(),
enable_select_queries=True,
limit_top_select=False,
restricted_properties=set(),
@@ -380,6 +393,7 @@ def test_lowers_numbers_to_bounded_unnest(source: str, expected: str) -> None:
def test_rejects_unbounded_numbers_input() -> None:
context = HogQLContext(
database=Database(include_posthog_tables=True),
+ modifiers=_trino_modifiers(),
enable_select_queries=True,
limit_top_select=False,
restricted_properties=set(),
diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.py
index 75bb8cbe7f42..07d8adaf1dfc 100644
--- a/posthog/hogql/printer/utils.py
+++ b/posthog/hogql/printer/utils.py
@@ -160,16 +160,18 @@ def prepare_ast_for_printing(
normalize_trino_ast,
)
from posthog.hogql.transforms.trino.validate import ( # noqa: PLC0415 — breaks validator → printer package cycle
+ validate_trino_context,
validate_trino_source_ast,
)
+ with context.timings.measure("validate_trino_context"):
+ validate_trino_context(context)
with context.timings.measure("validate_trino_source_ast"):
validate_trino_source_ast(node)
- # Load property-level access control restrictions onto the context. They are enforced only on the ClickHouse path —
- # the printer wraps the JSON blob in JSONDropKeys, and property resolution declines backing columns (and reads a
- # restricted property as NULL). The warehouse (Postgres / DuckDB) dialects only compile external data-warehouse
- # sources, which carry no restrictable event/person properties, so they need no enforcement here.
+ # Load restrictions before type resolution because ClickHouse removes restricted fields while resolving properties.
+ # Trino rejects the entire compilation because partial masking could miss indirect reads through expanded queries.
+ # Postgres and DuckDB compile external warehouse sources, which do not contain restrictable event/person properties.
if context.team_id is not None and context.restricted_properties is None:
# Deferred: a Django-side load at the prepare boundary (same seam as Database.create_for and
# load_property_metadata) — keeping it behind the call is what lets the printer package import
@@ -188,6 +190,18 @@ def prepare_ast_for_printing(
user=context.user, team_id=context.team_id
)
+ if dialect == "trino" and context.restricted_properties:
+ from posthog.hogql.transforms.trino.errors import ( # noqa: PLC0415 -- load the optional backend only for Trino compilation
+ TrinoLoweringError,
+ )
+
+ raise TrinoLoweringError(
+ "TRINO_RESTRICTED_PROPERTIES_UNSUPPORTED",
+ "property-level access control",
+ node if isinstance(node, ast.Expr) else None,
+ detail="Trino compilation is unavailable when property-level access restrictions apply.",
+ )
+
if context.modifiers.inCohortVia == InCohortVia.LEFTJOIN_CONJOINED:
with context.timings.measure("resolve_in_cohorts_conjoined"):
resolve_in_cohorts_conjoined(node, dialect, context, stack, resolver_factory=resolver_factory)
diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.py
index de3282c00ce0..4a00fbef26d2 100644
--- a/posthog/hogql/resolver.py
+++ b/posthog/hogql/resolver.py
@@ -52,6 +52,11 @@ from posthog.hogql.resolver_utils import (
suggest_field_names,
suggested_field_fix,
)
+from posthog.hogql.transforms.trino.persons import (
+ lower_trino_table,
+ resolve_internal_trino_logical_table,
+ resolve_trino_table_reference,
+)
from posthog.hogql.type_system import (
infer_array_access_constant_type,
infer_array_constant_type,
@@ -1347,17 +1352,28 @@ class Resolver(CloningVisitor):
return node
- try:
- database_table = cast(Database, self.database).get_table(table_name_chain)
- except QueryError:
- # Direct Postgres/DuckDB sources expose introspected table-valued functions
- # (range, generate_series, unnest, …) via connection metadata. If the lookup
- # failed but the name matches one of those, synthesize an opaque single-column
- # table so the call resolves and the printer emits it as a passthrough.
- opaque_table = self._build_opaque_table_function(table_name_chain, node)
- if opaque_table is None:
- raise
- database_table = opaque_table
+ if self.dialect == "trino":
+ database_table = resolve_trino_table_reference(
+ cast(ast.Field, node.table), self.context
+ ) or resolve_internal_trino_logical_table(table_name_chain, self.context)
+ else:
+ database_table = None
+
+ if database_table is None:
+ try:
+ database_table = cast(Database, self.database).get_table(table_name_chain)
+ except QueryError:
+ # Direct Postgres/DuckDB sources expose introspected table-valued functions
+ # (range, generate_series, unnest, …) via connection metadata. If the lookup
+ # failed but the name matches one of those, synthesize an opaque single-column
+ # table so the call resolves and the printer emits it as a passthrough.
+ opaque_table = self._build_opaque_table_function(table_name_chain, node)
+ if opaque_table is None:
+ raise
+ database_table = opaque_table
+
+ if self.dialect == "trino":
+ database_table = lower_trino_table(database_table, self.context)
if isinstance(database_table, SavedQuery):
self.current_view_depth += 1
diff --git a/posthog/hogql/test/test_trino_semantics.py b/posthog/hogql/test/test_trino_semantics.py
index f6a8f0d162a2..3011fcbeb87c 100644
--- a/posthog/hogql/test/test_trino_semantics.py
+++ b/posthog/hogql/test/test_trino_semantics.py
@@ -1,14 +1,23 @@
from posthog.test.base import APIBaseTest
+from django.test import SimpleTestCase
+
from posthog.schema import HogQLQueryModifiers
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
+from posthog.hogql.errors import QueryError
from posthog.hogql.parser import parse_select
from posthog.hogql.printer import prepare_and_print_ast
+from posthog.hogql.property_access_types import RestrictedProperty
+from posthog.hogql.transforms.trino.errors import TrinoLoweringError
+from posthog.constants import AvailableFeature
+from posthog.models import PropertyDefinition
from posthog.schema_enums import InCohortVia, InlineCohortCalculation, PersonsOnEventsMode
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
+from products.access_control.backend.property_access_control import PropertyAccessLevel
from products.actions.backend.models.action import Action
from products.cohorts.backend.models.cohort import Cohort
@@ -20,6 +29,8 @@ class TestTrinoSemantics(APIBaseTest):
modifiers: HogQLQueryModifiers | None = None,
) -> HogQLContext:
modifiers = modifiers or HogQLQueryModifiers()
+ if modifiers.personsOnEventsMode is None:
+ modifiers.personsOnEventsMode = PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS
return HogQLContext(
team_id=self.team.pk,
team=self.team,
@@ -77,19 +88,148 @@ class TestTrinoSemantics(APIBaseTest):
self.assertNotIn("COHORT", sql)
self.assertIn('"ducklake"."analytics"."raw_cohort_people"', sql)
- def test_lazy_person_join_expands_before_trino_printing(self) -> None:
- modifiers = HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.DISABLED)
- context = self._semantic_context(
- ["events", "raw_persons", "raw_person_distinct_ids", "raw_person_distinct_id_overrides"],
- modifiers,
+ def test_v2_events_person_fields_use_exported_properties_and_latest_person_mapping(self) -> None:
+ context = self._semantic_context(["events", "persons"])
+
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT person_id, person.id, person.properties.email FROM events"),
+ context,
+ "trino",
+ )
+
+ self.assertIn('"ducklake"."analytics"."events"', sql)
+ self.assertIn('"ducklake"."analytics"."persons"', sql)
+ self.assertIn('"events"."person_properties"', sql)
+ self.assertNotIn("raw_persons", sql)
+ self.assertNotIn("raw_person_distinct_ids", sql)
+ self.assertNotIn("raw_person_distinct_id_overrides", sql)
+ self.assertIn("person_distinct_id_version", sql)
+ self.assertIn("person_version", sql)
+ self.assertIn("_inserted_at", sql)
+
+ def test_restricted_user_cannot_compile_any_trino_query(self) -> None:
+ self.organization.available_product_features = [
+ {
+ "name": AvailableFeature.PROPERTY_ACCESS_CONTROL,
+ "key": AvailableFeature.PROPERTY_ACCESS_CONTROL,
+ }
+ ]
+ self.organization.save()
+ self.team.organization.refresh_from_db()
+ restricted_property = PropertyDefinition.objects.create(
+ team=self.team,
+ name="private_email",
+ property_type="String",
+ type=PropertyDefinition.Type.EVENT,
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=restricted_property,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ context = self._semantic_context(["events"])
+ context.restricted_properties = None
+
+ with self.assertRaisesRegex(TrinoLoweringError, "TRINO_RESTRICTED_PROPERTIES_UNSUPPORTED"):
+ prepare_and_print_ast(parse_select("SELECT 1"), context, "trino")
+
+
+class TestTrinoAccessControl(SimpleTestCase):
+ def test_preloaded_restriction_rejects_query_without_property_reads(self) -> None:
+ context = HogQLContext(
+ database=Database(include_posthog_tables=True),
+ enable_select_queries=True,
+ modifiers=HogQLQueryModifiers(
+ personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS
+ ),
+ restricted_properties={
+ RestrictedProperty(
+ name="private_email",
+ property_type=PropertyDefinition.Type.EVENT,
+ )
+ },
)
+ with self.assertRaisesRegex(TrinoLoweringError, "TRINO_RESTRICTED_PROPERTIES_UNSUPPORTED"):
+ prepare_and_print_ast(parse_select("SELECT 1"), context, "trino")
+
+
+class TestTrinoPersonsSemantics(SimpleTestCase):
+ def _context(self, modifiers: HogQLQueryModifiers | None = None) -> HogQLContext:
+ return HogQLContext(
+ database=Database(include_posthog_tables=True),
+ modifiers=modifiers
+ or HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS),
+ enable_select_queries=True,
+ trino_table_locators={
+ "events": ("ducklake", "analytics", "events_production"),
+ "persons": ("ducklake", "analytics", "persons_production"),
+ },
+ )
+
+ def test_logical_persons_table_deduplicates_latest_person_versions(self) -> None:
+ context = self._context()
+
+ sql, _ = prepare_and_print_ast(
+ parse_select("SELECT id, properties.email FROM persons"),
+ context,
+ "trino",
+ )
+
+ self.assertIn('"ducklake"."analytics"."persons_production"', sql)
+ self.assertNotIn("__trino_physical_persons", sql)
+ self.assertNotIn("raw_persons", sql)
+ self.assertIn("GROUP BY", sql)
+ self.assertIn("max_by", sql)
+ self.assertIn("person_version", sql)
+ self.assertIn("_inserted_at", sql)
+
+ def test_logical_persons_table_rejects_unexported_fields(self) -> None:
+ context = self._context()
+
+ with self.assertRaisesRegex(QueryError, "Last seen is not available for managed warehouse queries"):
+ prepare_and_print_ast(
+ parse_select("SELECT last_seen_at FROM persons"),
+ context,
+ "trino",
+ )
+
+ def test_logical_persons_pdi_uses_physical_persons_table(self) -> None:
+ context = self._context()
+
sql, _ = prepare_and_print_ast(
- parse_select("SELECT person.properties.email FROM events"),
+ parse_select("SELECT pdi.distinct_id FROM persons"),
context,
"trino",
)
- self.assertNotIn("person.properties.email", sql)
- self.assertIn('"ducklake"."analytics"."raw_persons"', sql)
- self.assertIn(" JOIN ", sql)
+ self.assertIn('"ducklake"."analytics"."persons_production"', sql)
+ self.assertNotIn("raw_person_distinct_ids", sql)
+ self.assertIn("person_distinct_id_version", sql)
+ self.assertIn("_inserted_at", sql)
+
+ def test_physical_persons_relation_is_not_addressable_by_hogql_name(self) -> None:
+ context = self._context()
+
+ with self.assertRaises(QueryError):
+ prepare_and_print_ast(
+ parse_select("SELECT id FROM __trino_physical_persons"),
+ context,
+ "trino",
+ )
+
+ def test_non_v2_persons_on_events_modes_fail_closed(self) -> None:
+ for mode in (
+ None,
+ PersonsOnEventsMode.DISABLED,
+ PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS,
+ PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED,
+ ):
+ with self.subTest(mode=mode):
+ context = self._context(HogQLQueryModifiers(personsOnEventsMode=mode))
+
+ with self.assertRaisesRegex(
+ TrinoLoweringError,
+ "TRINO_PERSONS_ON_EVENTS_MODE_UNSUPPORTED",
+ ):
+ prepare_and_print_ast(parse_select("SELECT 1"), context, "trino")
diff --git a/posthog/hogql/transforms/trino/persons.py b/posthog/hogql/transforms/trino/persons.py
new file mode 100644
index 000000000000..8b85a7a6b5a3
--- /dev/null
+++ b/posthog/hogql/transforms/trino/persons.py
@@ -0,0 +1,181 @@
+from typing import ClassVar
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.lazy_join_tags import FOREIGN_KEY
+from posthog.hogql.database.models import (
+ DateTimeDatabaseField,
+ FieldOrTable,
+ IntegerDatabaseField,
+ LazyJoin,
+ LazyTable,
+ LazyTableToAdd,
+ StringDatabaseField,
+ Table,
+ UUIDDatabaseField,
+)
+from posthog.hogql.database.schema.events import EventsTable
+from posthog.hogql.database.schema.persons import PERSONS_FIELDS, PersonsTable
+from posthog.hogql.errors import QueryError
+
+TRINO_PERSONS_PDI_TABLE_NAME = "__trino_persons_pdi"
+
+# DuckLake does not export last_seen_at, so the lowering rejects it before SQL reaches Trino.
+TRINO_EXPORTED_PERSONS_FIELDS: dict[str, FieldOrTable] = {
+ name: field for name, field in PERSONS_FIELDS.items() if name != "last_seen_at"
+}
+
+
+class TrinoPhysicalPersonsTable(Table):
+ name: str | None = None
+ fields: dict[str, FieldOrTable] = {
+ **TRINO_EXPORTED_PERSONS_FIELDS,
+ "distinct_id": StringDatabaseField(name="distinct_id", nullable=False),
+ "person_distinct_id_version": IntegerDatabaseField(name="person_distinct_id_version", nullable=False),
+ "person_version": IntegerDatabaseField(name="person_version", nullable=False),
+ "_inserted_at": DateTimeDatabaseField(name="_inserted_at", nullable=False),
+ }
+ trino_locator_name: ClassVar[str] = "persons"
+
+ def to_printed_hogql(self) -> str:
+ return "persons"
+
+
+TRINO_PHYSICAL_PERSONS_TABLE = TrinoPhysicalPersonsTable()
+
+
+def _latest_rows_select(
+ table_to_add: LazyTableToAdd,
+ *,
+ group_field: str,
+ version_fields: tuple[str, ...],
+) -> ast.SelectQuery:
+ select: list[ast.Expr] = [ast.Field(chain=[group_field])]
+ version = ast.Call(name="tuple", args=[ast.Field(chain=[field]) for field in version_fields])
+
+ for alias, chain in table_to_add.fields_accessed.items():
+ if chain and chain[0] == "last_seen_at":
+ raise QueryError("Last seen is not available for managed warehouse queries.")
+ if chain == [group_field]:
+ if alias != group_field:
+ select.append(ast.Alias(alias=alias, expr=ast.Field(chain=[group_field])))
+ continue
+ select.append(
+ ast.Alias(
+ alias=alias,
+ expr=ast.Call(name="argMax", args=[ast.Field(chain=chain), version]),
+ )
+ )
+
+ return ast.SelectQuery(
+ select=select,
+ select_from=ast.JoinExpr(
+ table=ast.Field(chain=["persons"], type=ast.TableType(table=TRINO_PHYSICAL_PERSONS_TABLE))
+ ),
+ group_by=[ast.Field(chain=[group_field])],
+ )
+
+
+class TrinoPersonsPDITable(LazyTable):
+ name: str | None = TRINO_PERSONS_PDI_TABLE_NAME
+ fields: dict[str, FieldOrTable] = {
+ "team_id": IntegerDatabaseField(name="team_id", nullable=False),
+ "distinct_id": StringDatabaseField(name="distinct_id", nullable=False),
+ "person_id": UUIDDatabaseField(name="person_id", nullable=False),
+ }
+
+ def lazy_select(
+ self,
+ table_to_add: LazyTableToAdd,
+ context: HogQLContext,
+ node: ast.SelectQuery,
+ ) -> ast.SelectQuery:
+ fields_accessed = {
+ alias: ["id", *chain[1:]] if chain and chain[0] == "person_id" else chain
+ for alias, chain in table_to_add.fields_accessed.items()
+ }
+ fields_accessed.setdefault("person_id", ["id"])
+ return _latest_rows_select(
+ LazyTableToAdd(lazy_table=self, fields_accessed=fields_accessed),
+ group_field="distinct_id",
+ version_fields=("person_distinct_id_version", "person_version", "_inserted_at"),
+ )
+
+ def to_printed_hogql(self) -> str:
+ return TRINO_PERSONS_PDI_TABLE_NAME
+
+
+TRINO_PERSONS_PDI_TABLE = TrinoPersonsPDITable()
+
+
+class TrinoPersonsTable(LazyTable):
+ name: str | None = "persons"
+ fields: dict[str, FieldOrTable] = {
+ **PERSONS_FIELDS,
+ "pdi": LazyJoin(
+ from_field=["id"],
+ join_table=TRINO_PERSONS_PDI_TABLE,
+ to_field=["person_id"],
+ resolver=FOREIGN_KEY,
+ ),
+ }
+
+ def lazy_select(
+ self,
+ table_to_add: LazyTableToAdd,
+ context: HogQLContext,
+ node: ast.SelectQuery,
+ ) -> ast.SelectQuery:
+ return _latest_rows_select(
+ table_to_add,
+ group_field="id",
+ version_fields=("person_version", "_inserted_at"),
+ )
+
+ def to_printed_hogql(self) -> str:
+ return "persons"
+
+
+TRINO_PERSONS_TABLE = TrinoPersonsTable()
+
+
+def resolve_trino_table_reference(field: ast.Field, context: HogQLContext) -> Table | None:
+ if "persons" not in context.trino_table_locators:
+ return None
+ if isinstance(field.type, ast.TableType) and field.type.table is TRINO_PHYSICAL_PERSONS_TABLE:
+ return TRINO_PHYSICAL_PERSONS_TABLE
+ return None
+
+
+def is_internal_trino_logical_table(table_name_chain: list[str | int]) -> bool:
+ return table_name_chain == [TRINO_PERSONS_PDI_TABLE_NAME]
+
+
+def resolve_internal_trino_logical_table(table_name_chain: list[str], context: HogQLContext) -> Table | None:
+ if "persons" not in context.trino_table_locators:
+ return None
+ if table_name_chain == [TRINO_PERSONS_PDI_TABLE_NAME]:
+ return TRINO_PERSONS_PDI_TABLE
+ return None
+
+
+def lower_trino_table(table: Table, context: HogQLContext) -> Table:
+ if "persons" not in context.trino_table_locators:
+ return table
+ if isinstance(table, PersonsTable):
+ return TRINO_PERSONS_TABLE
+ if isinstance(table, EventsTable):
+ return table.model_copy(
+ update={
+ "fields": {
+ **table.fields,
+ "override": LazyJoin(
+ from_field=["distinct_id"],
+ join_table=TRINO_PERSONS_PDI_TABLE,
+ to_field=["distinct_id"],
+ resolver=FOREIGN_KEY,
+ ),
+ }
+ }
+ )
+ return table
diff --git a/posthog/hogql/transforms/trino/validate.py b/posthog/hogql/transforms/trino/validate.py
index 9aee7b4b1208..816753f7cbe8 100644
--- a/posthog/hogql/transforms/trino/validate.py
+++ b/posthog/hogql/transforms/trino/validate.py
@@ -10,8 +10,11 @@ from posthog.hogql.printer.trino_functions import (
TRINO_PASSTHROUGH_FUNCTIONS,
)
from posthog.hogql.transforms.trino.errors import TrinoLoweringError
+from posthog.hogql.transforms.trino.persons import is_internal_trino_logical_table
from posthog.hogql.visitor import TraversingVisitor
+from posthog.schema_enums import PersonsOnEventsMode
+
_SPECIAL_CALLS = frozenset(
{
"percentile_cont",
@@ -100,7 +103,27 @@ _SUPPORTED_CALLS = frozenset(
)
+def validate_trino_context(context: HogQLContext) -> None:
+ mode = context.modifiers.personsOnEventsMode
+ if mode != PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS:
+ mode_name = mode.value if mode is not None else "unset"
+ raise TrinoLoweringError(
+ "TRINO_PERSONS_ON_EVENTS_MODE_UNSUPPORTED",
+ f"personsOnEventsMode={mode_name}",
+ detail=(
+ "Trino compilation supports only "
+ "personsOnEventsMode=person_id_override_properties_on_events. "
+ f"The effective mode is {mode_name}. Change the query or project setting before compiling."
+ ),
+ )
+
+
class TrinoSourceValidator(TraversingVisitor):
+ def visit_join_expr(self, node: ast.JoinExpr) -> None:
+ if isinstance(node.table, ast.Field) and is_internal_trino_logical_table(node.table.chain):
+ raise TrinoLoweringError("TRINO_INTERNAL_TABLE_UNAVAILABLE", "internal Trino table", node)
+ super().visit_join_expr(node)
+
def visit_select_query(self, node: ast.SelectQuery) -> None:
if node.settings is not None:
raise TrinoLoweringError("TRINO_SETTINGS_UNSUPPORTED", "SETTINGS", node)
diff --git a/products/managed_warehouse/backend/README.md b/products/managed_warehouse/backend/README.md
index 36c4e9783ac6..0a7dd19f0204 100644
--- a/products/managed_warehouse/backend/README.md
+++ b/products/managed_warehouse/backend/README.md
@@ -125,8 +125,8 @@ Every copy is written to a deterministic schema inside DuckLake. Each workflow n
### Data Modeling
- **Schema**: `posthog_data_modeling_team_<team_id>`
-- **Table**: `<model_label>` (derived from saved query name)
-- **Example**: `ducklake.posthog_data_modeling_team_123.my_saved_query`
+- **Table**: the sanitized model label, with the normalized saved query name as a fallback
+- **Example**: `ducklake.posthog_data_modeling_team_123.model_12345678123456781234567812345678`
### Data Imports and Data Import Registration
diff --git a/products/managed_warehouse/backend/common.py b/products/managed_warehouse/backend/common.py
index 565c8204f1c0..8f7415db3764 100644
--- a/products/managed_warehouse/backend/common.py
+++ b/products/managed_warehouse/backend/common.py
@@ -45,6 +45,7 @@ DUCKLAKE_CATALOG_RESET_ENV_VAR = "POSTHOG_ALLOW_DUCKLAKE_CATALOG_RESET"
# The duckgres schema prefix the data-modeling shadow materialization writes models into.
DATA_MODELING_DUCKGRES_SHADOW_SCHEMA_PREFIX = "shadow"
+DATA_MODELING_DUCKLAKE_SCHEMA_PREFIX = "posthog_data_modeling_team"
logger = logging.getLogger(__name__)
@@ -566,6 +567,14 @@ def duckgres_data_modeling_schema(team_id: int) -> str:
return f"{DATA_MODELING_DUCKGRES_SHADOW_SCHEMA_PREFIX}_{team_id}_models"
+def ducklake_data_modeling_schema(team_id: int) -> str:
+ return f"{DATA_MODELING_DUCKLAKE_SCHEMA_PREFIX}_{team_id}"
+
+
+def ducklake_data_modeling_table_name(model_label: str, normalized_name: str) -> str:
+ return sanitize_ducklake_identifier(model_label or normalized_name, default_prefix="model")
+
+
TABLE_SUFFIX_MAX_LENGTH = 63
# A schema name doubles as the suffix in `events_<suffix>` / `persons_<suffix>`, so it must
# already be a safe SQL identifier — lowercase letters, numbers, and underscores. We validate
@@ -696,6 +705,8 @@ __all__ = [
"duckgres_data_imports_schema",
"duckgres_data_imports_table_name",
"duckgres_data_modeling_schema",
+ "ducklake_data_modeling_schema",
+ "ducklake_data_modeling_table_name",
"escape",
"get_config",
"get_ducklake_connection_string",
diff --git a/products/managed_warehouse/backend/facade/client.py b/products/managed_warehouse/backend/facade/client.py
index e885894b4a07..1f0807e5ae47 100644
--- a/products/managed_warehouse/backend/facade/client.py
+++ b/products/managed_warehouse/backend/facade/client.py
@@ -1,8 +1,9 @@
"""
DuckLake query-client surface for managed_warehouse.
-Compile and run queries against an org's duckgres server — the endpoints shadow path,
-the data-modeling materialization activity, and the duckling backfill.
+Compile queries for managed DuckLake data, and run DuckDB SQL against an org's duckgres
+server — the endpoints shadow path, the data-modeling materialization activity, and the
+duckling backfill.
Delegates to ``client`` at call time rather than re-exporting its functions: a bound
re-export would freeze a copy that ``@patch`` on the source module never reaches. The
@@ -33,6 +34,7 @@ if TYPE_CHECKING:
DuckLakeQueryResult,
DuckLakeS3Secret,
DuckLakeTableResult,
+ TrinoCompiledQuery,
)
from products.managed_warehouse.backend.service_credentials import ServiceCredential
@@ -40,6 +42,7 @@ __all__ = [
"ServiceCredential",
"ServiceCredentialUnavailable",
"compile_hogql_to_ducklake_sql",
+ "compile_hogql_to_trino_sql",
"execute_ducklake_create_table",
"execute_ducklake_query",
"make_duckgres_conninfo",
@@ -48,6 +51,27 @@ __all__ = [
]
+def compile_hogql_to_trino_sql(
+ team_id: int,
+ query: HogQLQuery,
+ *,
+ team: Team | None = None,
+ user: User | None = None,
+ bypass_warehouse_access_control: bool = False,
+) -> TrinoCompiledQuery:
+ from products.managed_warehouse.backend.trino_compiler import ( # noqa: PLC0415 -- keep the optional compiler off startup paths
+ compile_hogql_to_trino_sql as _compile_hogql_to_trino_sql,
+ )
+
+ return _compile_hogql_to_trino_sql(
+ team_id,
+ query,
+ team=team,
+ user=user,
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
+ )
+
+
def make_duckgres_conninfo(
team_id: int,
*,
diff --git a/products/managed_warehouse/backend/facade/contracts.py b/products/managed_warehouse/backend/facade/contracts.py
index 898319812e9e..7974a255ee0f 100644
--- a/products/managed_warehouse/backend/facade/contracts.py
+++ b/products/managed_warehouse/backend/facade/contracts.py
@@ -44,6 +44,7 @@ __all__ = [
"ServiceCredential",
"ServiceCredentialConnect",
"ServiceCredentialUnavailable",
+ "TrinoCompiledQuery",
]
@@ -283,6 +284,15 @@ class DuckLakeCompiledQuery:
s3_secrets: tuple[DuckLakeS3Secret, ...] = ()
+@frozen
+class TrinoCompiledQuery:
+ """A HogQL query compiled to Trino SQL with named parameter bindings."""
+
+ sql: str
+ values: dict[str, Any]
+ hogql: str
+
+
@dataclass
class DuckLakeQueryResult:
columns: list[str]
diff --git a/products/managed_warehouse/backend/table_binding.py b/products/managed_warehouse/backend/table_binding.py
index dba0d55e1d30..194c84bb0ab2 100644
--- a/products/managed_warehouse/backend/table_binding.py
+++ b/products/managed_warehouse/backend/table_binding.py
@@ -1,17 +1,24 @@
from __future__ import annotations
import logging
-from typing import Any
+from typing import TYPE_CHECKING, Any
+
+from posthog.hogql.database.trino_locator import TrinoTableLocator
from products.managed_warehouse.backend.common import (
duckgres_data_imports_schema,
duckgres_data_imports_table_name,
duckgres_data_modeling_schema,
+ ducklake_data_modeling_schema,
+ ducklake_data_modeling_table_name,
)
from products.warehouse_sources.backend.facade.types import ExternalDataSourceAccessMethod
logger = logging.getLogger(__name__)
+if TYPE_CHECKING:
+ from products.managed_warehouse.backend.facade.contracts import ManagedWarehouseTableNames
+
def bind_tables_to_ducklake(database: Any, team_id: int) -> None:
"""Bind a built HogQL database's tables to their duckgres-materialized counterparts.
@@ -29,6 +36,57 @@ def bind_tables_to_ducklake(database: Any, team_id: int) -> None:
_bind_source_tables(database, team_id)
+def build_trino_table_locators(
+ database: Any,
+ team_id: int,
+ *,
+ catalog_name: str,
+ 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
+
+ locators: dict[str, TrinoTableLocator] = {
+ "events": (catalog_name, "posthog", table_names.events_table),
+ "persons": (catalog_name, "posthog", table_names.persons_table),
+ }
+
+ model_schema = ducklake_data_modeling_schema(team_id)
+ materialized_models = list(
+ DataWarehouseSavedQuery.objects.filter(team_id=team_id, is_materialized=True, table__isnull=False).exclude(
+ 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
+ }
+ 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),
+ )
+
+ naming_version = team_state_facade.data_imports_table_naming_version(team_id)
+ for table in list_ducklake_imported_tables(team_id, naming_version):
+ locator = (catalog_name, table_names.data_imports_schema, table.physical_table_name)
+ for logical_name in table.logical_table_names:
+ if database.has_table(logical_name):
+ locators[logical_name] = locator
+
+ return locators
+
+
def _bind_materialized_models(database: Any, team_id: int) -> None:
"""Bind materialized data-modeling models to their DuckLake schema (``shadow_<team_id>_models``)."""
from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
diff --git a/products/managed_warehouse/backend/temporal/ducklake_copy_data_modeling_workflow.py b/products/managed_warehouse/backend/temporal/ducklake_copy_data_modeling_workflow.py
index 65387a06c4c2..82d0c47ae2b2 100644
--- a/products/managed_warehouse/backend/temporal/ducklake_copy_data_modeling_workflow.py
+++ b/products/managed_warehouse/backend/temporal/ducklake_copy_data_modeling_workflow.py
@@ -22,11 +22,12 @@ from products.managed_warehouse.backend.common import (
_get_org_id_for_team,
_server_to_catalog_config,
attach_catalog,
+ ducklake_data_modeling_schema,
+ ducklake_data_modeling_table_name,
get_config,
get_duckgres_server_by_team_org,
get_duckgres_server_for_organization,
is_dev_mode,
- sanitize_ducklake_identifier,
)
from products.managed_warehouse.backend.logic.verification import (
DuckLakeCopyVerificationParameter,
@@ -172,8 +173,8 @@ async def prepare_data_modeling_ducklake_metadata_activity(
saved_query_name=saved_query.name,
normalized_name=normalized_name,
source_table_uri=model.table_uri,
- schema_name=f"posthog_data_modeling_team_{inputs.team_id}",
- table_name=sanitize_ducklake_identifier(model.model_label or normalized_name, default_prefix="model"),
+ schema_name=ducklake_data_modeling_schema(inputs.team_id),
+ table_name=ducklake_data_modeling_table_name(model.model_label, normalized_name),
verification_queries=list(get_data_modeling_verification_queries(model.model_label)),
partition_column=partition_column,
staging_uri=staging_uri,
diff --git a/products/managed_warehouse/backend/tests/temporal/test_ducklake_copy_data_modeling_workflow.py b/products/managed_warehouse/backend/tests/temporal/test_ducklake_copy_data_modeling_workflow.py
index a5c61eef7849..4de99d4e85b3 100644
--- a/products/managed_warehouse/backend/tests/temporal/test_ducklake_copy_data_modeling_workflow.py
+++ b/products/managed_warehouse/backend/tests/temporal/test_ducklake_copy_data_modeling_workflow.py
@@ -55,6 +55,7 @@ async def test_prepare_data_modeling_ducklake_metadata_activity_returns_models(
activity_environment, ateam, monkeypatch
):
saved_query = await DataWarehouseSavedQuery.objects.acreate(
+ id=uuid.UUID("22345678-1234-5678-1234-567812345678"),
team=ateam,
name="ducklake_model",
query={"query": "SELECT 1", "kind": "HogQLQuery"},
@@ -181,6 +182,8 @@ async def test_prepare_data_modeling_ducklake_metadata_activity_applies_yaml_ove
"default_row_check",
"inherited_extra_check",
]
+ assert override_metadata.table_name == "override_only_model"
+ assert inherit_metadata.table_name == "inherits_defaults_model"
def test_copy_data_modeling_model_to_ducklake_activity_via_duckgres(monkeypatch):
diff --git a/products/managed_warehouse/backend/tests/test_trino_compiler.py b/products/managed_warehouse/backend/tests/test_trino_compiler.py
new file mode 100644
index 000000000000..9959bcf4a88f
--- /dev/null
+++ b/products/managed_warehouse/backend/tests/test_trino_compiler.py
@@ -0,0 +1,236 @@
+from uuid import UUID
+
+import pytest
+from unittest import mock
+
+from rest_framework.response import Response
+
+from posthog.schema import HogQLQuery, HogQLQueryModifiers
+
+from posthog.models import Organization, 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.contracts import (
+ ManagedWarehouseTableNames,
+ ManagedWarehouseTeamMembership,
+)
+from products.managed_warehouse.backend.table_binding import build_trino_table_locators
+from products.managed_warehouse.backend.trino_compiler import (
+ TrinoTargetUnavailable,
+ compile_hogql_to_trino_sql,
+ get_ready_trino_catalog_name,
+)
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource
+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
+
+
+def _membership(*, team_id: int, organization_id: str) -> ManagedWarehouseTeamMembership:
+ return ManagedWarehouseTeamMembership(
+ team_id=team_id,
+ organization_id=organization_id,
+ schema_name="production",
+ enabled=True,
+ backfill_enabled=True,
+ table_names=ManagedWarehouseTableNames(
+ events_table="events_production",
+ persons_table="persons_production",
+ data_imports_schema="posthog_data_imports_production",
+ ),
+ earliest_event_date=None,
+ )
+
+
+def _team() -> Team:
+ return Team(id=7, organization_id=UUID("00000000-0000-0000-0000-000000000001"))
+
+
+class TestReadyTrinoCatalogName:
+ @pytest.mark.parametrize("catalog_key", ["trino_catalog_name", "catalog"])
+ def test_reads_ready_catalog_and_supports_rolling_deploys(self, catalog_key: str) -> None:
+ body = {
+ "enabled": True,
+ "status": {
+ "org": "org-1",
+ "state": "ready",
+ catalog_key: "org_catalog",
+ },
+ }
+ with mock.patch(
+ "products.managed_warehouse.backend.presentation.views._request",
+ return_value=Response(body, status=200),
+ ) as request:
+ assert get_ready_trino_catalog_name("org-1") == "org_catalog"
+
+ request.assert_called_once_with("GET", "org-1", "/trino", require_enabled=False)
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ {"enabled": False},
+ {"enabled": True, "status": {"org": "org-1", "state": "pending", "trino_catalog_name": "cat"}},
+ {"enabled": True, "status": {"org": "another-org", "state": "ready", "trino_catalog_name": "cat"}},
+ {"enabled": True, "status": {"org": "org-1", "state": "ready", "trino_catalog_name": ""}},
+ ],
+ )
+ def test_rejects_an_unusable_target(self, body: dict[str, object]) -> None:
+ with mock.patch(
+ "products.managed_warehouse.backend.presentation.views._request",
+ return_value=Response(body, status=200),
+ ):
+ assert get_ready_trino_catalog_name("org-1") is None
+
+
+class TestCompileHogQLToTrinoSQL:
+ def test_populates_core_table_locators_from_control_plane_state(self) -> None:
+ team = _team()
+ membership = _membership(team_id=team.pk, organization_id=str(team.organization_id))
+ database = mock.MagicMock()
+ locators = {"events": ("org_catalog", "posthog", "events_production")}
+ modifiers = HogQLQueryModifiers()
+
+ with (
+ mock.patch(
+ "products.managed_warehouse.backend.trino_compiler.get_ready_trino_catalog_name",
+ return_value="org_catalog",
+ ),
+ mock.patch(
+ "products.managed_warehouse.backend.trino_compiler.get_org_team_membership",
+ return_value=membership,
+ ),
+ mock.patch("posthog.hogql.database.database.Database.create_for", return_value=database),
+ mock.patch(
+ "posthog.hogql.modifiers.create_default_modifiers_for_team",
+ return_value=modifiers,
+ ),
+ mock.patch(
+ "products.managed_warehouse.backend.trino_compiler.build_trino_table_locators",
+ return_value=locators,
+ ) as build_locators,
+ mock.patch(
+ "posthog.hogql.printer.utils.prepare_and_print_ast",
+ side_effect=[("SELECT event FROM target", None), ("SELECT event FROM events", None)],
+ ) as prepare_and_print,
+ ):
+ compiled = compile_hogql_to_trino_sql(
+ team.pk,
+ HogQLQuery(query="SELECT event FROM events LIMIT 1"),
+ team=team,
+ )
+
+ assert compiled.sql == "SELECT event FROM target"
+ assert compiled.values == {}
+ build_locators.assert_called_once_with(
+ database,
+ team.pk,
+ catalog_name="org_catalog",
+ table_names=membership.table_names,
+ )
+ trino_context = prepare_and_print.call_args_list[0].args[1]
+ assert trino_context.trino_table_locators == locators
+ assert trino_context.modifiers is modifiers
+ assert prepare_and_print.call_args_list[0].kwargs["dialect"] == "trino"
+
+ def test_fails_closed_without_a_ready_catalog(self) -> None:
+ team = _team()
+
+ with mock.patch(
+ "products.managed_warehouse.backend.trino_compiler.get_ready_trino_catalog_name",
+ return_value=None,
+ ):
+ with pytest.raises(TrinoTargetUnavailable, match="ready Trino catalog"):
+ compile_hogql_to_trino_sql(team.pk, HogQLQuery(query="SELECT 1"), team=team)
+
+ def test_fails_closed_without_a_team_mapping(self) -> None:
+ team = _team()
+
+ with (
+ mock.patch(
+ "products.managed_warehouse.backend.trino_compiler.get_ready_trino_catalog_name",
+ return_value="org_catalog",
+ ),
+ mock.patch(
+ "products.managed_warehouse.backend.trino_compiler.get_org_team_membership",
+ return_value=None,
+ ),
+ ):
+ with pytest.raises(TrinoTargetUnavailable, match="physical table mapping"):
+ compile_hogql_to_trino_sql(team.pk, HogQLQuery(query="SELECT 1"), team=team)
+
+
+def test_build_trino_table_locators_uses_provisioned_names_and_canonical_source_aliases() -> None:
+ organization = Organization.objects.create(name="trino-locators")
+ team = Team.objects.create(organization=organization)
+ model_table = DataWarehouseTable.objects.create(
+ name="orders_model",
+ format="Parquet",
+ team=team,
+ url_pattern="https://bucket.s3.amazonaws.com/models/orders/*.parquet",
+ )
+ saved_query_id = UUID("32345678-1234-5678-1234-567812345678")
+ saved_query = DataWarehouseSavedQuery.objects.create(
+ id=saved_query_id,
+ team=team,
+ name="orders_model",
+ query={"query": "SELECT 1", "kind": "HogQLQuery"},
+ table=model_table,
+ is_materialized=True,
+ )
+ DataWarehouseModelPath.objects.create(
+ team=team,
+ saved_query=saved_query,
+ path=["legacy_orders_model"],
+ )
+ source = ExternalDataSource.objects.create(
+ team=team,
+ source_id="source_id",
+ connection_id="connection_id",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=ExternalDataSourceType.STRIPE,
+ prefix="myprefix_",
+ )
+ source_table = DataWarehouseTable.objects.create(
+ name="myprefix_stripe_customers",
+ format="Parquet",
+ team=team,
+ external_data_source=source,
+ url_pattern="https://bucket.s3.amazonaws.com/stripe/customers/*.parquet",
+ )
+ ExternalDataSchema.objects.create(
+ team=team,
+ name="customers",
+ source=source,
+ table=source_table,
+ should_sync=True,
+ )
+ table_names = ManagedWarehouseTableNames(
+ events_table="events_production",
+ persons_table="persons_production",
+ data_imports_schema="imports_production",
+ )
+ database = mock.Mock()
+ database.has_table.return_value = True
+
+ with mock.patch(
+ "products.managed_warehouse.backend.team_state.data_imports_table_naming_version",
+ return_value="copy_v1",
+ ):
+ locators = build_trino_table_locators(
+ database,
+ team.pk,
+ catalog_name="org_catalog",
+ table_names=table_names,
+ )
+
+ assert locators == {
+ "events": ("org_catalog", "posthog", "events_production"),
+ "persons": ("org_catalog", "posthog", "persons_production"),
+ "orders_model": (
+ "org_catalog",
+ f"posthog_data_modeling_team_{team.pk}",
+ "legacy_orders_model",
+ ),
+ "myprefix_stripe_customers": ("org_catalog", "imports_production", "stripe_myprefix_customers"),
+ "stripe.myprefix.customers": ("org_catalog", "imports_production", "stripe_myprefix_customers"),
+ }
diff --git a/products/managed_warehouse/backend/trino_compiler.py b/products/managed_warehouse/backend/trino_compiler.py
new file mode 100644
index 000000000000..62c12a82017d
--- /dev/null
+++ b/products/managed_warehouse/backend/trino_compiler.py
@@ -0,0 +1,149 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, cast
+
+import structlog
+from rest_framework import status
+
+from products.managed_warehouse.backend.facade.contracts import TrinoCompiledQuery
+from products.managed_warehouse.backend.facade.cp_teams import get_org_team_membership
+from products.managed_warehouse.backend.table_binding import build_trino_table_locators
+
+if TYPE_CHECKING:
+ from posthog.schema import HogQLQuery
+
+ from posthog.models import Team, User
+
+logger = structlog.get_logger(__name__)
+
+
+class TrinoTargetUnavailable(RuntimeError):
+ pass
+
+
+def get_ready_trino_catalog_name(organization_id: str) -> str | None:
+ """Return the control-plane-owned catalog only after its Trino target is ready."""
+ from products.managed_warehouse.backend.presentation.views import _request # noqa: PLC0415
+
+ response = _request("GET", organization_id, "/trino", require_enabled=False)
+ if not status.is_success(response.status_code) or not isinstance(response.data, dict):
+ return None
+ if response.data.get("enabled") is not True:
+ return None
+
+ trino_status = response.data.get("status")
+ if not isinstance(trino_status, dict) or trino_status.get("state") != "ready":
+ return None
+ response_org = trino_status.get("org")
+ if response_org is not None and str(response_org) != str(organization_id):
+ logger.warning(
+ "refusing_trino_catalog_for_mismatched_organization",
+ requested_organization_id=str(organization_id),
+ response_organization_id=str(response_org),
+ )
+ return None
+
+ catalog_name = trino_status.get("trino_catalog_name") or trino_status.get("catalog")
+ return catalog_name.strip() if isinstance(catalog_name, str) and catalog_name.strip() else None
+
+
+def compile_hogql_to_trino_sql(
+ team_id: int,
+ query: HogQLQuery,
+ *,
+ team: Team | None = None,
+ user: User | None = None,
+ bypass_warehouse_access_control: bool = False,
+) -> TrinoCompiledQuery:
+ """Compile HogQL for the ready Trino catalog that serves the team's DuckLake data.
+
+ Set ``bypass_warehouse_access_control`` only for trusted internal callers that compile
+ without a user. This entry point does not execute the returned SQL or alter query routing.
+ """
+ from posthog.hogql import ast # noqa: PLC0415
+ from posthog.hogql.context import HogQLContext # noqa: PLC0415
+ from posthog.hogql.database.database import Database # noqa: PLC0415
+ from posthog.hogql.filters import replace_filters # noqa: PLC0415
+ from posthog.hogql.modifiers import create_default_modifiers_for_team # noqa: PLC0415
+ from posthog.hogql.parser import parse_select, sanitize_client_parser_mode # noqa: PLC0415
+ from posthog.hogql.placeholders import find_placeholders, replace_placeholders # noqa: PLC0415
+ from posthog.hogql.printer.utils import prepare_and_print_ast # noqa: PLC0415
+ from posthog.hogql.variables import replace_variables # noqa: PLC0415
+ from posthog.hogql.visitor import clone_expr # noqa: PLC0415
+
+ from posthog.models.team.team import Team # noqa: PLC0415
+
+ team = team or Team.objects.get(pk=team_id)
+ organization_id = str(team.organization_id)
+ catalog_name = get_ready_trino_catalog_name(organization_id)
+ if catalog_name is None:
+ raise TrinoTargetUnavailable("The organization does not have a ready Trino catalog")
+
+ membership = get_org_team_membership(organization_id, team_id)
+ if membership is None:
+ raise TrinoTargetUnavailable("The project does not have an authoritative physical table mapping")
+
+ query_modifiers = create_default_modifiers_for_team(team, query.modifiers)
+ placeholder_values: dict[str, ast.Expr] | None = (
+ {key: ast.Constant(value=value) for key, value in query.values.items()} if query.values else None
+ )
+ parsed = parse_select(
+ query.query,
+ placeholders=placeholder_values,
+ parser_mode=sanitize_client_parser_mode(query_modifiers.parserMode),
+ )
+
+ database = Database.create_for(
+ team_id,
+ team=team,
+ user=user,
+ modifiers=query_modifiers,
+ # Preserve an explicit trusted-internal bypass; the public default remains fail-closed.
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
+ trigger="trino",
+ )
+ placeholders = find_placeholders(parsed)
+ if placeholders.has_filters:
+ parsed = replace_filters(parsed, query.filters, team, database=database)
+ if query.variables:
+ parsed = replace_variables(parsed, list(query.variables.values()), team)
+ if placeholders.placeholder_fields or placeholders.placeholder_expressions:
+ variables: dict[str, Any] = {}
+ replacements: dict[str, Any] = {"variables": variables, **(placeholder_values or {})}
+ if query.variables:
+ for variable in query.variables.values():
+ variables[variable.code_name] = variable.value
+ parsed = cast("ast.SelectQuery | ast.SelectSetQuery", replace_placeholders(parsed, replacements))
+
+ trino_table_locators = build_trino_table_locators(
+ database,
+ team_id,
+ catalog_name=catalog_name,
+ table_names=membership.table_names,
+ )
+ trino_context = HogQLContext(
+ team_id=team_id,
+ team=team,
+ user=user,
+ enable_select_queries=True,
+ modifiers=query_modifiers,
+ # Match the access-controlled database above instead of widening it during resolution.
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
+ database=database,
+ trino_table_locators=trino_table_locators,
+ )
+ hogql_ast = clone_expr(parsed)
+ trino_sql, _ = prepare_and_print_ast(parsed, trino_context, dialect="trino")
+
+ hogql_context = HogQLContext(
+ team_id=team_id,
+ team=team,
+ user=user,
+ enable_select_queries=True,
+ modifiers=query_modifiers,
+ # The diagnostic HogQL rendering must use the same caller-authorized access posture.
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
+ )
+ hogql_pretty, _ = prepare_and_print_ast(hogql_ast, hogql_context, dialect="hogql")
+
+ return TrinoCompiledQuery(sql=trino_sql, values=dict(trino_context.values), hogql=hogql_pretty)
diff --git a/products/warehouse_sources/backend/facade/contracts.py b/products/warehouse_sources/backend/facade/contracts.py
index 7ca2d6af76ec..e5a89c81e86e 100644
--- a/products/warehouse_sources/backend/facade/contracts.py
+++ b/products/warehouse_sources/backend/facade/contracts.py
@@ -137,6 +137,12 @@ class DataWarehouseTable:
created_at: datetime
+@dataclass(frozen=True)
+class DuckLakeImportedTable:
+ logical_table_names: tuple[str, ...]
+ physical_table_name: str
+
+
@dataclass(frozen=True)
class TableSourceLocation:
"""Where a synced table is administered: the source and schema its detail page hangs off."""
diff --git a/products/warehouse_sources/backend/facade/ducklake.py b/products/warehouse_sources/backend/facade/ducklake.py
new file mode 100644
index 000000000000..1f7dbf4e488d
--- /dev/null
+++ b/products/warehouse_sources/backend/facade/ducklake.py
@@ -0,0 +1,40 @@
+from __future__ import annotations
+
+from posthog.hogql.database.database import get_data_warehouse_table_name
+
+from products.warehouse_sources.backend.duckgres_naming import duckgres_data_imports_table_name_for_version
+from products.warehouse_sources.backend.models.table import DataWarehouseTable
+
+from .contracts import DuckLakeImportedTable
+from .types import ExternalDataSourceAccessMethod
+
+
+def list_ducklake_imported_tables(team_id: int, naming_version: str) -> list[DuckLakeImportedTable]:
+ tables = (
+ DataWarehouseTable.objects.queryable()
+ .filter(team_id=team_id, external_data_source__isnull=False)
+ .exclude(external_data_source__access_method=ExternalDataSourceAccessMethod.DIRECT)
+ .prefetch_related("externaldataschema_set__source")
+ )
+
+ imported_tables: list[DuckLakeImportedTable] = []
+ for table in tables:
+ external_schema = next(iter(table.externaldataschema_set.all()), None)
+ if external_schema is None:
+ continue
+
+ imported_tables.append(
+ DuckLakeImportedTable(
+ logical_table_names=tuple(
+ dict.fromkeys((table.name, get_data_warehouse_table_name(external_schema.source, table.name)))
+ ),
+ physical_table_name=duckgres_data_imports_table_name_for_version(
+ external_schema.source.source_type,
+ external_schema.source.prefix,
+ external_schema.normalized_name,
+ naming_version,
+ ),
+ )
+ )
+
+ return imported_tables