: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-imports): treat all incompatible Delta casts as schema changes (#73135)
Tom Owersfaa7896f074d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.pyindex 933e97872bd0..b7688ccb0e45 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_pipeline_utils.py@@ -750,6 +750,37 @@ def test_evolve_pyarrow_schema_whole_valued_floats_cast_into_stored_integer_coluassert evolved_table.column("val").to_pylist() == [10, 20]+ "delta_type, incoming_column",+ [+ # Non-numeric text arriving for a column stored as int (Failed to parse string).+ (pa.int32(), pa.array(["80", "80-150"], type=pa.string())),+ # Non-boolean text arriving for a column stored as bool (Failed to parse value).+ (pa.bool_(), pa.array(["true", "processed"], type=pa.string())),+ # A value that overflows the stored decimal precision (Cannot convert ... overflow).+ (pa.decimal128(3, 1), pa.array([1.0, 999999999.0], type=pa.float64())),+ ],+)+def test_evolve_pyarrow_schema_incompatible_cast_raises_actionable_error(+ delta_type: pa.DataType, incoming_column: pa.Array+):+ """Incoming data that can't be cast into the stored Delta type — non-numeric text into a+ numeric/boolean column, or a value that overflows the stored decimal precision — raises the+ actionable reset-and-re-sync error rather than a raw pyarrow ArrowInvalid that gets retried."""+ arrow_table = pa.table(+ {+ "id": pa.array([1, 2], type=pa.int64()),+ "val": incoming_column,+ }+ )+ delta_schema = deltalake.Schema.from_arrow(+ pa.schema([pa.field("id", pa.int64(), nullable=False), pa.field("val", delta_type, nullable=True)])+ )++ with pytest.raises(SchemaColumnTypeChangedException, match="Source column type changed"):+ evolve_pyarrow_schema(arrow_table, delta_schema)++def test_evolve_pyarrow_schema_with_struct_containing_datetime_and_decimal():"""Test that evolve_pyarrow_schema can handle struct columns with non-JSON-serializable types."""metadata_struct_type = pa.struct(diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.pyindex 235614bbac62..8cba0513ac66 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/utils.py@@ -293,26 +293,24 @@ def evolve_pyarrow_schema(incoming_table: pa.Table, delta_schema: deltalake.Schetry:casted_column = incoming_column.cast(delta_field.type).combine_chunks()except pa.ArrowInvalid as e:- # A narrowing cast overflowed. The usual causes are the source column's type- # being widened upstream (e.g. Postgres `integer` → `bigint`) after the Delta- # column was created with the narrower type, or an integer-created column now- # receiving fractional values — e.g. a price field whose first-synced rows were- # all whole numbers, later failing with "ArrowInvalid: Float value 19.990000- # was truncated converting to int64". delta-rs cannot widen an existing column- # in place, so retrying is futile — surface an actionable error telling the- # user to reset and fully re-sync the table. Whole-valued floats/decimals still- # cast into an integer column losslessly, so this only fires on genuine data loss.- if pa.types.is_integer(delta_field.type) and (- pa.types.is_integer(incoming_column.type)- or pa.types.is_floating(incoming_column.type)- or pa.types.is_decimal(incoming_column.type)- ):- raise SchemaColumnTypeChangedException(- f"Source column type changed: '{delta_field.name}' has values that no longer "- f"fit its stored type {delta_field.type} (incoming data is now "- f"{incoming_column.type}). Reset and fully re-sync this table to adopt the new type."- ) from e- raise+ # Reaching this cast already means the incoming type differs from the stored+ # Delta type (see the guard above) and the timestamp path didn't apply, so a+ # failure here is a deterministic, unretryable incompatibility: the source+ # column's type changed under a table created with a narrower type. Common+ # shapes are an integer column widened upstream (Postgres `integer` → `bigint`),+ # an integer-created column now receiving fractional values ("Float value 19.99+ # was truncated converting to int64"), non-numeric text arriving for a numeric+ # column ("Failed to parse string: '80-150' as a scalar of type int32"), or a+ # value that overflows the stored decimal precision. delta-rs cannot change a+ # column's type in place, so retrying is futile — surface an actionable error+ # telling the user to reset and fully re-sync. Lossless widening (e.g. a+ # whole-valued float into an integer column) still casts fine and never reaches+ # here.+ raise SchemaColumnTypeChangedException(+ f"Source column type changed: '{delta_field.name}' has values that no longer "+ f"fit its stored type {delta_field.type} (incoming data is now "+ f"{incoming_column.type}). Reset and fully re-sync this table to adopt the new type."+ ) from eincoming_table = incoming_table.set_column(incoming_table.schema.get_field_index(delta_field.name),diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.pyindex ee1922dc8c8a..e02022405d5c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py@@ -39,6 +39,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineSourceInputs,SourceResponse,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import (+ SchemaColumnTypeChangedException,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import PipelineInputsfrom products.warehouse_sources.backend.temporal.data_imports.row_tracking import setup_row_trackingfrom products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistry@@ -343,6 +346,13 @@ async def _handle_import_error(job_inputs.team_id, str(job_inputs.source_id), job_inputs.run_id, error_msg, logger, error)+ # Raised in shared pipeline code when incoming data can't be cast into the stored (narrower)+ # Delta column type. delta-rs can't change a column's type in place, so this fails identically+ # on every retry regardless of source — classify it non-retryable by type here rather than+ # relying on each source listing the message in get_non_retryable_errors.+ if isinstance(error, SchemaColumnTypeChangedException):+ await handle_non_retryable_error(job_inputs, error_msg, logger, error)+non_retryable_errors = source_cls.get_non_retryable_errors()if any(match in error_msg for match in non_retryable_errors):await handle_non_retryable_error(diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.pyindex 22cf22784386..851452f64e43 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py@@ -5,6 +5,9 @@ from datetime import datetimeimport pytestfrom unittest import mock+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import (+ SchemaColumnTypeChangedException,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import SimpleSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (RESTClientNonRetryableError,@@ -186,6 +189,39 @@ async def test_rest_client_non_retryable_error_routes_through_handler_without_sologger.aexception.assert_not_awaited()+async def test_schema_column_type_changed_routes_through_handler_without_source_opt_in():+ # SchemaColumnTypeChangedException is raised in shared pipeline code when incoming data can't be+ # cast into the stored Delta column type — a deterministic failure that only a reset and re-sync+ # fixes. It must be non-retryable by type for every source, not just the SQL sources that list+ # "Source column type changed" in get_non_retryable_errors, so non-SQL sources stop retrying it.+ error = SchemaColumnTypeChangedException(+ "Source column type changed: 'val' has values that no longer fit its stored type int32 "+ "(incoming data is now string). Reset and fully re-sync this table to adopt the new type."+ )+ source = mock.MagicMock(spec=SimpleSource)+ source.get_non_retryable_errors.return_value = {}+ source.get_retryable_errors.return_value = set()++ logger = mock.MagicMock()+ logger.awarning = mock.AsyncMock()+ logger.aexception = mock.AsyncMock()+ logger.adebug = mock.AsyncMock()++ with (+ mock.patch.object(module.SourceRegistry, "get_source", return_value=source),+ mock.patch.object(module, "handle_non_retryable_error", new=mock.AsyncMock()) as handle_mock,+ ):+ handle_mock.side_effect = NonRetryableException()+ with pytest.raises(NonRetryableException):+ await module._handle_import_error(mock.MagicMock(), logger, error)++ handle_mock.assert_awaited_once()+ assert handle_mock.await_args is not None+ assert handle_mock.await_args.args[3] is error+ logger.aexception.assert_not_awaited()++def _incremental_schema(*, is_incremental: bool, lookback_seconds: int | None) -> mock.MagicMock:schema = mock.MagicMock()schema.should_use_incremental_field = True