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): align duckgres table bindings (#75290)

Eric Duong12ed9ac83faa
diff --git a/posthog/ducklake/README.md b/posthog/ducklake/README.md
index 7e5d2f5be756..d7ead9faf8c9 100644
--- a/posthog/ducklake/README.md
+++ b/posthog/ducklake/README.md
@@ -48,11 +48,14 @@ Each workflow is gated by its own feature flag (evaluated via `feature_enabled`)
| Workflow | Feature Flag |
| ------------------------ | --------------------------------------------- |
| Data Modeling | `ducklake-data-modeling-copy-workflow` |
+| Data Modeling Shadow | `duckgres-data-modeling-shadow` |
| Data Imports | `ducklake-data-imports-copy-workflow` |
| Data Import Registration | `ducklake-data-imports-registration-workflow` |
The two data-import flags are independent and target the same stable DuckLake table. During rollout, enable only the intended path for a project; if both run for the same import, the last atomic table swap wins.
+The data-modeling shadow flag starts a Duckgres materialization alongside the normal ClickHouse materialization. It writes to `shadow_<team_id>_models`, records comparison metrics after the ClickHouse job completes, and does not fail the main job when the shadow run fails. HogQL compiled for Duckgres resolves materialized model dependencies from this shadow schema.
+
## Target bucket layout
Every copy is written to a deterministic schema inside DuckLake. Each workflow namespaces its data under a workflow-specific schema:
@@ -65,13 +68,15 @@ Every copy is written to a deterministic schema inside DuckLake. Each workflow n
### Data Imports and Data Import Registration
-- **Schema**: `posthog_data_imports_team_<team_id>`
-- **Table**: `<source_type>_<prefix>_<normalized_name>` (prefix is user-defined on the external data source)
+- **Schema**: `posthog_data_imports_<cluster_schema_name>` for an onboarded team, or the legacy `posthog_data_imports_team_<team_id>` schema
+- **Table**: `<source_type>_<prefix>_<normalized_name>` using the same snake-case and 63-character shortening convention as the v3 Duckgres sink
- **Example**: `ducklake.posthog_data_imports_team_123.stripe_prod_invoices`
- **Registered files**: `s3://<ducklake-bucket>/<ducklake-schema>/<ducklake-table>/_imports/<source-schema-id>/<job-id>/<prepared-relative-path>`
Each completed import creates a timestamped prepared Parquet snapshot in the data warehouse bucket. The registration workflow copies those objects directly into the DuckLake bucket, preserving Hive partition directories, registers the destination objects with `ducklake_add_data_files`, verifies the shadow table's row count, and only then swaps it into the stable table name through the Duckgres PostgreSQL connection. Registration, verification, and the swap share one catalog transaction, so a mismatch leaves the previous table live. Each import job gets its own object prefix and child workflow ID, so a later sync does not append into the previous snapshot.
+Duckgres query compilation applies these physical names recursively. This includes source tables referenced through non-materialized saved queries, plus the cluster-specific `events_<schema_name>` and `persons_<schema_name>` tables written by the Dagster backfills.
+
The registered objects are permanent DuckLake data files, not staging files. Old generations remain reachable through DuckLake snapshots until snapshot expiration and old-file cleanup make them eligible for object deletion. Choose the bucket lifecycle policy with that retention behavior in mind.
## Required permissions
diff --git a/posthog/ducklake/common.py b/posthog/ducklake/common.py
index 087b78d6b693..1cb2e91e64e2 100644
--- a/posthog/ducklake/common.py
+++ b/posthog/ducklake/common.py
@@ -551,10 +551,22 @@ def duckgres_data_imports_table_name(schema: ExternalDataSchema) -> str:
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",
- )
+ raw_name = f"{source_type}_{prefix}_{normalized_name}" if prefix else f"{source_type}_{normalized_name}"
+ return _normalize_duckgres_table_name(raw_name, max_length=63)
+
+
+def duckgres_data_modeling_table_name(saved_query_name: str) -> str:
+ """Resolve the duckgres table name used for a materialized data model."""
+ normalized_name = _normalize_duckgres_table_name(saved_query_name)
+ # PostgreSQL caps identifiers at 63 bytes; shadow tables rely on its prefix truncation semantics.
+ return normalized_name[:63]
+
+
+def _normalize_duckgres_table_name(raw_name: str, max_length: int | None = None) -> str:
+ # Deferred to keep warehouse-source model imports off DuckLake's shared configuration path.
+ from products.warehouse_sources.backend.facade.sources import NamingConvention # noqa: PLC0415
+
+ return NamingConvention.normalize_identifier(raw_name, max_length=max_length)
def duckgres_data_modeling_schema(team_id: int) -> str:
@@ -692,6 +704,7 @@ __all__ = [
"duckgres_data_imports_schema",
"duckgres_data_imports_table_name",
"duckgres_data_modeling_schema",
+ "duckgres_data_modeling_table_name",
"escape",
"get_config",
"get_ducklake_connection_string",
diff --git a/posthog/ducklake/table_binding.py b/posthog/ducklake/table_binding.py
index 1f494bdfedf3..7e3929a7886e 100644
--- a/posthog/ducklake/table_binding.py
+++ b/posthog/ducklake/table_binding.py
@@ -7,6 +7,7 @@ from posthog.ducklake.common import (
duckgres_data_imports_schema,
duckgres_data_imports_table_name,
duckgres_data_modeling_schema,
+ duckgres_data_modeling_table_name,
)
logger = logging.getLogger(__name__)
@@ -15,19 +16,38 @@ 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.
+ Rebind the logical PostHog, data-modeling, and imported source table names to
+ the physical names written for this team in the Duckgres cluster.
Mutates ``database`` in place. Scoped to the DuckLake compile path only — the
ClickHouse path never calls this, so its table resolution is unchanged.
"""
+ _bind_posthog_tables(database, team_id)
_bind_materialized_models(database, team_id)
_bind_source_tables(database, team_id)
+def _bind_posthog_tables(database: Any, team_id: int) -> None:
+ """Bind built-in events and persons tables to the team's cluster tables."""
+ from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
+
+ from posthog.ducklake.team_state import resolve_events_persons_tables
+
+ physical_names = dict(zip(("events", "persons"), resolve_events_persons_tables(team_id), strict=True))
+ for logical_name, physical_name in physical_names.items():
+ node = database.get_table_node([logical_name])
+ existing = node.table
+ if existing is None:
+ continue
+ node.table = DirectPostgresTable(
+ name=logical_name,
+ external_data_source_id="",
+ postgres_schema="posthog",
+ postgres_table_name=physical_name,
+ fields=existing.fields,
+ )
+
+
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
@@ -52,7 +72,7 @@ def _bind_materialized_models(database: Any, team_id: int) -> None:
name=saved_query.name,
external_data_source_id="",
postgres_schema=schema_name,
- postgres_table_name=saved_query.normalized_name,
+ postgres_table_name=duckgres_data_modeling_table_name(saved_query.name),
fields=existing.fields,
)
@@ -66,6 +86,7 @@ def _bind_source_tables(database: Any, team_id: int) -> None:
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.database import get_data_warehouse_table_name
from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
from posthog.hogql.errors import ResolutionError
@@ -76,24 +97,33 @@ def _bind_source_tables(database: Any, team_id: int) -> None:
DataWarehouseTable.objects.queryable()
.filter(team_id=team_id, external_data_source__isnull=False)
.exclude(external_data_source__access_method=ExternalDataSource.AccessMethod.DIRECT)
+ .select_related("external_data_source")
.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,
- )
+
+ name_chains = [table.name_chain]
+ logical_name_chain = get_data_warehouse_table_name(table.external_data_source, table.name).split(".")
+ if logical_name_chain != table.name_chain:
+ name_chains.append(logical_name_chain)
+
+ physical_table_name = duckgres_data_imports_table_name(external_schema)
+ for name_chain in name_chains:
+ try:
+ node = database.get_table_node(name_chain)
+ except ResolutionError:
+ logger.debug("Source table %s not in HogQL database; skipping DuckLake bind", ".".join(name_chain))
+ continue
+ existing = node.table
+ if existing is None:
+ continue
+ node.table = DirectPostgresTable(
+ name=".".join(name_chain),
+ external_data_source_id="",
+ postgres_schema=schema_name,
+ postgres_table_name=physical_table_name,
+ fields=existing.fields,
+ )
diff --git a/posthog/ducklake/test_client.py b/posthog/ducklake/test_client.py
index 882b98663e2a..512013756e62 100644
--- a/posthog/ducklake/test_client.py
+++ b/posthog/ducklake/test_client.py
@@ -49,6 +49,7 @@ class TestCompileHogQLToDuckLakeSQL:
class TestDuckLakeModelRedirect:
def test_materialized_model_resolves_to_ducklake_table_not_s3(self):
+ from posthog.ducklake.common import duckgres_data_modeling_schema, duckgres_data_modeling_table_name
from posthog.models import Organization, Team
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
@@ -81,12 +82,14 @@ class TestDuckLakeModelRedirect:
# 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 duckgres_data_modeling_schema(team.pk) in postgres_sql
+ assert duckgres_data_modeling_table_name("vitally_org") in postgres_sql
- def test_source_table_resolves_to_ducklake_table_not_s3(self):
+ def test_non_materialized_view_resolves_its_source_to_cluster_table(self):
from posthog.ducklake.common import duckgres_data_imports_schema, duckgres_data_imports_table_name
from posthog.models import Organization, Team
+ from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.warehouse_sources.backend.facade.models import (
DataWarehouseCredential,
DataWarehouseTable,
@@ -102,36 +105,63 @@ class TestDuckLakeModelRedirect:
source_id="source_id",
connection_id="connection_id",
status=ExternalDataSource.Status.COMPLETED,
- source_type=ExternalDataSourceType.STRIPE,
- prefix="myprefix_",
+ source_type=ExternalDataSourceType.GOOGLEADS,
)
credential = DataWarehouseCredential.objects.create(team=team, access_key="key", access_secret="secret")
warehouse_table = DataWarehouseTable.objects.create(
- name="myprefix_stripe_customers",
+ name="googleads_video",
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",
+ url_pattern="https://bucket.s3.amazonaws.com/googleads/video/*.parquet",
columns={"id": {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)", "schema_valid": True}},
)
schema = ExternalDataSchema.objects.create(
team=team,
- name="customers",
+ name="video",
source=source,
table=warehouse_table,
should_sync=True,
)
+ DataWarehouseSavedQuery.objects.create(
+ team=team,
+ name="google_ads_video_view",
+ query={"query": "SELECT id FROM googleads.video"},
+ columns={"id": {"clickhouse": "String", "hogql": "StringDatabaseField"}},
+ is_materialized=False,
+ status=DataWarehouseSavedQuery.Status.COMPLETED,
+ )
- query = HogQLQuery(query="SELECT id FROM myprefix_stripe_customers")
+ query = HogQLQuery(query="SELECT id FROM google_ads_video_view")
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
+ assert duckgres_data_imports_table_name(schema) == "google_ads_video"
+ assert f"{duckgres_data_imports_schema(team.pk)}.google_ads_video" in postgres_sql
+
+ def test_events_and_persons_resolve_to_cluster_tables(self):
+ from posthog.models import Organization, Team
+
+ org = Organization.objects.create(name="ducklake-posthog-table-redirect")
+ team = Team.objects.create(organization=org)
+
+ with mock.patch(
+ "posthog.ducklake.team_state.resolve_events_persons_tables",
+ return_value=("events_prod", "persons_prod"),
+ ):
+ events_sql, _values, _hogql = compile_hogql_to_ducklake_sql(
+ team.pk, HogQLQuery(query="SELECT uuid FROM events LIMIT 1")
+ )
+ persons_sql, _values, _hogql = compile_hogql_to_ducklake_sql(
+ team.pk, HogQLQuery(query="SELECT id FROM persons LIMIT 1")
+ )
+
+ assert "posthog.events_prod" in events_sql
+ assert "posthog.persons_prod" in persons_sql
class TestDuckgresShadowCompilation:
diff --git a/posthog/ducklake/test_common.py b/posthog/ducklake/test_common.py
index 1159622802d8..1f9aaf7c3e23 100644
--- a/posthog/ducklake/test_common.py
+++ b/posthog/ducklake/test_common.py
@@ -8,6 +8,8 @@ from parameterized import parameterized
from posthog.ducklake.common import (
default_bucket_region,
+ duckgres_data_imports_table_name,
+ duckgres_data_modeling_table_name,
initialize_ducklake,
is_version_mismatch,
reset_ducklake_catalog,
@@ -53,6 +55,44 @@ class TestDefaultBucketRegion:
assert default_bucket_region() == expected
+class TestDuckgresTableNames:
+ @parameterized.expand(
+ [
+ ("mysql_with_prefix", "MySQL", "SalesEU", "customer_orders", "my_sql_sales_eu_customer_orders"),
+ ("bigquery_without_prefix", "BigQuery", None, "daily_stats", "big_query_daily_stats"),
+ (
+ "long_name",
+ "MySQL",
+ "SalesEU",
+ "customer_order_history_" * 5,
+ "my_sql_sales_eu_customer_ordezbh0hqtory_customer_order_historyx",
+ ),
+ ]
+ )
+ def test_data_import_name_matches_sink_convention(
+ self, _name: str, source_type: str, prefix: str | None, normalized_name: str, expected: str
+ ) -> None:
+ schema = MagicMock()
+ schema.source.source_type = source_type
+ schema.source.prefix = prefix
+ schema.normalized_name = normalized_name
+
+ assert duckgres_data_imports_table_name(schema) == expected
+
+ @parameterized.expand(
+ [
+ ("short_name", "RevenueByAccount", "revenue_by_account"),
+ (
+ "long_name_keeps_postgres_prefix_truncation",
+ "RevenueByAccount" * 7,
+ "revenue_by_account_revenue_by_account_revenue_by_account_revenu",
+ ),
+ ]
+ )
+ def test_data_model_name_uses_cluster_convention(self, _name: str, model_name: str, expected: str) -> None:
+ assert duckgres_data_modeling_table_name(model_name) == expected
+
+
TEST_CONFIG = {
"DUCKLAKE_RDS_HOST": "localhost",
"DUCKLAKE_RDS_PORT": "5432",
diff --git a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
index 07161bb3182d..b6fa1c822a4c 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
@@ -6,7 +6,12 @@ import dataclasses
from structlog.contextvars import bind_contextvars
from temporalio import activity
-from posthog.ducklake.common import duckgres_data_modeling_schema, get_duckgres_server_for_organization, is_dev_mode
+from posthog.ducklake.common import (
+ duckgres_data_modeling_schema,
+ duckgres_data_modeling_table_name,
+ 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
@@ -161,7 +166,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 = duckgres_data_modeling_schema(team.pk)
- table_name = saved_query.normalized_name
+ table_name = duckgres_data_modeling_table_name(saved_query.name)
await logger.ainfo(
"Starting duckgres shadow materialization",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py
index 8fe711465398..8ce1c8af86e1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py
@@ -18,7 +18,11 @@ import structlog
from prometheus_client import Histogram
from psycopg import sql
-from posthog.ducklake.common import duckgres_data_imports_schema, get_duckgres_config_for_org
+from posthog.ducklake.common import (
+ duckgres_data_imports_schema,
+ duckgres_data_imports_table_name,
+ get_duckgres_config_for_org,
+)
from posthog.ducklake.storage import setup_duckgres_session
from posthog.models import Team
@@ -601,14 +605,7 @@ def _duckgres_schema_name(team_id: int) -> str:
def _duckgres_table_name(schema: ExternalDataSchema) -> str:
- source_type = schema.source.source_type
- normalized_name = schema.normalized_name
- raw_name = (
- f"{source_type}_{schema.source.prefix}_{normalized_name}"
- if schema.source.prefix
- else f"{source_type}_{normalized_name}"
- )
- return NamingConvention.normalize_identifier(raw_name, max_length=63)
+ return duckgres_data_imports_table_name(schema)
def _should_replace_table(batch: PendingBatch) -> bool: