:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(hogql): default trino compilation to manifest mode (#93745)
Bill Guowei Yang64d753184793
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.mdindex 61a09c0116bb..7345dcfe37bb 100644--- a/docs/internal/hogql-trino-compiler.md+++ b/docs/internal/hogql-trino-compiler.md@@ -8,9 +8,11 @@ Call `prepare_and_print_ast(node, context, "trino")` explicitly to use the backeThe returned SQL uses named placeholders, with values stored in `context.values`. `convert_pyformat_placeholders` converts these into positional placeholders and values for a Trino client; calling this helper does not execute SQL.-The existing preparation path still owns schema construction, access checks, saved-query expansion, lazy-table resolution, and resolver passes. It then passes the prepared AST and snapshots of bindings, table locators, modifiers, limits, timezone, and week start in a frozen input to the final Trino transpiler. The final transpiler clones the AST and creates a fresh print context without a team, user, or schema database before final lowering, validation, and printing.+The final Trino transpiler accepts a prepared AST plus frozen snapshots of bindings, table locators, modifiers, limits, timezone, and week start. It clones the AST and creates a fresh print context without a team, user, or schema database before final lowering, validation, and printing.-This boundary does not add a restricted manifest-backed entry point. Callers still use the Django-backed preparation path described below.+`transpile_hogql_to_trino(...)` is the restricted, manifest-backed front end. Its immutable manifest allowlists logical tables, physical Trino locators, and warehouse column types. `events` and `persons` use fixed built-in schemas. The function resolves and prints with no team, user, Django model, saved query, or lazy database callback, and its tests assert that it executes zero Django queries.++Pure transpilation accepts caller-supplied constant values. It rejects unresolved placeholders, action and cohort references, tables absent from the manifest, non-leaf warehouse column types, and invalid or incomplete manifest entries. Callers needing Django-backed semantics must select the explicit expansion mode described below.Query Editor capability changes, case-insensitive connection lookup, and parameter submission belong to separate integration changes. They are not prerequisites for compilation.@@ -45,17 +47,19 @@ Trino table rendering stays in Trino-specific modules. Neither the built-in numbAfter 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:+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. Pure manifest-backed compilation is the default. It maps `events` and `persons` to the project's provisioned tables in the `posthog` schema, and accepts additional allowlisted warehouse relations through `catalog_manifest`.++Pass `expansion_mode=TrinoExpansionMode.DJANGO` when a query requires actions, cohorts, saved queries, filters, variables, access-controlled warehouse discovery, or other Django-backed semantic expansion. This compatibility mode builds the full database and maps:- `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 compiler returns Trino SQL and parameter values by default. Pass `include_hogql=True` to include a normalized HogQL diagnostic; this optional rendering reuses the compilation database.+The compiler returns Trino SQL and parameter values by default. Pass `include_hogql=True` to include a normalized HogQL diagnostic. Compilation mode is a trusted function argument; serialized `HogQLQuery` input cannot enable Django expansion.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 currently requires `personsOnEventsMode=person_id_override_properties_on_events`. Pure mode uses that fixed export contract when the modifier is absent and rejects any explicitly incompatible mode. Django mode resolves the effective team modifier and rejects unset, disabled, V1, and joined modes before semantic lowering.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.diff --git a/posthog/hogql/transforms/trino/manifest.py b/posthog/hogql/transforms/trino/manifest.pynew file mode 100644index 000000000000..e2c3bb7bc35e--- /dev/null+++ b/posthog/hogql/transforms/trino/manifest.py@@ -0,0 +1,266 @@+from __future__ import annotations++from collections.abc import Mapping+from typing import Any++from posthog.schema import HogQLQueryModifiers++from posthog.hogql import ast+from posthog.hogql.constants import LimitContext+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Database+from posthog.hogql.database.direct_trino_table import DirectTrinoTable+from posthog.hogql.database.models import (+ BooleanDatabaseField,+ DatabaseField,+ DateDatabaseField,+ DateTimeDatabaseField,+ DecimalDatabaseField,+ ExpressionField,+ FieldTraverser,+ FloatDatabaseField,+ IntegerDatabaseField,+ StringArrayDatabaseField,+ StringDatabaseField,+ StringJSONDatabaseField,+ TableNode,+ UnknownDatabaseField,+ VirtualTable,+)+from posthog.hogql.database.trino_locator import TrinoTableLocator+from posthog.hogql.parser import parse_expr, parse_select+from posthog.hogql.placeholders import find_placeholders+from posthog.hogql.printer.utils import prepare_and_print_ast+from posthog.hogql.transforms.trino.errors import TrinoLoweringError+from posthog.hogql.visitor import TraversingVisitor, clone_expr++from posthog.dataclasses import frozen+from posthog.schema_enums import DatabaseSerializedFieldType, PersonsOnEventsMode+from posthog.week_start_day import WeekStartDay+++@frozen+class TrinoManifestColumn:+ name: str+ type: DatabaseSerializedFieldType+ nullable: bool = True+++@frozen+class TrinoManifestTable:+ logical_name: str+ locator: TrinoTableLocator+ columns: tuple[TrinoManifestColumn, ...] = ()+++@frozen+class TrinoCatalogManifest:+ tables: tuple[TrinoManifestTable, ...]+ timezone: str = "UTC"+ week_start_day: WeekStartDay = WeekStartDay.SUNDAY+++@frozen+class TrinoManifestTranspilerResult:+ sql: str+ values: dict[str, Any]+ hogql: str | None = None+++_CORE_TABLES = frozenset({"events", "persons"})+_FIELD_TYPES: dict[DatabaseSerializedFieldType, type[DatabaseField]] = {+ DatabaseSerializedFieldType.INTEGER: IntegerDatabaseField,+ DatabaseSerializedFieldType.FLOAT: FloatDatabaseField,+ DatabaseSerializedFieldType.DECIMAL: DecimalDatabaseField,+ DatabaseSerializedFieldType.STRING: StringDatabaseField,+ DatabaseSerializedFieldType.DATETIME: DateTimeDatabaseField,+ DatabaseSerializedFieldType.DATE: DateDatabaseField,+ DatabaseSerializedFieldType.BOOLEAN: BooleanDatabaseField,+ DatabaseSerializedFieldType.ARRAY: StringArrayDatabaseField,+ DatabaseSerializedFieldType.JSON: StringJSONDatabaseField,+ DatabaseSerializedFieldType.UNKNOWN: UnknownDatabaseField,+}+++class _UnsupportedSemanticFeatureFinder(TraversingVisitor):+ def visit_call(self, node: ast.Call) -> None:+ if node.name == "matchesAction":+ raise TrinoLoweringError(+ "TRINO_PURE_ACTION_UNSUPPORTED",+ "action expansion",+ node,+ detail="Action references require Django semantic expansion.",+ )+ super().visit_call(node)++ def visit_compare_operation(self, node: ast.CompareOperation) -> None:+ if node.op in (ast.CompareOperationOp.InCohort, ast.CompareOperationOp.NotInCohort):+ raise TrinoLoweringError(+ "TRINO_PURE_COHORT_UNSUPPORTED",+ "cohort expansion",+ node,+ detail="Cohort references require Django semantic expansion.",+ )+ super().visit_compare_operation(node)+++def _manifest_field(column: TrinoManifestColumn) -> DatabaseField:+ field_class = _FIELD_TYPES.get(column.type)+ if field_class is None:+ raise TrinoLoweringError(+ "TRINO_PURE_COLUMN_TYPE_UNSUPPORTED",+ "manifest column type",+ detail=f"Manifest column `{column.name}` uses unsupported type `{column.type.value}`.",+ )+ if not column.name:+ raise TrinoLoweringError(+ "TRINO_PURE_INVALID_MANIFEST",+ "manifest column",+ detail="Manifest column names must not be empty.",+ )+ return field_class(name=column.name, nullable=column.nullable)+++def _configure_events_for_trino(database: Database) -> None:+ events = database.get_table("events")+ events.fields["person"] = FieldTraverser(chain=["poe"])+ events.fields["person_id"] = ExpressionField(+ name="person_id",+ expr=parse_expr("if(not(empty(override.distinct_id)), override.person_id, event_person_id)"),+ isolate_scope=True,+ )+ poe = events.fields["poe"]+ if not isinstance(poe, VirtualTable):+ raise TrinoLoweringError(+ "TRINO_PURE_INVALID_CORE_SCHEMA",+ "events table",+ detail="The fixed events definition does not expose its person-on-events fields.",+ )+ poe.fields["id"] = events.fields["person_id"]+++def build_trino_manifest_database(manifest: TrinoCatalogManifest) -> tuple[Database, dict[str, TrinoTableLocator]]:+ database = Database(+ timezone=manifest.timezone,+ week_start_day=manifest.week_start_day,+ include_posthog_tables=True,+ )+ logical_names = [table.logical_name for table in manifest.tables]+ if len(logical_names) != len(set(logical_names)):+ raise TrinoLoweringError(+ "TRINO_PURE_INVALID_MANIFEST",+ "manifest tables",+ detail="Manifest logical table names must be unique.",+ )++ core_tables = set(_CORE_TABLES.intersection(logical_names))+ database.prune_to_table_names(core_tables)+ if "events" in core_tables:+ _configure_events_for_trino(database)++ locators: dict[str, TrinoTableLocator] = {}+ for table in manifest.tables:+ chain = table.logical_name.split(".")+ if not table.logical_name or any(not part for part in chain):+ raise TrinoLoweringError(+ "TRINO_PURE_INVALID_MANIFEST",+ "manifest table",+ detail=f"Invalid logical table name `{table.logical_name}`.",+ )+ if any(not value.strip() for value in table.locator):+ raise TrinoLoweringError(+ "TRINO_PURE_INVALID_MANIFEST",+ "manifest table locator",+ detail=f"Manifest table `{table.logical_name}` has an empty physical locator component.",+ )++ locators[table.logical_name] = table.locator+ if table.logical_name in _CORE_TABLES:+ if table.columns:+ raise TrinoLoweringError(+ "TRINO_PURE_INVALID_MANIFEST",+ "core table manifest",+ detail=f"Core table `{table.logical_name}` uses its fixed schema and cannot declare columns.",+ )+ continue++ columns = {column.name: _manifest_field(column) for column in table.columns}+ if not columns or len(columns) != len(table.columns):+ raise TrinoLoweringError(+ "TRINO_PURE_INVALID_MANIFEST",+ "manifest columns",+ detail=f"Manifest table `{table.logical_name}` must declare unique columns.",+ )+ direct_table = DirectTrinoTable(+ name=chain[-1],+ fields=columns,+ has_complete_columns=True,+ external_data_source_id="",+ trino_catalog=table.locator[0],+ trino_schema=table.locator[1],+ trino_table_name=table.locator[2],+ )+ database.tables.add_child(+ TableNode.create_nested_for_chain(chain, direct_table),+ table_conflict_mode="override",+ )++ return database, locators+++def transpile_hogql_to_trino(+ query: str,+ *,+ manifest: TrinoCatalogManifest,+ values: Mapping[str, object] | None = None,+ convert_to_project_timezone: bool | None = None,+ limit_top_select: bool = True,+ limit_context: LimitContext | None = None,+ pretty: bool = False,+ include_hogql: bool = False,+) -> TrinoManifestTranspilerResult:+ placeholders: dict[str, ast.Expr] | None = (+ {key: ast.Constant(value=value) for key, value in values.items()} if values else None+ )+ node = parse_select(query, placeholders=placeholders)+ unsupported_placeholders = find_placeholders(node)+ if (+ unsupported_placeholders.has_filters+ or unsupported_placeholders.placeholder_fields+ or unsupported_placeholders.placeholder_expressions+ ):+ raise TrinoLoweringError(+ "TRINO_PURE_PLACEHOLDER_UNSUPPORTED",+ "unresolved placeholder",+ node,+ detail="Pure Trino transpilation only accepts constant values supplied by the caller.",+ )+ _UnsupportedSemanticFeatureFinder().visit(node)++ database, locators = build_trino_manifest_database(manifest)++ def create_context() -> HogQLContext:+ return HogQLContext(+ database=database,+ team_id=None,+ team=None,+ user=None,+ enable_select_queries=True,+ limit_top_select=limit_top_select,+ limit_context=limit_context,+ modifiers=HogQLQueryModifiers(+ personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS,+ convertToProjectTimezone=convert_to_project_timezone,+ ),+ restricted_properties=set(),+ trino_table_locators=locators,+ timezone=manifest.timezone,+ week_start_day=manifest.week_start_day,+ )++ context = create_context()+ hogql: str | None = None+ if include_hogql:+ hogql, _ = prepare_and_print_ast(clone_expr(node), create_context(), dialect="hogql")+ sql, _ = prepare_and_print_ast(node, context, dialect="trino", pretty=pretty)+ return TrinoManifestTranspilerResult(sql=sql, values=dict(context.values), hogql=hogql)diff --git a/posthog/hogql/transforms/trino/test/test_manifest.py b/posthog/hogql/transforms/trino/test/test_manifest.pynew file mode 100644index 000000000000..298bde02836e--- /dev/null+++ b/posthog/hogql/transforms/trino/test/test_manifest.py@@ -0,0 +1,90 @@+from typing import Any++import pytest++from posthog.hogql.errors import QueryError+from posthog.hogql.transforms.trino.errors import TrinoLoweringError+from posthog.hogql.transforms.trino.manifest import (+ TrinoCatalogManifest,+ TrinoManifestColumn,+ TrinoManifestTable,+ transpile_hogql_to_trino,+)++from posthog.schema_enums import DatabaseSerializedFieldType++pytestmark = pytest.mark.django_db+++def _manifest(*tables: TrinoManifestTable) -> TrinoCatalogManifest:+ return TrinoCatalogManifest(tables=tables)+++def _events() -> TrinoManifestTable:+ return TrinoManifestTable(+ logical_name="events",+ locator=("org_catalog", "posthog", "events_production"),+ )+++def test_transpiles_core_table_with_values_without_django_queries(+ django_assert_num_queries: Any,+) -> None:+ with django_assert_num_queries(0):+ result = transpile_hogql_to_trino(+ "SELECT event FROM events WHERE event = {event}",+ manifest=_manifest(_events()),+ values={"event": "signup"},+ include_hogql=True,+ )++ assert result.sql == (+ 'SELECT "org_catalog"."posthog"."events_production"."event" '+ 'FROM "org_catalog"."posthog"."events_production" '+ 'WHERE ("org_catalog"."posthog"."events_production"."event" = %(hogql_val_0)s) LIMIT 50000'+ )+ assert result.values == {"hogql_val_0": "signup"}+ assert result.hogql == "SELECT event FROM events WHERE equals(event, 'signup') LIMIT 50000"+++def test_transpiles_manifest_table_without_django_queries(django_assert_num_queries: Any) -> None:+ orders = TrinoManifestTable(+ logical_name="stripe.orders",+ locator=("org_catalog", "imports", "stripe_orders"),+ columns=(+ TrinoManifestColumn(name="id", type=DatabaseSerializedFieldType.STRING, nullable=False),+ TrinoManifestColumn(name="total", type=DatabaseSerializedFieldType.DECIMAL),+ ),+ )++ with django_assert_num_queries(0):+ result = transpile_hogql_to_trino(+ "SELECT id, total FROM stripe.orders",+ manifest=_manifest(orders),+ )++ assert result.sql == (+ 'SELECT "stripe__orders"."id", "stripe__orders"."total" '+ 'FROM "org_catalog"."imports"."stripe_orders" AS "stripe__orders" LIMIT 50000'+ )+ assert result.values == {}+++ ("query", "feature_code"),+ [+ ("SELECT matchesAction(1) FROM events", "TRINO_PURE_ACTION_UNSUPPORTED"),+ ("SELECT event FROM events WHERE person_id IN COHORT 1", "TRINO_PURE_COHORT_UNSUPPORTED"),+ ("SELECT event FROM events WHERE {filters}", "TRINO_PURE_PLACEHOLDER_UNSUPPORTED"),+ ],+)+def test_rejects_django_backed_semantics(query: str, feature_code: str) -> None:+ with pytest.raises(TrinoLoweringError) as error:+ transpile_hogql_to_trino(query, manifest=_manifest(_events()))++ assert error.value.feature_code == feature_code+++def test_rejects_tables_absent_from_manifest() -> None:+ with pytest.raises(QueryError, match="Unknown table `saved_query`"):+ transpile_hogql_to_trino("SELECT * FROM saved_query", manifest=_manifest(_events()))diff --git a/products/managed_warehouse/backend/facade/client.py b/products/managed_warehouse/backend/facade/client.pyindex 8f79ea48e321..9ff7d001d63d 100644--- a/products/managed_warehouse/backend/facade/client.py+++ b/products/managed_warehouse/backend/facade/client.py@@ -17,7 +17,10 @@ from contextlib import AbstractContextManagerfrom typing import TYPE_CHECKINGfrom products.managed_warehouse.backend import client-from products.managed_warehouse.backend.facade.contracts import ManagedWarehouseTrinoConnectionUnavailable+from products.managed_warehouse.backend.facade.contracts import (+ ManagedWarehouseTrinoConnectionUnavailable,+ TrinoExpansionMode,+)from products.managed_warehouse.backend.service_credentials import (ServiceCredential,ServiceCredentialUnavailable,@@ -30,6 +33,8 @@ if TYPE_CHECKING:from posthog.schema import HogQLQuery+ from posthog.hogql.transforms.trino.manifest import TrinoCatalogManifest+from posthog.models.team.team import Teamfrom posthog.models.user import User@@ -83,6 +88,8 @@ def compile_hogql_to_trino_sql(user: User | None = None,bypass_warehouse_access_control: bool = False,include_hogql: bool = False,+ expansion_mode: TrinoExpansionMode = TrinoExpansionMode.PURE,+ catalog_manifest: TrinoCatalogManifest | None = None,) -> TrinoCompiledQuery:from products.managed_warehouse.backend.trino_compiler import ( # noqa: PLC0415 -- keep the optional compiler off startup pathscompile_hogql_to_trino_sql as _compile_hogql_to_trino_sql,@@ -95,6 +102,8 @@ def compile_hogql_to_trino_sql(user=user,bypass_warehouse_access_control=bypass_warehouse_access_control,include_hogql=include_hogql,+ expansion_mode=expansion_mode,+ catalog_manifest=catalog_manifest,)diff --git a/products/managed_warehouse/backend/facade/contracts.py b/products/managed_warehouse/backend/facade/contracts.pyindex eff4c3738cb8..52b06319dc40 100644--- a/products/managed_warehouse/backend/facade/contracts.py+++ b/products/managed_warehouse/backend/facade/contracts.py@@ -47,6 +47,7 @@ __all__ = ["ServiceCredentialConnect","ServiceCredentialUnavailable","TrinoCompiledQuery",+ "TrinoExpansionMode",]@@ -310,6 +311,11 @@ class TrinoCompiledQuery:hogql: str | None = None+class TrinoExpansionMode(StrEnum):+ PURE = "pure"+ DJANGO = "django"++@dataclassclass DuckLakeQueryResult:columns: list[str]diff --git a/products/managed_warehouse/backend/tests/test_trino_compiler.py b/products/managed_warehouse/backend/tests/test_trino_compiler.pyindex a75f197e300d..900d238e8e0f 100644--- a/products/managed_warehouse/backend/tests/test_trino_compiler.py+++ b/products/managed_warehouse/backend/tests/test_trino_compiler.py@@ -7,16 +7,14 @@ from rest_framework.response import Responsefrom posthog.schema import HogQLQuery, HogQLQueryModifiers-from posthog.hogql.database.database import Database-from posthog.models import Organization, Team-from posthog.schema_enums import PersonsOnEventsModefrom products.data_modeling.backend.facade.modeling import DataWarehouseModelPathfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.managed_warehouse.backend.facade.contracts import (ManagedWarehouseTableNames,ManagedWarehouseTeamMembership,+ TrinoExpansionMode,)from products.managed_warehouse.backend.table_binding import build_trino_table_locatorsfrom products.managed_warehouse.backend.trino_compiler import (@@ -88,8 +86,6 @@ class TestCompileHogQLToTrinoSQL:def test_preserves_sql_bind_values_and_diagnostics_across_the_transpiler_boundary(self) -> None:team = _team()membership = _membership(team_id=team.pk, organization_id=str(team.organization_id))- database = Database(include_posthog_tables=True)- modifiers = HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS)with (mock.patch(@@ -100,19 +96,11 @@ class TestCompileHogQLToTrinoSQL:"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("posthog.hogql.database.database.Database.create_for") as create_database,+ mock.patch("posthog.hogql.modifiers.create_default_modifiers_for_team") as create_modifiers,mock.patch(- "products.managed_warehouse.backend.trino_compiler.build_trino_table_locators",- return_value={"events": ("org_catalog", "posthog", "events_production")},- ),- mock.patch(- "products.access_control.backend.property_access_control.get_restricted_properties_with_group_type_index_for_team",- return_value=set(),- ),+ "products.managed_warehouse.backend.trino_compiler.build_trino_table_locators"+ ) as build_locators,):compiled = compile_hogql_to_trino_sql(team.pk,@@ -121,6 +109,10 @@ class TestCompileHogQLToTrinoSQL:include_hogql=True,)+ create_database.assert_not_called()+ create_modifiers.assert_not_called()+ build_locators.assert_not_called()+assert compiled.sql == ('SELECT "org_catalog"."posthog"."events_production"."event" ''FROM "org_catalog"."posthog"."events_production" '@@ -151,7 +143,7 @@ class TestCompileHogQLToTrinoSQL:"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.database.database.Database.create_for", return_value=database) as create_database,mock.patch("posthog.hogql.modifiers.create_default_modifiers_for_team",return_value=modifiers,@@ -170,6 +162,7 @@ class TestCompileHogQLToTrinoSQL:HogQLQuery(query="SELECT event FROM events LIMIT 1"),team=team,include_hogql=include_hogql,+ expansion_mode=TrinoExpansionMode.DJANGO,)assert compiled.sql == "SELECT event FROM target"@@ -181,6 +174,7 @@ class TestCompileHogQLToTrinoSQL:catalog_name="org_catalog",table_names=membership.table_names,)+ create_database.assert_called_once()trino_context = prepare_and_print.call_args_list[0].args[1]assert trino_context.trino_table_locators == locatorsassert trino_context.modifiers is modifiersdiff --git a/products/managed_warehouse/backend/trino_compiler.py b/products/managed_warehouse/backend/trino_compiler.pyindex 4d82555e981e..aa5e5fa6d5fc 100644--- a/products/managed_warehouse/backend/trino_compiler.py+++ b/products/managed_warehouse/backend/trino_compiler.py@@ -3,24 +3,43 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any, castimport structlog+from prometheus_client import Counterfrom rest_framework import status-from products.managed_warehouse.backend.facade.contracts import TrinoCompiledQuery+from products.managed_warehouse.backend.facade.contracts import TrinoCompiledQuery, TrinoExpansionModefrom products.managed_warehouse.backend.facade.cp_teams import get_org_team_membershipfrom products.managed_warehouse.backend.table_binding import build_trino_table_locatorsif TYPE_CHECKING:from posthog.schema import HogQLQuery+ from posthog.hogql.transforms.trino.manifest import TrinoCatalogManifest+from posthog.models import Team, Userlogger = structlog.get_logger(__name__)+TRINO_COMPILATION_TOTAL = Counter(+ "managed_warehouse_trino_compilation_total",+ "Managed warehouse Trino compilations by semantic expansion mode.",+ labelnames=["mode"],+)+TRINO_PURE_REJECTION_TOTAL = Counter(+ "managed_warehouse_trino_pure_rejection_total",+ "Pure managed warehouse Trino compilation rejections by stable feature code.",+ labelnames=["feature_code"],+)+class TrinoTargetUnavailable(RuntimeError):pass+def _reject_pure_compilation(error: Exception, *, feature_code: str) -> None:+ TRINO_PURE_REJECTION_TOTAL.labels(feature_code=feature_code).inc()+ raise error++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@@ -55,12 +74,16 @@ def compile_hogql_to_trino_sql(user: User | None = None,bypass_warehouse_access_control: bool = False,include_hogql: bool = False,+ expansion_mode: TrinoExpansionMode = TrinoExpansionMode.PURE,+ catalog_manifest: TrinoCatalogManifest | None = None,) -> 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 compilewithout a user. This entry point does not execute the returned SQL or alter query routing.- Set ``include_hogql`` to render normalized HogQL for diagnostics.+ Set ``include_hogql`` to render normalized HogQL for diagnostics. Pure manifest-backed+ compilation is the default; select ``TrinoExpansionMode.DJANGO`` only when the query needs+ actions, cohorts, saved queries, variables, filters, or other Django-backed semantics."""from posthog.hogql import ast # noqa: PLC0415from posthog.hogql.context import HogQLContext # noqa: PLC0415@@ -85,6 +108,106 @@ def compile_hogql_to_trino_sql(if membership is None:raise TrinoTargetUnavailable("The project does not have an authoritative physical table mapping")+ TRINO_COMPILATION_TOTAL.labels(mode=expansion_mode.value).inc()+ if expansion_mode == TrinoExpansionMode.PURE:+ from posthog.hogql.transforms.trino.errors import TrinoLoweringError # noqa: PLC0415+ from posthog.hogql.transforms.trino.manifest import ( # noqa: PLC0415+ TrinoCatalogManifest,+ TrinoManifestTable,+ transpile_hogql_to_trino,+ )++ from posthog.schema_enums import PersonsOnEventsMode # noqa: PLC0415+ from posthog.week_start_day import WeekStartDay # noqa: PLC0415++ if query.filters is not None:+ _reject_pure_compilation(+ TrinoLoweringError(+ "TRINO_PURE_FILTERS_UNSUPPORTED",+ "query filters",+ detail="Query filters require Django semantic expansion.",+ ),+ feature_code="TRINO_PURE_FILTERS_UNSUPPORTED",+ )+ if query.variables:+ _reject_pure_compilation(+ TrinoLoweringError(+ "TRINO_PURE_VARIABLES_UNSUPPORTED",+ "query variables",+ detail="Query variables require Django semantic expansion.",+ ),+ feature_code="TRINO_PURE_VARIABLES_UNSUPPORTED",+ )++ modifiers = query.modifiers+ explicitly_set_modifiers = set(modifiers.model_fields_set) if modifiers is not None else set()+ supported_modifiers = {"personsOnEventsMode", "convertToProjectTimezone"}+ unsupported_modifiers = explicitly_set_modifiers - supported_modifiers+ if unsupported_modifiers:+ unsupported = ", ".join(sorted(unsupported_modifiers))+ _reject_pure_compilation(+ TrinoLoweringError(+ "TRINO_PURE_MODIFIER_UNSUPPORTED",+ "query modifier",+ detail=f"Pure Trino transpilation does not support these modifiers: {unsupported}.",+ ),+ feature_code="TRINO_PURE_MODIFIER_UNSUPPORTED",+ )+ persons_mode = modifiers.personsOnEventsMode if modifiers is not None else None+ if persons_mode not in (None, PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS):+ mode_name = persons_mode.value if persons_mode is not None else "unset"+ _reject_pure_compilation(+ TrinoLoweringError(+ "TRINO_PERSONS_ON_EVENTS_MODE_UNSUPPORTED",+ f"personsOnEventsMode={mode_name}",+ detail=(+ "Trino compilation supports only personsOnEventsMode=person_id_override_properties_on_events."+ ),+ ),+ feature_code="TRINO_PERSONS_ON_EVENTS_MODE_UNSUPPORTED",+ )++ additional_tables = catalog_manifest.tables if catalog_manifest is not None else ()+ if any(table.logical_name in {"events", "persons"} for table in additional_tables):+ _reject_pure_compilation(+ TrinoLoweringError(+ "TRINO_PURE_CORE_TABLE_OVERRIDE",+ "core table manifest",+ detail="Managed warehouse compilation owns the events and persons physical mappings.",+ ),+ feature_code="TRINO_PURE_CORE_TABLE_OVERRIDE",+ )+ pure_manifest = TrinoCatalogManifest(+ tables=(+ TrinoManifestTable(+ logical_name="events",+ locator=(catalog_name, "posthog", membership.table_names.events_table),+ ),+ TrinoManifestTable(+ logical_name="persons",+ locator=(catalog_name, "posthog", membership.table_names.persons_table),+ ),+ *additional_tables,+ ),+ timezone=team.timezone,+ week_start_day=team.week_start_day or WeekStartDay.SUNDAY,+ )+ try:+ transpiled = transpile_hogql_to_trino(+ query.query,+ manifest=pure_manifest,+ values=query.values,+ convert_to_project_timezone=(modifiers.convertToProjectTimezone if modifiers is not None else None),+ include_hogql=include_hogql,+ )+ except TrinoLoweringError as error:+ TRINO_PURE_REJECTION_TOTAL.labels(feature_code=error.feature_code).inc()+ raise+ return TrinoCompiledQuery(sql=transpiled.sql, values=transpiled.values, hogql=transpiled.hogql)++ if expansion_mode != TrinoExpansionMode.DJANGO:+ raise ValueError(f"Unknown Trino expansion mode: {expansion_mode}")+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