: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 deltalite fallbacks from batch-nullability drift (#80498)
Tom Owers012b82bf6058
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.pyindex 0ab11f75d0f0..f5f9ee0cd511 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py@@ -744,6 +744,28 @@ def align_incoming_decimals_to_delta(pa_table: pa.Table, delta_schema: deltalakereturn pa_table+def raise_on_nullability_drift(pa_table: pa.Table, delta_schema: deltalake.Schema) -> None:+ """Stop the sync when a batch has nulls in a column the table declares non-nullable.++ delta-rs cannot write a null into a non-nullable column, and deltalake 1.6.1 has no operation to+ relax an existing column to nullable in place. So a source that starts emitting nulls in a+ column the table created non-nullable is a schema change under the table, and the only fix is to+ reset and fully re-sync it -- which recreates the column as nullable. Surfaced as+ SchemaColumnTypeChangedException, the same reset-and-re-sync signal the decimal-widening path+ uses, so the sync stops non-retryably instead of failing opaquely (deltalite) or silently+ writing the nulls into a lying non-nullable schema (the delta-rs MERGE fallback).+ """+ delta_arrow_schema = pyarrow_schema_from_arrow_exportable(delta_schema)+ for delta_field in delta_arrow_schema:+ if delta_field.nullable or delta_field.name not in pa_table.schema.names:+ continue+ if pa_table.column(delta_field.name).null_count > 0:+ raise SchemaColumnTypeChangedException(+ f"Source column '{delta_field.name}' now contains nulls, but the table declares it "+ f"non-nullable. Reset and fully re-sync this table to recreate the column as nullable."+ )++def _python_type_to_pyarrow_type(type_: type, value: Any):python_to_pa = {int: pa.int64(),diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.pyindex f8e694f40596..49a29f25b687 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arralign_incoming_decimals_to_delta,first_per_pk_table,normalize_column_name,+ raise_on_nullability_drift,realign_decimal_buffers,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY@@ -338,6 +339,11 @@ class DeltaWriter:# 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())+ # A source that starts emitting nulls in a column the table created non-nullable is a+ # schema change under the table; neither deltalite nor delta-rs can relax it in place, so+ # raise the same reset signal to get the table fully re-synced.+ raise_on_nullability_drift(data, delta_table.schema())+existing_delta_table = delta_tableawait self._logger.adebug(f"write: merging...")diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.pyindex c7f01feeb1c4..80891e4651f7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py@@ -31,6 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrnormalize_table_column_names,observe_and_project_table,observed_schema_metadata_columns,+ raise_on_nullability_drift,source_uses_delta_write_column_selection,table_from_py_list,)@@ -872,6 +873,56 @@ def test_evolve_pyarrow_schema_time_columns_reconcile_to_stored_seconds(assert evolved_table.column("redeem_time").to_pylist() == expected_values+def test_raise_on_nullability_drift_null_in_non_nullable_column_raises():+ """A batch with a null in a column the table declares non-nullable raises the reset signal,+ because neither deltalite nor delta-rs can relax an existing column to nullable in place."""+ pa_table = pa.table(+ {+ "id": pa.array([1, 2], type=pa.int64()),+ "name": pa.array(["a", None], type=pa.string()),+ }+ )+ delta_fields: list[pa.Field] = [+ pa.field("id", pa.int64(), nullable=False),+ pa.field("name", pa.string(), nullable=False),+ ]+ delta_schema = deltalake.Schema.from_arrow(pa.schema(delta_fields))++ with pytest.raises(SchemaColumnTypeChangedException, match="now contains nulls"):+ raise_on_nullability_drift(pa_table, delta_schema)+++ "delta_fields, batch_columns",+ [+ # Null lands in a column the table already marks nullable — the writer accepts it.+ (+ [pa.field("id", pa.int64(), nullable=False), pa.field("name", pa.string(), nullable=True)],+ {"id": pa.array([1, 2], type=pa.int64()), "name": pa.array(["a", None], type=pa.string())},+ ),+ # No nulls arrive in the non-nullable column — nothing drifts.+ (+ [pa.field("id", pa.int64(), nullable=False), pa.field("name", pa.string(), nullable=False)],+ {"id": pa.array([1, 2], type=pa.int64()), "name": pa.array(["a", "b"], type=pa.string())},+ ),+ # The non-nullable column is absent from the batch — no null to check.+ (+ [pa.field("id", pa.int64(), nullable=False), pa.field("name", pa.string(), nullable=False)],+ {"id": pa.array([1, 2], type=pa.int64())},+ ),+ ],+)+def test_raise_on_nullability_drift_permits_valid_batches(+ delta_fields: list[pa.Field], batch_columns: dict[str, pa.Array]+):+ """No drift is raised when the null lands in a nullable column, when the non-nullable column+ carries no nulls, or when it is absent from the batch entirely."""+ pa_table = pa.table(batch_columns)+ delta_schema = deltalake.Schema.from_arrow(pa.schema(delta_fields))++ raise_on_nullability_drift(pa_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/pyproject.toml b/pyproject.tomlindex 615e2662bed2..4cde41ce19bc 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -200,7 +200,7 @@ dependencies = ["braintrust-core>=0.0.59,<1","wrapt==1.17.3","limits==5.8.0",- "deltalite==0.1.5",+ "deltalite==0.1.6",][dependency-groups]diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 290bfa4bc046..6e46da7e740e 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -3767,7 +3767,7 @@ dependencies = [[[package]]name = "deltalite-python"-version = "0.1.5"+version = "0.1.6"dependencies = ["arrow","arrow-array",diff --git a/rust/deltalite/core/src/schema.rs b/rust/deltalite/core/src/schema.rsindex ce5293086e14..4fd82b66f5f7 100644--- a/rust/deltalite/core/src/schema.rs+++ b/rust/deltalite/core/src/schema.rs@@ -10,7 +10,7 @@ use arrow_array::{make_array, new_null_array, Array, RecordBatch};use arrow_buffer::Buffer;use arrow_cast::{cast_with_options, CastOptions};use arrow_data::ArrayData;-use arrow_schema::{DataType, Field, Schema, SchemaRef};+use arrow_schema::{DataType, Schema, SchemaRef};use crate::errors::{Error, Result};@@ -138,30 +138,12 @@ pub fn cast_to_schema(batch: &RecordBatch, target: &SchemaRef) -> Result<RecordB}}- // Validate against a nullable-relaxed copy of the schema. A source can legitimately carry- // nulls in a column the table's schema still marks non-nullable (and null-padding a- // recently-added column always does), and delta-rs's own MERGE accepts such rows -- its- // writer emits physical Parquet as nullable regardless of the logical Delta schema. Building- // against the strict schema would instead reject them with "Column X is declared as- // non-nullable but contains null values", forcing a fallback to the MERGE. Relaxing here- // matches delta-rs; the table's logical schema is untouched.- Ok(RecordBatch::try_new(relax_nullability(target), cols)?)-}--/// A copy of `schema` with every field marked nullable, or `schema` itself when all fields-/// already are. delta-rs writes physical Parquet as nullable irrespective of the logical Delta-/// schema; matching that lets a source carry nulls in a column the table still declares-/// non-nullable without a hard rejection.-fn relax_nullability(schema: &SchemaRef) -> SchemaRef {- if schema.fields().iter().all(|f| f.is_nullable()) {- return schema.clone();- }- let fields: Vec<Field> = schema- .fields()- .iter()- .map(|f| f.as_ref().clone().with_nullable(true))- .collect();- Arc::new(Schema::new_with_metadata(fields, schema.metadata().clone()))+ // The batch must match the table's arrow schema exactly, including nullability: delta-rs's+ // RecordBatchWriter rejects any deviation ("RecordBatch schema does not match"). A column that+ // carries nulls but the table still marks non-nullable must therefore be relaxed to nullable in+ // the table's metadata BEFORE the upsert (the pipeline's schema-evolution step does this), not+ // here -- relaxing only the batch produces a schema mismatch the writer refuses.+ Ok(RecordBatch::try_new(target.clone(), cols)?)}/// Columns present in `source` but absent from the table schema. Schema evolution is@@ -304,33 +286,6 @@ mod tests {assert_eq!(out.column_by_name("added_later").unwrap().null_count(), 2);}- #[test]- fn cast_relaxes_non_nullable_columns_receiving_nulls() {- // A source may carry nulls in a column the table still declares non-nullable, and a- // null-padded added column always does. delta-rs's MERGE accepts such rows; cast_to_schema- // must too (relaxing physical nullability) rather than reject them and force a fallback.- let target: SchemaRef = Arc::new(Schema::new(vec![- Field::new("id", DataType::Utf8, false),- Field::new("added_later", DataType::Int64, false),- ]));- let batch = RecordBatch::try_new(- Arc::new(Schema::new(vec![Field::new("id", DataType::Utf8, true)])),- vec![Arc::new(StringArray::from(vec![Some("a"), None]))],- )- .unwrap();-- let out = cast_to_schema(&batch, &target).unwrap();- assert_eq!(out.num_rows(), 2);- assert!(out.schema().field_with_name("id").unwrap().is_nullable());- assert!(out- .schema()- .field_with_name("added_later")- .unwrap()- .is_nullable());- assert_eq!(out.column_by_name("id").unwrap().null_count(), 1);- assert_eq!(out.column_by_name("added_later").unwrap().null_count(), 2);- }-#[test]fn uncastable_column_is_a_schema_mismatch() {let target: SchemaRef = Arc::new(Schema::new(vec![Field::new("n", DataType::Int64, true)]));diff --git a/rust/deltalite/python/Cargo.toml b/rust/deltalite/python/Cargo.tomlindex d14b5788e010..0d89cc7fccfc 100644--- a/rust/deltalite/python/Cargo.toml+++ b/rust/deltalite/python/Cargo.toml@@ -1,7 +1,7 @@[package]name = "deltalite-python"# Mirrors pyproject.toml in this directory (always identical); bump both together.-version = "0.1.5"+version = "0.1.6"edition = "2021"# CI compiles with this exact toolchain; cargo's MSRV-aware resolver uses it to# avoid picking dependency versions CI cannot build (aws-* crates move MSRV often).diff --git a/rust/deltalite/python/pyproject.toml b/rust/deltalite/python/pyproject.tomlindex c3a711f232ea..b68d8907ced1 100644--- a/rust/deltalite/python/pyproject.toml+++ b/rust/deltalite/python/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "maturin"[project]name = "deltalite"# Mirrors `rust/deltalite/python/Cargo.toml` (always identical); bump both together.-version = "0.1.5"+version = "0.1.6"description = "Streaming partition upsert for Delta tables, replacing delta-rs SQL MERGE"readme = "README.md"requires-python = ">=3.12"diff --git a/uv.lock b/uv.lockindex 02ceb20d3777..c5d90b25cb52 100644--- a/uv.lock+++ b/uv.lock@@ -1731,16 +1731,16 @@ pyarrow = [[[package]]name = "deltalite"-version = "0.1.5"+version = "0.1.6"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/d6/48/9bcfde29c0995ea05e2c19461a3dc0c6be0a50fece497c288682cb1596d3/deltalite-0.1.5.tar.gz", hash = "sha256:f32bfdc3694eaf50c9ebdaaecbc5c2569f7bbb25e654c4993e1be38c0d20551b", size = 175881, upload-time = "2026-08-06T14:12:23.211Z" }+sdist = { url = "https://files.pythonhosted.org/packages/e6/07/51964c17d24dce50a90e617e959dac50bd6ee961ec1d30149a11221435da/deltalite-0.1.6.tar.gz", hash = "sha256:b5f8f728ad12be62875e01e7959e761d0fb350b3279571d32727aa959e78fb4c", size = 175456, upload-time = "2026-08-10T12:43:28.963Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/fd/43/93519f0b3ca35ea2d8ce261d49eebc5b702e5ebefb4f2f8e783ef6a25f2d/deltalite-0.1.5-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:2af20ea42d2a5f658870a18b628f1a6ad1e36c9f68677ff392aa7b59d43f6605", size = 17966299, upload-time = "2026-08-06T14:11:58.436Z" },- { url = "https://files.pythonhosted.org/packages/da/e3/9dab3f1694528a3f745933d8d83e686f4d3bd1fdec544ae490faf3ab81f6/deltalite-0.1.5-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:e2d7579bd39551c28af81969d7d6710f7ee45e2ccd09eef5c067152171b1be93", size = 17853173, upload-time = "2026-08-06T14:12:01.014Z" },- { url = "https://files.pythonhosted.org/packages/a4/e3/fdc5efd9c05bf96e52f2928f1cd83b9f1ad844d84feafc31d66fe68061aa/deltalite-0.1.5-cp312-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:16e98ea37abda4f24743c816d8e31277c77523fbe92e0add0a0429b41cd442e3", size = 63179978, upload-time = "2026-08-06T14:12:05.44Z" },- { url = "https://files.pythonhosted.org/packages/be/5f/495a00f9bd369585fee0f8f4d777239a4f0502da795b540b5589452744e3/deltalite-0.1.5-cp312-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c21e7dde62aef0feb63fb214466c384c918c13b2ae1abadefb3c412df9aab06b", size = 65477944, upload-time = "2026-08-06T14:12:10.61Z" },- { url = "https://files.pythonhosted.org/packages/bc/44/963c25fe15702cda11f48c45c20a584196b51bb9b4d0f94f1532437c9d13/deltalite-0.1.5-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a64e87c31d11127062ecddeed0ca19ae4ace89cea8fae4ab188fa2fa627764ea", size = 62767721, upload-time = "2026-08-06T14:12:15.959Z" },- { url = "https://files.pythonhosted.org/packages/f1/09/580aafe9ed5a82379986d654739455b3c0eb8ac3faf9b232c192d60e82fc/deltalite-0.1.5-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ed7eabd20a48516204e152cd571417257b83d37dd960d75c83d498a4b04e68e7", size = 63838450, upload-time = "2026-08-06T14:12:20.613Z" },+ { url = "https://files.pythonhosted.org/packages/8c/3b/c28f2fcba6ebbbab14a7781108956a288e5e275d6ae342c3641d56ff410b/deltalite-0.1.6-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:6fbdbe6e110c738f567b2bd01e79897479f11989b437735daab7b144c5267503", size = 17964670, upload-time = "2026-08-10T12:43:08.032Z" },+ { url = "https://files.pythonhosted.org/packages/db/a2/917ca2215a7c54ce42f7b3669c7917d1b5470b236c5d680d8ec83f065cc1/deltalite-0.1.6-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:b4ad22983bfbc8335c7880b7d9a2bc8d575f2225b05437f426ec86ceb060891b", size = 17852501, upload-time = "2026-08-10T12:43:11.098Z" },+ { url = "https://files.pythonhosted.org/packages/16/81/27ca3a8da82ae61c556dbf648bb9ff9eeaf400b03d32b8a7429f2dac5fce/deltalite-0.1.6-cp312-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:5308c408502aca987f1a315621fbe5937301263e4a236971525db2d5bc98df89", size = 63172312, upload-time = "2026-08-10T12:43:14.383Z" },+ { url = "https://files.pythonhosted.org/packages/cf/fa/07d484ef2f8db20ad8841b91084edd0e885fe2c4a7f9e7e7f44aa6210a4d/deltalite-0.1.6-cp312-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:dfbccd799364847e262004acb5dc61d6e373ed79ac9e0e0bf5fae8c4aacfce2d", size = 65472792, upload-time = "2026-08-10T12:43:18.12Z" },+ { url = "https://files.pythonhosted.org/packages/4f/3c/a05a0addbf7b9ca333ded94b360782afd6b9bdd163b665bdf13143cb5d12/deltalite-0.1.6-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:701e7093ff60ed2e6764caf1c8846430f71714b469ac0dcc052740c00fca5f80", size = 62768622, upload-time = "2026-08-10T12:43:22.397Z" },+ { url = "https://files.pythonhosted.org/packages/d1/7a/0039dcf77fdfe54962311e5f61491f4155e761f7059f1c331ae0c594e399/deltalite-0.1.6-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b267a1adbc22ed802475dbf9e6ea629275c0dc99a77b6c119bd9909d5965ca54", size = 63835586, upload-time = "2026-08-10T12:43:26.654Z" },][[package]]@@ -5859,7 +5859,7 @@ requires-dist = [{ name = "databricks-sql-connector", specifier = "~=4.3.0" },{ name = "defusedxml", specifier = "~=0.7.1" },{ name = "deltalake", extras = ["pyarrow"], specifier = "==1.6.1" },- { name = "deltalite", specifier = "==0.1.5" },+ { name = "deltalite", specifier = "==0.1.6" },{ name = "disposable-email-domains", specifier = "~=0.0.140" },{ name = "dj-database-url", specifier = "~=3.0.0" },{ name = "django", specifier = "~=5.2.0" },