: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): stop unmapped ClickHouse types blocking view saves (#91283)
posthog[bot]2156d8e542fc
diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.pyindex 7018d3232e87..1623540c2ca7 100644--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py@@ -33,10 +33,9 @@ from posthog.schema_enums import DataWarehouseSavedQueryOriginfrom posthog.sync import database_sync_to_asyncfrom products.warehouse_sources.backend.facade.hogql import (- CLICKHOUSE_HOGQL_MAPPING,LEGACY_CLICKHOUSE_HOGQL_MAPPING,STR_TO_HOGQL_MAPPING,- clean_type,+ hogql_type_name_for_clickhouse_type,reconstruct_ordered_columns,remove_named_tuples,)@@ -436,7 +435,7 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,columns = {str(item[0]): {- "hogql": CLICKHOUSE_HOGQL_MAPPING[clean_type(str(item[1]))].__name__,+ "hogql": hogql_type_name_for_clickhouse_type(str(item[1])),"clickhouse": item[1],"valid": True,}diff --git a/products/data_warehouse/backend/presentation/views/saved_query.py b/products/data_warehouse/backend/presentation/views/saved_query.pyindex 790cbaed4afb..6c10122d6c34 100644--- a/products/data_warehouse/backend/presentation/views/saved_query.py+++ b/products/data_warehouse/backend/presentation/views/saved_query.py@@ -29,6 +29,7 @@ from posthog.hogql.printer import prepare_and_print_astfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.shared import UserBasicSerializer+from posthog.errors import ExposedCHQueryErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.models import Team, User@@ -65,9 +66,8 @@ from products.data_warehouse.backend.presentation.views.column_annotation_base iupsert_annotation,)from products.warehouse_sources.backend.facade.hogql import (- CLICKHOUSE_HOGQL_MAPPING,- clean_type,get_view_or_table_by_name,+ hogql_type_name_for_clickhouse_type,)from products.warehouse_sources.backend.facade.models import (DataWarehouseTable,@@ -78,6 +78,16 @@ from products.warehouse_sources.backend.facade.models import (logger = structlog.get_logger(__name__)+def _view_types_validation_error(e: Exception) -> serializers.ValidationError:+ # Column inference runs the HogQL-to-ClickHouse path, so a raw exception can carry stack+ # traces, internal table or column names, and S3 URIs. Surface only the errors already marked+ # user-safe; reduce everything else to its class name. Mirrors validate_query below, which+ # keeps the full cause in error tracking and logs instead of the response.+ if isinstance(e, ExposedHogQLError | ExposedCHQueryError):+ return serializers.ValidationError(f"Failed to retrieve types for view: {e}")+ return serializers.ValidationError(f"Failed to retrieve types for view: unexpected {type(e).__name__}")++@dataclass(frozen=True, kw_only=True)class _CancelTarget:workflow_id: str@@ -870,7 +880,7 @@ class DataWarehouseSavedQuerySerializer(else:columns = {str(item[0]): {- "hogql": CLICKHOUSE_HOGQL_MAPPING[clean_type(str(item[1]))].__name__,+ "hogql": hogql_type_name_for_clickhouse_type(str(item[1])),"clickhouse": item[1],"valid": True,}@@ -882,7 +892,7 @@ class DataWarehouseSavedQuerySerializer(except Exception as e:capture_exception(e)logger.exception("Failed to retrieve types for view %s", view.name)- raise serializers.ValidationError("Failed to retrieve types for view")+ raise _view_types_validation_error(e)with transaction.atomic():view.save()@@ -1046,7 +1056,7 @@ class DataWarehouseSavedQuerySerializer(else:columns = {str(item[0]): {- "hogql": CLICKHOUSE_HOGQL_MAPPING[clean_type(str(item[1]))].__name__,+ "hogql": hogql_type_name_for_clickhouse_type(str(item[1])),"clickhouse": item[1],"valid": True,}@@ -1060,7 +1070,7 @@ class DataWarehouseSavedQuerySerializer(except Exception as e:capture_exception(e)logger.exception("Failed to retrieve types for view %s", view.name)- raise serializers.ValidationError("Failed to retrieve types for view")+ raise _view_types_validation_error(e)view.status = DataWarehouseSavedQuery.Status.MODIFIEDview.save()diff --git a/products/warehouse_sources/backend/facade/hogql.py b/products/warehouse_sources/backend/facade/hogql.pyindex 061e1ab72dea..885a4497b88f 100644--- a/products/warehouse_sources/backend/facade/hogql.py+++ b/products/warehouse_sources/backend/facade/hogql.py@@ -33,6 +33,7 @@ from products.warehouse_sources.backend.models.util import (STR_TO_HOGQL_MAPPING,clean_type,get_view_or_table_by_name,+ hogql_type_name_for_clickhouse_type,reconstruct_ordered_columns,remove_named_tuples,)@@ -50,6 +51,7 @@ __all__ = ["ExternalDataSource","clean_type","get_view_or_table_by_name",+ "hogql_type_name_for_clickhouse_type","hogql_fields_and_structure_for_columns","reconstruct_ordered_columns","remove_named_tuples",diff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.pyindex 40aa7f6fce6d..8e6f0fe95850 100644--- a/products/warehouse_sources/backend/models/util.py+++ b/products/warehouse_sources/backend/models/util.py@@ -197,6 +197,8 @@ CLICKHOUSE_HOGQL_MAPPING: dict[str, DatabaseFieldFactory] = {"UInt16": IntegerDatabaseField,"UInt32": IntegerDatabaseField,"UInt64": IntegerDatabaseField,+ "UInt128": IntegerDatabaseField,+ "UInt256": IntegerDatabaseField,"Float8": FloatDatabaseField,"Float16": FloatDatabaseField,"Float32": FloatDatabaseField,@@ -205,6 +207,8 @@ CLICKHOUSE_HOGQL_MAPPING: dict[str, DatabaseFieldFactory] = {"Int16": IntegerDatabaseField,"Int32": IntegerDatabaseField,"Int64": IntegerDatabaseField,+ "Int128": IntegerDatabaseField,+ "Int256": IntegerDatabaseField,"Tuple": StringJSONDatabaseField,"Array": StringArrayDatabaseField,"Map": StringJSONDatabaseField,@@ -212,8 +216,24 @@ CLICKHOUSE_HOGQL_MAPPING: dict[str, DatabaseFieldFactory] = {"Decimal": DecimalDatabaseField,"FixedString": StringDatabaseField,"Enum8": StringDatabaseField,+ "Enum16": StringDatabaseField,+ "IPv4": StringDatabaseField,+ "IPv6": StringDatabaseField,+ "JSON": StringJSONDatabaseField,+ "Variant": UnknownDatabaseField,+ "Dynamic": UnknownDatabaseField,}++def hogql_type_name_for_clickhouse_type(clickhouse_type: str) -> str:+ """Resolve a ClickHouse type name to its HogQL field class name.++ Types absent from ``CLICKHOUSE_HOGQL_MAPPING`` fall back to ``UnknownDatabaseField`` so an+ unfamiliar column type downgrades to a usable column instead of raising ``KeyError``.+ """+ return CLICKHOUSE_HOGQL_MAPPING.get(clean_type(clickhouse_type), UnknownDatabaseField).__name__++# Old-style column metadata stores only the ClickHouse type string and resolves through a# mapping on every query, so retyping UUID in CLICKHOUSE_HOGQL_MAPPING would flip every# legacy column at once on deploy. Pin those to their historical String typing — UUID typingdiff --git a/products/warehouse_sources/backend/tests/test_util.py b/products/warehouse_sources/backend/tests/test_util.pyindex 6b7e41e6b611..0ffe474bc43b 100644--- a/products/warehouse_sources/backend/tests/test_util.py+++ b/products/warehouse_sources/backend/tests/test_util.py@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.models.util import (_BUCKET_SETTINGS_NOT_READABLE_BY_THE_NODE_ROLE,_POSTHOG_OWNED_BUCKET_SETTING_NAMES,get_view_or_table_by_name,+ hogql_type_name_for_clickhouse_type,reconstruct_ordered_columns,validate_warehouse_table_url_pattern,)@@ -47,6 +48,27 @@ class TestReconstructOrderedColumns(SimpleTestCase):assert dict(result) == columns+class TestHogqlTypeNameForClickhouseType(SimpleTestCase):+ @parameterized.expand(+ [+ # A mapped type resolves to its HogQL field class.+ ("string", "String", "StringDatabaseField"),+ ("nullable_wrapper_stripped", "Nullable(Int64)", "IntegerDatabaseField"),+ # Types added to close the gap that blocked saving views.+ ("variant", "Variant(String, Int64)", "UnknownDatabaseField"),+ ("json", "JSON", "StringJSONDatabaseField"),+ ("dynamic", "Dynamic", "UnknownDatabaseField"),+ ("enum16", "Enum16('a' = 1)", "StringDatabaseField"),+ ("wide_int", "Int128", "IntegerDatabaseField"),+ ("ipv6", "IPv6", "StringDatabaseField"),+ # An unmapped type must fall back instead of raising KeyError.+ ("unmapped", "SomeFutureType", "UnknownDatabaseField"),+ ]+ )+ def test_resolves_clickhouse_type(self, _name: str, clickhouse_type: str, expected: str) -> None:+ assert hogql_type_name_for_clickhouse_type(clickhouse_type) == expected++@override_settings(DATAWAREHOUSE_BUCKET_DOMAIN="warehouse-files.posthog.example",DATAWAREHOUSE_BUCKET="ph-warehouse",