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.

fix(batch-exports): Handle invalid schema when merging into Databricks table (#72518)

Ross9b51ee7b14f1
diff --git a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py
index 8cc1fb9ee97b..a349af7b3713 100644
--- a/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/databricks_batch_export.py
@@ -75,8 +75,8 @@ 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).
+ # Raised when the destination table's column names or types are incompatible with the exported
+ # data (e.g. the table column is VARIANT but the export is configured to write STRING).
"DatabricksIncompatibleSchemaError",
]
@@ -155,26 +155,28 @@ class DatabricksWarehouseStoppedError(DatabricksOperationError):
class DatabricksIncompatibleSchemaError(DatabricksOperationError):
- """Raised when the destination table's column types are incompatible with the exported data.
+ """Raised when the destination table's columns 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).
+ This happens, for example, 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):
+ def __init__(
+ self, operation: str, reason: str, export_schema: collections.abc.Iterable[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}."
+ 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. "
+ "This means the destination table's column names/types don't match the data being exported. "
"Please check the schema of your destination table.",
)
@@ -798,6 +800,19 @@ class DatabricksClient:
try:
async with handle_common_errors("Merge into target table", timeout):
await self.execute_async_query(merge_query, fetch_results=False, timeout=timeout)
+ except ServerOperationError as err:
+ if err.message and "[DELTA_MERGE_UNRESOLVED_EXPRESSION]" in err.message:
+ # don't return the full error message as it reveals information about the
+ # destination table schema
+ raise DatabricksIncompatibleSchemaError(
+ operation=f"MERGE INTO `{target_table}`",
+ reason="[DELTA_MERGE_UNRESOLVED_EXPRESSION]",
+ export_schema=source_table_fields,
+ ) from err
+ self.logger.exception(
+ "Merge failed", with_schema_evolution=with_schema_evolution, query="MERGE", query_details=merge_query
+ )
+ raise
except Exception:
self.logger.exception(
"Merge failed", with_schema_evolution=with_schema_evolution, query="MERGE", query_details=merge_query
diff --git a/products/batch_exports/backend/tests/temporal/destinations/databricks/test_workflow.py b/products/batch_exports/backend/tests/temporal/destinations/databricks/test_workflow.py
index a9514eff39f4..a3308d0c300f 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/databricks/test_workflow.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/databricks/test_workflow.py
@@ -457,6 +457,56 @@ class TestDatabricksBatchExportWorkflow(CommonWorkflowTests):
else:
assert "created_at" not in records_from_destination[0]
+ async def test_workflow_raises_incompatible_schema_error_when_target_table_schema_is_wrong(
+ self,
+ destination_test: DatabricksDestinationTest,
+ interval: str,
+ generate_test_data,
+ data_interval_start: dt.datetime,
+ data_interval_end: dt.datetime,
+ ateam,
+ batch_export_for_destination,
+ integration: Integration,
+ setup_destination,
+ ):
+ # Pre-create the target table with a schema that doesn't match the persons model. None of
+ # these columns match the merge keys (`team_id`, `distinct_id`), so the MERGE condition
+ # references columns that can't be resolved on the target.
+ destination_config = batch_export_for_destination.destination.config
+ catalog = destination_config["catalog"]
+ schema = destination_config["schema"]
+ table_name = destination_config["table_name"]
+ query = f"""
+ CREATE TABLE IF NOT EXISTS `{catalog}`.`{schema}`.`{table_name}` (
+ `wrong_id` BIGINT,
+ `wrong_data` STRING
+ )
+ USING DELTA
+ COMMENT 'User created table with the wrong schema'
+ """
+ with destination_test.cursor(ateam.pk, integration) as cursor:
+ cursor.execute(query)
+
+ batch_export_model = BatchExportModel(name="persons", schema=None)
+
+ inputs = destination_test.create_batch_export_inputs(
+ team_id=ateam.pk,
+ data_interval_end=data_interval_end,
+ interval=interval,
+ batch_export_model=batch_export_model,
+ batch_export_schema=None,
+ batch_export=batch_export_for_destination,
+ )
+
+ run = await destination_test.run_workflow(
+ batch_export_id=batch_export_for_destination.id,
+ inputs=inputs,
+ )
+
+ assert run.status == "Failed"
+ assert run.latest_error is not None
+ assert "DatabricksIncompatibleSchemaError" in run.latest_error
+
async def test_workflow_cleans_up_volume_and_stage_table_if_there_is_an_error(
self,
destination_test: DatabricksDestinationTest,