Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(data-warehouse): bind duckgres queries to DuckLake tables (#66122)

Jovan Sakovic4120e0eed0f7
diff --git a/posthog/ducklake/client.py b/posthog/ducklake/client.py
index 2b9556c89cdd..bc70eb3660ee 100644
--- a/posthog/ducklake/client.py
+++ b/posthog/ducklake/client.py
@@ -9,6 +9,7 @@ from psycopg import sql as psql
from psycopg.conninfo import make_conninfo
from posthog.ducklake.common import get_duckgres_config_for_org, is_dev_mode, sanitize_ducklake_identifier
+from posthog.ducklake.table_binding import bind_tables_to_ducklake
if TYPE_CHECKING:
from posthog.schema import HogQLQuery
@@ -81,6 +82,7 @@ def compile_hogql_to_ducklake_sql(
the query will fail with an unbound-placeholder error.
"""
from posthog.hogql.context import HogQLContext
+ from posthog.hogql.database.database import Database
from posthog.hogql.parser import parse_select
from posthog.hogql.printer.utils import prepare_and_print_ast
from posthog.hogql.variables import replace_variables
@@ -91,9 +93,13 @@ def compile_hogql_to_ducklake_sql(
if query.variables:
team = team or Team.objects.get(pk=team_id)
parsed = replace_variables(parsed, list(query.variables.values()), team)
+ # Build the database up front so warehouse tables can be bound from the ClickHouse
+ # S3 table function to their DuckLake-materialized tables before printing.
+ database = Database.create_for(team_id)
+ bind_tables_to_ducklake(database, team_id)
# Separate context for the DuckDB print — the HogQL round-trip below shouldn't
# contribute to ``postgres_context.values``.
- postgres_context = HogQLContext(team_id=team_id, enable_select_queries=True)
+ postgres_context = HogQLContext(team_id=team_id, enable_select_queries=True, database=database)
postgres_sql, _ = prepare_and_print_ast(parsed, postgres_context, dialect="duckdb")
hogql_context = HogQLContext(team_id=team_id, enable_select_queries=True)
diff --git a/posthog/ducklake/common.py b/posthog/ducklake/common.py
index 5f94501c3c72..13cbb4290015 100644
--- a/posthog/ducklake/common.py
+++ b/posthog/ducklake/common.py
@@ -28,8 +28,14 @@ from psycopg import sql
if TYPE_CHECKING:
from posthog.ducklake.models import DuckgresServer, DuckLakeCatalog
+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+
DUCKLAKE_CATALOG_RESET_ENV_VAR = "POSTHOG_ALLOW_DUCKLAKE_CATALOG_RESET"
+# The duckgres schema prefix the data-modeling shadow materialization writes models into.
+DATA_MODELING_DUCKGRES_SHADOW_SCHEMA_PREFIX = "shadow"
+
logger = logging.getLogger(__name__)
DEFAULTS: dict[str, str] = {
@@ -587,6 +593,26 @@ def duckgres_data_imports_schema(team_id: int) -> str:
return f"posthog_data_imports_{suffix}"
+def duckgres_data_imports_table_name(schema: ExternalDataSchema) -> str:
+ """Resolve the duckgres table name the data-import copy workflow writes a schema's snapshot into.
+
+ Must stay byte-identical to what the copy workflow computes so the reader resolves to the same
+ table the writer produced.
+ """
+ source_type = schema.source.source_type
+ prefix = schema.source.prefix
+ normalized_name = schema.normalized_name
+ return sanitize_ducklake_identifier(
+ f"{source_type}_{prefix}_{normalized_name}" if prefix else f"{source_type}_{normalized_name}",
+ default_prefix="data_import",
+ )
+
+
+def duckgres_data_modeling_schema(team_id: int) -> str:
+ """Resolve the duckgres schema the data-modeling shadow materialization writes a team's models into."""
+ return f"{DATA_MODELING_DUCKGRES_SHADOW_SCHEMA_PREFIX}_{team_id}_models"
+
+
TABLE_SUFFIX_MAX_LENGTH = 63
# The table name the user supplies is used verbatim as the suffix in `events_<suffix>` /
# `persons_<suffix>`, so it must already be a safe SQL identifier — lowercase letters,
@@ -690,6 +716,8 @@ __all__ = [
"DucklingBackfillEnableError",
"attach_catalog",
"duckgres_data_imports_schema",
+ "duckgres_data_imports_table_name",
+ "duckgres_data_modeling_schema",
"enable_team_backfill",
"escape",
"get_config",
diff --git a/posthog/ducklake/table_binding.py b/posthog/ducklake/table_binding.py
new file mode 100644
index 000000000000..eeb44f5b8568
--- /dev/null
+++ b/posthog/ducklake/table_binding.py
@@ -0,0 +1,100 @@
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from posthog.ducklake.common import (
+ duckgres_data_imports_schema,
+ duckgres_data_imports_table_name,
+ duckgres_data_modeling_schema,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def bind_tables_to_ducklake(database: Any, team_id: int) -> None:
+ """Bind a built HogQL database's tables to their duckgres-materialized counterparts.
+
+ On the warehouse HogQL database, both materialized data-modeling models and
+ imported source tables resolve to the ClickHouse S3 table function (``s3(...)``),
+ which DuckDB/duckgres cannot execute. The duckgres materialization / copy
+ workflows write these into DuckLake schemas, so rebind each table node to a
+ ``DirectPostgresTable`` that prints as the schema-qualified DuckLake name.
+
+ Mutates ``database`` in place. Scoped to the DuckLake compile path only — the
+ ClickHouse path never calls this, so its table resolution is unchanged.
+ """
+ _bind_materialized_models(database, team_id)
+ _bind_source_tables(database, team_id)
+
+
+def _bind_materialized_models(database: Any, team_id: int) -> None:
+ """Bind materialized data-modeling models to their DuckLake schema (``shadow_<team_id>_models``)."""
+ from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
+ from posthog.hogql.errors import ResolutionError
+
+ from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+
+ schema_name = duckgres_data_modeling_schema(team_id)
+ materialized = DataWarehouseSavedQuery.objects.filter(
+ team_id=team_id, is_materialized=True, table__isnull=False
+ ).exclude(deleted=True)
+ for saved_query in materialized:
+ try:
+ node = database.get_table_node(saved_query.name.split("."))
+ except ResolutionError:
+ logger.debug("Model %s not in HogQL database; skipping DuckLake bind", saved_query.name)
+ continue
+ existing = node.table
+ if existing is None:
+ continue
+ node.table = DirectPostgresTable(
+ name=saved_query.name,
+ external_data_source_id="",
+ postgres_schema=schema_name,
+ postgres_table_name=saved_query.normalized_name,
+ fields=existing.fields,
+ )
+
+
+def _bind_source_tables(database: Any, team_id: int) -> None:
+ """Bind imported source tables to their DuckLake-copied counterparts.
+
+ Each queryable, S3-backed warehouse table that has a linked ``ExternalDataSchema`` was
+ copied into the team's data-imports schema by the copy workflow. Model backing tables
+ have no schema, so they are naturally skipped; direct-query tables already render
+ schema-qualified and are not S3-backed, so they are skipped too. The binding is blind —
+ if a table hasn't been synced yet, duckgres errors at query time, which is intended.
+ """
+ from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
+ from posthog.hogql.errors import ResolutionError
+
+ from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+ from products.warehouse_sources.backend.models.table import DataWarehouseTable
+
+ schema_name = duckgres_data_imports_schema(team_id)
+ tables = (
+ DataWarehouseTable.objects.queryable()
+ .filter(team_id=team_id, external_data_source__isnull=False)
+ .exclude(external_data_source__access_method=ExternalDataSource.AccessMethod.DIRECT)
+ .prefetch_related("externaldataschema_set__source")
+ )
+ for table in tables:
+ external_schema = next(iter(table.externaldataschema_set.all()), None)
+ if external_schema is None:
+ continue
+ try:
+ node = database.get_table_node(table.name_chain)
+ except ResolutionError:
+ logger.debug("Source table %s not in HogQL database; skipping DuckLake bind", table.name)
+ continue
+ existing = node.table
+ if existing is None:
+ continue
+ node.table = DirectPostgresTable(
+ name=table.name,
+ external_data_source_id="",
+ postgres_schema=schema_name,
+ postgres_table_name=duckgres_data_imports_table_name(external_schema),
+ fields=existing.fields,
+ )
diff --git a/posthog/ducklake/test_client.py b/posthog/ducklake/test_client.py
index 47e408b688f2..d697410779a2 100644
--- a/posthog/ducklake/test_client.py
+++ b/posthog/ducklake/test_client.py
@@ -35,6 +35,92 @@ class TestCompileHogQLToDuckLakeSQL:
assert "variables" not in postgres_sql
+class TestDuckLakeModelRedirect:
+ def test_materialized_model_resolves_to_ducklake_table_not_s3(self):
+ from posthog.models import Organization, Team
+
+ from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+ from products.warehouse_sources.backend.models.credential import DataWarehouseCredential
+ from products.warehouse_sources.backend.models.table import DataWarehouseTable
+
+ org = Organization.objects.create(name="ducklake-redirect")
+ team = Team.objects.create(organization=org)
+ credential = DataWarehouseCredential.objects.create(team=team, access_key="key", access_secret="secret")
+ source_table = DataWarehouseTable.objects.create(
+ name="vitally_source",
+ team=team,
+ columns={"org_id": "String"},
+ credential=credential,
+ url_pattern="https://bucket.s3.amazonaws.com/vitally/*.parquet",
+ format="Parquet",
+ )
+ DataWarehouseSavedQuery.objects.create(
+ team=team,
+ name="vitally_org",
+ query={"query": "SELECT org_id FROM vitally_source"},
+ columns={"org_id": {"clickhouse": "String", "hogql": "StringDatabaseField"}},
+ table=source_table,
+ is_materialized=True,
+ status=DataWarehouseSavedQuery.Status.COMPLETED,
+ )
+
+ query = HogQLQuery(query="SELECT org_id FROM vitally_org")
+ postgres_sql, _values, _hogql = 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
+
+ def test_source_table_resolves_to_ducklake_table_not_s3(self):
+ from posthog.ducklake.common import duckgres_data_imports_schema, duckgres_data_imports_table_name
+ from posthog.models import Organization, Team
+
+ from products.warehouse_sources.backend.models.credential import DataWarehouseCredential
+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+ from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+ from products.warehouse_sources.backend.models.table import DataWarehouseTable
+ from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+ org = Organization.objects.create(name="ducklake-source-redirect")
+ team = Team.objects.create(organization=org)
+ source = ExternalDataSource.objects.create(
+ team=team,
+ source_id="source_id",
+ connection_id="connection_id",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=ExternalDataSourceType.STRIPE,
+ prefix="myprefix_",
+ )
+ credential = DataWarehouseCredential.objects.create(team=team, access_key="key", access_secret="secret")
+ warehouse_table = DataWarehouseTable.objects.create(
+ name="myprefix_stripe_customers",
+ format="Parquet",
+ team=team,
+ external_data_source=source,
+ external_data_source_id=source.id,
+ credential=credential,
+ url_pattern="https://bucket.s3.amazonaws.com/stripe/customers/*.parquet",
+ columns={"id": {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)", "schema_valid": True}},
+ )
+ schema = ExternalDataSchema.objects.create(
+ team=team,
+ name="customers",
+ source=source,
+ table=warehouse_table,
+ should_sync=True,
+ )
+
+ query = HogQLQuery(query="SELECT id FROM myprefix_stripe_customers")
+ postgres_sql, _values, _hogql = 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
+
+
class TestExecuteDuckLakeQuery:
def test_rejects_both_sql_and_query(self):
with pytest.raises(ValueError, match="not both"):
diff --git a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
index 802ff59f771f..42cfcc6239ac 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
@@ -6,7 +6,7 @@ import dataclasses
from structlog.contextvars import bind_contextvars
from temporalio import activity
-from posthog.ducklake.common import get_duckgres_server_for_organization, is_dev_mode
+from posthog.ducklake.common import duckgres_data_modeling_schema, get_duckgres_server_for_organization, is_dev_mode
from posthog.exceptions_capture import capture_exception
from posthog.models import Team
from posthog.ph_client import feature_enabled_or_false
@@ -21,7 +21,6 @@ from products.endpoints.backend.services.materialization import prepare_executab
LOGGER = get_logger(__name__)
FEATURE_FLAG = "duckgres-data-modeling-shadow"
-SHADOW_SCHEMA_PREFIX = "shadow"
@dataclasses.dataclass
@@ -147,7 +146,7 @@ async def materialize_view_duckgres_activity(inputs: DuckgresShadowInputs) -> Du
team, node, saved_query = await _get_shadow_input_objects(inputs)
hogql_query = typing.cast(dict, saved_query.query)["query"]
- schema_name = f"{SHADOW_SCHEMA_PREFIX}_{team.pk}_models"
+ schema_name = duckgres_data_modeling_schema(team.pk)
table_name = saved_query.normalized_name
await logger.ainfo(
diff --git a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py
index 0a137d9d624e..770e76092246 100644
--- a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py
+++ b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py
@@ -17,12 +17,12 @@ from posthog.ducklake.common import (
_get_org_id_for_team,
attach_catalog,
duckgres_data_imports_schema,
+ duckgres_data_imports_table_name,
get_config,
get_duckgres_server_for_organization,
get_ducklake_catalog_by_team_org,
get_ducklake_catalog_for_organization,
is_dev_mode,
- sanitize_ducklake_identifier,
)
from posthog.ducklake.storage import (
cleanup_staged_files,
@@ -253,12 +253,7 @@ async def prepare_data_imports_ducklake_metadata_activity(
source_normalized_name=normalized_name,
source_table_uri=source_table_uri,
ducklake_schema_name=ducklake_schema_name,
- ducklake_table_name=sanitize_ducklake_identifier(
- f"{source_type}_{schema.source.prefix}_{normalized_name}"
- if schema.source.prefix
- else f"{source_type}_{normalized_name}",
- default_prefix="data_import",
- ),
+ ducklake_table_name=duckgres_data_imports_table_name(schema),
verification_queries=list(get_data_imports_verification_queries(normalized_name)),
source_partition_column=partition_column,
staging_uri=staging_uri,