: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): add prepared Trino compiler sessions (#94456)
Bill Guowei Yang60adcc50e699
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.mdindex b92ba3c69cdb..1003b70dc6af 100644--- a/docs/internal/hogql-trino-compiler.md+++ b/docs/internal/hogql-trino-compiler.md@@ -12,6 +12,16 @@ The final Trino transpiler accepts a prepared AST plus frozen snapshots of bindi`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.+Use `prepare_trino_catalog(...)` when several queries share one manifest. Preparation validates the manifest and builds its schema database and physical locator map once. Each `PreparedTrinoCatalog.transpile(...)` call creates a new AST, context, modifiers, and bound-value map, so query state does not cross compilation boundaries.++```python+catalog = prepare_trino_catalog(manifest)+first = catalog.transpile("SELECT event FROM events WHERE event = {event}", values={"event": "signup"})+second = catalog.transpile("SELECT count() FROM events")+```++`transpile_hogql_to_trino(...)` remains the one-shot wrapper and prepares a catalog for that call. The manifest contract has no version field, so the compiler does not keep a process-global prepared-catalog cache. Callers must create a new prepared catalog when their immutable manifest snapshot changes.+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 connection integration@@ -57,6 +67,15 @@ After deployment, Django shell can call the same compilation API. Construct theFor 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`.+Batch and session callers should use `prepare_hogql_to_trino_compiler(...)` through the same facade. Preparation resolves and validates the ready catalog and project mapping once, then builds the pure manifest catalog. The returned compiler is bound to that organization, project, and catalog and accepts only a `HogQLQuery` per compilation. Additional manifest relations keep their explicitly allowlisted physical locators; Trino authorizes catalog access when the query executes.++```python+compiler = prepare_hogql_to_trino_compiler(team_id, team=team, catalog_manifest=manifest)+queries = [compiler.compile(query) for query in batch]+```++Create a new compiler when the batch needs fresh control-plane placement or team-table mappings. The one-shot `compile_hogql_to_trino_sql(...)` API prepares and compiles in one call. Django expansion stays one-shot because its schema and semantic expansion depend on query-specific team and user state.+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;diff --git a/posthog/hogql/context.py b/posthog/hogql/context.pyindex d44f652e7951..6346effd37e4 100644--- a/posthog/hogql/context.py+++ b/posthog/hogql/context.py@@ -1,3 +1,4 @@+from collections.abc import Mappingfrom dataclasses import dataclass, fieldfrom datetime import datetimefrom functools import cached_property@@ -69,7 +70,7 @@ class HogQLContext:# Metadata discovered for a direct Postgres connection, if one is selecteddirect_postgres_connection_metadata: dict[str, Any] | None = None# Query-scoped mappings preserve resolved logical tables through Trino lowering.- trino_table_locators: dict[str, tuple[str, str, str]] = field(default_factory=dict)+ trino_table_locators: Mapping[str, tuple[str, str, str]] = field(default_factory=dict)# Detached printer stages snapshot these values so they do not retain the schema database.timezone: Optional[str] = Noneweek_start_day: Optional[WeekStartDay] = Nonediff --git a/posthog/hogql/database/trino_unnest_table.py b/posthog/hogql/database/trino_unnest_table.pyindex f2d9ef10ec53..f4e0fcbbca31 100644--- a/posthog/hogql/database/trino_unnest_table.py+++ b/posthog/hogql/database/trino_unnest_table.py@@ -11,6 +11,9 @@ if TYPE_CHECKING:from posthog.hogql.context import HogQLContext+TRINO_UNNEST_TABLE_NAME = "__trino_unnest"++class TrinoUnnestTable(FunctionCallTable, DANGEROUS_NoTeamIdCheckTable):name: strfields: dict[str, FieldOrTable] = {"value": UnknownDatabaseField(name="value")}@@ -22,3 +25,10 @@ class TrinoUnnestTable(FunctionCallTable, DANGEROUS_NoTeamIdCheckTable):def to_printed_trino(self, context: "HogQLContext") -> str:return "UNNEST"+++TRINO_UNNEST_TABLE = TrinoUnnestTable(name=TRINO_UNNEST_TABLE_NAME)+++def resolve_internal_trino_table_function(table_name_chain: list[str]) -> TrinoUnnestTable | None:+ return TRINO_UNNEST_TABLE if table_name_chain == [TRINO_UNNEST_TABLE_NAME] else Nonediff --git a/posthog/hogql/printer/test/test_trino_printer.py b/posthog/hogql/printer/test/test_trino_printer.pyindex beca963f3cbe..bcb2a4c27e01 100644--- a/posthog/hogql/printer/test/test_trino_printer.py+++ b/posthog/hogql/printer/test/test_trino_printer.py@@ -83,7 +83,7 @@ def test_prepared_trino_transpiler_does_not_rebuild_the_schema_database() -> Nontranspiler_input = TrinoTranspilerInput(node=prepared,values=tuple(preparation_context.values.items()),- table_locators=tuple(preparation_context.trino_table_locators.items()),+ table_locators=preparation_context.trino_table_locators,persons_on_events_mode=preparation_context.modifiers.personsOnEventsMode,convert_to_project_timezone=preparation_context.modifiers.convertToProjectTimezone,limit_top_select=preparation_context.limit_top_select,@@ -457,6 +457,19 @@ def test_lowers_single_array_join_to_cross_join_unnest() -> None:)+def test_internal_unnest_function_is_not_shadowed_by_a_cte() -> None:+ context = _context_with_trino_table()++ sql, _ = prepare_and_print_ast(+ parse_select("WITH __trino_unnest AS (SELECT 1 AS value) SELECT arrayJoin([1, 2]) AS item"),+ context,+ "trino",+ )++ assert "FROM UNNEST(transform(ARRAY[1, 2]" in sql+ assert 'AS "__trino_array_function_0" ("value_0")' in sql++def test_rejects_multi_array_join_with_different_cardinality_semantics() -> None:context = _context_with_trino_table()diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.pyindex 7fc2cfdfaf67..3b6bdd9b125b 100644--- a/posthog/hogql/printer/utils.py+++ b/posthog/hogql/printer/utils.py@@ -126,7 +126,7 @@ def prepare_and_print_ast(TrinoTranspilerInput(node=prepared_ast,values=tuple(context.values.items()),- table_locators=tuple(context.trino_table_locators.items()),+ table_locators=context.trino_table_locators,persons_on_events_mode=context.modifiers.personsOnEventsMode,convert_to_project_timezone=context.modifiers.convertToProjectTimezone,limit_top_select=context.limit_top_select,diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex 012455a021c4..40ea4d094c8e 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -24,6 +24,7 @@ from posthog.hogql.database.schema.duckdb_table_functions import ()from posthog.hogql.database.schema.events import EventsTablefrom posthog.hogql.database.schema.persons import PersonsTable+from posthog.hogql.database.trino_unnest_table import resolve_internal_trino_table_functionfrom posthog.hogql.errors import ImpossibleASTError, NotImplementedError, QueryError, ResolutionErrorfrom posthog.hogql.escape_sql import safe_identifierfrom posthog.hogql.functions import find_hogql_posthog_function@@ -1319,7 +1320,12 @@ class Resolver(CloningVisitor):if table_alias in scope.tables:raise QueryError(f'Already have joined a table called "{table_alias}". Can\'t redefine.')- cte_table = self.ctes.get(".".join(table_name_chain))+ internal_table_function = (+ resolve_internal_trino_table_function(table_name_chain)+ if self.dialect == "trino" and node.table_args is not None+ else None+ )+ cte_table = self.ctes.get(".".join(table_name_chain)) if internal_table_function is None else Noneif cte_table:assert isinstance(cte_table.expr.type, ast.SelectQueryType | ast.SelectSetQueryType)# Use CTETableType so that fields are properly qualified with the CTE name when printed@@ -1354,9 +1360,11 @@ class Resolver(CloningVisitor):return nodeif 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)+ database_table = (+ internal_table_function+ or 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 = Nonediff --git a/posthog/hogql/transforms/trino/manifest.py b/posthog/hogql/transforms/trino/manifest.pyindex 9926756f69c9..7ee2df08b2bc 100644--- a/posthog/hogql/transforms/trino/manifest.py+++ b/posthog/hogql/transforms/trino/manifest.py@@ -1,6 +1,8 @@from __future__ import annotationsfrom collections.abc import Mapping+from dataclasses import field+from types import MappingProxyTypefrom typing import Anyfrom posthog.schema import HogQLFilters, HogQLQueryModifiers, HogQLVariable@@ -69,6 +71,46 @@ class TrinoManifestTranspilerResult:print_columns: tuple[str, ...] = ()+@frozen+class PreparedTrinoCatalog:+ """A reusable catalog snapshot that creates fresh query state for every transpilation."""++ manifest: TrinoCatalogManifest+ _database: Database = field(repr=False, compare=False)+ _table_locators: Mapping[str, TrinoTableLocator] = field(repr=False, compare=False)++ def transpile(+ self,+ query: str | ast.SelectQuery | ast.SelectSetQuery,+ *,+ values: Mapping[str, object] | None = None,+ filters: HogQLFilters | None = None,+ variables: Mapping[str, HogQLVariable] | None = None,+ modifiers: HogQLQueryModifiers | None = None,+ convert_to_project_timezone: bool | None = None,+ limit_top_select: bool = True,+ limit_context: LimitContext | None = None,+ default_limit: int | None = None,+ pretty: bool = False,+ include_hogql: bool = False,+ ) -> TrinoManifestTranspilerResult:+ return transpile_hogql_to_trino_with_database(+ query,+ database=self._database,+ locators=self._table_locators,+ values=values,+ filters=filters,+ variables=variables,+ modifiers=modifiers,+ convert_to_project_timezone=convert_to_project_timezone,+ limit_top_select=limit_top_select,+ limit_context=limit_context,+ default_limit=default_limit,+ pretty=pretty,+ include_hogql=include_hogql,+ )++_CORE_TABLES = frozenset({"events", "persons"})_SUPPORTED_PURE_MODIFIERS = frozenset({"personsOnEventsMode", "convertToProjectTimezone"})_FIELD_TYPES: dict[DatabaseSerializedFieldType, type[DatabaseField]] = {@@ -260,6 +302,15 @@ def _validate_pure_inputs()+def prepare_trino_catalog(manifest: TrinoCatalogManifest) -> PreparedTrinoCatalog:+ database, table_locators = build_trino_manifest_database(manifest)+ return PreparedTrinoCatalog(+ manifest=manifest,+ _database=database,+ _table_locators=MappingProxyType(table_locators),+ )++def transpile_hogql_to_trino(query: str | ast.SelectQuery | ast.SelectSetQuery,*,@@ -275,11 +326,8 @@ def transpile_hogql_to_trino(pretty: bool = False,include_hogql: bool = False,) -> TrinoManifestTranspilerResult:- database, locators = build_trino_manifest_database(manifest)- return transpile_hogql_to_trino_with_database(+ return prepare_trino_catalog(manifest).transpile(query,- database=database,- locators=locators,values=values,filters=filters,variables=variables,@@ -337,7 +385,7 @@ def transpile_hogql_to_trino_with_database()_UnsupportedSemanticFeatureFinder().visit(node)- table_locators = dict(locators) if locators else {}+ table_locators = locators if locators is not None else {}def create_context() -> HogQLContext:return HogQLContext(diff --git a/posthog/hogql/transforms/trino/normalize.py b/posthog/hogql/transforms/trino/normalize.pyindex 969b2532f098..2e7e085e636a 100644--- a/posthog/hogql/transforms/trino/normalize.py+++ b/posthog/hogql/transforms/trino/normalize.py@@ -1,8 +1,7 @@from posthog.hogql import astfrom posthog.hogql.context import HogQLContext-from posthog.hogql.database.models import TableNodefrom posthog.hogql.database.schema.numbers import NumbersTable-from posthog.hogql.database.trino_unnest_table import TrinoUnnestTable+from posthog.hogql.database.trino_unnest_table import TRINO_UNNEST_TABLE_NAMEfrom posthog.hogql.transforms.trino.any_join import lower_trino_any_joinsfrom posthog.hogql.transforms.trino.errors import TrinoLoweringErrorfrom posthog.hogql.transforms.trino.query_wrappers import lower_trino_query_wrappers@@ -164,7 +163,7 @@ class TrinoArrayJoinFunctionLowerer(CloningVisitor):for table_name, output_name, array_expr in pending:join = ast.JoinExpr(join_type="CROSS JOIN" if lowered.select_from is not None else None,- table=ast.Field(chain=[table_name]),+ table=ast.Field(chain=[TRINO_UNNEST_TABLE_NAME]),table_args=[_wrap_unnest_elements(array_expr, f"{table_name}_value")],alias=table_name,column_aliases=[output_name],@@ -183,17 +182,9 @@ class TrinoArrayJoinFunctionLowerer(CloningVisitor):return super().visit_call(node)if len(node.args) != 1:raise TrinoLoweringError("TRINO_ARRAY_JOIN_ARGUMENT_COUNT", "arrayJoin with other than one argument", node)- if self.context.database is None:- raise TrinoLoweringError(- "TRINO_ARRAY_JOIN_DATABASE_REQUIRED", "arrayJoin without a resolved database", node- )table_name = f"__trino_array_function_{self.unnest_index}"output_name = f"value_{self.unnest_index}"self.unnest_index += 1- self.context.database.tables.add_child(- TableNode(name=table_name, table=TrinoUnnestTable(name=table_name)),- table_conflict_mode="override",- )self.pending_unnests.append((table_name, output_name, self.visit(node.args[0])))return ast.Field(chain=[output_name], start=node.start, end=node.end)@@ -225,23 +216,14 @@ class TrinoNormalizer(TraversingVisitor):raise TrinoLoweringError("TRINO_ARRAY_JOIN_ALIAS_REQUIRED", "ARRAY JOIN without an output alias", node)if node.select_from is None:raise TrinoLoweringError("TRINO_ARRAY_JOIN_RELATION_REQUIRED", "ARRAY JOIN without a FROM relation", node)- if self.context.database is None:- raise TrinoLoweringError(- "TRINO_ARRAY_JOIN_DATABASE_REQUIRED", "ARRAY JOIN without a resolved database", node- )-table_name = f"__trino_unnest_{self.unnest_index}"self.unnest_index += 1- self.context.database.tables.add_child(- TableNode(name=table_name, table=TrinoUnnestTable(name=table_name)),- table_conflict_mode="override",- )final_join = node.select_fromwhile final_join.next_join is not None:final_join = final_join.next_joinfinal_join.next_join = ast.JoinExpr(join_type="CROSS JOIN",- table=ast.Field(chain=[table_name]),+ table=ast.Field(chain=[TRINO_UNNEST_TABLE_NAME]),table_args=[_wrap_unnest_elements(array_expr.expr, f"{table_name}_value")],alias=table_name,column_aliases=[array_expr.alias],diff --git a/posthog/hogql/transforms/trino/test/test_manifest.py b/posthog/hogql/transforms/trino/test/test_manifest.pyindex d91b7e172b74..068d55c7660c 100644--- a/posthog/hogql/transforms/trino/test/test_manifest.py+++ b/posthog/hogql/transforms/trino/test/test_manifest.py@@ -1,6 +1,7 @@from typing import Anyimport pytest+from unittest import mockfrom posthog.schema import DateRange, HogQLFilters, HogQLQueryModifiers, HogQLVariable@@ -10,6 +11,8 @@ from posthog.hogql.transforms.trino.manifest import (TrinoCatalogManifest,TrinoManifestColumn,TrinoManifestTable,+ build_trino_manifest_database,+ prepare_trino_catalog,transpile_hogql_to_trino,)@@ -72,6 +75,48 @@ def test_transpiles_manifest_table_without_django_queries(django_assert_num_querassert result.values == {}+def test_prepared_catalog_reuses_metadata_and_isolates_query_state(django_assert_num_queries: Any) -> None:+ manifest = _manifest(_events())++ with (+ django_assert_num_queries(0),+ mock.patch(+ "posthog.hogql.transforms.trino.manifest.build_trino_manifest_database",+ wraps=build_trino_manifest_database,+ ) as build_database,+ ):+ catalog = prepare_trino_catalog(manifest)+ first = catalog.transpile("SELECT {value}", values={"value": "first"}, limit_top_select=False)+ second = catalog.transpile("SELECT {value}", values={"value": "second"})+ unnested = catalog.transpile("SELECT arrayJoin([1, 2])")++ build_database.assert_called_once_with(manifest)+ assert first.values == {"hogql_val_0": "first"}+ assert second.values == {"hogql_val_0": "second"}+ assert "LIMIT" not in first.sql+ assert second.sql.endswith("LIMIT 50000")+ assert "UNNEST" in unnested.sql++ first.values["hogql_val_0"] = "changed"+ assert second.values == {"hogql_val_0": "second"}+++def test_manifest_relation_can_share_the_internal_unnest_function_name() -> None:+ relation = TrinoManifestTable(+ logical_name="__trino_unnest",+ locator=("org_catalog", "imports", "unnest_rows"),+ columns=(TrinoManifestColumn(name="value", type=DatabaseSerializedFieldType.STRING),),+ )++ result = transpile_hogql_to_trino(+ "SELECT value, arrayJoin([1, 2]) AS item FROM __trino_unnest",+ manifest=_manifest(relation),+ )++ assert 'FROM "org_catalog"."imports"."unnest_rows" AS "__trino_unnest"' in result.sql+ assert "CROSS JOIN UNNEST(transform(ARRAY[1, 2]" in result.sql++@pytest.mark.parametrize(("query", "kwargs", "feature_code"),[diff --git a/posthog/hogql/transforms/trino/transpiler.py b/posthog/hogql/transforms/trino/transpiler.pyindex 09349534eab7..42549f1867e3 100644--- a/posthog/hogql/transforms/trino/transpiler.py+++ b/posthog/hogql/transforms/trino/transpiler.py@@ -1,5 +1,6 @@from __future__ import annotations+from collections.abc import Mappingfrom typing import Anyfrom posthog.schema import HogQLQueryModifiers@@ -23,7 +24,7 @@ from posthog.week_start_day import WeekStartDayclass TrinoTranspilerInput:node: ast.ASTvalues: tuple[tuple[str, Any], ...]- table_locators: tuple[tuple[str, TrinoTableLocator], ...]+ table_locators: Mapping[str, TrinoTableLocator]persons_on_events_mode: PersonsOnEventsMode | Noneconvert_to_project_timezone: bool | Nonelimit_top_select: bool@@ -59,7 +60,7 @@ def transpile_prepared_hogql_to_trino(transpiler_input: TrinoTranspilerInput) ->convertToProjectTimezone=transpiler_input.convert_to_project_timezone,),restricted_properties=set(),- trino_table_locators=dict(transpiler_input.table_locators),+ trino_table_locators=transpiler_input.table_locators,values=dict(transpiler_input.values),timezone=transpiler_input.timezone,week_start_day=transpiler_input.week_start_day,diff --git a/products/managed_warehouse/backend/facade/client.py b/products/managed_warehouse/backend/facade/client.pyindex 9ff7d001d63d..424b74249de4 100644--- a/products/managed_warehouse/backend/facade/client.py+++ b/products/managed_warehouse/backend/facade/client.py@@ -47,6 +47,7 @@ if TYPE_CHECKING:TrinoCompiledQuery,)from products.managed_warehouse.backend.service_credentials import ServiceCredential+ from products.managed_warehouse.backend.trino_compiler import PreparedTrinoCompiler__all__ = ["ServiceCredential",@@ -59,6 +60,7 @@ __all__ = ["execute_ducklake_query","make_duckgres_conninfo","mint_service_credential",+ "prepare_hogql_to_trino_compiler","refresh_service_credential","resolve_managed_warehouse_trino_connection",]@@ -107,6 +109,23 @@ def compile_hogql_to_trino_sql()+def prepare_hogql_to_trino_compiler(+ team_id: int,+ *,+ team: Team | None = None,+ catalog_manifest: TrinoCatalogManifest | None = None,+) -> PreparedTrinoCompiler:+ from products.managed_warehouse.backend.trino_compiler import ( # noqa: PLC0415 -- keep the optional compiler off startup paths+ prepare_hogql_to_trino_compiler as _prepare_hogql_to_trino_compiler,+ )++ return _prepare_hogql_to_trino_compiler(+ team_id,+ team=team,+ catalog_manifest=catalog_manifest,+ )++def make_duckgres_conninfo(team_id: int,*,diff --git a/products/managed_warehouse/backend/tests/test_trino_compiler.py b/products/managed_warehouse/backend/tests/test_trino_compiler.pyindex 900d238e8e0f..c41012e644f2 100644--- a/products/managed_warehouse/backend/tests/test_trino_compiler.py+++ b/products/managed_warehouse/backend/tests/test_trino_compiler.py@@ -7,7 +7,15 @@ from rest_framework.response import Responsefrom posthog.schema import HogQLQuery, HogQLQueryModifiers+from posthog.hogql.transforms.trino.manifest import (+ TrinoCatalogManifest,+ TrinoManifestColumn,+ TrinoManifestTable,+ build_trino_manifest_database,+)+from posthog.models import Organization, Team+from posthog.schema_enums import DatabaseSerializedFieldTypefrom products.data_modeling.backend.facade.modeling import DataWarehouseModelPathfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQuery@@ -21,6 +29,7 @@ from products.managed_warehouse.backend.trino_compiler import (TrinoTargetUnavailable,compile_hogql_to_trino_sql,get_ready_trino_catalog_name,+ prepare_hogql_to_trino_compiler,)from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSourcefrom products.warehouse_sources.backend.facade.types import ExternalDataSourceType@@ -212,6 +221,99 @@ class TestCompileHogQLToTrinoSQL:compile_hogql_to_trino_sql(team.pk, HogQLQuery(query="SELECT 1"), team=team)+class TestPreparedTrinoCompiler:+ def test_reuses_one_control_plane_snapshot_for_multiple_queries(self) -> None:+ team = _team()+ membership = _membership(team_id=team.pk, organization_id=str(team.organization_id))++ with (+ mock.patch(+ "products.managed_warehouse.backend.trino_compiler.get_ready_trino_catalog_name",+ return_value="org_catalog",+ ) as get_catalog,+ mock.patch(+ "products.managed_warehouse.backend.trino_compiler.get_org_team_membership",+ return_value=membership,+ ) as get_membership,+ mock.patch(+ "posthog.hogql.transforms.trino.manifest.build_trino_manifest_database",+ wraps=build_trino_manifest_database,+ ) as build_database,+ ):+ compiler = prepare_hogql_to_trino_compiler(team.pk, team=team)+ first = compiler.compile(HogQLQuery(query="SELECT {value}", values={"value": "first"}))+ second = compiler.compile(HogQLQuery(query="SELECT {value}", values={"value": "second"}))++ get_catalog.assert_called_once_with(str(team.organization_id))+ get_membership.assert_called_once_with(str(team.organization_id), team.pk)+ build_database.assert_called_once()+ assert compiler.team_id == team.pk+ assert compiler.organization_id == str(team.organization_id)+ assert compiler.catalog_name == "org_catalog"+ assert first.values == {"hogql_val_0": "first"}+ assert second.values == {"hogql_val_0": "second"}++ def test_rejects_a_team_object_for_another_project(self) -> None:+ team = _team()++ with mock.patch(+ "products.managed_warehouse.backend.trino_compiler.get_ready_trino_catalog_name"+ ) as get_catalog:+ with pytest.raises(TrinoTargetUnavailable, match="provided team"):+ prepare_hogql_to_trino_compiler(team.pk + 1, team=team)++ get_catalog.assert_not_called()++ def test_rejects_a_control_plane_mapping_for_another_tenant(self) -> None:+ team = _team()+ membership = _membership(team_id=team.pk, organization_id="another-organization")++ 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,+ ),+ ):+ with pytest.raises(TrinoTargetUnavailable, match="mapping does not match"):+ prepare_hogql_to_trino_compiler(team.pk, team=team)++ def test_preserves_explicitly_allowlisted_relations_from_another_catalog(self) -> None:+ team = _team()+ membership = _membership(team_id=team.pk, organization_id=str(team.organization_id))+ manifest = TrinoCatalogManifest(+ tables=(+ TrinoManifestTable(+ logical_name="orders",+ locator=("another_catalog", "imports", "orders"),+ columns=(TrinoManifestColumn(name="id", type=DatabaseSerializedFieldType.STRING),),+ ),+ )+ )++ 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,+ ),+ ):+ compiled = compile_hogql_to_trino_sql(+ team.pk,+ HogQLQuery(query="SELECT id FROM orders"),+ team=team,+ catalog_manifest=manifest,+ )++ assert 'FROM "another_catalog"."imports"."orders"' in compiled.sql++@pytest.mark.django_dbdef test_build_trino_table_locators_uses_provisioned_names_and_canonical_source_aliases() -> None:organization = Organization.objects.create(name="trino-locators")diff --git a/products/managed_warehouse/backend/trino_compiler.py b/products/managed_warehouse/backend/trino_compiler.pyindex 3d02dce9de0e..c8cf2a287d9f 100644--- a/products/managed_warehouse/backend/trino_compiler.py+++ b/products/managed_warehouse/backend/trino_compiler.py@@ -1,11 +1,14 @@from __future__ import annotations+from dataclasses import fieldfrom typing import TYPE_CHECKING, Any, castimport structlogfrom prometheus_client import Counterfrom rest_framework import status+from posthog.dataclasses import frozen+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_locators@@ -13,7 +16,7 @@ from products.managed_warehouse.backend.table_binding import build_trino_table_lif TYPE_CHECKING:from posthog.schema import HogQLQuery- from posthog.hogql.transforms.trino.manifest import TrinoCatalogManifest+ from posthog.hogql.transforms.trino.manifest import PreparedTrinoCatalog, TrinoCatalogManifestfrom posthog.models import Team, User@@ -35,6 +38,39 @@ class TrinoTargetUnavailable(RuntimeError):pass+@frozen+class PreparedTrinoCompiler:+ """A validated managed-warehouse target with reusable pure catalog metadata."""++ team_id: int+ organization_id: str+ catalog_name: str+ _catalog: PreparedTrinoCatalog = field(repr=False, compare=False)++ def compile(self, query: HogQLQuery, *, include_hogql: bool = False) -> TrinoCompiledQuery:+ from posthog.hogql.transforms.trino.errors import TrinoLoweringError # noqa: PLC0415++ TRINO_COMPILATION_TOTAL.labels(mode=TrinoExpansionMode.PURE.value).inc()+ try:+ transpiled = self._catalog.transpile(+ query.query,+ values=query.values,+ filters=query.filters,+ variables=query.variables,+ modifiers=query.modifiers,+ 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)+++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@@ -61,6 +97,70 @@ def get_ready_trino_catalog_name(organization_id: str) -> str | None:return catalog_name.strip() if isinstance(catalog_name, str) and catalog_name.strip() else None+def prepare_hogql_to_trino_compiler(+ team_id: int,+ *,+ team: Team | None = None,+ catalog_manifest: TrinoCatalogManifest | None = None,+) -> PreparedTrinoCompiler:+ from posthog.hogql.transforms.trino.errors import TrinoLoweringError # noqa: PLC0415+ from posthog.hogql.transforms.trino.manifest import ( # noqa: PLC0415+ TrinoCatalogManifest,+ TrinoManifestTable,+ prepare_trino_catalog,+ )++ from posthog.models.team.team import Team # noqa: PLC0415+ from posthog.week_start_day import WeekStartDay # noqa: PLC0415++ team = team or Team.objects.get(pk=team_id)+ if team.pk != team_id:+ raise TrinoTargetUnavailable("The provided team does not match the requested project")++ 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")+ if membership.team_id != team_id or str(membership.organization_id) != organization_id:+ raise TrinoTargetUnavailable("The physical table mapping does not match the requested project")++ 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,+ )+ return PreparedTrinoCompiler(+ team_id=team_id,+ organization_id=organization_id,+ catalog_name=catalog_name,+ _catalog=prepare_trino_catalog(pure_manifest),+ )++def compile_hogql_to_trino_sql(team_id: int,query: HogQLQuery,@@ -80,6 +180,13 @@ def compile_hogql_to_trino_sql(compilation is the default; select ``TrinoExpansionMode.DJANGO`` only when the query needsactions, cohorts, saved queries, variables, filters, or other Django-backed semantics."""+ if expansion_mode == TrinoExpansionMode.PURE:+ return prepare_hogql_to_trino_compiler(+ team_id,+ team=team,+ catalog_manifest=catalog_manifest,+ ).compile(query, include_hogql=include_hogql)+from posthog.hogql import ast # noqa: PLC0415from posthog.hogql.context import HogQLContext # noqa: PLC0415from posthog.hogql.database.database import Database # noqa: PLC0415@@ -104,55 +211,6 @@ def compile_hogql_to_trino_sql(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.week_start_day import WeekStartDay # noqa: PLC0415-- 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):- error = TrinoLoweringError(- "TRINO_PURE_CORE_TABLE_OVERRIDE",- "core table manifest",- detail="Managed warehouse compilation owns the events and persons physical mappings.",- )- TRINO_PURE_REJECTION_TOTAL.labels(feature_code=error.feature_code).inc()- raise error- 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,- filters=query.filters,- variables=query.variables,- modifiers=query.modifiers,- 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}")