: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(batch-exports): raise non-retryable Databricks incompatible schema errors (#64844)
Ross4bafffced3c9
diff --git a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.pyindex bb5a4990884f..318fd7ab8ba2 100644--- a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py@@ -74,6 +74,9 @@ NON_RETRYABLE_ERROR_TYPES: list[str] = ["DatabricksSchemaNotFoundError",# Raised when the Databricks warehouse is stopped."DatabricksWarehouseStoppedError",+ # Raised when the destination table's column types are incompatible with the exported data+ # (e.g. the table column is VARIANT but the export is configured to write STRING).+ "DatabricksIncompatibleSchemaError",]DatabricksField = tuple[str, str]@@ -150,6 +153,31 @@ class DatabricksWarehouseStoppedError(DatabricksOperationError):pass+class DatabricksIncompatibleSchemaError(DatabricksOperationError):+ """Raised when the destination table's column types are incompatible with the exported data.++ This happens when an existing table column has a type that can't accept the data we're+ exporting into it. One common cause is the export's `use_variant_type` setting not matching+ the existing table (e.g. a column is VARIANT in the table but the export is configured to+ write STRING, or vice versa).+ """++ def __init__(self, operation: str, reason: str, export_schema: list[DatabricksField] | None = None):+ detail = reason+ if export_schema is not None:+ # We only report the schema of the data we're exporting (which the user already controls)+ # and deliberately not the destination table's schema: this error is surfaced to users via+ # the batch export run APIs, and the table could be any table the integration can reach.+ export_schema_str = ", ".join(f"`{name}` {type_name}" for name, type_name in export_schema)+ detail += f" Exported data schema: {export_schema_str}."+ super().__init__(+ operation,+ detail,+ "This means the destination table's column types don't match the data being exported. "+ "Please check the schema of your destination table.",+ )++@dataclasses.dataclass(kw_only=True)class DatabricksInsertInputs(BatchExportInsertInputs):"""Inputs for Databricks.@@ -567,8 +595,21 @@ class DatabricksClient:query = self._get_copy_into_table_from_volume_query(table_name=table_name, volume_path=volume_path, fields=fields, with_schema_evolution=with_schema_evolution)- async with handle_common_errors(f"COPY INTO {table_name} FROM VOLUME", timeout):- await self.execute_async_query(query, fetch_results=False, timeout=timeout)+ operation = f"COPY INTO {table_name} FROM VOLUME"+ async with handle_common_errors(operation, timeout):+ try:+ await self.execute_async_query(query, fetch_results=False, timeout=timeout)+ except ServerOperationError as err:+ # Delta raises DELTA_FAILED_TO_MERGE_FIELDS when the destination table's column+ # types are incompatible with the data we're loading (e.g. a VARIANT vs STRING+ # mismatch). Re-raise as a clear, non-retryable error reporting the schema we're+ # exporting so the user can compare it against their table.+ message = err.message or ""+ if "failed to merge fields" in message.lower() or "delta_failed_to_merge_fields" in message.lower():+ raise DatabricksIncompatibleSchemaError(+ operation=operation, reason=message, export_schema=fields+ ) from err+ raisedef _get_copy_into_table_from_volume_query(self, table_name: str, volume_path: str, fields: list[DatabricksField], with_schema_evolution: bool = Truediff --git a/products/batch_exports/backend/tests/temporal/destinations/databricks/test_client.py b/products/batch_exports/backend/tests/temporal/destinations/databricks/test_client.pyindex e56ec00e5073..24b28149ce8c 100644--- a/products/batch_exports/backend/tests/temporal/destinations/databricks/test_client.py+++ b/products/batch_exports/backend/tests/temporal/destinations/databricks/test_client.py@@ -11,6 +11,7 @@ from databricks.sql.exc import RequestError, ServerOperationErrorfrom products.batch_exports.backend.temporal.destinations.databricks_batch_export import (DatabricksClient,DatabricksConnectionError,+ DatabricksIncompatibleSchemaError,DatabricksOperationTimeoutError,)@@ -285,6 +286,39 @@ class TestQueryBuilders:)+class TestCopyIntoSchemaMismatch:+ MERGE_ERROR = "[DELTA_FAILED_TO_MERGE_FIELDS] Failed to merge fields 'properties' and 'properties'."++ async def test_remaps_merge_error_to_schema_mismatch(self, client: DatabricksClient):+ """The merge-fields error is remapped to a clear error reporting only the exported schema."""+ fields = [("properties", "STRING"), ("event", "STRING")]+ with patch.object(+ client, "execute_async_query", new=AsyncMock(side_effect=ServerOperationError(self.MERGE_ERROR))+ ):+ with pytest.raises(DatabricksIncompatibleSchemaError) as exc_info:+ await client.acopy_into_table_from_volume(+ table_name="test_table", volume_path="/Volumes/x", fields=fields+ )++ message = str(exc_info.value)+ assert "Failed to merge fields" in message+ assert "Exported data schema: `properties` STRING, `event` STRING" in message+ # we must not disclose the destination table's schema (it could be any table the integration reaches)+ assert "Destination table schema" not in message++ async def test_non_merge_error_passes_through(self, client: DatabricksClient):+ """A non-merge ServerOperationError should still be handled by handle_common_errors."""+ with patch.object(+ client,+ "execute_async_query",+ new=AsyncMock(side_effect=ServerOperationError("Statement has timed out after 5 seconds")),+ ):+ with pytest.raises(DatabricksOperationTimeoutError):+ await client.acopy_into_table_from_volume(+ table_name="test_table", volume_path="/Volumes/x", fields=[("properties", "STRING")]+ )++@skip_without_real_databricksclass TestRealDatabricksConnection:"""Tests that exercise behavior against a real Databricks SQL warehouse.