: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(deltalite): close the three delta-rs MERGE fallback causes (#78791)
Tom Owersa7f226ca350c
diff --git a/pyproject.toml b/pyproject.tomlindex dd4df83e1ca5..3d6f1f31be90 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.3",+ "deltalite==0.1.5",][dependency-groups]diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex bec5bfc8e641..c7522cd83340 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -3789,7 +3789,7 @@ dependencies = [[[package]]name = "deltalite-python"-version = "0.1.3"+version = "0.1.5"dependencies = ["arrow","arrow-array",diff --git a/rust/deltalite/core/src/errors.rs b/rust/deltalite/core/src/errors.rsindex ee4ba9c1143f..613abc415cf9 100644--- a/rust/deltalite/core/src/errors.rs+++ b/rust/deltalite/core/src/errors.rs@@ -23,7 +23,9 @@ pub enum Error {NotFound(String),/// The table declares features deltalite cannot safely rewrite (deletion vectors,- /// column mapping, multiple partition columns).+ /// column mapping, multiple partition columns), or a concurrent transaction changed+ /// the table's schema/protocol mid-upsert so the planned rewrite can no longer be+ /// applied safely. Either way the caller falls back to the delta-rs MERGE.#[error("{0}")]Unsupported(String),@@ -41,11 +43,27 @@ pub enum Error {impl From<deltalake::DeltaTableError> for Error {fn from(e: deltalake::DeltaTableError) -> Self {+ use deltalake::kernel::transaction::{CommitConflictError, TransactionError};use deltalake::DeltaTableError as D;match &e {D::NotATable(_) | D::InvalidTableLocation(_) => Error::NotFound(e.to_string()),D::SchemaMismatch { .. } => Error::SchemaMismatch(e.to_string()),- // The transaction layer surfaces exhausted-retry / logical conflicts here.+ // A concurrent transaction changed the table's schema or protocol. deltalite planned+ // its blind file rewrite against the old metadata; re-running it against a fresh+ // snapshot would null-pad a concurrently-added column and could overwrite matched rows+ // with NULL. Surface as Unsupported (not Conflict) so the upsert's conflict-retry loop+ // skips it and the caller falls back to the delta-rs MERGE, which re-plans against the+ // new schema. This must sit before the catch-all Transaction arm below.+ D::Transaction {+ source:+ TransactionError::CommitConflict(+ CommitConflictError::MetadataChanged+ | CommitConflictError::ProtocolChanged(_),+ ),+ } => Error::Unsupported(e.to_string()),+ // Remaining transaction failures are exhausted-retry / logical data conflicts (a+ // concurrent writer added or removed files this upsert read). These are re-runnable:+ // a fresh snapshot and re-plan can succeed, so the retry loop retries them.D::Transaction { .. } => Error::Conflict(e.to_string()),_ => Error::Generic(e.to_string()),}@@ -85,3 +103,33 @@ impl Error {}}}++#[cfg(test)]+mod tests {+ use super::*;+ use deltalake::kernel::transaction::{CommitConflictError, TransactionError};+ use deltalake::DeltaTableError;++ #[test]+ fn concurrent_metadata_or_protocol_change_is_not_a_retryable_conflict() {+ // A concurrent schema/protocol change must not map to Conflict: the retry loop would+ // re-run the blind rewrite against the changed metadata. Unsupported breaks it out to+ // the MERGE fallback instead.+ for source in [+ TransactionError::CommitConflict(CommitConflictError::MetadataChanged),+ TransactionError::CommitConflict(CommitConflictError::ProtocolChanged("v3".into())),+ ] {+ let mapped: Error = DeltaTableError::Transaction { source }.into();+ assert!(matches!(mapped, Error::Unsupported(_)), "{mapped:?}");+ }+ }++ #[test]+ fn concurrent_data_conflict_is_retryable() {+ // A concurrent append/delete of files this upsert read is re-runnable against a fresh+ // snapshot, so it stays a Conflict the retry loop will retry.+ let source = TransactionError::CommitConflict(CommitConflictError::ConcurrentAppend);+ let mapped: Error = DeltaTableError::Transaction { source }.into();+ assert!(matches!(mapped, Error::Conflict(_)), "{mapped:?}");+ }+}diff --git a/rust/deltalite/core/src/schema.rs b/rust/deltalite/core/src/schema.rsindex 4b0e4e806edc..ce5293086e14 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, Schema, SchemaRef};+use arrow_schema::{DataType, Field, Schema, SchemaRef};use crate::errors::{Error, Result};@@ -138,7 +138,30 @@ pub fn cast_to_schema(batch: &RecordBatch, target: &SchemaRef) -> Result<RecordB}}- Ok(RecordBatch::try_new(target.clone(), cols)?)+ // 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()))}/// Columns present in `source` but absent from the table schema. Schema evolution is@@ -281,6 +304,33 @@ 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/core/src/store.rs b/rust/deltalite/core/src/store.rsindex 0462436b96aa..080d58bbde69 100644--- a/rust/deltalite/core/src/store.rs+++ b/rust/deltalite/core/src/store.rs@@ -24,11 +24,11 @@ use async_trait::async_trait;use bytes::Bytes;use deltalake::kernel::transaction::TransactionError;use deltalake::logstore::{CommitOrBytes, LogStore, LogStoreConfig};-use futures::stream::BoxStream;+use futures::stream::{BoxStream, StreamExt};use object_store::path::Path;use object_store::{- GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, PutMode,- PutMultipartOptions, PutOptions, PutPayload, PutResult,+ GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, ObjectStoreExt,+ PutMode, PutMultipartOptions, PutOptions, PutPayload, PutResult,};use uuid::Uuid;@@ -38,6 +38,9 @@ pub const DEFAULT_MULTIPART_THRESHOLD: usize = 64 * 1024 * 1024;/// count against retry granularity.pub const DEFAULT_MULTIPART_PART_SIZE: usize = 16 * 1024 * 1024;+/// Objects deleted concurrently by the per-object `delete_stream` override.+const DELETE_CONCURRENCY: usize = 16;+/// An [`ObjectStore`] wrapper that turns large plain-overwrite `put`s into multipart/// uploads and delegates everything else.#[derive(Debug)]@@ -162,7 +165,24 @@ impl ObjectStore for MultipartPutStore {&self,locations: BoxStream<'static, object_store::Result<Path>>,) -> BoxStream<'static, object_store::Result<Path>> {- self.inner.delete_stream(locations)+ // object_store 0.13.2's S3 bulk `DeleteObjects` mis-parses a partial-error response+ // ("unknown variant `Code`, expected `Deleted` or `Error`") and times out on very large+ // delete batches (tables with many small files, e.g. GoogleAds) -- either failure aborts+ // the whole upsert and forces a fallback to the delta-rs MERGE. Delete each object+ // individually instead: a plain DELETE per key, run concurrently, sidesteps both the XML+ // parse bug and the batch-size timeout. Delete volume is small next to the rewrite.+ let inner = self.inner.clone();+ locations+ .map(move |loc| {+ let inner = inner.clone();+ async move {+ let path = loc?;+ inner.delete(&path).await?;+ Ok(path)+ }+ })+ .buffer_unordered(DELETE_CONCURRENCY)+ .boxed()}fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, object_store::Result<ObjectMeta>> {diff --git a/rust/deltalite/core/src/upsert.rs b/rust/deltalite/core/src/upsert.rsindex d8a6af4df639..358af2b385de 100644--- a/rust/deltalite/core/src/upsert.rs+++ b/rust/deltalite/core/src/upsert.rs@@ -146,6 +146,7 @@ impl std::str::FromStr for PruneStrategy {}/// Options controlling a single `upsert` call.+#[derive(Clone)]pub struct UpsertOptions {/// Column names forming the primary key, in order.pub primary_keys: Vec<String>,diff --git a/rust/deltalite/python/Cargo.toml b/rust/deltalite/python/Cargo.tomlindex 0e9297287070..d14b5788e010 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.3"+version = "0.1.5"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 b4953343d83e..c3a711f232ea 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.3"+version = "0.1.5"description = "Streaming partition upsert for Delta tables, replacing delta-rs SQL MERGE"readme = "README.md"requires-python = ">=3.12"diff --git a/rust/deltalite/python/src/lib.rs b/rust/deltalite/python/src/lib.rsindex af149b6b0b2c..2316ebc78342 100644--- a/rust/deltalite/python/src/lib.rs+++ b/rust/deltalite/python/src/lib.rs@@ -392,10 +392,43 @@ impl DeltaLiteTable {let stats = py.detach(|| {runtime().block_on(async move {- // Take a fresh snapshot for the upsert so a retried batch never- // plans against stale state.- let table = open_table_multipart(&uri, so, multipart).await?;- deltalite_core::upsert::upsert(&table, batches, schema, opts).await+ // A concurrent writer can make delta-rs reject the commit with a+ // "must rerun" conflict (it read data another transaction deleted).+ // delta-rs's own commit retries re-attempt the SAME, now-stale actions and+ // keep conflicting; the only fix is to re-read the table and re-plan. So on+ // a Conflict we re-open a fresh snapshot and re-run the whole upsert a few+ // times before giving up -- after which the caller falls back to the MERGE.+ // Re-opening each attempt also gives every try a fresh snapshot, so a+ // retried batch never plans against stale state.+ //+ // Only data conflicts are retried. A concurrent schema/protocol change+ // surfaces as Error::Unsupported (see core `errors.rs`), not Conflict, and so+ // breaks straight out to the MERGE fallback -- re-planning a blind rewrite+ // against changed metadata could null-pad a newly-added column.+ const CONFLICT_RETRIES: usize = 5;+ let mut attempt = 0usize;+ loop {+ let table = open_table_multipart(&uri, so.clone(), multipart).await?;+ match deltalite_core::upsert::upsert(+ &table,+ batches.clone(),+ schema.clone(),+ opts.clone(),+ )+ .await+ {+ Err(Error::Conflict(_)) if attempt < CONFLICT_RETRIES => {+ attempt += 1;+ // Short linear backoff so two upserts racing a hot table don't+ // live-lock re-reading each other's in-flight commit.+ tokio::time::sleep(std::time::Duration::from_millis(+ 50 * attempt as u64,+ ))+ .await;+ }+ other => break other,+ }+ }})}).map_err(to_py_err)?;diff --git a/uv.lock b/uv.lockindex 94cd17d18d70..f08be6dfb224 100644--- a/uv.lock+++ b/uv.lock@@ -1731,16 +1731,16 @@ pyarrow = [[[package]]name = "deltalite"-version = "0.1.3"+version = "0.1.5"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/f9/18/0ebcff958c74ea79f1e8dfbb261f5474bb06033da21ced1bde4d3e1cc2e7/deltalite-0.1.3.tar.gz", hash = "sha256:5daafab4ed9d6f54cdcfea1cb7bfd900b906b6ab9402759c5a176b06fd943815", size = 173464, upload-time = "2026-07-31T13:34:15.853Z" }+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" }wheels = [- { url = "https://files.pythonhosted.org/packages/69/b8/42fed73269c9b93aace404b1c33dfa5886cb9d03cd377982d3b70b4808b9/deltalite-0.1.3-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:f43539e33e90d9d2d4f6010a38a69ac1ebc943b7ddb34cb07682734b7d284594", size = 17956004, upload-time = "2026-07-31T13:33:58.697Z" },- { url = "https://files.pythonhosted.org/packages/68/3a/1f9fd47e3df3fc534abb43e97898c03c7e813f566ba484b5e3f3df43fc35/deltalite-0.1.3-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:91a5b5f72e37701ac1d4541681be99a78dd14456fadcbd685026c8d91be1aa41", size = 17837576, upload-time = "2026-07-31T13:34:00.907Z" },- { url = "https://files.pythonhosted.org/packages/31/f8/e10658fdb57819b473c824618928b659ad65f541143e9c7a9653a93e9084/deltalite-0.1.3-cp312-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:4e7cc11b98f4211027f9ab387fc01b6592430b4d699422bac6f5f1a8774e8210", size = 63147119, upload-time = "2026-07-31T13:34:03.7Z" },- { url = "https://files.pythonhosted.org/packages/d6/11/5aea109ae137d97e19f786e6e78114b326e8f334a71c534193815b69b006/deltalite-0.1.3-cp312-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:ed2d864ab2b63ffd83589f4fc24b23b69ccfc0165e593f04121e7da89b2c4e37", size = 65438695, upload-time = "2026-07-31T13:34:07.314Z" },- { url = "https://files.pythonhosted.org/packages/29/6b/2a5ea282e1ded2dfdc97f2dccc9fce88ec419a15f366db229a5e106160df/deltalite-0.1.3-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:206e41394a61182327120351e19df16932481a67a4edb14b3e77cbd6afd8e07e", size = 62731281, upload-time = "2026-07-31T13:34:10.303Z" },- { url = "https://files.pythonhosted.org/packages/2c/08/f0ddae42c7aef923a2b4b43b797b6a7ab781f05e05bfeee3916a3106a969/deltalite-0.1.3-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:5f4a13be6ff584cb18b2162877fcb9f017f5d7a650039c271679c33d89914b95", size = 63797093, upload-time = "2026-07-31T13:34:13.349Z" },+ { 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" },][[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.3" },+ { name = "deltalite", specifier = "==0.1.5" },{ name = "disposable-email-domains", specifier = "~=0.0.140" },{ name = "dj-database-url", specifier = "~=3.0.0" },{ name = "django", specifier = "~=5.2.0" },