: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): stop decimal merge overflows in warehouse imports (#73150)
Tom Owersf28d4dda929e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex 8ccdbf620144..1cd43f22e255 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py@@ -126,6 +126,15 @@ Any_Source_Errors: dict[str, str | None] = {"The incremental field configured for this table doesn't exist in the data the source returns. ""Edit the table's sync method, pick a valid incremental field, then re-enable the sync."),+ # Raised by the pipeline when a column's incoming values no longer fit the stored Delta column+ # type — the source column was widened (e.g. Postgres `integer` → `bigint`) or now carries larger+ # decimals than the stored type can hold. delta-rs can't widen a column in place, so every retry+ # replays the same failure. Already non-retryable for SQL sources; declare it here so REST and+ # managed sources stop retrying too.+ "Source column type changed": (+ "A column's type changed in your source and no longer fits the type we stored. We can't widen "+ "an existing column in place — please reset and fully re-sync this table to adopt the new type."+ ),}diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.pyindex 3ebc2429798e..51856b5a9427 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py@@ -23,6 +23,7 @@ from products.warehouse_sources.backend.models.external_data_job import Externalfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConventionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEYfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import (+ align_incoming_decimals_to_delta,conditional_lru_cache_async,normalize_column_name,pyarrow_schema_from_arrow_exportable,@@ -430,6 +431,11 @@ class DeltaTableHelper:if not primary_keys or len(primary_keys) == 0:raise Exception("Primary key required for incremental syncs")+ # The merge casts every source column to its stored column type; a scale-heavy decimal+ # column (e.g. decimal128(38, 32)) overflows that cast on larger values. Align to the+ # stored types up front so the merge cast is a no-op, or raise a clean reset signal.+ data = align_incoming_decimals_to_delta(data, delta_table.schema())+existing_delta_table = delta_tableawait self._logger.adebug(f"write_to_deltalake: merging...")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 532397ed213b..933e97872bd0 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@@ -19,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineSchemaColumnTypeChangedException,_get_max_decimal_type,_to_list_array,+ align_incoming_decimals_to_delta,append_partition_key_to_table,apply_enabled_columns_projection,evolve_pyarrow_schema,@@ -386,6 +387,10 @@ def test_table_from_py_list_with_schema_and_too_small_decimal_type():([decimal.Decimal("1.0100000")], pa.decimal128(8, 7)),# That is 1 followed by 37 zeroes to go over the pa.Decimal128 precision limit of 38.([decimal.Decimal("10000000000000000000000000000000000000.1")], pa.decimal256(39, 1)),+ # The big integer and the high-scale fraction live in different rows: precision must reserve+ # room for both (7 integer digits + 4 scale), not take max-precision and max-scale+ # independently (which would infer decimal128(7, 4), too narrow for 1000000).+ ([decimal.Decimal("1000000"), decimal.Decimal("0.0001")], pa.decimal128(11, 4)),],)def test_get_max_decimal_type_returns_correct_decimal_type(@@ -1314,3 +1319,51 @@ def test_append_partition_key_datetime_string_column(value, expected):partitioned_table, mode, _, _ = resultassert mode == "datetime"assert partitioned_table.column(PARTITION_KEY).to_pylist() == [expected]+++ "batch_type, batch_values, delta_type",+ [+ # A value that fits the stored column's integer capacity is rounded to its scale so the+ # subsequent merge cast is a no-op instead of overflowing.+ (pa.decimal128(10, 2), [decimal.Decimal("123.45")], pa.decimal128(38, 32)),+ (pa.decimal128(38, 18), [decimal.Decimal("0.0000000416000606")], pa.decimal128(38, 32)),+ (pa.decimal128(38, 30), [decimal.Decimal("999999.99"), None], pa.decimal128(38, 32)),+ # A decimal widened past decimal128 arrives as text (decimal256 → string); it must be+ # parsed back and fitted rather than failing the merge with "Cannot cast string '0E-19'".+ (pa.string(), ["0E-19", None], pa.decimal128(38, 10)),+ ],+)+def test_align_incoming_decimals_to_delta_fits(batch_type, batch_values, delta_type):+ arrow_table = pa.table(+ {+ "id": pa.array([1] * len(batch_values), type=pa.int64()),+ "amount": pa.array(batch_values, type=batch_type),+ }+ )+ delta_fields: list[pa.Field] = [pa.field("id", pa.int64()), pa.field("amount", delta_type)]+ delta_schema = deltalake.Schema.from_arrow(pa.schema(delta_fields))++ aligned = align_incoming_decimals_to_delta(arrow_table, delta_schema)++ assert aligned.schema.field("amount").type == delta_type+ for original, got in zip(batch_values, aligned.column("amount").to_pylist()):+ expected = None if original is None else decimal.Decimal(str(original))+ assert got == expected+++def test_align_incoming_decimals_to_delta_raises_when_integer_overflows():+ # 1234567.5 has 7 integer digits; a decimal128(38, 32) column holds only 6, so it can't be+ # stored no matter the rounding. delta-rs can't widen the column in place, so this must surface+ # as the non-retryable reset signal rather than an opaque merge overflow.+ arrow_table = pa.table(+ {+ "id": pa.array([1], type=pa.int64()),+ "amount": pa.array([decimal.Decimal("1234567.5")], type=pa.decimal128(10, 2)),+ }+ )+ delta_fields: list[pa.Field] = [pa.field("id", pa.int64()), pa.field("amount", pa.decimal128(38, 32))]+ delta_schema = deltalake.Schema.from_arrow(pa.schema(delta_fields))++ with pytest.raises(SchemaColumnTypeChangedException):+ align_incoming_decimals_to_delta(arrow_table, delta_schema)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 d62341be98fd..235614bbac62 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@@ -766,7 +766,7 @@ def _get_max_decimal_type(values: list[decimal.Decimal]) -> pa.Decimal128Type |A `pa.Decimal128Type` or `pa.Decimal256Type` with enough precision andscale to hold all `values`."""- max_precision = 1+ max_int_digits = 0max_scale = 0for value in values:@@ -774,23 +774,25 @@ def _get_max_decimal_type(values: list[decimal.Decimal]) -> pa.Decimal128Type |if not isinstance(exponent, int):continue- # This implementation accounts for leading zeroes being excluded from digits- # It is based on Arrow, see:+ # `len(digits) + exponent` is the number of digits left of the decimal point (<= 0 for a+ # pure fraction such as 0.0012). See Arrow's decimal inference:# https://github.com/apache/arrow/blob/main/python/pyarrow/src/arrow/python/decimal.cc#L75- if exponent < 0:- precision = max(len(digits), -exponent)- scale = -exponent- else:- precision = len(digits) + exponent- scale = 0+ scale = -exponent if exponent < 0 else 0+ int_digits = max(len(digits) + exponent, 0)- max_precision = max(precision, max_precision)+ max_int_digits = max(int_digits, max_int_digits)max_scale = max(scale, max_scale)# Deltalake doesn't like writing decimals with scale of 0 - it auto appends `.0`if max_scale == 0:max_scale = 1- max_precision += 1++ # Precision must cover BOTH the integer and fractional parts. Taking the max precision and the+ # max scale independently under-provisions integer digits when the widest value and the+ # highest-scale value are different rows — e.g. [1000000, 0.0001] would infer a type with no+ # room for the 7-digit integer, overflowing the Delta write. Sizing precision as+ # integer-digits + scale keeps every value representable.+ max_precision = max(max_int_digits + max_scale, 1)return build_pyarrow_decimal_type(max_precision, max_scale)@@ -826,6 +828,92 @@ def _decimal_array_from_values(values: list[decimal.Decimal | None]) -> pa.Arrayraise ValueError("Cannot build decimal array from values") from exc+def _decimal_values_from_column(column: pa.ChunkedArray) -> list[decimal.Decimal | None] | None:+ """Best-effort conversion of a column's values to Decimals, for a column expected to be decimal.++ Handles decimal columns directly and string columns — the pipeline (and dlt) stores a decimal+ that grew past decimal128 as text (decimal256 → string), so a batch column can arrive as+ strings even though its stored Delta column is decimal. Returns None when a non-null value+ can't be parsed as a decimal (a genuine decimal→text change, not a widened decimal), leaving+ that mismatch for the caller to ignore.+ """+ result: list[decimal.Decimal | None] = []+ for value in _to_list_array(column):+ if value is None:+ result.append(None)+ elif isinstance(value, decimal.Decimal):+ result.append(value)+ else:+ try:+ result.append(decimal.Decimal(str(value)))+ except (decimal.InvalidOperation, ValueError, TypeError):+ return None+ return result+++def _fit_decimal_values_to_type(+ values: list[decimal.Decimal | None], target: pa.Decimal128Type | pa.Decimal256Type+) -> pa.Array | None:+ """Round `values` to `target`'s scale and build an array of exactly `target`.++ Rounding only drops fractional precision beyond the target scale, never integer digits.+ Returns None when a value's integer part exceeds the target's capacity (unrepresentable no+ matter the rounding) so the caller can treat it as an unrecoverable column-type mismatch.+ """+ try:+ quantized = [None if v is None else _quantize_to_scale(v, target.scale) for v in values]+ except decimal.InvalidOperation:+ return None+ try:+ return pa.array(quantized, type=target)+ except pa.ArrowInvalid:+ return None+++def align_incoming_decimals_to_delta(pa_table: pa.Table, delta_schema: deltalake.Schema) -> pa.Table:+ """Reconcile a batch's decimal columns to the existing Delta table's decimal column types.++ A Delta merge casts every source column to its stored target column type, and delta-rs cannot+ widen a decimal column in place. When earlier schema inference stored a scale-heavy column+ (e.g. decimal128(38, 32), only 6 integer digits), a later, larger value overflows that implicit+ cast with an opaque ``DeltaError`` that retries forever. Pre-casting each batch column to the+ exact stored type makes the merge cast a no-op: fitting values are rounded to the column's+ scale, and a value whose integer part can't fit is surfaced as SchemaColumnTypeChangedException+ so the sync stops and the table can be reset and re-synced (which recreates the column with+ adequate integer headroom).+ """+ delta_arrow_schema = pyarrow_schema_from_arrow_exportable(delta_schema)+ for delta_field in delta_arrow_schema:+ if not pa.types.is_decimal(delta_field.type) or delta_field.name not in pa_table.schema.names:+ continue++ column = pa_table.column(delta_field.name)+ if column.type == delta_field.type:+ continue+ if not (+ pa.types.is_decimal(column.type) or pa.types.is_string(column.type) or pa.types.is_large_string(column.type)+ ):+ # A decimal column paired with a non-decimal, non-text batch column is a different+ # mismatch handled by evolve_pyarrow_schema; leave it alone.+ continue++ values = _decimal_values_from_column(column)+ if values is None:+ continue++ target = cast(pa.Decimal128Type | pa.Decimal256Type, delta_field.type)+ aligned = _fit_decimal_values_to_type(values, target)+ if aligned is None:+ raise SchemaColumnTypeChangedException(+ f"Source column type changed: '{delta_field.name}' has decimal values that no longer "+ f"fit its stored type {delta_field.type}. Reset and fully re-sync this table to adopt "+ f"a wider type."+ )+ pa_table = pa_table.set_column(pa_table.schema.get_field_index(delta_field.name), delta_field.name, aligned)++ return pa_table++def _python_type_to_pyarrow_type(type_: type, value: Any):python_to_pa = {int: pa.int64(),