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): match enabled_columns across naming namespaces (#61642)

Marcus Hofacf68b0ae812
diff --git a/posthog/temporal/data_imports/sources/common/sql/projection.py b/posthog/temporal/data_imports/sources/common/sql/projection.py
index c7195f249df9..000a738b303b 100644
--- a/posthog/temporal/data_imports/sources/common/sql/projection.py
+++ b/posthog/temporal/data_imports/sources/common/sql/projection.py
@@ -13,13 +13,38 @@ from __future__ import annotations
from typing import TypeVar
+import structlog
+
+from posthog.temporal.data_imports.naming_convention import NamingConvention
from posthog.temporal.data_imports.sources.common.sql.identifiers import IdentifierQuoter
from posthog.temporal.data_imports.sources.common.sql.types import Column, Table
+logger = structlog.get_logger(__name__)
+
_TColumnValue = TypeVar("_TColumnValue")
_ColumnT = TypeVar("_ColumnT", bound=Column)
+def _identity(name: str) -> str:
+ """Exact-match fold: source-keyed callers compare names verbatim."""
+ return name
+
+
+def _normalize_for_match(name: str) -> str:
+ """Fold a column name into the dlt-normalized namespace for comparison.
+
+ `enabled_columns` / primary keys / incremental fields arrive in the source
+ namespace (e.g. Snowflake's uppercase `HOUSEHOLD_ID`), while warehouse
+ `DataWarehouseTable.columns` keys are dlt-normalized (snake_cased + lowercased,
+ e.g. `household_id`). Matching either side raw drops every column. Normalizing
+ both sides lines them up; for already-normalized names it's a no-op.
+ """
+ try:
+ return NamingConvention.normalize_identifier(name)
+ except ValueError:
+ return name
+
+
def compute_projected_columns(
enabled_columns: list[str] | None,
primary_keys: list[str] | None = None,
@@ -80,16 +105,50 @@ def filter_dwh_columns_by_enabled_columns(
enabled_columns: list[str] | None,
primary_keys: list[str] | None,
incremental_field: str | None = None,
+ *,
+ normalize: bool = True,
) -> dict[str, _TColumnValue]:
- """Filter `DataWarehouseTable.columns`-shaped dict to the projection."""
+ """Filter `DataWarehouseTable.columns`-shaped dict to the projection.
+
+ `enabled_columns` / primary keys / incremental field always arrive in the source
+ namespace. `columns` keys differ by caller, which `normalize` selects between:
+
+ - `normalize=True` (warehouse tables): keys are dlt-normalized (snake_cased +
+ lowercased), so both sides are folded through `_normalize_for_match` to line up.
+ A raw set-membership test silently drops every column when source names aren't
+ already lowercase (e.g. Snowflake's uppercase identifiers).
+ - `normalize=False` (direct-postgres callers): keys are raw, case-sensitive source
+ names — the same namespace as `enabled_columns`. Match exactly so two columns
+ that fold to the same key (Postgres allows `"Foo"` and `"foo"` in one table) stay
+ independently selectable instead of collapsing into one match.
+
+ If the projection would empty out an otherwise non-empty table, fall back to all
+ columns: an empty `columns` dict leaves the table unqueryable (`SELECT *` returns
+ no rows), which is never the intended result of a column selection. This mirrors
+ the empty-result fallback in `compute_projected_columns`. The fallback is logged
+ so an operator can tell their column selection was bypassed (namespace mismatch,
+ stale names after a source rename, or schema drift) rather than silently applied.
+ """
if enabled_columns is None:
return columns
- retained: set[str] = set(enabled_columns)
+ fold = _normalize_for_match if normalize else _identity
+ retained: set[str] = {fold(name) for name in enabled_columns}
for pk in primary_keys or []:
- retained.add(pk)
+ retained.add(fold(pk))
if incremental_field:
- retained.add(incremental_field)
- return {name: column for name, column in columns.items() if name in retained}
+ retained.add(fold(incremental_field))
+ filtered = {name: column for name, column in columns.items() if fold(name) in retained}
+ if columns and not filtered:
+ logger.warning(
+ "filter_dwh_columns_by_enabled_columns.empty_projection_fallback",
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
+ incremental_field=incremental_field,
+ available_columns=list(columns.keys()),
+ normalize=normalize,
+ )
+ return columns
+ return filtered
def project_arrow_columns(
diff --git a/posthog/temporal/data_imports/sources/common/sql/tests/test_projection.py b/posthog/temporal/data_imports/sources/common/sql/tests/test_projection.py
index 02eacad989de..e8b007ad4ff7 100644
--- a/posthog/temporal/data_imports/sources/common/sql/tests/test_projection.py
+++ b/posthog/temporal/data_imports/sources/common/sql/tests/test_projection.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import pytest
+from unittest.mock import patch
import pyarrow as pa
from parameterized import parameterized
@@ -149,6 +150,56 @@ class TestFilterDwhColumnsByEnabledColumns:
)
assert set(result.keys()) == {"id", "email", "updated_at"}
+ def test_uppercase_source_names_match_normalized_keys(self) -> None:
+ # Snowflake hands back uppercase identifiers in enabled_columns / PKs, but the Delta
+ # column keys are dlt-normalized to lowercase. They must still line up.
+ result = filter_dwh_columns_by_enabled_columns(self.dwh_columns, ["EMAIL"], ["ID"])
+ assert set(result.keys()) == {"id", "email"}
+
+ def test_mixed_case_incremental_field_matches_normalized_key(self) -> None:
+ result = filter_dwh_columns_by_enabled_columns(
+ self.dwh_columns, ["EMAIL"], ["ID"], incremental_field="UpdatedAt"
+ )
+ assert set(result.keys()) == {"id", "email", "updated_at"}
+
+ def test_empty_projection_falls_back_to_all_columns(self) -> None:
+ # A selection that matches nothing (e.g. namespace mismatch or schema drift) must not
+ # wipe the table to zero columns — that leaves `SELECT *` returning no rows.
+ result = filter_dwh_columns_by_enabled_columns(self.dwh_columns, ["does_not_exist"], None)
+ assert result == self.dwh_columns
+
+ def test_empty_input_stays_empty(self) -> None:
+ assert filter_dwh_columns_by_enabled_columns({}, ["email"], ["id"]) == {}
+
+ def test_source_namespace_keys_on_both_sides_still_filter(self) -> None:
+ # Direct-postgres callers pass raw source-namespace keys on both sides with normalize=False;
+ # an actual subset must filter cleanly without tripping the all-columns fallback.
+ source_keyed = {"ID": {"hogql": "Integer"}, "EMAIL": {"hogql": "String"}, "NAME": {"hogql": "String"}}
+ result = filter_dwh_columns_by_enabled_columns(source_keyed, ["EMAIL"], ["ID"], normalize=False)
+ assert set(result.keys()) == {"ID", "EMAIL"}
+
+ def test_normalize_false_preserves_case_sensitive_selection(self) -> None:
+ # Postgres allows `"Foo"` and `"foo"` in one table. With normalize=False (direct-postgres),
+ # selecting only `"Foo"` must not drag in `"foo"` by folding them to the same key.
+ case_collision = {"Foo": {"hogql": "String"}, "foo": {"hogql": "String"}}
+ result = filter_dwh_columns_by_enabled_columns(case_collision, ["Foo"], None, normalize=False)
+ assert set(result.keys()) == {"Foo"}
+
+ def test_normalize_true_collapses_case_collision(self) -> None:
+ # Warehouse path: source names fold into the stored normalized namespace, so a case-only
+ # difference is intentionally matched as the same column.
+ case_collision = {"Foo": {"hogql": "String"}, "foo": {"hogql": "String"}}
+ result = filter_dwh_columns_by_enabled_columns(case_collision, ["Foo"], None)
+ assert set(result.keys()) == {"Foo", "foo"}
+
+ def test_empty_projection_fallback_logs_warning(self) -> None:
+ # The all-columns fallback must be observable: an operator should be able to tell their
+ # selection was bypassed rather than silently applied.
+ with patch("posthog.temporal.data_imports.sources.common.sql.projection.logger") as mock_logger:
+ result = filter_dwh_columns_by_enabled_columns(self.dwh_columns, ["does_not_exist"], None)
+ assert result == self.dwh_columns
+ mock_logger.warning.assert_called_once()
+
class TestPruneEnabledColumns:
def test_none_passes_through(self) -> None:
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index 01cc0ed61409..3b31c6af6f3d 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -1447,6 +1447,8 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
enabled_columns,
source_schema.detected_primary_keys if source_schema else None,
incremental_field,
+ # Direct-postgres columns are keyed by raw, case-sensitive source names.
+ normalize=False,
),
source_catalog=metadata_source_catalog,
source_schema=cast(str, metadata_source_schema),
diff --git a/products/data_warehouse/backend/postgres_helpers.py b/products/data_warehouse/backend/postgres_helpers.py
index f9d6cd3b6792..5906e7c9041d 100644
--- a/products/data_warehouse/backend/postgres_helpers.py
+++ b/products/data_warehouse/backend/postgres_helpers.py
@@ -318,6 +318,8 @@ def reproject_direct_postgres_table(
enabled_columns,
schema_row.primary_key_columns,
schema_row.incremental_field,
+ # Direct-postgres columns are keyed by raw, case-sensitive source names.
+ normalize=False,
),
source_catalog=source_catalog,
source_schema=source_schema,