: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(data-warehouse): read self-managed parquet in DuckLake (#79802)
Jovan Sakovic1ff3aa80ca16
diff --git a/posthog/hogql/database/s3_table.py b/posthog/hogql/database/s3_table.pyindex 7d4db75654d8..5cf1db1e113f 100644--- a/posthog/hogql/database/s3_table.py+++ b/posthog/hogql/database/s3_table.py@@ -1,6 +1,7 @@import re+from dataclasses import dataclassfrom pathlib import PurePosixPath-from typing import Optional+from typing import Literal, Optionalfrom urllib.parse import urlparse, urlunparsefrom django.conf import settings@@ -12,6 +13,98 @@ from posthog.hogql.escape_sql import escape_hogql_identifierfrom posthog.clickhouse.client.escape import substitute_params+_AWS_S3_ENDPOINT_RE = re.compile(r"s3(?:[.-][a-z0-9-]+)*\.amazonaws\.com(?:\.cn)?")+_AWS_S3_VIRTUAL_HOST_RE = re.compile(r"(?P<bucket>.+)\.(?P<endpoint>s3(?:[.-][a-z0-9-]+)*\.amazonaws\.com(?:\.cn)?)")+_AWS_REGION_RE = re.compile(r"(?:^|[.-])(?P<region>[a-z]{2,4}(?:-[a-z0-9]+)+-\d)(?:\.|$)")+_AZURE_BLOB_HOST_SUFFIX = ".blob.core.windows.net"+_FORMAT_LABELS = {+ "CSV": "CSV",+ "CSVWithNames": "CSV with headers",+ "JSONEachRow": "JSON",+ "Delta": "Delta",+ "DeltaS3Wrapper": "Delta",+}+++@dataclass(frozen=True, kw_only=True)+class DuckDBS3Source:+ uri: str+ scope: str+ endpoint: str | None+ region: str+ use_ssl: bool+ url_style: Literal["path", "vhost"]+++def _split_bucket_and_key(path: str) -> tuple[str, str] | None:+ bucket, separator, key = path.lstrip("/").partition("/")+ if not bucket or not separator or not key:+ return None+ return bucket, key+++def _scope_for_s3_uri(uri: str) -> str:+ wildcard_positions = [position for token in ("*", "?", "[") if (position := uri.find(token)) >= 0]+ return uri[: min(wildcard_positions)] if wildcard_positions else uri+++def _region_for_aws_endpoint(endpoint: str) -> str:+ match = _AWS_REGION_RE.search(endpoint)+ return match.group("region") if match else "us-east-1"+++def parse_duckdb_s3_source(url: str) -> DuckDBS3Source | None:+ parsed = urlparse(url)+ if parsed.scheme == "s3":+ if not parsed.netloc or not parsed.path.lstrip("/"):+ return None+ uri = f"s3://{parsed.netloc}/{parsed.path.lstrip('/')}"+ return DuckDBS3Source(+ uri=uri,+ scope=_scope_for_s3_uri(uri),+ endpoint=None,+ region="us-east-1",+ use_ssl=True,+ url_style="vhost",+ )++ if parsed.scheme not in {"http", "https"} or parsed.hostname is None:+ return None++ hostname = parsed.hostname.lower()+ if hostname.endswith(_AZURE_BLOB_HOST_SUFFIX):+ return None++ endpoint = hostname if parsed.port is None else f"{hostname}:{parsed.port}"+ key = parsed.path.lstrip("/")+ virtual_host_match = _AWS_S3_VIRTUAL_HOST_RE.fullmatch(hostname)+ if virtual_host_match is not None:+ bucket = virtual_host_match.group("bucket")+ aws_endpoint = virtual_host_match.group("endpoint")+ endpoint = aws_endpoint if parsed.port is None else f"{aws_endpoint}:{parsed.port}"+ url_style: Literal["path", "vhost"] = "vhost"+ region = _region_for_aws_endpoint(aws_endpoint)+ else:+ location = _split_bucket_and_key(parsed.path)+ if location is None:+ return None+ bucket, key = location+ url_style = "path"+ region = _region_for_aws_endpoint(hostname) if _AWS_S3_ENDPOINT_RE.fullmatch(hostname) else "us-east-1"++ if not key:+ return None++ uri = f"s3://{bucket}/{key}"+ return DuckDBS3Source(+ uri=uri,+ scope=_scope_for_s3_uri(uri),+ endpoint=endpoint,+ region=region,+ use_ssl=parsed.scheme == "https",+ url_style=url_style,+ )+def build_function_call(url: str,@@ -193,6 +286,31 @@ class S3Table(FunctionCallTable):table_size_mib=self.table_size_mib,)+ def to_printed_duckdb(self, context: HogQLContext) -> str:+ if self.format != "Parquet":+ format_label = _FORMAT_LABELS.get(self.format, self.format)+ raise ExposedHogQLError(+ "DuckLake currently supports Parquet self-managed tables only. "+ f"Support for {format_label} is coming soon. "+ "Use Parquet or run the query without DuckLake for now."+ )++ source = parse_duckdb_s3_source(self.url)+ if source is None:+ hostname = urlparse(self.url).hostname+ if hostname is not None and hostname.lower().endswith(_AZURE_BLOB_HOST_SUFFIX):+ raise ExposedHogQLError(+ "DuckLake currently supports S3-compatible self-managed sources only. "+ "Support for Azure Blob Storage is coming soon. "+ "Run the query without DuckLake for now."+ )+ raise ExposedHogQLError(+ "DuckLake currently supports S3-compatible self-managed sources only. "+ "Use an S3-compatible URL or run the query without DuckLake for now."+ )++ return f"read_parquet({context.add_value(source.uri)}, hive_partitioning = false)"+class DataWarehouseTable(S3Table):"""A table placeholder for checking warehouse tables"""diff --git a/posthog/hogql/database/test/test_s3_table_duckdb.py b/posthog/hogql/database/test/test_s3_table_duckdb.pynew file mode 100644index 000000000000..32b95f4dda8f--- /dev/null+++ b/posthog/hogql/database/test/test_s3_table_duckdb.py@@ -0,0 +1,166 @@+import pytest++from parameterized import parameterized++from posthog.hogql.context import HogQLContext+from posthog.hogql.database.s3_table import DuckDBS3Source, S3Table, parse_duckdb_s3_source+from posthog.hogql.errors import ExposedHogQLError+++class TestParseDuckDBS3Source:+ @parameterized.expand(+ [+ (+ "aws_virtual_host",+ "https://my-bucket.s3.amazonaws.com/data/*.parquet",+ DuckDBS3Source(+ uri="s3://my-bucket/data/*.parquet",+ scope="s3://my-bucket/data/",+ endpoint="s3.amazonaws.com",+ region="us-east-1",+ use_ssl=True,+ url_style="vhost",+ ),+ ),+ (+ "aws_regional_virtual_host",+ "https://my-bucket.s3.eu-west-2.amazonaws.com/data/items.parquet",+ DuckDBS3Source(+ uri="s3://my-bucket/data/items.parquet",+ scope="s3://my-bucket/data/items.parquet",+ endpoint="s3.eu-west-2.amazonaws.com",+ region="eu-west-2",+ use_ssl=True,+ url_style="vhost",+ ),+ ),+ (+ "aws_path_style",+ "https://s3.us-west-1.amazonaws.com/my-bucket/data/*.parquet",+ DuckDBS3Source(+ uri="s3://my-bucket/data/*.parquet",+ scope="s3://my-bucket/data/",+ endpoint="s3.us-west-1.amazonaws.com",+ region="us-west-1",+ use_ssl=True,+ url_style="path",+ ),+ ),+ (+ "aws_china_region",+ "https://my-bucket.s3.cn-north-1.amazonaws.com.cn/data/items.parquet",+ DuckDBS3Source(+ uri="s3://my-bucket/data/items.parquet",+ scope="s3://my-bucket/data/items.parquet",+ endpoint="s3.cn-north-1.amazonaws.com.cn",+ region="cn-north-1",+ use_ssl=True,+ url_style="vhost",+ ),+ ),+ (+ "google_cloud_storage",+ "https://storage.googleapis.com/my-bucket/data/*.parquet",+ DuckDBS3Source(+ uri="s3://my-bucket/data/*.parquet",+ scope="s3://my-bucket/data/",+ endpoint="storage.googleapis.com",+ region="us-east-1",+ use_ssl=True,+ url_style="path",+ ),+ ),+ (+ "cloudflare_r2",+ "https://account-id.r2.cloudflarestorage.com/my-bucket/data/*.parquet",+ DuckDBS3Source(+ uri="s3://my-bucket/data/*.parquet",+ scope="s3://my-bucket/data/",+ endpoint="account-id.r2.cloudflarestorage.com",+ region="us-east-1",+ use_ssl=True,+ url_style="path",+ ),+ ),+ (+ "local_s3_compatible",+ "http://objectstorage:19000/my-bucket/data/items.parquet",+ DuckDBS3Source(+ uri="s3://my-bucket/data/items.parquet",+ scope="s3://my-bucket/data/items.parquet",+ endpoint="objectstorage:19000",+ region="us-east-1",+ use_ssl=False,+ url_style="path",+ ),+ ),+ (+ "s3_uri",+ "s3://my-bucket/data/*.parquet",+ DuckDBS3Source(+ uri="s3://my-bucket/data/*.parquet",+ scope="s3://my-bucket/data/",+ endpoint=None,+ region="us-east-1",+ use_ssl=True,+ url_style="vhost",+ ),+ ),+ (+ "azure_is_not_s3_compatible",+ "https://account.blob.core.windows.net/container/data/*.parquet",+ None,+ ),+ ("missing_object_key", "https://storage.googleapis.com/my-bucket", None),+ ]+ )+ def test_parses_provider_url(+ self,+ _name: str,+ url: str,+ expected: DuckDBS3Source | None,+ ) -> None:+ assert parse_duckdb_s3_source(url) == expected+++class TestS3TableDuckDBPrinting:+ def test_parquet_uses_native_reader_without_credentials(self) -> None:+ context = HogQLContext(team_id=1)+ table = S3Table(+ name="orders",+ url="https://my-bucket.s3.amazonaws.com/data/*.parquet",+ format="Parquet",+ access_key="access-key",+ access_secret="access-secret",+ fields={},+ )++ sql = table.to_printed_duckdb(context)++ assert sql.startswith("read_parquet(")+ assert "hive_partitioning = false" in sql+ assert list(context.values.values()) == ["s3://my-bucket/data/*.parquet"]+ assert "access-key" not in sql+ assert "access-secret" not in sql++ def test_non_parquet_format_has_clear_error(self) -> None:+ table = S3Table(+ name="orders",+ url="https://my-bucket.s3.amazonaws.com/data/*.csv",+ format="CSVWithNames",+ fields={},+ )++ with pytest.raises(ExposedHogQLError, match="Support for CSV with headers is coming soon"):+ table.to_printed_duckdb(HogQLContext(team_id=1))++ def test_azure_has_clear_error(self) -> None:+ table = S3Table(+ name="orders",+ url="https://account.blob.core.windows.net/container/data/*.parquet",+ format="Parquet",+ fields={},+ )++ with pytest.raises(ExposedHogQLError, match="Support for Azure Blob Storage is coming soon"):+ table.to_printed_duckdb(HogQLContext(team_id=1))diff --git a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.pyindex 4fb100e8a5b4..cd481ab54b88 100644--- a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py+++ b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py@@ -26,6 +26,7 @@ from products.managed_warehouse.backend.facade.api import (has_provisioned_warehouse,is_dev_mode,)+from products.managed_warehouse.backend.facade.contracts import DuckLakeCompiledQuery, DuckLakeS3Secretfrom ..metrics import get_node_suspended_metricfrom .utils import (@@ -97,19 +98,18 @@ def _is_duckgres_shadow_enabled(team: Team) -> bool:return False-def _compile_hogql_to_postgres_sql(hogql_query: str, team_id: int) -> tuple[str, dict[str, object]]:+def _compile_hogql_for_ducklake(hogql_query: str, team_id: int) -> DuckLakeCompiledQuery:from posthog.schema import HogQLQueryfrom products.managed_warehouse.backend.facade.client import compile_hogql_to_ducklake_sql- postgres_sql, values, _ = compile_hogql_to_ducklake_sql(+ return compile_hogql_to_ducklake_sql(team_id,HogQLQuery(query=hogql_query),# Userless shadow materialization; mirror ClickHouse materialization so the# model query can resolve its warehouse source tables/views.bypass_warehouse_access_control=True,)- return postgres_sql, values@database_sync_to_async_pool@@ -183,17 +183,21 @@ async def materialize_view_duckgres_activity(inputs: DuckgresShadowInputs) -> Dustart_time = time.monotonic()sql: str = ""values: dict[str, object] = {}+ s3_secrets: tuple[DuckLakeS3Secret, ...] = ()try:if inputs.dangerously_execute_raw_sql:sql = hogql_queryelse:- sql, values = await database_sync_to_async_pool(_compile_hogql_to_postgres_sql)(hogql_query, team.pk)+ compiled = await database_sync_to_async_pool(_compile_hogql_for_ducklake)(hogql_query, team.pk)+ sql = compiled.sql+ values = compiled.values+ s3_secrets = compiled.s3_secretsawait logger.adebug("Duckgres shadow SQL generated", sql=sql)from products.managed_warehouse.backend.facade.client import execute_ducklake_create_tableresult = await database_sync_to_async_pool(execute_ducklake_create_table)(- team.pk, sql, schema_name, table_name, values+ team.pk, sql, schema_name, table_name, values, s3_secrets=s3_secrets)duration = time.monotonic() - start_timediff --git a/products/managed_warehouse/backend/README.md b/products/managed_warehouse/backend/README.mdindex 0b41934f79e4..d31e684ae7b8 100644--- a/products/managed_warehouse/backend/README.md+++ b/products/managed_warehouse/backend/README.md@@ -41,6 +41,14 @@ For local dev the defaults are:- `DUCKGRES_USERNAME=posthog`- `DUCKGRES_PASSWORD=posthog`+## Self-managed object storage reads++The DuckLake query path can read credentialed self-managed Parquet tables directly from S3-compatible object storage. HogQL compiles these tables to DuckDB's `read_parquet` function. Before each query, the Duckgres client creates a temporary secret from the table's `DataWarehouseCredential`. Secrets cover only the tables the compiled query's schema still exposes after warehouse access control, so a query cannot borrow credentials from a table it may not read. Each secret is scoped to the table's object path and disappears when the connection closes. Credentials use query parameters and never appear in the compiled SQL.++Supported URL forms include AWS S3, Google Cloud Storage with HMAC credentials, Cloudflare R2, and other path-style S3-compatible HTTPS endpoints. Local HTTP endpoints such as SeaweedFS are also supported. AWS regions are inferred from regional endpoints. Other providers use `us-east-1` for S3 request signing.++This path currently supports Parquet only. Support for Azure Blob Storage, CSV, JSON, and Delta will follow. Until then, these sources continue to use the existing non-DuckLake query path.+## Feature flag gatingEach workflow is gated by its own feature flag (evaluated via `feature_enabled`). Create or update the appropriate flag locally to target the team you are testing with—otherwise the copy workflow will be skipped even if the rest of the configuration is correct.diff --git a/products/managed_warehouse/backend/client.py b/products/managed_warehouse/backend/client.pyindex a3b6684ec322..46e01d3d353c 100644--- a/products/managed_warehouse/backend/client.py+++ b/products/managed_warehouse/backend/client.py@@ -1,27 +1,40 @@from __future__ import annotationsimport time+import logging+from collections.abc import Sequencefrom typing import TYPE_CHECKING, Anyimport psycopgfrom psycopg import sql as psqlfrom psycopg.conninfo import make_conninfo+from posthog.hogql.database.s3_table import S3Table, parse_duckdb_s3_source+from products.managed_warehouse.backend.common import (get_duckgres_config_for_org,is_dev_mode,sanitize_ducklake_identifier,)-from products.managed_warehouse.backend.facade.contracts import DuckLakeQueryResult, DuckLakeTableResult+from products.managed_warehouse.backend.facade.contracts import (+ DuckLakeCompiledQuery,+ DuckLakeQueryResult,+ DuckLakeS3Secret,+ DuckLakeTableResult,+)from products.managed_warehouse.backend.service_credentials import ServiceCredentialfrom products.managed_warehouse.backend.table_binding import bind_tables_to_ducklakeif TYPE_CHECKING:from posthog.schema import HogQLQuery+ from posthog.hogql.database.database import Database+from posthog.models import Userfrom posthog.models.team.team import Team+logger = logging.getLogger(__name__)+def make_duckgres_conninfo(team_id: int,@@ -99,6 +112,81 @@ def _set_search_path(conn: psycopg.Connection[Any], extra_schemas: list[str] | Nconn.execute(sql)+def _s3_secrets_for_database(database: Database) -> tuple[DuckLakeS3Secret, ...]:+ """Collect the S3 secrets the self-managed tables of a built HogQL database need.++ The table set comes from the database the query was compiled against, so warehouse access+ control has already pruned anything the querier may not read. Reading it from the team's+ tables instead would let a restricted table's credentials serve an allowed one: DuckDB+ matches a secret on its ``s3://bucket/key`` scope alone, ignoring the endpoint, and breaks+ a scope tie by picking the lexicographically smaller secret name.+ """+ secrets: list[DuckLakeS3Secret] = []+ for table_name in database.get_warehouse_table_names():+ try:+ table = database.get_table(table_name)+ except Exception:+ continue+ # Connector-synced tables are rebound to their DuckLake copy and read no object storage.+ if not isinstance(table, S3Table) or table.external_data_source_id or table.table_id is None:+ continue+ if table.format != "Parquet" or not table.access_key or not table.access_secret:+ continue+ source = parse_duckdb_s3_source(table.url)+ if source is None:+ continue+ secrets.append(+ DuckLakeS3Secret(+ name=f"self_managed_{str(table.table_id).replace('-', '')}",+ key_id=table.access_key,+ secret=table.access_secret,+ region=source.region,+ scope=source.scope,+ use_ssl=source.use_ssl,+ url_style=source.url_style,+ endpoint=source.endpoint,+ )+ )+ return tuple(secrets)+++def _configure_s3_secrets(conn: psycopg.Connection[Any], secrets: Sequence[DuckLakeS3Secret]) -> None:+ if not secrets:+ return++ with conn.cursor() as cur:+ for secret in secrets:+ secret_options = [+ psql.SQL("TYPE S3"),+ psql.SQL("KEY_ID %s"),+ psql.SQL("SECRET %s"),+ psql.SQL("REGION %s"),+ ]+ values: list[object] = [secret.key_id, secret.secret, secret.region]+ if secret.endpoint is not None:+ secret_options.append(psql.SQL("ENDPOINT %s"))+ values.append(secret.endpoint)+ secret_options.extend(+ [+ psql.SQL("USE_SSL %s"),+ psql.SQL("URL_STYLE %s"),+ psql.SQL("SCOPE %s"),+ ]+ )+ values.extend([secret.use_ssl, secret.url_style, secret.scope])+ statement = psql.SQL("CREATE OR REPLACE TEMPORARY SECRET {} ({})").format(+ psql.Identifier(secret.name),+ psql.SQL(", ").join(secret_options),+ )+ try:+ cur.execute(statement, values)+ except Exception:+ # A secret duckgres rejects only breaks the table it belongs to, so keep going+ # and let the query fail on that table instead of on every other one too.+ conn.rollback()+ logger.warning("Could not configure DuckLake S3 access for %s", secret.name, exc_info=True)++def compile_hogql_to_ducklake_sql(team_id: int,query: HogQLQuery,@@ -106,13 +194,14 @@ def compile_hogql_to_ducklake_sql(team: Team | None = None,user: User | None = None,bypass_warehouse_access_control: bool = False,-) -> tuple[str, dict[str, object], str]:+) -> DuckLakeCompiledQuery:"""Compile a HogQLQuery to DuckDB-dialect SQL for DuckLake.- Returns ``(postgres_sql, values, hogql_pretty)``. The ``values`` dict holds- parameter bindings for ``psycopg``'s ``%(name)s`` placeholders embedded in- ``postgres_sql``; callers must pass it to ``cursor.execute(sql, values)`` or- the query will fail with an unbound-placeholder error.+ The returned ``values`` hold parameter bindings for ``psycopg``'s ``%(name)s``+ placeholders embedded in ``sql``; callers must pass them to+ ``cursor.execute(sql, values)`` or the query will fail with an+ unbound-placeholder error. ``s3_secrets`` must be installed on the connection+ before the query runs, or its self-managed tables cannot be read."""from posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Database@@ -153,7 +242,12 @@ def compile_hogql_to_ducklake_sql()hogql_pretty, _ = prepare_and_print_ast(parsed, hogql_context, dialect="hogql")- return postgres_sql, dict(postgres_context.values), hogql_pretty+ return DuckLakeCompiledQuery(+ sql=postgres_sql,+ values=dict(postgres_context.values),+ hogql=hogql_pretty,+ s3_secrets=_s3_secrets_for_database(database),+ )def execute_ducklake_query(@@ -177,6 +271,9 @@ def execute_ducklake_query(resolves data warehouse access control the same way as normal query execution.Set bypass_warehouse_access_control only from trusted internal callers thatmust compile without a user, such as materialization.++ Only the `query` form can read self-managed object storage — raw `sql` carries no+ compiled schema, so no S3 secrets are installed for it."""if sql and query:raise ValueError("Provide either sql or query, not both")@@ -185,14 +282,19 @@ def execute_ducklake_query(hogql_pretty: str | None = Nonevalues: dict[str, object] = {}+ s3_secrets: Sequence[DuckLakeS3Secret] = ()if query:- sql, values, hogql_pretty = compile_hogql_to_ducklake_sql(+ compiled = compile_hogql_to_ducklake_sql(team_id,query,team=team,user=user,bypass_warehouse_access_control=bypass_warehouse_access_control,)+ sql = compiled.sql+ values = compiled.values+ hogql_pretty = compiled.hogql+ s3_secrets = compiled.s3_secretsassert sql is not None@@ -200,6 +302,7 @@ def execute_ducklake_query(_connect_start = time.monotonic()with psycopg.connect(conninfo) as conn:connect_ms = (time.monotonic() - _connect_start) * 1000+ _configure_s3_secrets(conn, s3_secrets)_set_search_path(conn)with conn.cursor() as cur:_query_start = time.monotonic()@@ -247,6 +350,7 @@ def execute_ducklake_create_table(values: dict[str, object] | None = None,*,organization_id: str | None = None,+ s3_secrets: Sequence[DuckLakeS3Secret] = (),) -> DuckLakeTableResult:"""Execute a query via duckgres and materialize the result as a DuckLake table.@@ -258,7 +362,8 @@ def execute_ducklake_create_table(``values`` carries parameter bindings for any ``%(name)s`` placeholders in ``sql``(as produced by ``compile_hogql_to_ducklake_sql``). It is passed through to- ``psycopg`` so the SELECT body is executed with safe parameter binding.+ ``psycopg`` so the SELECT body is executed with safe parameter binding. Pass that+ same compilation's ``s3_secrets`` so the SELECT can read self-managed object storage."""safe_schema = sanitize_ducklake_identifier(schema_name, default_prefix="shadow")safe_table = sanitize_ducklake_identifier(table_name, default_prefix="model")@@ -267,6 +372,7 @@ def execute_ducklake_create_table(# capture previous table size before replacing — best-effort, don't block materializationprevious_file_size_bytes = _calculate_table_size(conninfo, safe_schema, safe_table)with psycopg.connect(conninfo) as conn:+ _configure_s3_secrets(conn, s3_secrets)conn.execute(psql.SQL("CREATE SCHEMA IF NOT EXISTS {}").format(psql.Identifier(safe_schema)))# duckgres SET seems to only accept a single comma-separated string value with single quotes_set_search_path(conn, extra_schemas=[safe_schema])diff --git a/products/managed_warehouse/backend/facade/client.py b/products/managed_warehouse/backend/facade/client.pyindex 441fc6471426..604d7d819b27 100644--- a/products/managed_warehouse/backend/facade/client.py+++ b/products/managed_warehouse/backend/facade/client.py@@ -11,6 +11,7 @@ result types live in ``facade.contracts``.from __future__ import annotations+from collections.abc import Sequencefrom typing import TYPE_CHECKINGfrom products.managed_warehouse.backend import client@@ -27,7 +28,12 @@ if TYPE_CHECKING:from posthog.models.team.team import Teamfrom posthog.models.user import User- from products.managed_warehouse.backend.facade.contracts import DuckLakeQueryResult, DuckLakeTableResult+ from products.managed_warehouse.backend.facade.contracts import (+ DuckLakeCompiledQuery,+ DuckLakeQueryResult,+ DuckLakeS3Secret,+ DuckLakeTableResult,+ )from products.managed_warehouse.backend.service_credentials import ServiceCredential__all__ = [@@ -62,7 +68,7 @@ def compile_hogql_to_ducklake_sql(team: Team | None = None,user: User | None = None,bypass_warehouse_access_control: bool = False,-) -> tuple[str, dict[str, object], str]:+) -> DuckLakeCompiledQuery:return client.compile_hogql_to_ducklake_sql(team_id,query,@@ -101,6 +107,7 @@ def execute_ducklake_create_table(values: dict[str, object] | None = None,*,organization_id: str | None = None,+ s3_secrets: Sequence[DuckLakeS3Secret] = (),) -> DuckLakeTableResult:return client.execute_ducklake_create_table(team_id,@@ -109,4 +116,5 @@ def execute_ducklake_create_table(table_name,values,organization_id=organization_id,+ s3_secrets=s3_secrets,)diff --git a/products/managed_warehouse/backend/facade/contracts.py b/products/managed_warehouse/backend/facade/contracts.pyindex 66504dbc38e4..497c3b74c59d 100644--- a/products/managed_warehouse/backend/facade/contracts.py+++ b/products/managed_warehouse/backend/facade/contracts.py@@ -26,7 +26,9 @@ __all__ = ["DuckgresStoredBucketConfig","DuckgresStoredServerConfig","DuckLakeCatalogConnectionConfig",+ "DuckLakeCompiledQuery","DuckLakeQueryResult",+ "DuckLakeS3Secret","DuckLakeTableResult","ManagedWarehouseBackfillState","ManagedWarehouseProvisionStatus",@@ -221,6 +223,35 @@ class ManagedWarehouseSourceJobRecord:last_completed_at: datetime | None = None+@dataclass(frozen=True, kw_only=True)+class DuckLakeS3Secret:+ """One temporary DuckDB S3 secret, scoped to a single self-managed table's object path."""++ name: str+ key_id: str = field(repr=False)+ secret: str = field(repr=False)+ region: str+ scope: str+ use_ssl: bool+ url_style: str+ endpoint: str | None = None+++@dataclass(frozen=True, kw_only=True)+class DuckLakeCompiledQuery:+ """A HogQL query compiled to DuckDB SQL, with the secrets its self-managed tables need.++ ``s3_secrets`` covers only the self-managed tables the compiled schema still exposed after+ warehouse access control, so a caller cannot install credentials for a table its query was+ not allowed to read.+ """++ sql: str+ values: dict[str, Any]+ hogql: str+ s3_secrets: tuple[DuckLakeS3Secret, ...] = ()++@dataclassclass DuckLakeQueryResult:columns: list[str]diff --git a/products/managed_warehouse/backend/tests/test_client.py b/products/managed_warehouse/backend/tests/test_client.pyindex 94fe9eea86f0..25182028b7ed 100644--- a/products/managed_warehouse/backend/tests/test_client.py+++ b/products/managed_warehouse/backend/tests/test_client.py@@ -9,9 +9,12 @@ from posthog.schema import HogQLQuery, HogQLVariablefrom products.managed_warehouse.backend.client import (_SEARCH_PATH_SCHEMAS,+ _configure_s3_secrets,+ _s3_secrets_for_database,compile_hogql_to_ducklake_sql,execute_ducklake_query,)+from products.managed_warehouse.backend.facade.contracts import DuckLakeCompiledQuery@pytest.fixture(autouse=True)@@ -53,10 +56,10 @@ class TestCompileHogQLToDuckLakeSQL:},)- postgres_sql, values, _hogql_pretty = compile_hogql_to_ducklake_sql(team.pk, query)+ compiled = compile_hogql_to_ducklake_sql(team.pk, query)- assert "purchase" in values.values()- assert "variables" not in postgres_sql+ assert "purchase" in compiled.values.values()+ assert "variables" not in compiled.sqlclass TestDuckLakeModelRedirect:@@ -88,12 +91,12 @@ class TestDuckLakeModelRedirect:)query = HogQLQuery(query="SELECT org_id FROM vitally_org")- postgres_sql, _values, _hogql = compile_hogql_to_ducklake_sql(team.pk, query)+ compiled = compile_hogql_to_ducklake_sql(team.pk, query)# The duckgres path must read the DuckLake-materialized model, not the# ClickHouse s3() table function, which DuckDB cannot execute.- assert "s3(" not in postgres_sql.lower()- assert f"shadow_{team.pk}_models" in postgres_sql+ assert "s3(" not in compiled.sql.lower()+ assert f"shadow_{team.pk}_models" in compiled.sqldef test_source_table_resolves_to_ducklake_table_not_s3(self):from posthog.models import Organization, Team@@ -140,23 +143,155 @@ class TestDuckLakeModelRedirect:)query = HogQLQuery(query="SELECT id FROM myprefix_stripe_customers")- postgres_sql, _values, _hogql = compile_hogql_to_ducklake_sql(team.pk, query)+ compiled = compile_hogql_to_ducklake_sql(team.pk, query)# The duckgres path must read the DuckLake-copied source table, not the# ClickHouse s3() table function, which DuckDB cannot execute.- assert "s3(" not in postgres_sql.lower()- assert duckgres_data_imports_schema(team.pk) in postgres_sql- assert duckgres_data_imports_table_name(schema) in postgres_sql+ assert "s3(" not in compiled.sql.lower()+ assert duckgres_data_imports_schema(team.pk) in compiled.sql+ assert duckgres_data_imports_table_name(schema) in compiled.sql++ def test_self_managed_parquet_resolves_to_native_reader(self) -> None:+ from posthog.models import Organization, Team++ from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable++ org = Organization.objects.create(name="ducklake-self-managed")+ team = Team.objects.create(organization=org)+ credential = DataWarehouseCredential.objects.create(+ team=team,+ access_key="access-key",+ access_secret="access-secret",+ )+ DataWarehouseTable.objects.create(+ name="self_managed_orders",+ format="Parquet",+ team=team,+ credential=credential,+ url_pattern="https://my-bucket.s3.amazonaws.com/data/*.parquet",+ columns={+ "id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "schema_valid": True},+ },+ )++ compiled = compile_hogql_to_ducklake_sql(+ team.pk,+ HogQLQuery(query="SELECT id FROM self_managed_orders"),+ )++ assert "s3(" not in compiled.sql.lower()+ assert "read_parquet(" in compiled.sql.lower()+ assert "s3://my-bucket/data/*.parquet" in compiled.values.values()+ assert "access-key" not in compiled.sql+ assert "access-secret" not in compiled.sql+ assert "access-key" not in compiled.values.values()+ assert "access-secret" not in compiled.values.values()+++class TestSelfManagedS3Secrets:+ def test_credentials_are_bound_to_a_path_scoped_secret(self) -> None:+ from posthog.models import Organization, Team++ from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable++ org = Organization.objects.create(name="ducklake-self-managed-secret")+ team = Team.objects.create(organization=org)+ credential = DataWarehouseCredential.objects.create(+ team=team,+ access_key="access-key",+ access_secret="access-secret",+ )+ table = DataWarehouseTable.objects.create(+ name="self_managed_orders",+ format="Parquet",+ team=team,+ credential=credential,+ url_pattern="http://objectstorage:19000/my-bucket/data/*.parquet",+ columns={"id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "schema_valid": True}},+ )+ cursor = mock.MagicMock()+ connection = mock.MagicMock()+ connection.cursor.return_value.__enter__ = mock.Mock(return_value=cursor)+ connection.cursor.return_value.__exit__ = mock.Mock(return_value=False)++ compiled = compile_hogql_to_ducklake_sql(team.pk, HogQLQuery(query="SELECT id FROM self_managed_orders"))+ _configure_s3_secrets(connection, compiled.s3_secrets)++ statement, values = cursor.execute.call_args.args+ rendered_statement = statement.as_string()+ assert rendered_statement.startswith(f'CREATE OR REPLACE TEMPORARY SECRET "self_managed_{table.id.hex}"')+ assert "KEY_ID %s" in rendered_statement+ assert "SECRET %s" in rendered_statement+ assert "SCOPE %s" in rendered_statement+ assert "access-key" not in rendered_statement+ assert "access-secret" not in rendered_statement+ assert values == [+ "access-key",+ "access-secret",+ "us-east-1",+ "objectstorage:19000",+ False,+ "path",+ "s3://my-bucket/data/",+ ]++ def test_a_table_access_control_removed_gets_no_secret(self) -> None:+ from posthog.hogql.database.database import Database++ from posthog.models import Organization, Team++ from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable++ org = Organization.objects.create(name="ducklake-self-managed-restricted")+ team = Team.objects.create(organization=org)+ columns = {"id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "schema_valid": True}}+ allowed_credential = DataWarehouseCredential.objects.create(+ team=team,+ access_key="allowed-key",+ access_secret="allowed-secret",+ )+ restricted_credential = DataWarehouseCredential.objects.create(+ team=team,+ access_key="restricted-key",+ access_secret="restricted-secret",+ )+ allowed = DataWarehouseTable.objects.create(+ name="allowed_orders",+ format="Parquet",+ team=team,+ credential=allowed_credential,+ url_pattern="https://my-bucket.s3.amazonaws.com/data/*.parquet",+ columns=columns,+ )+ DataWarehouseTable.objects.create(+ name="restricted_orders",+ format="Parquet",+ team=team,+ credential=restricted_credential,+ url_pattern="https://my-bucket.s3.amazonaws.com/data/*.parquet",+ columns=columns,+ )++ database = Database.create_for(team.pk)+ # Access control prunes the schema through this same entry point.+ database.prune_to_table_names({"allowed_orders"})++ secrets = _s3_secrets_for_database(database)++ assert [secret.name for secret in secrets] == [f"self_managed_{allowed.id.hex}"]+ assert [secret.key_id for secret in secrets] == ["allowed-key"]class TestDuckgresShadowCompilation:@mock.patch("products.managed_warehouse.backend.client.compile_hogql_to_ducklake_sql")def test_materialization_compile_bypasses_warehouse_access_control(self, mock_compile):- from posthog.temporal.data_modeling.activities.materialize_view_duckgres import _compile_hogql_to_postgres_sql+ from posthog.temporal.data_modeling.activities.materialize_view_duckgres import _compile_hogql_for_ducklake- mock_compile.return_value = ("SELECT * FROM source", {}, "SELECT * FROM source")+ mock_compile.return_value = DuckLakeCompiledQuery(+ sql="SELECT * FROM source", values={}, hogql="SELECT * FROM source"+ )- _compile_hogql_to_postgres_sql("SELECT * FROM source", 1)+ _compile_hogql_for_ducklake("SELECT * FROM source", 1)query = mock_compile.call_args.args[1]assert query.query == "SELECT * FROM source"@@ -204,7 +339,9 @@ class TestExecuteDuckLakeQuery:@mock.patch("products.managed_warehouse.backend.client.is_dev_mode", return_value=True)@mock.patch("products.managed_warehouse.backend.client.compile_hogql_to_ducklake_sql")def test_query_path_compiles_and_executes(self, mock_compile, _mock_dev_mode, mock_psycopg):- mock_compile.return_value = ("SELECT count(*) FROM events", {}, "SELECT count() FROM events")+ mock_compile.return_value = DuckLakeCompiledQuery(+ sql="SELECT count(*) FROM events", values={}, hogql="SELECT count() FROM events"+ )mock_cursor = mock.MagicMock()mock_cursor.description = [mock.MagicMock(name="cnt", type_code=20)]mock_cursor.description[0].name = "cnt"