: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(managed-warehouse): add managed Trino connections (#92846)
Eric Duong1b47d413292a
diff --git a/docs/internal/hogql-trino-compiler.md b/docs/internal/hogql-trino-compiler.mdindex d9c0ba62a389..3e63c6088970 100644--- a/docs/internal/hogql-trino-compiler.md+++ b/docs/internal/hogql-trino-compiler.md@@ -8,7 +8,15 @@ 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.-Query Editor capability changes, case-insensitive connection lookup, and parameter submission belong to a separate connection-integration change. They are not prerequisites for compilation.+Query Editor capability changes, case-insensitive connection lookup, and parameter submission belong to separate integration changes. They are not prerequisites for compilation.++## Managed Trino connections++Call `resolve_managed_warehouse_trino_connection(...)` through the managed-warehouse client facade when a backend job needs a live Trino target. The resolver accepts a target only when the control plane reports the organization as enabled and ready. It reads the catalog plus non-secret host, port, and username from `status.connection`, then combines them with the root password already stored for the managed warehouse. The connection contract redacts that password from its representation.++Call `connect_managed_warehouse_trino(...)` to open the Python Trino client with basic authentication, HTTPS, certificate verification, and a bounded request timeout. The connector has no Duckgres fallback. A disabled target, non-ready state, organization mismatch, malformed endpoint, or missing stored credential fails before opening a socket.++The Django `DuckgresServer` row remains the transitional owner of the existing root secret; it does not become the source of truth for Trino placement. Trino cell assignment, endpoint identity, and catalog naming stay in the control plane. No second Django model or copied control-plane status is required.For supported string, array, and map arguments, `empty(x)` returns true when the value is NULL or has zero length. `notEmpty(x)` requires a non-NULL value with nonzero length. String predicates use an empty-string comparison; arrays and maps use `cardinality`.diff --git a/products/managed_warehouse/backend/facade/client.py b/products/managed_warehouse/backend/facade/client.pyindex 55caa60c3e45..8f79ea48e321 100644--- a/products/managed_warehouse/backend/facade/client.py+++ b/products/managed_warehouse/backend/facade/client.py@@ -1,9 +1,9 @@"""DuckLake query-client surface for managed_warehouse.-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.+Connect to managed Trino, compile queries for managed DuckLake data, and run queries against+an org's duckgres server. This surface serves the endpoints shadow path, data-modeling+materialization, and the duckling backfill.Delegates to ``client`` at call time rather than re-exporting its functions: a boundre-export would freeze a copy that ``@patch`` on the source module never reaches. The@@ -13,9 +13,11 @@ result types live in ``facade.contracts``.from __future__ import annotationsfrom collections.abc import Sequence+from contextlib import AbstractContextManagerfrom typing import TYPE_CHECKINGfrom products.managed_warehouse.backend import client+from products.managed_warehouse.backend.facade.contracts import ManagedWarehouseTrinoConnectionUnavailablefrom products.managed_warehouse.backend.service_credentials import (ServiceCredential,ServiceCredentialUnavailable,@@ -24,6 +26,8 @@ from products.managed_warehouse.backend.service_credentials import ()if TYPE_CHECKING:+ from trino.dbapi import Connection+from posthog.schema import HogQLQueryfrom posthog.models.team.team import Team@@ -34,6 +38,7 @@ if TYPE_CHECKING:DuckLakeQueryResult,DuckLakeS3Secret,DuckLakeTableResult,+ ManagedWarehouseTrinoConnection,TrinoCompiledQuery,)from products.managed_warehouse.backend.service_credentials import ServiceCredential@@ -41,16 +46,35 @@ if TYPE_CHECKING:__all__ = ["ServiceCredential","ServiceCredentialUnavailable",+ "ManagedWarehouseTrinoConnectionUnavailable","compile_hogql_to_ducklake_sql","compile_hogql_to_trino_sql",+ "connect_managed_warehouse_trino","execute_ducklake_create_table","execute_ducklake_query","make_duckgres_conninfo","mint_service_credential","refresh_service_credential",+ "resolve_managed_warehouse_trino_connection",]+def resolve_managed_warehouse_trino_connection(organization_id: str) -> ManagedWarehouseTrinoConnection:+ from products.managed_warehouse.backend.trino_connection import ( # noqa: PLC0415 -- keep the optional connection path off startup paths+ resolve_managed_warehouse_trino_connection as _resolve_managed_warehouse_trino_connection,+ )++ return _resolve_managed_warehouse_trino_connection(organization_id)+++def connect_managed_warehouse_trino(organization_id: str) -> AbstractContextManager[Connection]:+ from products.managed_warehouse.backend.trino_connection import ( # noqa: PLC0415 -- keep the optional connection path off startup paths+ connect_managed_warehouse_trino as _connect_managed_warehouse_trino,+ )++ return _connect_managed_warehouse_trino(organization_id)++def compile_hogql_to_trino_sql(team_id: int,query: HogQLQuery,diff --git a/products/managed_warehouse/backend/facade/contracts.py b/products/managed_warehouse/backend/facade/contracts.pyindex 418546635cde..eff4c3738cb8 100644--- a/products/managed_warehouse/backend/facade/contracts.py+++ b/products/managed_warehouse/backend/facade/contracts.py@@ -33,6 +33,8 @@ __all__ = ["DucklingTables","ManagedWarehouseBackfillState","ManagedWarehousePostgresConnection",+ "ManagedWarehouseTrinoConnection",+ "ManagedWarehouseTrinoConnectionUnavailable","ManagedWarehouseProvisionStatus","ManagedWarehouseSourceAuth","ManagedWarehouseSourceJobRecord",@@ -113,6 +115,21 @@ class ManagedWarehousePostgresConnection:sslmode: str+@frozen+class ManagedWarehouseTrinoConnection:+ """A ready managed Trino target with the existing organization root secret."""++ host: str+ port: int+ catalog: str+ username: str+ password: str = field(repr=False)+++class ManagedWarehouseTrinoConnectionUnavailable(RuntimeError):+ pass++@frozenclass ManagedWarehouseSourceAuth:"""Non-secret source fields needed to choose managed warehouse authentication."""diff --git a/products/managed_warehouse/backend/tests/test_trino_connection.py b/products/managed_warehouse/backend/tests/test_trino_connection.pynew file mode 100644index 000000000000..d3dc66157652--- /dev/null+++ b/products/managed_warehouse/backend/tests/test_trino_connection.py@@ -0,0 +1,154 @@+import pytest+from unittest import mock++from rest_framework.response import Response++from products.managed_warehouse.backend.facade.contracts import (+ DuckgresQueryServerConfig,+ ManagedWarehouseTrinoConnectionUnavailable,+)+from products.managed_warehouse.backend.trino_connection import (+ connect_managed_warehouse_trino,+ resolve_managed_warehouse_trino_connection,+)+++def _ready_response(**connection_overrides: object) -> Response:+ return Response(+ {+ "enabled": True,+ "status": {+ "org": "org-1",+ "state": "ready",+ "trino_catalog_name": "org_catalog",+ "connection": {+ "host": "trino.postwh.com",+ "port": 8443,+ "username": "org_database",+ **connection_overrides,+ },+ },+ },+ status=200,+ )+++def _root_connection(password: str = "root-secret") -> DuckgresQueryServerConfig:+ return DuckgresQueryServerConfig(+ host="duckgres.postwh.com",+ port=5432,+ flight_port=8815,+ database="ducklake",+ username="root",+ password=password,+ )+++class TestResolveManagedWarehouseTrinoConnection:+ def test_combines_the_control_plane_target_with_the_existing_root_secret(self) -> None:+ with (+ mock.patch(+ "products.managed_warehouse.backend.presentation.views._request",+ return_value=_ready_response(),+ ) as request,+ mock.patch(+ "products.managed_warehouse.backend.trino_connection.get_duckgres_query_server_config",+ return_value=_root_connection(),+ ),+ ):+ connection = resolve_managed_warehouse_trino_connection("org-1")++ assert connection.host == "trino.postwh.com"+ assert connection.port == 8443+ assert connection.catalog == "org_catalog"+ assert connection.username == "org_database"+ assert connection.password == "root-secret"+ assert "root-secret" not in repr(connection)+ request.assert_called_once_with("GET", "org-1", "/trino", require_enabled=False)++ @pytest.mark.parametrize(+ "response",+ [+ Response({"enabled": False}, status=200),+ Response({"enabled": True, "status": {"org": "org-1", "state": "pending"}}, status=200),+ Response(+ {+ "enabled": True,+ "status": {+ "state": "ready",+ "trino_catalog_name": "catalog",+ "connection": {"host": "trino.postwh.com", "port": 8443, "username": "org_database"},+ },+ },+ status=200,+ ),+ Response(+ {+ "enabled": True,+ "status": {+ "org": "another-org",+ "state": "ready",+ "trino_catalog_name": "catalog",+ "connection": {"host": "trino.postwh.com", "port": 8443, "username": "org_database"},+ },+ },+ status=200,+ ),+ _ready_response(host=""),+ _ready_response(port=0),+ _ready_response(username=""),+ ],+ )+ def test_rejects_an_unusable_or_cross_organization_target(self, response: Response) -> None:+ with mock.patch("products.managed_warehouse.backend.presentation.views._request", return_value=response):+ with pytest.raises(ManagedWarehouseTrinoConnectionUnavailable, match="ready managed Trino connection"):+ resolve_managed_warehouse_trino_connection("org-1")++ def test_rejects_a_missing_stored_root_secret(self) -> None:+ with (+ mock.patch(+ "products.managed_warehouse.backend.presentation.views._request",+ return_value=_ready_response(),+ ),+ mock.patch(+ "products.managed_warehouse.backend.trino_connection.get_duckgres_query_server_config",+ return_value=_root_connection(password=""),+ ),+ ):+ with pytest.raises(ManagedWarehouseTrinoConnectionUnavailable, match="stored managed warehouse credential"):+ resolve_managed_warehouse_trino_connection("org-1")+++def test_connect_managed_warehouse_trino_enforces_verified_https_and_closes() -> None:+ driver_connection = mock.MagicMock()+ authentication = mock.sentinel.authentication++ with (+ mock.patch(+ "products.managed_warehouse.backend.trino_connection.resolve_managed_warehouse_trino_connection",+ return_value=mock.Mock(+ host="trino.postwh.com",+ port=8443,+ catalog="org_catalog",+ username="org_database",+ password="root-secret",+ ),+ ),+ mock.patch("trino.auth.BasicAuthentication", return_value=authentication) as basic_authentication,+ mock.patch("trino.dbapi.connect", return_value=driver_connection) as connect,+ ):+ with connect_managed_warehouse_trino("org-1") as connection:+ assert connection is driver_connection++ basic_authentication.assert_called_once_with("org_database", "root-secret")+ connect.assert_called_once_with(+ host="trino.postwh.com",+ port=8443,+ user="org_database",+ catalog="org_catalog",+ http_scheme="https",+ auth=authentication,+ request_timeout=60,+ verify=True,+ )+ driver_connection.close.assert_called_once_with()diff --git a/products/managed_warehouse/backend/trino_connection.py b/products/managed_warehouse/backend/trino_connection.pynew file mode 100644index 000000000000..8df1a231c138--- /dev/null+++ b/products/managed_warehouse/backend/trino_connection.py@@ -0,0 +1,64 @@+from __future__ import annotations++from collections.abc import Iterator+from contextlib import contextmanager+from typing import TYPE_CHECKING++from products.managed_warehouse.backend.facade.api import get_duckgres_query_server_config+from products.managed_warehouse.backend.facade.contracts import (+ ManagedWarehouseTrinoConnection,+ ManagedWarehouseTrinoConnectionUnavailable,+)+from products.managed_warehouse.backend.trino_target import get_ready_trino_connection_target++if TYPE_CHECKING:+ from trino.dbapi import Connection+++def resolve_managed_warehouse_trino_connection(organization_id: str) -> ManagedWarehouseTrinoConnection:+ target = get_ready_trino_connection_target(organization_id)+ if target is None:+ raise ManagedWarehouseTrinoConnectionUnavailable(+ "The organization does not have a ready managed Trino connection"+ )++ try:+ root_connection = get_duckgres_query_server_config(organization_id)+ except ValueError as error:+ raise ManagedWarehouseTrinoConnectionUnavailable(+ "The organization does not have a stored managed warehouse credential"+ ) from error+ if not root_connection.password:+ raise ManagedWarehouseTrinoConnectionUnavailable(+ "The organization does not have a stored managed warehouse credential"+ )++ return ManagedWarehouseTrinoConnection(+ host=target.host,+ port=target.port,+ catalog=target.catalog,+ username=target.username,+ password=root_connection.password,+ )+++@contextmanager+def connect_managed_warehouse_trino(organization_id: str) -> Iterator[Connection]:+ from trino.auth import BasicAuthentication # noqa: PLC0415 -- keeps the optional driver off startup paths+ from trino.dbapi import connect # noqa: PLC0415 -- keeps the optional driver off startup paths++ config = resolve_managed_warehouse_trino_connection(organization_id)+ connection = connect(+ host=config.host,+ port=config.port,+ user=config.username,+ catalog=config.catalog,+ http_scheme="https",+ auth=BasicAuthentication(config.username, config.password),+ request_timeout=60,+ verify=True,+ )+ try:+ yield connection+ finally:+ connection.close()diff --git a/products/managed_warehouse/backend/trino_target.py b/products/managed_warehouse/backend/trino_target.pynew file mode 100644index 000000000000..980e340c0d9e--- /dev/null+++ b/products/managed_warehouse/backend/trino_target.py@@ -0,0 +1,70 @@+from __future__ import annotations++from typing import cast++import structlog+from rest_framework import status++from posthog.dataclasses import frozen++from products.managed_warehouse.backend.presentation import views as provisioning_views++logger = structlog.get_logger(__name__)+++@frozen+class _ReadyTrinoConnectionTarget:+ host: str+ port: int+ catalog: str+ username: str+++def _nonempty_string(value: object) -> str | None:+ return value.strip() if isinstance(value, str) and value.strip() else None+++def _ready_trino_status(organization_id: str) -> dict[str, object] | None:+ response = provisioning_views._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 str(response_org) != str(organization_id):+ logger.warning(+ "refusing_trino_target_for_mismatched_organization",+ requested_organization_id=str(organization_id),+ response_organization_id=str(response_org),+ )+ return None+ return cast(dict[str, object], trino_status)+++def get_ready_trino_connection_target(organization_id: str) -> _ReadyTrinoConnectionTarget | None:+ trino_status = _ready_trino_status(organization_id)+ if trino_status is None:+ return None++ catalog = _nonempty_string(trino_status.get("trino_catalog_name") or trino_status.get("catalog"))+ connection = trino_status.get("connection")+ if catalog is None or not isinstance(connection, dict):+ return None++ host = _nonempty_string(connection.get("host"))+ username = _nonempty_string(connection.get("username"))+ port = connection.get("port")+ if (+ host is None+ or username is None+ or isinstance(port, bool)+ or not isinstance(port, int)+ or not 1 <= port <= 65535+ ):+ return None++ return _ReadyTrinoConnectionTarget(host=host, port=port, catalog=catalog, username=username)