: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): show columns for non-SQL sources + enrichment logging (#66650)
Tom Owers5031a1dd697c
diff --git a/products/data_warehouse/backend/presentation/views/external_data_schema.py b/products/data_warehouse/backend/presentation/views/external_data_schema.pyindex c6c88a7f9a21..7cac29adc7c5 100644--- a/products/data_warehouse/backend/presentation/views/external_data_schema.py+++ b/products/data_warehouse/backend/presentation/views/external_data_schema.py@@ -302,8 +302,9 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):)available_columns = serializers.SerializerMethodField(read_only=True,- help_text="Source-side column metadata (name, data type, nullable) discovered for this schema. "- "Empty until the source has been refreshed via `refresh_schemas`.",+ help_text="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.",)# `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.@@ -372,17 +373,25 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):def get_available_columns(self, schema: ExternalDataSchema) -> list[dict[str, Any]]:metadata = schema.schema_metadata or {}columns = metadata.get("columns") if isinstance(metadata, dict) else None- if not isinstance(columns, list):- return []- return [- {- "name": column.get("name"),- "data_type": column.get("data_type"),- "is_nullable": column.get("is_nullable"),- }- for column in columns- if isinstance(column, dict) and isinstance(column.get("name"), str)- ]+ if isinstance(columns, list):+ sql_columns = [+ {+ "name": column.get("name"),+ "data_type": column.get("data_type"),+ "is_nullable": column.get("is_nullable"),+ }+ for column in columns+ if isinstance(column, dict) and isinstance(column.get("name"), str)+ ]+ if sql_columns:+ return sql_columns+ # `schema_metadata` is only written on source creation and explicit schema reload+ # (`refresh_schemas`) — never by background schema discovery or the data sync, and never for+ # non-SQL sources. So it's empty for non-SQL sources and for SQL schemas discovered/added later+ # or not yet reloaded. Fall back to the synced table's universal column store so the Descriptions+ # UI can still list columns (and surface their existing annotations) and let users edit them.+ table = schema.table+ return table.get_user_facing_columns() if table is not None else []@extend_schema_field({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.pyindex 4994f38879a6..fb3b93dbf128 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@@ -3010,6 +3010,42 @@ 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)+ table = DataWarehouseTable.objects.create(+ name="billing_customer",+ format="DeltaS3Wrapper",+ team=self.team,+ url_pattern="https://bucket.s3/data/*",+ columns={+ "id": {"clickhouse": "String"},+ "balance": {"clickhouse": "Nullable(Int64)"},+ "_dlt_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()+ # Sort by name: `columns` is JSONB, which doesn't preserve key insertion order.+ assert sorted(response.json()["available_columns"], key=lambda column: column["name"]) == [+ {"name": "balance", "data_type": "Int64", "is_nullable": True},+ {"name": "id", "data_type": "String", "is_nullable": False},+ ]+@parameterized.expand([# source_type, supports_column_selection_expecteddiff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex 630950b28a94..2f59cb49230e 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -96,6 +96,10 @@ class DataWarehouseTableIntrospectedColumn(TypedDict):type DataWarehouseTableIntrospectedColumns = dict[str, DataWarehouseTableIntrospectedColumn]+# Internal plumbing columns added during sync, hidden from the HogQL catalog (see hogql_definition)+# and never user-facing.+HIDDEN_COLUMNS: frozenset[str] = frozenset({"_dlt_id", "_dlt_load_id", "_ph_debug", PARTITION_KEY})+class DataWarehouseTableQuerySet(models.QuerySet["DataWarehouseTable"]):def queryable(self) -> "DataWarehouseTableQuerySet":@@ -193,6 +197,31 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletprefix = ""return self.name[len(prefix) :]+ def get_user_facing_columns(self) -> list[dict[str, Any]]:+ """Synced columns as `[{name, data_type, is_nullable}]`, skipping internal plumbing columns.++ Reads the universal `columns` store (populated after every sync for every source type), so it+ works for REST sources (Stripe, Hubspot, …) too — unlike the SQL-only+ `ExternalDataSchema.schema_metadata`. Handles both the dict (`{"clickhouse": ...}`) and the+ legacy plain-string column shapes.+ """+ result: list[dict[str, Any]] = []+ for name, definition in (self.columns or {}).items():+ if name in HIDDEN_COLUMNS:+ continue+ if isinstance(definition, dict):+ clickhouse_type = definition.get("clickhouse") or definition.get("hogql") or ""+ else:+ clickhouse_type = definition or ""+ result.append(+ {+ "name": name,+ "data_type": clean_type(clickhouse_type) if clickhouse_type else "unknown",+ "is_nullable": "Nullable(" in clickhouse_type,+ }+ )+ return result+def validate_column_type(self,column_key: str,diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.pyindex aa146c9edfdc..efcea98533ec 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py@@ -25,7 +25,6 @@ from typing import Anyfrom django.utils import timezone-import structlogimport posthoganalyticsfrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy@@ -36,17 +35,19 @@ from posthog.models import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeater+from posthog.temporal.common.logger import get_write_only_loggerfrom products.warehouse_sources.backend.models.column_annotation import WarehouseColumnAnnotationfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.table import DataWarehouseTable-from products.warehouse_sources.backend.models.util import clean_type-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEYfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (get_canonical_descriptions_for_source,)-logger = structlog.get_logger(__name__)+# Write-only (no Kafka `log_entries` production): this is an internal background activity, not a+# user-facing sync, and its workflow type isn't mapped in `resolve_log_source`. The temporal worker's+# global structlog config still merges workflow_id/run_id/attempt/task_queue onto every line.+logger = get_write_only_logger(__name__)ENRICHMENT_FEATURE_FLAG = "data-warehouse-semantic-enrichment"ENRICHMENT_MODEL = "claude-haiku-4-5"@@ -340,27 +341,20 @@ def _get_business_context(team: Team) -> str:return (core_memory.text or "").strip() if core_memory else ""-# Internal plumbing columns the HogQL catalog hides from users (see DataWarehouseTable.hogql_definition).-# Never worth enriching: they carry no user-facing meaning and each one would burn an LLM column slot.-_INTERNAL_COLUMNS = frozenset({"_dlt_id", "_dlt_load_id", "_ph_debug", PARTITION_KEY})-# An annotation is keyed by `column_name`, a varchar(400). A column whose name doesn't fit can't be# stored or surfaced, so skip it rather than letting the insert raise (DataError) and crash the whole# table's enrichment into a Temporal retry loop._MAX_COLUMN_NAME_LENGTH: int = WarehouseColumnAnnotation._meta.get_field("column_name").max_length or 400-def _columns_from_table(table: DataWarehouseTable, log: Any = logger) -> list[dict[str, Any]]:- """Source-agnostic `[{name, data_type, is_nullable}]` from `DataWarehouseTable.columns`.-- `columns` is populated after every sync for every source type (unlike SQL-only `schema_metadata`),- keyed by column name with a ClickHouse type. Handles both the dict shape (`{"clickhouse": ...}`)- and the legacy plain-string shape. Internal plumbing columns, and any whose name exceeds the- annotation key length, are skipped.+def _columns_for_enrichment(table: DataWarehouseTable, log: Any = logger) -> list[dict[str, Any]]:+ """User-facing columns to enrich (see `DataWarehouseTable.get_user_facing_columns`), minus any+ whose name exceeds the annotation key length — those can't be stored as a `WarehouseColumnAnnotation`."""result: list[dict[str, Any]] = []- for name, definition in (table.columns or {}).items():- if name in _INTERNAL_COLUMNS:+ for column in table.get_user_facing_columns():+ name = column.get("name")+ if not name:continueif len(name) > _MAX_COLUMN_NAME_LENGTH:# Surface the drop — otherwise the column silently vanishes from enrichment with no trace,@@ -372,13 +366,7 @@ def _columns_from_table(table: DataWarehouseTable, log: Any = logger) -> list[dimax_column_name_length=_MAX_COLUMN_NAME_LENGTH,)continue- if isinstance(definition, dict):- clickhouse_type = definition.get("clickhouse") or definition.get("hogql") or ""- else:- clickhouse_type = definition or ""- is_nullable = "Nullable(" in clickhouse_type- data_type = clean_type(clickhouse_type) if clickhouse_type else ""- result.append({"name": name, "data_type": data_type or "unknown", "is_nullable": is_nullable})+ result.append(column)return result@@ -399,11 +387,13 @@ def enrich_table_semantics_sync(team_id: int, schema_id: uuid.UUID) -> dict[str,capture_enrichment_event(team, EVENT_COMPLETED, {"status": status, **event_props, **props})if not enrichment_enabled(team):+ log.info("warehouse_enrichment.skipped", reason="flag_disabled")emit_completed("skipped", reason="flag_disabled")return {"status": "skipped", "reason": "flag_disabled"}# Respect the org's AI data-processing opt-out: this path ships table/column metadata and core# memory to the LLM gateway, so the feature flag alone is not enough of a gate.if team.organization.is_ai_data_processing_approved is not True:+ log.info("warehouse_enrichment.skipped", reason="ai_data_processing_not_approved")emit_completed("skipped", reason="ai_data_processing_not_approved")return {"status": "skipped", "reason": "ai_data_processing_not_approved"}@@ -415,10 +405,17 @@ def enrich_table_semantics_sync(team_id: int, schema_id: uuid.UUID) -> dict[str,table = schema.tableevent_props["source_type"] = schema.source.source_typeevent_props["schema_name"] = schema.name+ # Bind the schema/table context onto every subsequent log line so failures are traceable to the+ # exact schema and table that produced them. schema_id is already bound above; repeated here so+ # the full identifying context lives on one line.+ log = log.bind(schema_id=str(schema_id), source_type=schema.source.source_type, schema_name=schema.name)if table is None:+ log.warning("warehouse_enrichment.skipped", reason="no_table")emit_completed("skipped", reason="no_table")return {"status": "skipped", "reason": "no_table"}event_props["table_id"] = str(table.id)+ log = log.bind(table_id=str(table.id))+ log.info("warehouse_enrichment.started")capture_enrichment_event(team, EVENT_STARTED, event_props)existing = {@@ -428,9 +425,10 @@ def enrich_table_semantics_sync(team_id: int, schema_id: uuid.UUID) -> dict[str,# Columns + types come from `table.columns`, populated for every source type after sync — so this# enriches REST sources (Stripe, Hubspot, …) as well as SQL ones. Foreign keys remain SQL-only.- columns = [column for column in _columns_from_table(table, log) if column.get("name")]+ columns = _columns_for_enrichment(table, log)event_props["columns_total"] = len(columns)if not columns:+ log.warning("warehouse_enrichment.skipped", reason="no_columns")emit_completed("skipped", reason="no_columns")return {"status": "skipped", "reason": "no_columns"}columns = columns[:MAX_COLUMNS_PER_TABLE]@@ -457,8 +455,15 @@ def enrich_table_semantics_sync(team_id: int, schema_id: uuid.UUID) -> dict[str,table_needs_description = not bool(schema.description) and "" not in existingevent_props["new_columns"] = len(new_columns)if not new_columns and not table_needs_description:+ log.info("warehouse_enrichment.skipped", reason="already_enriched", columns_total=len(columns))emit_completed("skipped", reason="already_enriched")return {"status": "skipped", "reason": "already_enriched"}+ log.info(+ "warehouse_enrichment.enriching",+ columns_total=len(columns),+ new_columns=len(new_columns),+ table_needs_description=table_needs_description,+ )# 1) Canonical descriptions are authoritative — persist them directly, no LLM.canonical_count = 0@@ -479,6 +484,7 @@ def enrich_table_semantics_sync(team_id: int, schema_id: uuid.UUID) -> dict[str,columns_needing_description = [column["name"] for column in new_columns if column["name"] not in canonical_columns]if not columns_needing_description and not table_needs_description:+ log.info("warehouse_enrichment.done", canonical=canonical_count, ai=0, llm_called=False)emit_completed("done", canonical_annotations=canonical_count, ai_annotations=0, llm_called=False)return {"status": "done", "canonical_annotations": canonical_count, "ai_annotations": 0}@@ -486,6 +492,12 @@ def enrich_table_semantics_sync(team_id: int, schema_id: uuid.UUID) -> dict[str,# model context about neighbouring columns without re-describing them.known_descriptions = {**{name: a.description for name, a in existing.items() if name}, **canonical_columns}business_context = _get_business_context(team)+ log.info(+ "warehouse_enrichment.llm_call_started",+ columns_requested=len(columns_needing_description),+ canonical=canonical_count,+ table_needs_description=table_needs_description,+ )try:generated, usage = _generate_descriptions(team_id=team_id,@@ -501,7 +513,12 @@ def enrich_table_semantics_sync(team_id: int, schema_id: uuid.UUID) -> dict[str,)except Exception as e:capture_exception(e)- log.error("warehouse_enrichment.llm_failed", exc_info=True)+ log.error(+ "warehouse_enrichment.llm_failed",+ error=str(e),+ columns_requested=len(columns_needing_description),+ exc_info=True,+ )capture_enrichment_event(team,EVENT_ERROR,@@ -555,7 +572,13 @@ def enrich_table_semantics_sync(team_id: int, schema_id: uuid.UUID) -> dict[str,team, table, "", table_description.strip(), WarehouseColumnAnnotation.DescriptionSource.AI_GENERATED)- log.info("warehouse_enrichment.done", canonical=canonical_count, ai=ai_count)+ log.info(+ "warehouse_enrichment.done",+ canonical=canonical_count,+ ai=ai_count,+ columns_requested=len(columns_needing_description),+ llm_called=True,+ )emit_completed("done", canonical_annotations=canonical_count, ai_annotations=ai_count, llm_called=True, llm_error=False)@@ -609,9 +632,15 @@ async def enrich_table_semantics_activity(inputs: EnrichTableSemanticsInputs) ->inputs.team_id, inputs.schema_id)except Exception as e:- # Surface unexpected failures (DB errors, etc.) to Sentry and product analytics, then re-raise- # so Temporal applies its retry policy.+ # Surface unexpected failures (DB errors, etc.) to Sentry, structured logs, and product+ # analytics — all keyed by schema_id/team_id — then re-raise so Temporal retries.capture_exception(e)+ logger.exception(+ "warehouse_enrichment.activity_failed",+ team_id=inputs.team_id,+ schema_id=str(inputs.schema_id),+ error=str(e),+ )try:posthoganalytics.capture(distinct_id=f"team-{inputs.team_id}",diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.pyindex 4f4db19a3cdb..96017f95e449 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.py@@ -24,7 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitieMAX_PROMPT_CHARS,EnrichTableSemanticsInputs,EnrichTableSemanticsWorkflow,- _columns_from_table,+ _columns_for_enrichment,_extract_json_object,build_bounded_enrichment_prompt,build_enrichment_prompt,@@ -316,7 +316,7 @@ class TestColumnsFromTable:"_ph_partition_key": {"clickhouse": "String"},})- names = {column["name"] for column in _columns_from_table(table)}+ names = {column["name"] for column in table.get_user_facing_columns()}assert names == {"id", "amount"}def test_skips_columns_whose_name_exceeds_annotation_key_length(self):@@ -324,7 +324,7 @@ class TestColumnsFromTable:# crash the whole table's enrichment with a DataError. It must be dropped, not enriched.long_name = "a" * (_MAX_COLUMN_NAME_LENGTH + 1)table = DataWarehouseTable(columns={"id": {"clickhouse": "String"}, long_name: {"clickhouse": "String"}})- names = {column["name"] for column in _columns_from_table(table)}+ names = {column["name"] for column in _columns_for_enrichment(table)}assert names == {"id"}diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.tsindex fed05c64cbd1..31946f72ac78 100644--- a/products/warehouse_sources/frontend/generated/api.schemas.ts+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts@@ -211,7 +211,7 @@ export interface ExternalDataSchemaApi {* @nullable*/row_filters?: ExternalDataSchemaApiRowFiltersItem[] | null- /** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */+ /** 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[]/*** Lightweight parent-source summary (id, source_type, 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.@@ -351,7 +351,7 @@ export interface PatchedExternalDataSchemaApi {* @nullable*/row_filters?: PatchedExternalDataSchemaApiRowFiltersItem[] | null- /** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */+ /** 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[]/*** Lightweight parent-source summary (id, source_type, 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.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e807e0885afb..eb9c0b0f21e9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -22456,7 +22456,7 @@ export namespace Schemas {* @nullable*/row_filters?: ExternalDataSchemaRowFiltersItem[] | null;- /** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */+ /** 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[];/*** Lightweight parent-source summary (id, source_type, 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.@@ -37570,7 +37570,7 @@ export namespace Schemas {* @nullable*/row_filters?: PatchedExternalDataSchemaRowFiltersItem[] | null;- /** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */+ /** 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[];/*** Lightweight parent-source summary (id, source_type, 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.