: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
fix(data-warehouse): preserve source column identifiers (#88619)
ella-c753b7190d225
diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex b03b42825f3b..a1376cb64595 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -6621,6 +6621,8 @@ export interface ExternalDataSourceSchema extends SimpleExternalDataSourceSchema*/enabled_columns?: string[] | nullavailable_columns?: { name: string; data_type?: string; is_nullable?: boolean }[]+ /** Exact source identifiers are available for sources that project columns upstream. */+ source_column_metadata_available?: boolean/*** Predicates ANDed onto the source query so only matching rows sync.* `null` means "sync all rows". Applied on the next sync — not retroactive.@@ -6641,6 +6643,7 @@ export interface ExternalDataSchemaSourceSummary {access_method?: ExternalDataSource['access_method']supports_column_selection?: booleansupports_row_filters?: boolean+ requires_exact_column_metadata?: booleanuser_access_level: AccessControlLevel | null/** The source's effective vendor API version — what schemas without an override sync on */api_version?: string | nulldiff --git a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsxindex 78a090071e78..74eee4cb428e 100644--- a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx+++ b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx@@ -658,7 +658,7 @@ function ColumnsAndRowFiltersSection({refreshingSchemas,supportsRowFilters,}: {- source: ExternalDataSource | null+ source: SchemaSceneSource | nullschema: ExternalDataSourceSchemaupdateSchema: (schema: ExternalDataSourceSchema) => voidresyncSchema: (schema: ExternalDataSourceSchema) => void@@ -668,6 +668,8 @@ function ColumnsAndRowFiltersSection({}): JSX.Element {const available = schema.available_columns ?? []const hasAvailableColumns = available.length > 0+ const columnSelectionNeedsRefresh =+ !!source?.requires_exact_column_metadata && schema.source_column_metadata_available === false// Plain value, not the render-prop form of SchemaEditorAction: a fresh inline render-prop on// every edit would remount the editors and wipe their drafts. See useSchemaEditorAccess's docstring.@@ -766,12 +768,14 @@ function ColumnsAndRowFiltersSection({description="Choose which columns from this table get synced. Primary keys and the active incremental field are always synced."/><div className="border rounded p-4 bg-surface-primary flex flex-col gap-3">- {!hasAvailableColumns ? (+ {!hasAvailableColumns || columnSelectionNeedsRefresh ? (<div className="flex flex-col items-center gap-2 text-center text-muted-alt py-6"><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.'}+ {columnSelectionNeedsRefresh+ ? 'Pull the latest source schema before changing columns. Existing synced columns remain available under Descriptions.'+ : !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><SchemaEditorAction schema={schema}><LemonButton@@ -802,7 +806,7 @@ function ColumnsAndRowFiltersSection({description="Sync only rows that match these conditions. Filters are ANDed together and applied on the next sync — they don't remove rows already synced."/><div className="border rounded p-4 bg-surface-primary flex flex-col gap-3">- {!hasAvailableColumns ? (+ {!hasAvailableColumns || columnSelectionNeedsRefresh ? (<div className="text-sm text-muted-alt py-2 text-center">No columns discovered yet — pull schemas from the Columns section above to add rowfilters.diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.pyindex 2eb5c6ddd186..4299c996ce42 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py@@ -96,6 +96,25 @@ def source_supports_row_filters(source_type: str) -> bool:return bool(source.supports_row_filters)+def source_requires_exact_column_metadata(source_type: str) -> bool:+ """Whether enabled column names are interpolated into a source-side query.++ These sources require exact source identifiers. Warehouse table columns have already+ passed through dlt normalization, so they are not a safe fallback for configuration.++ This is intentionally narrower than ``source_supports_column_selection``: the latter+ also includes sources whose columns are projected generically after extraction.+ """+ try:+ source = SourceRegistry.get_source(ExternalDataSourceType(source_type))+ except Exception as e:+ capture_exception(e)+ # Unknown source types already fail the broader column-selection check. Keep the+ # read path available so a registry failure does not also blank column descriptions.+ return False+ return bool(source.supports_column_selection)++_CDC_WRITE_TARGETS_BY_TABLE_MODE: dict[str, frozenset[str]] = {"consolidated": frozenset({"consolidated"}),"cdc_only": frozenset({"cdc_history"}),@@ -368,6 +387,10 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers"source-side schema discovered via `refresh_schemas`; for other sources (and once synced) it falls back ""to the synced table's columns. Empty only before the first successful sync/refresh.",)+ source_column_metadata_available = serializers.SerializerMethodField(+ read_only=True,+ help_text="Whether exact source-side column metadata is available for safe source-query projection.",+ )# `source` shadows DRF's reserved `Field.source` attribute, so mypy flags the assignment;# the runtime behaviour (a read-only SerializerMethodField backed by get_source) is correct.source = serializers.SerializerMethodField( # type: ignore[assignment]@@ -402,6 +425,7 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers"enabled_columns","row_filters","available_columns",+ "source_column_metadata_available","source","api_version","api_version_deprecation",@@ -418,6 +442,7 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers"status","description","available_columns",+ "source_column_metadata_available","source","api_version_deprecation","user_access_level",@@ -460,6 +485,10 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializerstable = schema.tablereturn table.get_user_facing_columns() if table is not None else []+ def get_source_column_metadata_available(self, schema: ExternalDataSchema) -> bool:+ metadata = schema.schema_metadata or {}+ return isinstance(metadata.get("columns"), list) if isinstance(metadata, dict) else False+@extend_schema_field({"type": "object",@@ -470,6 +499,7 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers"access_method": {"type": "string"},"supports_column_selection": {"type": "boolean"},"supports_row_filters": {"type": "boolean"},+ "requires_exact_column_metadata": {"type": "boolean"},"user_access_level": {"type": "string", "nullable": True},"api_version": {"type": "string", "nullable": True},"supported_api_versions": {"type": "array", "items": {"type": "string"}},@@ -502,6 +532,7 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers"access_method": source.access_method,"supports_column_selection": source_supports_column_selection(source.source_type),"supports_row_filters": source_supports_row_filters(source.source_type),+ "requires_exact_column_metadata": source_requires_exact_column_metadata(source.source_type),"user_access_level": user_access_level,"api_version": source_api_version,"supported_api_versions": supported_api_versions,@@ -681,6 +712,10 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializersvalidated_data.pop("primary_key_columns", None)validated_data.pop("cdc_table_mode", None)+ enabled_columns_changed = "enabled_columns" in validated_data and (+ validated_data["enabled_columns"] != instance.enabled_columns+ )+if "enabled_columns" in validated_data:enabled_columns = validated_data["enabled_columns"]if enabled_columns is not None:@@ -704,6 +739,14 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializersf"Unknown columns in enabled_columns: {sorted(unknown)}. ""Run `Pull new schemas` to refresh available columns.")+ elif (+ enabled_columns_changed+ and enabled_columns+ and source_requires_exact_column_metadata(instance.source.source_type)+ ):+ raise ValidationError(+ "Column metadata is unavailable. Run `Pull new schemas` before selecting source columns."+ )# 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:@@ -985,10 +1028,6 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializersvalidated_data["sync_type_config"]["reset_pipeline"] = Truetrigger_refresh = True- enabled_columns_changed = "enabled_columns" in validated_data and (- validated_data["enabled_columns"] != instance.enabled_columns- )-if source.is_direct_query:direct_engine_adapter = get_direct_query_engine(source.direct_engine)# Direct-mode lifecycle hooks that need a fresh DataWarehouseTable projection:diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py b/products/warehouse_sources/backend/tests/api/test_external_data_schema.pyindex c410ff0ce668..8a58250fb4ec 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_schema.py@@ -3341,6 +3341,7 @@ class TestSyncTypeConfigLostUpdateProtection(APIBaseTest):"cdc_table_mode": "consolidated","cdc_last_log_position": "0/100","primary_key_columns": ["id"],+ "schema_metadata": {"columns": [{"name": "id", "data_type": "integer", "is_nullable": False}]},},)@@ -3471,12 +3472,11 @@ class TestAvailableColumnsAcrossSqlSources(APIBaseTest):assert response.status_code == 200, response.json()assert response.json()["available_columns"] == []- def test_available_columns_falls_back_to_synced_table_when_metadata_missing(self):- # `schema_metadata` is empty whenever it hasn't been reconciled (non-SQL sources, or SQL schemas- # discovered/added after the last reload). available_columns must then fall back to the synced- # table's columns — otherwise the Descriptions UI shows no columns (even when annotations exist)- # and users can't edit them. Internal plumbing columns (`_dlt_id`, …) stay hidden.- source = ExternalDataSource.objects.create(team=self.team, source_type=ExternalDataSourceType.POSTGRES)+ def test_available_columns_falls_back_to_synced_table_for_pipeline_projected_source(self):+ # Non-SQL sources match selections against dlt-normalized Arrow columns, so the synced+ # table remains a safe fallback when observed source metadata is unavailable. Internal+ # plumbing columns (`_dlt_id`, …) stay hidden.+ source = ExternalDataSource.objects.create(team=self.team, source_type=ExternalDataSourceType.HUBSPOT)table = DataWarehouseTable.objects.create(name="billing_customer",format="DeltaS3Wrapper",@@ -3507,6 +3507,69 @@ class TestAvailableColumnsAcrossSqlSources(APIBaseTest):{"name": "id", "data_type": "String", "is_nullable": False},]+ def test_available_columns_fallback_preserves_descriptions_for_source_projection(self):+ source = ExternalDataSource.objects.create(team=self.team, source_type=ExternalDataSourceType.POSTGRES)+ table = DataWarehouseTable.objects.create(+ name="billing_customer",+ format="DeltaS3Wrapper",+ team=self.team,+ url_pattern="https://bucket.s3/data/*",+ columns={"account_id": {"clickhouse": "String"}},+ )+ schema = ExternalDataSchema.objects.create(+ name="billing_customer",+ team=self.team,+ source=source,+ table=table,+ should_sync=True,+ status=ExternalDataSchema.Status.COMPLETED,+ )++ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}/")++ assert response.status_code == 200, response.json()+ assert response.json()["available_columns"] == [+ {"name": "account_id", "data_type": "String", "is_nullable": False}+ ]+ assert response.json()["source_column_metadata_available"] is False++ def test_enabled_columns_rejected_without_source_metadata_for_source_projection(self):+ source = ExternalDataSource.objects.create(team=self.team, source_type=ExternalDataSourceType.POSTGRES)+ schema = ExternalDataSchema.objects.create(name="customers", team=self.team, source=source)++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}",+ data={"enabled_columns": ["account_id"]},+ )++ assert response.status_code == 400+ assert "Pull new schemas" in str(response.json())++ def test_unchanged_enabled_columns_do_not_block_unrelated_update_without_source_metadata(self):+ source = ExternalDataSource.objects.create(team=self.team, source_type=ExternalDataSourceType.POSTGRES)+ schema = ExternalDataSchema.objects.create(+ name="customers", team=self.team, source=source, enabled_columns=["account_id"], should_sync=True+ )++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}",+ data={"enabled_columns": ["account_id"], "should_sync": False},+ )++ assert response.status_code == 200, response.json()+ schema.refresh_from_db()+ assert schema.should_sync is False++ def test_empty_enabled_columns_allowed_without_source_metadata(self):+ source = ExternalDataSource.objects.create(team=self.team, source_type=ExternalDataSourceType.POSTGRES)+ schema = ExternalDataSchema.objects.create(name="customers", team=self.team, source=source)++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}", data={"enabled_columns": []}+ )++ assert response.status_code == 200, response.json()+@parameterized.expand([# source_type, expected — column selection is available for every registered sourcediff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.pyindex 5aa745d29075..5f582d053931 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py@@ -2868,6 +2868,7 @@ class TestExternalDataSource(APIBaseTest):"enabled_columns": None,"row_filters": None,"available_columns": [],+ "source_column_metadata_available": False,"source": None,"api_version": None,"api_version_deprecation": None,diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.tsindex 062b4165da43..3231021e83fb 100644--- a/products/warehouse_sources/frontend/generated/api.schemas.ts+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts@@ -129,6 +129,7 @@ export type ExternalDataSchemaApiSource = {readonly access_method?: stringreadonly supports_column_selection?: booleanreadonly supports_row_filters?: boolean+ readonly requires_exact_column_metadata?: boolean/** @nullable */readonly user_access_level?: string | null/** @nullable */@@ -231,6 +232,8 @@ export interface ExternalDataSchemaApi {row_filters?: ExternalDataSchemaApiRowFiltersItem[] | null/** Column metadata (name, data type, nullable) for this schema. For SQL sources this is the source-side schema discovered via `refresh_schemas`; for other sources (and once synced) it falls back to the synced table's columns. Empty only before the first successful sync/refresh. */readonly available_columns: readonly ExternalDataSchemaApiAvailableColumnsItem[]+ /** Whether exact source-side column metadata is available for safe source-query projection. */+ readonly source_column_metadata_available: boolean/*** Lightweight parent-source summary (id, source_type, access_method, column-selection support, the requesting user's access level). Only populated on the single-schema retrieve endpoint — `null` elsewhere — so read-only views can render without fetching the full source and all its schemas.* @nullable@@ -289,6 +292,7 @@ export type PatchedExternalDataSchemaApiSource = {readonly access_method?: stringreadonly supports_column_selection?: booleanreadonly supports_row_filters?: boolean+ readonly requires_exact_column_metadata?: boolean/** @nullable */readonly user_access_level?: string | null/** @nullable */@@ -391,6 +395,8 @@ export interface PatchedExternalDataSchemaApi {row_filters?: PatchedExternalDataSchemaApiRowFiltersItem[] | null/** Column metadata (name, data type, nullable) for this schema. For SQL sources this is the source-side schema discovered via `refresh_schemas`; for other sources (and once synced) it falls back to the synced table's columns. Empty only before the first successful sync/refresh. */readonly available_columns?: readonly PatchedExternalDataSchemaApiAvailableColumnsItem[]+ /** Whether exact source-side column metadata is available for safe source-query projection. */+ readonly source_column_metadata_available?: boolean/*** Lightweight parent-source summary (id, source_type, access_method, column-selection support, the requesting user's access level). Only populated on the single-schema retrieve endpoint — `null` elsewhere — so read-only views can render without fetching the full source and all its schemas.* @nullablediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f1aa250a09b9..df8c0db35e40 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -34903,6 +34903,7 @@ export namespace Schemas {readonly access_method?: string;readonly supports_column_selection?: boolean;readonly supports_row_filters?: boolean;+ readonly requires_exact_column_metadata?: boolean;/** @nullable */readonly user_access_level?: string | null;/** @nullable */@@ -35087,6 +35088,8 @@ export namespace Schemas {row_filters?: ExternalDataSchemaRowFiltersItem[] | null;/** Column metadata (name, data type, nullable) for this schema. For SQL sources this is the source-side schema discovered via `refresh_schemas`; for other sources (and once synced) it falls back to the synced table's columns. Empty only before the first successful sync/refresh. */readonly available_columns: readonly ExternalDataSchemaAvailableColumnsItem[];+ /** Whether exact source-side column metadata is available for safe source-query projection. */+ readonly source_column_metadata_available: boolean;/*** Lightweight parent-source summary (id, source_type, access_method, column-selection support, the requesting user's access level). Only populated on the single-schema retrieve endpoint — `null` elsewhere — so read-only views can render without fetching the full source and all its schemas.* @nullable@@ -60485,6 +60488,7 @@ export namespace Schemas {readonly access_method?: string;readonly supports_column_selection?: boolean;readonly supports_row_filters?: boolean;+ readonly requires_exact_column_metadata?: boolean;/** @nullable */readonly user_access_level?: string | null;/** @nullable */@@ -60587,6 +60591,8 @@ export namespace Schemas {row_filters?: PatchedExternalDataSchemaRowFiltersItem[] | null;/** Column metadata (name, data type, nullable) for this schema. For SQL sources this is the source-side schema discovered via `refresh_schemas`; for other sources (and once synced) it falls back to the synced table's columns. Empty only before the first successful sync/refresh. */readonly available_columns?: readonly PatchedExternalDataSchemaAvailableColumnsItem[];+ /** Whether exact source-side column metadata is available for safe source-query projection. */+ readonly source_column_metadata_available?: boolean;/*** Lightweight parent-source summary (id, source_type, access_method, column-selection support, the requesting user's access level). Only populated on the single-schema retrieve endpoint — `null` elsewhere — so read-only views can render without fetching the full source and all its schemas.* @nullable