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.

feat(data-warehouse): column selection for all warehouse sources via delta-write projection (#67544)

Daniel RC6ba9bcd310f4
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index ae5d34af28be..cba26a7d3a6f 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6302,6 +6302,7 @@ export interface ExternalDataSchemaSourceSummary {
id: string
source_type: ExternalDataSourceType
supports_column_selection?: boolean
+ supports_row_filters?: boolean
user_access_level: AccessControlLevel | null
}
diff --git a/products/data_warehouse/backend/presentation/views/external_data_schema.py b/products/data_warehouse/backend/presentation/views/external_data_schema.py
index 04ebe4218856..d478774089e9 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_schema.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_schema.py
@@ -66,13 +66,28 @@ logger = structlog.get_logger(__name__)
def source_supports_column_selection(source_type: str) -> bool:
+ """Column selection is available for every registered source: SQL sources project the
+ selection into their SELECT, everything else is projected generically just before the
+ Delta write. Unknown source types stay False so the UI fails closed.
+
+ Excludes managed-schema sources (Stripe, Paddle, Zendesk): their HogQL tables expose a
+ fixed canonical schema, so dropping a referenced column breaks the query."""
+ try:
+ source = SourceRegistry.get_source(ExternalDataSourceType(source_type))
+ except Exception as e:
+ capture_exception(e)
+ return False
+ return not source.has_managed_hogql_schema
+
+
+def source_supports_row_filters(source_type: str) -> bool:
try:
source = SourceRegistry.get_source(ExternalDataSourceType(source_type))
except Exception as e:
capture_exception(e)
return False
# `bool()` guards against test mocks whose attribute access returns a Mock — orjson can't serialize.
- return bool(source.supports_column_selection)
+ return bool(source.supports_row_filters)
_CDC_WRITE_TARGETS_BY_TABLE_MODE: dict[str, frozenset[str]] = {
@@ -406,6 +421,7 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
"id": {"type": "string"},
"source_type": {"type": "string"},
"supports_column_selection": {"type": "boolean"},
+ "supports_row_filters": {"type": "boolean"},
"user_access_level": {"type": "string", "nullable": True},
},
}
@@ -425,6 +441,7 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
"id": str(source.id),
"source_type": source.source_type,
"supports_column_selection": source_supports_column_selection(source.source_type),
+ "supports_row_filters": source_supports_row_filters(source.source_type),
"user_access_level": user_access_level,
}
@@ -560,6 +577,10 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
if "enabled_columns" in validated_data:
enabled_columns = validated_data["enabled_columns"]
if enabled_columns is not None:
+ # Managed-schema sources expose a fixed canonical HogQL schema; dropping a
+ # referenced column breaks the query, so column selection isn't offered for them.
+ if not source_supports_column_selection(instance.source.source_type):
+ raise ValidationError("Column selection is not supported for this source type.")
if not isinstance(enabled_columns, list) or not all(isinstance(c, str) for c in enabled_columns):
raise ValidationError("enabled_columns must be a list of column-name strings or null.")
metadata = instance.schema_metadata or {}
@@ -579,6 +600,10 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
# Validate against the schema's columns; raw filters are persisted as-is and re-coerced at sync time.
if "row_filters" in validated_data and validated_data["row_filters"] is not None:
+ # Only sources that push filters into their query (SQL WHERE) can honor them — a
+ # saved-but-ignored filter would silently sync unfiltered rows.
+ if not source_supports_row_filters(instance.source.source_type):
+ raise ValidationError("Row filters are not supported for this source type.")
incoming_sync_type = data.get("sync_type")
target_is_cdc = (
incoming_sync_type == ExternalDataSchema.SyncType.CDC if "sync_type" in data else instance.is_cdc
diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.py
index 53fe12a48fec..f6380cbdc604 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_source.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py
@@ -2024,6 +2024,17 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
)
if row_filters is not None:
+ # Only sources that push filters into their query (SQL WHERE) can honor them — a
+ # saved-but-ignored filter would silently sync unfiltered rows.
+ if not source.supports_row_filters:
+ new_source_model.delete()
+ return Response(
+ status=status.HTTP_400_BAD_REQUEST,
+ data={
+ "message": f"Row filter not allowed for schema '{schema_name}': "
+ "row filters are not supported for this source type."
+ },
+ )
if reason := unsupported_row_filter_reason(
is_direct_query=new_source_model.is_direct_query, is_cdc=sync_type == "cdc"
):
diff --git a/products/data_warehouse/backend/tests/api/test_external_data_schema.py b/products/data_warehouse/backend/tests/api/test_external_data_schema.py
index 22f3604eddd4..d945b1886d2a 100644
--- a/products/data_warehouse/backend/tests/api/test_external_data_schema.py
+++ b/products/data_warehouse/backend/tests/api/test_external_data_schema.py
@@ -3180,17 +3180,15 @@ class TestAvailableColumnsAcrossSqlSources(APIBaseTest):
@parameterized.expand(
[
- # source_type, supports_column_selection_expected
+ # source_type, expected — column selection is available for every registered source
+ # (SQL projects in its SELECT, others drop before the Delta write) EXCEPT managed-schema
+ # sources (Stripe/Paddle/Zendesk), whose canonical HogQL schema needs the full column set.
(ExternalDataSourceType.POSTGRES, True),
- (ExternalDataSourceType.MYSQL, True),
- (ExternalDataSourceType.MSSQL, True),
- (ExternalDataSourceType.BIGQUERY, True),
(ExternalDataSourceType.SNOWFLAKE, True),
- (ExternalDataSourceType.REDSHIFT, True),
- # ClickHouse isn't a SQLSource but opts into column selection.
(ExternalDataSourceType.CLICKHOUSE, True),
- # Non-SQL sources stay False
+ (ExternalDataSourceType.HUBSPOT, True),
(ExternalDataSourceType.STRIPE, False),
+ (ExternalDataSourceType.ZENDESK, False),
]
)
def test_source_supports_column_selection_flag(self, source_type: ExternalDataSourceType, expected: bool):
@@ -3202,6 +3200,23 @@ class TestAvailableColumnsAcrossSqlSources(APIBaseTest):
assert response.status_code == 200, response.json()
assert response.json()["supports_column_selection"] is expected
+ def test_enabled_columns_rejected_for_managed_schema_source(self):
+ # Stripe/Paddle/Zendesk expose a fixed canonical HogQL schema; dropping a referenced
+ # column makes the s3() structure miss it and the query fails to resolve the field.
+ # Reject the selection at save so column selection can't corrupt those tables.
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_type=ExternalDataSourceType.STRIPE,
+ job_inputs={"auth_method": {"selection": "api_key", "stripe_secret_key": "123"}},
+ )
+ schema = ExternalDataSchema.objects.create(name="Payout", team=self.team, source=source)
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}",
+ data={"enabled_columns": ["id", "status"]},
+ )
+ assert response.status_code == 400
+ assert "Column selection is not supported" in str(response.json())
+
class TestExternalDataSchemaRetrieveSource(APIBaseTest):
def _create(self, source_type: ExternalDataSourceType = ExternalDataSourceType.STRIPE):
@@ -3215,12 +3230,14 @@ class TestExternalDataSchemaRetrieveSource(APIBaseTest):
@parameterized.expand(
[
- (ExternalDataSourceType.STRIPE, False),
- (ExternalDataSourceType.POSTGRES, True),
+ # source_type, expected supports_column_selection, expected supports_row_filters.
+ # Stripe is a managed-schema source (no column selection); row filters are SQL-only.
+ (ExternalDataSourceType.STRIPE, False, False),
+ (ExternalDataSourceType.POSTGRES, True, True),
]
)
def test_retrieve_includes_source_summary(
- self, source_type: ExternalDataSourceType, expected_supports_column_selection: bool
+ self, source_type: ExternalDataSourceType, expected_column_selection: bool, expected_row_filters: bool
):
source, schema = self._create(source_type=source_type)
response = self.client.get(f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}/")
@@ -3228,7 +3245,8 @@ class TestExternalDataSchemaRetrieveSource(APIBaseTest):
summary = response.json()["source"]
assert summary["id"] == str(source.id)
assert summary["source_type"] == source_type.value
- assert summary["supports_column_selection"] is expected_supports_column_selection
+ assert summary["supports_column_selection"] is expected_column_selection
+ assert summary["supports_row_filters"] is expected_row_filters
assert "user_access_level" in summary
def test_list_omits_source_summary(self):
@@ -3353,6 +3371,24 @@ class TestExternalDataSchemaRowFilters(APIBaseTest):
assert response.status_code == 400
assert "not supported for direct-query sources" in str(response.json())
+ def test_row_filters_rejected_for_source_without_pushdown(self):
+ # Only sources that push filters into their query (SQL WHERE) honor them — accepting a
+ # filter for an API source would save it and then silently sync unfiltered rows.
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_type=ExternalDataSourceType.STRIPE,
+ job_inputs={"auth_method": {"selection": "api_key", "stripe_secret_key": "123"}},
+ )
+ schema = ExternalDataSchema.objects.create(
+ name="Customers",
+ team=self.team,
+ source=source,
+ sync_type_config={"schema_metadata": self.SCHEMA_METADATA},
+ )
+ response = self._patch(schema, [{"column": "id", "operator": ">", "value": 10}])
+ assert response.status_code == 400
+ assert "not supported for this source type" in str(response.json())
+
def test_row_filters_rejected_for_cdc_schema(self):
source = ExternalDataSource.objects.create(
team=self.team,
diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.py
index 56b45c70f9e0..4d4f4dc603b5 100644
--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py
+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py
@@ -171,6 +171,37 @@ class TestExternalDataSource(APIBaseTest):
len(STRIPE_ENDPOINTS),
)
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",
+ return_value=(True, None),
+ )
+ def test_create_rejects_row_filters_for_source_without_pushdown(self, _mock_validate):
+ # Stripe doesn't push filters into a SQL WHERE — accepting one on creation would save it
+ # and then silently sync unfiltered rows (mirrors the PATCH-path
+ # test_row_filters_rejected_for_source_without_pushdown in test_external_data_schema.py).
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/",
+ data={
+ "source_type": "Stripe",
+ "created_via": "web",
+ "payload": {
+ "auth_method": {"selection": "api_key", "stripe_secret_key": "sk_test_123"},
+ "schemas": [
+ {
+ "name": STRIPE_CUSTOMER_RESOURCE_NAME,
+ "should_sync": True,
+ "sync_type": "full_refresh",
+ "row_filters": [{"column": "id", "operator": ">", "value": "10"}],
+ },
+ ],
+ },
+ },
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "not supported for this source type" in str(response.json())
+ assert not ExternalDataSource.objects.filter(team_id=self.team.pk).exists()
+
@patch("products.data_warehouse.backend.presentation.views.external_data_source.sync_discover_schemas_schedule")
@patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
index d37b9d2d75c1..02c6211242d2 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
@@ -85,7 +85,7 @@ export function ConfigurationTab({
onViewSyncHistory,
}: ConfigurationTabProps): JSX.Element {
const logic = schemaSceneLogic({ sourceId, schemaId: schema.id })
- const { isProjectTime, refreshingSchemas, resyncingSchema } = useValues(logic)
+ const { isProjectTime, refreshingSchemas, resyncingSchema, supportsRowFilters } = useValues(logic)
const { setIsProjectTime, updateSchema, reloadSchema, resyncSchema, cancelSchema, deleteTable, refreshSchemas } =
useActions(logic)
const { featureFlags } = useValues(featureFlagLogic)
@@ -114,6 +114,7 @@ export function ConfigurationTab({
resyncSchema={resyncSchema}
refreshSchemas={refreshSchemas}
refreshingSchemas={refreshingSchemas}
+ supportsRowFilters={supportsRowFilters}
/>
)
case 'schedule':
@@ -494,6 +495,7 @@ function ColumnsAndRowFiltersSection({
resyncSchema,
refreshSchemas,
refreshingSchemas,
+ supportsRowFilters,
}: {
source: ExternalDataSource | null
schema: ExternalDataSourceSchema
@@ -501,6 +503,7 @@ function ColumnsAndRowFiltersSection({
resyncSchema: (schema: ExternalDataSourceSchema) => void
refreshSchemas: () => void
refreshingSchemas: boolean
+ supportsRowFilters: boolean
}): JSX.Element {
const available = schema.available_columns ?? []
const hasAvailableColumns = available.length > 0
@@ -604,7 +607,11 @@ function ColumnsAndRowFiltersSection({
<div className="border rounded p-4 bg-surface-primary flex flex-col gap-3">
{!hasAvailableColumns ? (
<div className="flex flex-col items-center gap-2 text-center text-muted-alt py-6">
- <span className="text-sm">No columns discovered yet for this schema.</span>
+ <span className="text-sm">
+ {!schema.last_synced_at
+ ? 'No columns discovered yet for this schema — they will appear after the first successful sync.'
+ : 'No columns discovered yet for this schema.'}
+ </span>
<SourceEditorAction source={source}>
<LemonButton
type="secondary"
@@ -627,7 +634,7 @@ function ColumnsAndRowFiltersSection({
</div>
</div>
- {source?.access_method !== 'direct' && schema.sync_type !== 'cdc' && (
+ {supportsRowFilters && source?.access_method !== 'direct' && schema.sync_type !== 'cdc' && (
<div>
<SectionHeader
title="Row filters"
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts b/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts
index d6dd08cd2fca..f727ab2233d1 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts
@@ -163,6 +163,10 @@ export const schemaSceneLogic = kea<schemaSceneLogicType>([
(s) => [s.schemaData],
(schemaData): boolean => !!schemaData?.source?.supports_column_selection,
],
+ supportsRowFilters: [
+ (s) => [s.schemaData],
+ (schemaData): boolean => !!schemaData?.source?.supports_row_filters,
+ ],
breadcrumbs: [
(s) => [s.schemaData, (_, props) => props.sourceId],
(schemaData, sourceId): Breadcrumb[] => {
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py
index ecddf16bf08f..5fa7ebc022b1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py
@@ -16,7 +16,11 @@ from posthog.sync import database_sync_to_async_pool
from posthog.temporal.common.shutdown import ShutdownMonitor
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema, process_incremental_value
+from products.warehouse_sources.backend.models.external_data_schema import (
+ ExternalDataSchema,
+ process_incremental_value,
+ update_sync_type_config_keys,
+)
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.temporal.data_imports.pipelines.common.extract import (
@@ -54,8 +58,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
_append_debug_column_to_pyarrows_table,
_handle_null_columns_with_definitions,
evolve_pyarrow_schema,
+ merge_observed_columns_into_schema_metadata,
normalize_table_column_names,
+ observe_and_project_table,
setup_partitioning,
+ source_uses_delta_write_column_selection,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (
set_initial_sync_complete,
@@ -193,6 +200,11 @@ class PipelineNonDLT(Generic[ResumableData]):
self._earliest_incremental_field_value: Any = process_incremental_value(
schema.incremental_field_earliest_value, schema.incremental_field_type
)
+ # SQL sources project enabled_columns in their SELECT and own schema_metadata via
+ # introspection; managed-schema sources don't allow selection. Everything else gets the
+ # Delta-write-side drop plus observed-columns capture so the column picker has a catalog.
+ self._uses_delta_write_column_selection = source_uses_delta_write_column_selection(source.source_type)
+ self._observed_columns: dict[str, dict[str, Any]] = {}
async def run(self) -> PipelineResult:
pa_memory_pool = pa.default_memory_pool()
@@ -279,6 +291,8 @@ class PipelineNonDLT(Generic[ResumableData]):
)
chunk_index += 1
+ await self._persist_observed_columns()
+
await self._post_run_operations(row_count=row_count)
await advance_xmin_state(self._resource, self._schema, self._logger)
@@ -304,6 +318,24 @@ class PipelineNonDLT(Generic[ResumableData]):
cleanup_memory(pa_memory_pool, py_table if "py_table" in locals() else None)
+ async def _persist_observed_columns(self) -> None:
+ """Union the columns the source actually returned into `schema_metadata["columns"]`.
+
+ Bookkeeping for the column picker — a failure here must not fail an otherwise
+ successful sync.
+ """
+ if not self._observed_columns:
+ return
+ observed = list(self._observed_columns.values())
+ try:
+ await database_sync_to_async_pool(update_sync_type_config_keys)(
+ self._schema.id,
+ self._job.team_id,
+ mutate=lambda config: merge_observed_columns_into_schema_metadata(config, observed),
+ )
+ except Exception:
+ await self._logger.aexception("Failed to persist observed columns into schema_metadata")
+
async def _process_pa_table(
self, pa_table: pa.Table, index: int, resuming_sync: bool, row_count: int, is_first_ever_sync: bool
):
@@ -313,6 +345,22 @@ class PipelineNonDLT(Generic[ResumableData]):
pa_table = _append_debug_column_to_pyarrows_table(pa_table, self._load_id)
pa_table = normalize_table_column_names(pa_table)
+ if self._uses_delta_write_column_selection:
+ pa_table = await observe_and_project_table(
+ pa_table,
+ self._schema.enabled_columns,
+ self._resource.primary_keys,
+ self._schema.incremental_field,
+ [
+ *(self._schema.partitioning_keys_override or []),
+ *(self._schema.partitioning_keys or []),
+ *(self._resource.partition_keys or []),
+ ],
+ self._observed_columns,
+ self._logger,
+ "Dropped non-enabled columns before Delta write",
+ )
+
pa_table = await setup_partitioning(pa_table, delta_table, self._schema, self._resource, self._logger)
pa_table = evolve_pyarrow_schema(pa_table, delta_table.schema() if delta_table is not None else None)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py
index b8438c4a8924..4513a276f04e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py
@@ -5,7 +5,7 @@ from ipaddress import IPv4Address, IPv6Address
from typing import Any, cast
import pytest
-from unittest.mock import MagicMock
+from unittest.mock import AsyncMock, MagicMock, patch
import pyarrow as pa
import deltalake
@@ -19,9 +19,14 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
_get_max_decimal_type,
_to_list_array,
append_partition_key_to_table,
+ apply_enabled_columns_projection,
evolve_pyarrow_schema,
+ merge_observed_columns_into_schema_metadata,
normalize_table_column_names,
+ observe_and_project_table,
+ observed_schema_metadata_columns,
setup_partitioning,
+ source_uses_delta_write_column_selection,
table_from_py_list,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.test_mocks import mock_delta_table
@@ -1018,3 +1023,161 @@ async def test_setup_partitioning_mode_override_forces_datetime_on_non_standard_
assert applied_mode == "datetime"
assert applied_keys == ["action_date"]
assert applied_format == "month"
+
+
+def _projection_input_table() -> pa.Table:
+ return pa.table(
+ {
+ "id": [1, 2],
+ "name": ["a", "b"],
+ "amount": [10, 20],
+ "updated_at": ["2026-01-01", "2026-01-02"],
+ "_ph_debug": ["{}", "{}"],
+ }
+ )
+
+
+ "enabled_columns,primary_keys,incremental_field,partition_keys,expected_columns",
+ [
+ # None syncs everything untouched
+ (None, ["id"], "updated_at", None, ["id", "name", "amount", "updated_at", "_ph_debug"]),
+ # plain selection drops the rest, internals survive
+ (["name"], None, None, None, ["name", "_ph_debug"]),
+ # PK + incremental field retained even when not selected
+ (["name"], ["id"], "updated_at", None, ["id", "name", "updated_at", "_ph_debug"]),
+ # source-namespace names (e.g. Snowflake uppercase) fold onto normalized table columns
+ (["NAME"], ["ID"], None, None, ["id", "name", "_ph_debug"]),
+ # stale enabled names are ignored, not fatal
+ (["name", "dropped_upstream"], None, None, None, ["name", "_ph_debug"]),
+ # a projection that would empty the table falls back to all columns
+ (["dropped_upstream"], None, None, None, ["id", "name", "amount", "updated_at", "_ph_debug"]),
+ # [] keeps only the always-retained set
+ ([], ["id"], "updated_at", None, ["id", "updated_at", "_ph_debug"]),
+ # partition-key source columns retained
+ (["name"], None, None, ["amount"], ["name", "amount", "_ph_debug"]),
+ ],
+)
+def test_apply_enabled_columns_projection(
+ enabled_columns, primary_keys, incremental_field, partition_keys, expected_columns
+):
+ table, dropped = apply_enabled_columns_projection(
+ _projection_input_table(), enabled_columns, primary_keys, incremental_field, partition_keys
+ )
+
+ assert table.column_names == expected_columns
+ assert sorted(dropped) == sorted(set(_projection_input_table().column_names) - set(expected_columns))
+
+
+def test_apply_enabled_columns_projection_drops_spoofed_internal_lookalikes():
+ # A source can't smuggle a deselected column past the projection by giving it a name that
+ # merely looks internal (_ph_*/_dlt_*) — only the pipeline's own exact internal columns survive.
+ table = pa.table(
+ {
+ "name": ["a", "b"],
+ "_ph_debug": ["{}", "{}"],
+ "_ph_secret": ["s1", "s2"],
+ "_dlt_secret": ["d1", "d2"],
+ }
+ )
+
+ result, dropped = apply_enabled_columns_projection(table, ["name"], None, None, None)
+
+ assert result.column_names == ["name", "_ph_debug"]
+ assert sorted(dropped) == ["_dlt_secret", "_ph_secret"]
+
+
+async def test_observe_and_project_table_observes_then_projects_and_logs():
+ logger: FilteringBoundLogger = structlog.get_logger()
+ observed_columns: dict[str, Any] = {}
+ table = _projection_input_table()
+
+ with patch.object(logger, "adebug", new=AsyncMock()) as mock_adebug:
+ result = await observe_and_project_table(
+ table,
+ ["name"],
+ None,
+ None,
+ None,
+ observed_columns,
+ logger,
+ "Dropped non-enabled columns",
+ )
+
+ assert result.column_names == ["name", "_ph_debug"]
+ # Observed before projection, so deselected columns stay visible to the column picker.
+ assert set(observed_columns) == {"id", "name", "amount", "updated_at"}
+ mock_adebug.assert_called_once()
+ assert "Dropped non-enabled columns" in mock_adebug.call_args.args[0]
+
+
+def test_observed_schema_metadata_columns_excludes_internal_columns():
+ fields: list[pa.Field] = [
+ pa.field("id", pa.int64(), nullable=False),
+ pa.field("name", pa.string()),
+ pa.field("_ph_debug", pa.string()),
+ pa.field("_dlt_id", pa.string()),
+ ]
+ schema = pa.schema(fields)
+
+ assert observed_schema_metadata_columns(schema) == [
+ {"name": "id", "data_type": "int64", "is_nullable": False},
+ {"name": "name", "data_type": "string", "is_nullable": True},
+ ]
+
+
+def test_merge_observed_columns_creates_schema_metadata_from_empty_config():
+ config: dict[str, Any] = {}
+
+ merge_observed_columns_into_schema_metadata(config, [{"name": "id", "data_type": "int64", "is_nullable": False}])
+
+ assert config["schema_metadata"]["columns"] == [{"name": "id", "data_type": "int64", "is_nullable": False}]
+
+
+def test_merge_observed_columns_unions_and_refreshes():
+ # Deselected columns must stay listed (union) or the picker could never re-enable them,
+ # while re-observed columns pick up type changes.
+ config: dict[str, Any] = {
+ "schema_metadata": {
+ "columns": [
+ {"name": "id", "data_type": "int32", "is_nullable": False},
+ {"name": "deselected", "data_type": "string", "is_nullable": True},
+ ],
+ "source_table_name": "customers",
+ }
+ }
+
+ merge_observed_columns_into_schema_metadata(
+ config,
+ [
+ {"name": "id", "data_type": "int64", "is_nullable": False},
+ {"name": "brand_new", "data_type": "string", "is_nullable": True},
+ ],
+ )
+
+ assert config["schema_metadata"]["columns"] == [
+ {"name": "id", "data_type": "int64", "is_nullable": False},
+ {"name": "deselected", "data_type": "string", "is_nullable": True},
+ {"name": "brand_new", "data_type": "string", "is_nullable": True},
+ ]
+ assert config["schema_metadata"]["source_table_name"] == "customers"
+
+
+ "source_type,expected",
+ [
+ # SQL sources project enabled_columns in their SELECT — no Delta-write drop.
+ ("Postgres", False),
+ # Managed-schema sources must never drop columns (canonical HogQL schema needs them all),
+ # even if a stale enabled_columns is still persisted.
+ ("Stripe", False),
+ ("Zendesk", False),
+ # Generic API sources get the generic Delta-write drop.
+ ("Hubspot", True),
+ # Unknown source types fail closed.
+ ("NotARealSource", False),
+ ],
+)
+def test_source_uses_delta_write_column_selection(source_type, expected):
+ assert source_uses_delta_write_column_selection(source_type) is expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py
index 8629e466fdd6..cec90ee31ae2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py
@@ -358,6 +358,154 @@ def normalize_table_column_names(table: pa.Table) -> pa.Table:
return table
+INTERNAL_COLUMN_NAMES = frozenset({"_ph_debug", PARTITION_KEY, "_dlt_id", "_dlt_load_id"})
+
+
+def _fold_column_name_for_match(name: str) -> str:
+ try:
+ return NamingConvention.normalize_identifier(name)
+ except ValueError:
+ return name
+
+
+def apply_enabled_columns_projection(
+ table: pa.Table,
+ enabled_columns: list[str] | None,
+ primary_keys: list[str] | None,
+ incremental_field: str | None,
+ partition_keys: list[str] | None,
+) -> tuple[pa.Table, list[str]]:
+ """Drop table columns not selected in `enabled_columns`. Returns `(table, dropped_names)`.
+
+ Delta-write-side counterpart of the SQL sources' SELECT projection, for sources that can't
+ push the projection into the fetch. `None` means all columns sync. Primary keys, the active
+ incremental field, partition-key source columns, and the pipeline's own internal columns
+ (`INTERNAL_COLUMN_NAMES`) are always retained — matched by exact name, not prefix, so an
+ upstream source can't smuggle a deselected column past the projection by naming it e.g.
+ `_ph_secret` or `_dlt_secret`. Both sides are folded through the dlt naming convention: the table has already been
+ through `normalize_table_column_names` while `enabled_columns`/primary keys arrive in the
+ source namespace, so a raw comparison would drop every non-lowercase column. If the
+ projection would drop every user-facing column, the table is returned unchanged (mirrors the
+ empty-projection fallback in `filter_dwh_columns_by_enabled_columns`) — an empty table is
+ never the intended result of a column selection.
+ """
+ if enabled_columns is None:
+ return table, []
+
+ retained = {_fold_column_name_for_match(name) for name in enabled_columns}
+ for primary_key in primary_keys or []:
+ retained.add(_fold_column_name_for_match(primary_key))
+ if incremental_field:
+ retained.add(_fold_column_name_for_match(incremental_field))
+ for partition_key in partition_keys or []:
+ retained.add(_fold_column_name_for_match(partition_key))
+
+ kept_names = [
+ name
+ for name in table.column_names
+ if name in INTERNAL_COLUMN_NAMES or _fold_column_name_for_match(name) in retained
+ ]
+ dropped_names = [name for name in table.column_names if name not in set(kept_names)]
+ if not dropped_names:
+ return table, []
+ if all(name in INTERNAL_COLUMN_NAMES for name in kept_names):
+ return table, []
+ return table.select(kept_names), dropped_names
+
+
+async def observe_and_project_table(
+ table: pa.Table,
+ enabled_columns: list[str] | None,
+ primary_keys: list[str] | None,
+ incremental_field: str | None,
+ partition_keys: list[str] | None,
+ observed_columns: dict[str, dict[str, Any]],
+ logger: FilteringBoundLogger,
+ log_message: str,
+) -> pa.Table:
+ """Shared observe-then-project step for `_uses_delta_write_column_selection` pipelines.
+
+ Unions the batch's columns into `observed_columns` (for the column picker) before dropping
+ non-enabled ones, so a pinned selection never hides a column from the picker. `log_message`
+ is logged with the dropped column names appended, letting each pipeline keep its own wording.
+ """
+ for observed_column in observed_schema_metadata_columns(table.schema):
+ observed_columns[observed_column["name"]] = observed_column
+
+ table, dropped_names = apply_enabled_columns_projection(
+ table, enabled_columns, primary_keys, incremental_field, partition_keys
+ )
+ if dropped_names:
+ await logger.adebug(f"{log_message}: {dropped_names}")
+ return table
+
+
+def source_uses_delta_write_column_selection(source_type: str) -> bool:
+ """True when the pipeline applies `enabled_columns` by dropping columns before the Delta
+ write (and captures the observed columns into `schema_metadata`).
+
+ False for:
+ - SQL sources — they project `enabled_columns` into their SELECT and own
+ `schema_metadata["columns"]` via schema introspection;
+ - managed-schema sources (Stripe/Paddle/Zendesk) — column selection is disabled for them
+ (their canonical HogQL schema needs the full physical column set), so the pipeline must
+ never drop their columns even if a stale `enabled_columns` is still persisted.
+ """
+ # Imported lazily: the registry pulls in every source's (often heavy) dependencies on first use.
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import (
+ SourceRegistry, # noqa: PLC0415
+ )
+ from products.warehouse_sources.backend.types import ExternalDataSourceType # noqa: PLC0415
+
+ try:
+ source = SourceRegistry.get_source(ExternalDataSourceType(source_type))
+ except Exception:
+ return False
+ return not source.supports_column_selection and not source.has_managed_hogql_schema
+
+
+def observed_schema_metadata_columns(schema: pa.Schema) -> list[dict[str, Any]]:
+ """`schema_metadata["columns"]`-shaped entries from a pre-projection arrow schema.
+
+ Captured before `apply_enabled_columns_projection` so the persisted catalog keeps listing
+ columns the source returns even while they're being dropped — otherwise a pinned selection
+ would make deselected (and newly-added upstream) columns invisible to the column picker.
+ """
+ return [
+ {"name": field.name, "data_type": str(field.type), "is_nullable": field.nullable}
+ for field in schema
+ if field.name not in INTERNAL_COLUMN_NAMES
+ ]
+
+
+def merge_observed_columns_into_schema_metadata(config: dict[str, Any], observed_columns: list[dict[str, Any]]) -> None:
+ """Union observed column entries into `sync_type_config["schema_metadata"]["columns"]` in place.
+
+ Existing entries keep their position and are refreshed with the observed type/nullability;
+ columns previously observed but absent from this run stay listed (union, not replace) so a
+ projection or an upstream removal never shrinks the picker. Designed as a `mutate` callback
+ for `update_sync_type_config_keys`.
+ """
+ metadata = config.get("schema_metadata")
+ if not isinstance(metadata, dict):
+ metadata = {}
+ config["schema_metadata"] = metadata
+ columns = metadata.get("columns")
+ if not isinstance(columns, list):
+ columns = []
+ metadata["columns"] = columns
+ entries_by_name = {
+ column.get("name"): column for column in columns if isinstance(column, dict) and column.get("name")
+ }
+ for observed in observed_columns:
+ existing = entries_by_name.get(observed["name"])
+ if existing is None:
+ columns.append(observed)
+ else:
+ existing["data_type"] = observed["data_type"]
+ existing["is_nullable"] = observed["is_nullable"]
+
+
PARTITION_DATETIME_COLUMN_NAMES = ["created_at", "inserted_at", "createdAt"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index 4b727f079145..0f41f8f44c01 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -8,6 +8,7 @@ from structlog.types import FilteringBoundLogger
from temporalio import activity
from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
+from posthog.sync import database_sync_to_async_pool
from posthog.temporal.common.activity_context import (
current_activity_attempt,
current_workflow_id,
@@ -18,7 +19,11 @@ from posthog.utils import get_machine_id
from products.warehouse_sources.backend.models import DataWarehouseTable
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema, process_incremental_value
+from products.warehouse_sources.backend.models.external_data_schema import (
+ ExternalDataSchema,
+ process_incremental_value,
+ update_sync_type_config_keys,
+)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
advance_xmin_state,
@@ -51,7 +56,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
_append_debug_column_to_pyarrows_table,
_handle_null_columns_with_definitions,
evolve_pyarrow_schema,
+ merge_observed_columns_into_schema_metadata,
normalize_table_column_names,
+ observe_and_project_table,
+ source_uses_delta_write_column_selection,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import set_initial_sync_complete
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.metrics import (
@@ -165,6 +173,12 @@ class PipelineV3(Generic[ResumableData]):
# Determine if this is the first-ever sync (no DWH table exists yet)
is_first_ever_sync = self._schema.table is None
+ # SQL sources project enabled_columns in their SELECT and own schema_metadata via
+ # introspection; managed-schema sources don't allow selection. Everything else gets the
+ # write-side drop plus observed-columns capture so the column picker has a catalog.
+ self._uses_delta_write_column_selection = source_uses_delta_write_column_selection(source.source_type)
+ self._observed_columns: dict[str, dict[str, Any]] = {}
+
is_resume = resumable_source_manager is not None and resumable_source_manager.can_resume()
self._pg_producer = PostgresProducer(
@@ -362,6 +376,22 @@ class PipelineV3(Generic[ResumableData]):
pa_table = _append_debug_column_to_pyarrows_table(pa_table, self._load_id)
pa_table = normalize_table_column_names(pa_table)
+ if self._uses_delta_write_column_selection:
+ pa_table = await observe_and_project_table(
+ pa_table,
+ self._schema.enabled_columns,
+ self._resource.primary_keys,
+ self._schema.incremental_field,
+ [
+ *(self._schema.partitioning_keys_override or []),
+ *(self._schema.partitioning_keys or []),
+ *(self._resource.partition_keys or []),
+ ],
+ self._observed_columns,
+ self._logger,
+ "V3 Pipeline: Dropped non-enabled columns before write",
+ )
+
pa_table = evolve_pyarrow_schema(pa_table, None)
pa_table = _handle_null_columns_with_definitions(pa_table, self._resource)
@@ -408,6 +438,18 @@ class PipelineV3(Generic[ResumableData]):
)
async def _finalize(self, row_count: int) -> None:
+ # Column-picker bookkeeping — a failure here must not fail an otherwise successful sync.
+ if self._observed_columns:
+ observed = list(self._observed_columns.values())
+ try:
+ await database_sync_to_async_pool(update_sync_type_config_keys)(
+ self._schema.id,
+ self._job.team_id,
+ mutate=lambda config: merge_observed_columns_into_schema_metadata(config, observed),
+ )
+ except Exception:
+ await self._logger.aexception("V3 Pipeline: Failed to persist observed columns into schema_metadata")
+
total_batches = len(self._batch_results)
if total_batches == 0:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
index b3a1f5a397db..a652fc9fb5d1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
@@ -49,6 +49,8 @@ def _make_pipeline() -> PipelineV3:
pipeline._batch_results = []
pipeline._shutdown_monitor = MagicMock()
pipeline._attempt = 1
+ pipeline._uses_delta_write_column_selection = False
+ pipeline._observed_columns = {}
return pipeline
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py
index faf861f03026..d9dd2b54a579 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py
@@ -68,6 +68,7 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Val
# Lets users pick which columns to sync (and, in the wizard, surfaces the
# row-filter editor that shares the same column-selection modal).
supports_column_selection: bool = True
+ supports_row_filters: bool = True
@property
def source_type(self) -> ExternalDataSourceType:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
index 149bb11a4fe5..b57b65f1026d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py
@@ -100,8 +100,24 @@ class _BaseSource(ABC, Generic[ConfigType]):
# Default `False` for every source; `SQLSource` flips to `True` (subclasses opt out
# via their own override if a driver genuinely can't project columns).
+ # `True` means the source lists typed columns at schema discovery and applies
+ # `enabled_columns` itself (SELECT projection). Sources left `False` still get column
+ # selection — the pipeline drops non-enabled columns just before the Delta write and
+ # captures the observed columns into `schema_metadata` after the first sync.
supports_column_selection: bool = False
+ # `True` only for sources that push `row_filters` into their query (SQL WHERE).
+ # Sources without pushdown must reject filters — a saved-but-ignored filter would
+ # silently sync unfiltered rows.
+ supports_row_filters: bool = False
+
+ # `True` for sources whose HogQL tables use a PostHog-managed canonical schema
+ # (`external_table_definitions`) — Stripe, Paddle, Zendesk. Their query exposes a fixed
+ # field set (and powers revenue analytics), so the physical column set must stay complete.
+ # Column selection is disabled for these: dropping a canonically-referenced column makes the
+ # generated s3() structure miss it and the query fails to resolve the field.
+ has_managed_hogql_schema: bool = False
+
# Opt-in: set `True` only on sources whose `get_schemas` iterates a static endpoint
# catalog with NO I/O — no network, no DB, no credentials. Those sources surface their
# table list in public docs (see `get_documented_tables`). Left `False` for SQL / file /
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/base.py
index 0072c43907a1..b7271b12863b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/base.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sql/base.py
@@ -60,6 +60,7 @@ class SQLSource(SimpleSource[ConfigType], Generic[ConfigType]):
"""
supports_column_selection: bool = True
+ supports_row_filters: bool = True
@property
@abstractmethod
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/source.py
index b506880a686b..4059770298c4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/source.py
@@ -36,6 +36,7 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class PaddleSource(ResumableSource[PaddleSourceConfig, PaddleResumeConfig]):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ has_managed_hogql_schema = True # canonical Paddle schema in external_table_definitions
@property
def source_type(self) -> ExternalDataSourceType:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py
index b650e3d6c94f..00a304c5425d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py
@@ -102,6 +102,7 @@ class StripeSource(
OAuthMixin,
):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ has_managed_hogql_schema = True # canonical Stripe schema in external_table_definitions
@property
def source_type(self) -> ExternalDataSourceType:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py
index 1a540425a8e8..28373f0c145b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py
@@ -37,6 +37,7 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class ZendeskSource(SimpleSource[ZendeskSourceConfig]):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ has_managed_hogql_schema = True # canonical Zendesk schema in external_table_definitions
@property
def source_type(self) -> ExternalDataSourceType:
diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.ts
index 5071f8b65ec5..ecdff4253772 100644
--- a/products/warehouse_sources/frontend/generated/api.schemas.ts
+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts
@@ -116,6 +116,7 @@ export type ExternalDataSchemaApiSource = {
readonly id?: string
readonly source_type?: string
readonly supports_column_selection?: boolean
+ readonly supports_row_filters?: boolean
/** @nullable */
readonly user_access_level?: string | null
} | null
@@ -256,6 +257,7 @@ export type PatchedExternalDataSchemaApiSource = {
readonly id?: string
readonly source_type?: string
readonly supports_column_selection?: boolean
+ readonly supports_row_filters?: boolean
/** @nullable */
readonly user_access_level?: string | null
} | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 30670263d131..67689d3fed0c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -22526,6 +22526,7 @@ export namespace Schemas {
readonly id?: string;
readonly source_type?: string;
readonly supports_column_selection?: boolean;
+ readonly supports_row_filters?: boolean;
/** @nullable */
readonly user_access_level?: string | null;
} | null;
@@ -37949,6 +37950,7 @@ export namespace Schemas {
readonly id?: string;
readonly source_type?: string;
readonly supports_column_selection?: boolean;
+ readonly supports_row_filters?: boolean;
/** @nullable */
readonly user_access_level?: string | null;
} | null;