This is an automated email from the ASF dual-hosted git repository.

JingsongLi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/paimon-rust.git


The following commit(s) were added to refs/heads/main by this push:
     new 729a5558 [core] Validate row-ID updates across schema changes (#1374)
729a5558 is described below

commit 729a5558944bdd3a483f7031d25cf43a5a96b5e8
Author: Jingsong Lee <[email protected]>
AuthorDate: Wed Nov 11 13:33:41 2026 +0800

    [core] Validate row-ID updates across schema changes (#1374)
---
 crates/paimon/src/table/schema_manager.rs          |   4 +
 crates/paimon/src/table/table_commit.rs            |  70 ++--
 .../table/table_commit/row_id_conflict_tests.rs    |   8 +-
 .../paimon/src/table/table_commit/row_id_fields.rs | 140 +++++++
 .../src/table/table_commit/row_id_schema_tests.rs  | 430 +++++++++++++++++++++
 .../paimon/tests/historical_table_update_test.rs   |  46 ++-
 crates/paimon/tests/rest_catalog/row_id_schema.rs  | 245 ++++++++++++
 crates/paimon/tests/rest_catalog_test.rs           |   3 +
 docs/src/python-binding.md                         |   7 +
 9 files changed, 921 insertions(+), 32 deletions(-)

diff --git a/crates/paimon/src/table/schema_manager.rs 
b/crates/paimon/src/table/schema_manager.rs
index 96fdb13f..97bd1a59 100644
--- a/crates/paimon/src/table/schema_manager.rs
+++ b/crates/paimon/src/table/schema_manager.rs
@@ -67,6 +67,10 @@ impl SchemaManager {
             .or_insert_with(|| Arc::new(schema));
     }
 
+    pub(super) fn cached_schema(&self, schema_id: i64) -> 
Option<Arc<TableSchema>> {
+        self.cache.lock().unwrap().get(&schema_id).cloned()
+    }
+
     /// Carry immutable, already loaded metadata to a same-table read view.
     /// Copy the source under its lock before locking the destination so clones
     /// sharing one cache cannot deadlock each other.
diff --git a/crates/paimon/src/table/table_commit.rs 
b/crates/paimon/src/table/table_commit.rs
index 92965c03..1e5cf5c2 100644
--- a/crates/paimon/src/table/table_commit.rs
+++ b/crates/paimon/src/table/table_commit.rs
@@ -55,6 +55,7 @@ mod auto_index_tests;
 mod auto_maintenance;
 mod global_index_source_check;
 mod index_commit;
+mod row_id_fields;
 
 use index_commit::IndexChanges;
 mod row_tracking;
@@ -302,9 +303,9 @@ impl TableCommit {
     /// Check logical row-ID/column conflicts before rebasing staged updates.
     ///
     /// Both snapshot IDs are resolved through this table's snapshot manager.
-    /// The captured interval must not cross a schema change, and this
-    /// committer's resolved schema must still be current. A newer schema may
-    /// exist before the next data snapshot is published.
+    /// Files retain their historical field identities across compatible schema
+    /// changes. Written fields must still exist in the current schema, even
+    /// when DDL has not published a new data snapshot.
     /// Like Java's `checkRowIdFromSnapshot(..., false)`, COMPACT snapshots are
     /// excluded: the caller may rewrite physical layouts only after this check
     /// has rejected concurrent logical writes. This method publishes nothing
@@ -340,21 +341,19 @@ impl TableCommit {
             .snapshot_manager
             .get_snapshot(latest_snapshot_id)
             .await?;
-        let baseline = if check_from_snapshot == latest_snapshot_id {
-            latest.clone()
-        } else {
+        if check_from_snapshot != latest_snapshot_id {
             self.snapshot_manager
                 .get_snapshot(check_from_snapshot)
-                .await?
-        };
-        if baseline.schema_id() != latest.schema_id()
-            || self.latest_schema_id().await? != self.table.schema().id()
-        {
-            return Err(crate::Error::DataInvalid {
-                message: "Row-ID conflict checks require an unchanged, current 
table schema".into(),
-                source: None,
-            });
+                .await?;
         }
+        let schema = self.latest_row_id_schema().await?;
+        let files = messages
+            .iter()
+            .flat_map(|message| &message.new_files)
+            .filter(|file| file.first_row_id.is_some())
+            .cloned()
+            .collect::<Vec<_>>();
+        self.validate_row_id_update_fields(&schema, &files).await?;
         self.check_row_id_from_snapshot(
             Some(&latest),
             &self.messages_to_entries(messages),
@@ -1493,6 +1492,23 @@ impl TableCommit {
     ) -> Result<(Snapshot, Vec<PartitionStatistics>)> {
         let new_snapshot_id = latest_snapshot.as_ref().map(|s| s.id() + 
1).unwrap_or(1);
 
+        // Capture existing-row updates before assigning IDs to new appends.
+        // A mixed update/delete can be an OVERWRITE through deletion vectors.
+        let update_files = if self.data_evolution_enabled
+            && matches!(resolved.kind, CommitKind::APPEND | 
CommitKind::OVERWRITE)
+        {
+            resolved
+                .entries
+                .iter()
+                .filter(|entry| {
+                    *entry.kind() == FileKind::Add && 
entry.file().first_row_id.is_some()
+                })
+                .map(|entry| entry.file().clone())
+                .collect::<Vec<_>>()
+        } else {
+            vec![]
+        };
+
         if self.deletion_vectors_enabled && resolved.kind == 
CommitKind::COMPACT {
             if let Some(snapshot) = latest_snapshot {
                 if let Some(mut indexes) = 
super::compact::deletion_vectors::rewrite_indexes(
@@ -1654,7 +1670,16 @@ impl TableCommit {
                 .write_index_manifest(file_io, &manifest_dir, entries, 
created_files)
                 .await?;
         }
-        let schema_id = self.latest_schema_id().await?;
+        let schema_id = if update_files.is_empty() {
+            self.latest_schema_id().await?
+        } else {
+            // Every CAS retry resolves the schema again. Validate against the
+            // same schema recorded by this attempt, including catalog-only 
DDL.
+            let schema = self.latest_row_id_schema().await?;
+            self.validate_row_id_update_fields(&schema, &update_files)
+                .await?;
+            schema.id()
+        };
         let statistics_file = self
             .inherited_statistics(latest_snapshot.as_ref(), schema_id)
             .await?;
@@ -3374,15 +3399,11 @@ impl TableCommit {
     }
 
     async fn write_field_ids(&self, file: &DataFileMeta) -> 
Result<HashSet<i32>> {
-        let fields = if file.schema_id == self.table.schema().id() {
-            self.table.schema().fields().to_vec()
+        let schema = self.row_id_file_schema(file).await?;
+        let fields = if file.write_cols.is_none() {
+            schema.data_file_fields(None)
         } else {
-            self.table
-                .schema_manager()
-                .schema(file.schema_id)
-                .await?
-                .fields()
-                .to_vec()
+            schema.fields().to_vec()
         };
         let data_fields = fields
             .into_iter()
@@ -4095,6 +4116,7 @@ mod tests {
         include!("table_commit/callback_tests.rs");
         include!("table_commit/index_delete_tests.rs");
         include!("table_commit/row_id_conflict_tests.rs");
+        include!("table_commit/row_id_schema_tests.rs");
     }
 
     #[tokio::test]
diff --git a/crates/paimon/src/table/table_commit/row_id_conflict_tests.rs 
b/crates/paimon/src/table/table_commit/row_id_conflict_tests.rs
index 83daebc8..9eaa3f4d 100644
--- a/crates/paimon/src/table/table_commit/row_id_conflict_tests.rs
+++ b/crates/paimon/src/table/table_commit/row_id_conflict_tests.rs
@@ -188,7 +188,7 @@ async fn standalone_row_id_check_skips_compaction_history() 
{
 }
 
 #[tokio::test]
-async fn 
standalone_row_id_check_validates_snapshot_baselines_and_current_schema() {
+async fn 
standalone_row_id_check_validates_baselines_and_accepts_compatible_schema() {
     let commit = 
row_id_check_history("memory:/standalone_check_validation").await;
     let message = row_id_check_message("staged.parquet", "name");
     for (latest, baseline) in [(2, 0), (1, 2), (0, 1), (2, -1), (2, 2)] {
@@ -217,7 +217,11 @@ async fn 
standalone_row_id_check_validates_snapshot_baselines_and_current_schema
         .check_row_id_conflicts(&[message], 2, 1)
         .await
         .unwrap_err();
-    assert!(error.to_string().contains("current table schema"));
+    assert!(error.to_string().contains("multiple MERGE INTO"));
+    commit
+        .check_row_id_conflicts(&[row_id_check_message("id-only.parquet", 
"id")], 2, 1)
+        .await
+        .unwrap();
 }
 
 #[tokio::test]
diff --git a/crates/paimon/src/table/table_commit/row_id_fields.rs 
b/crates/paimon/src/table/table_commit/row_id_fields.rs
new file mode 100644
index 00000000..69c651c4
--- /dev/null
+++ b/crates/paimon/src/table/table_commit/row_id_fields.rs
@@ -0,0 +1,140 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Resolve staged writes by field identity before publishing existing-row 
updates.
+
+use super::*;
+use crate::spec::{DataField, TableSchema};
+
+impl TableCommit {
+    pub(super) async fn row_id_file_schema(&self, file: &DataFileMeta) -> 
Result<Arc<TableSchema>> {
+        if file.schema_id == self.table.schema().id() {
+            return Ok(Arc::new(self.table.schema().clone()));
+        }
+        if let Some(schema) = 
self.table.schema_manager().cached_schema(file.schema_id) {
+            return Ok(schema);
+        }
+        // Conflict detection precedes snapshot preparation. A concurrent REST
+        // update may introduce a catalog-only schema the old handle has never
+        // seen. Resolve it before attempting to read a missing schema file.
+        if self.table.rest_env.is_some() {
+            let current = self.latest_row_id_schema().await?;
+            if current.id() == file.schema_id {
+                return Ok(current);
+            }
+        }
+        self.table.schema_manager().schema(file.schema_id).await
+    }
+
+    pub(super) async fn latest_row_id_schema(&self) -> 
Result<Arc<TableSchema>> {
+        if let Some(env) = &self.table.rest_env {
+            // REST catalogs need not store schema files. Use one response for
+            // both field identities and the snapshot's schema ID.
+            let response = env
+                .api()
+                .get_table(&env.identifier().with_branch(self.table.branch())?)
+                .await?;
+            let id = response
+                .schema_id
+                .ok_or_else(|| crate::Error::DataInvalid {
+                    message: "REST table response is missing schemaId".into(),
+                    source: None,
+                })?;
+            let schema = response.schema.ok_or_else(|| 
crate::Error::DataInvalid {
+                message: "REST table response is missing schema".into(),
+                source: None,
+            })?;
+            let schema = TableSchema::new(id, &schema);
+            self.table
+                .schema_manager()
+                .cache_resolved_schema(schema.clone());
+            return Ok(Arc::new(schema));
+        }
+        if let Some(schema) = self.table.schema_manager().latest().await? {
+            return Ok(schema);
+        }
+        if self.table.is_main_branch() {
+            Ok(Arc::new(self.table.schema().clone()))
+        } else {
+            Err(crate::Error::DataInvalid {
+                message: format!("Branch '{}' does not exist.", 
self.table.branch()),
+                source: None,
+            })
+        }
+    }
+
+    pub(super) async fn validate_row_id_update_fields(
+        &self,
+        current: &TableSchema,
+        files: &[DataFileMeta],
+    ) -> Result<()> {
+        let mut current_ids = HashSet::new();
+        collect_field_ids(current.fields(), &mut current_ids);
+        let mut checked = HashSet::new();
+        for file in files {
+            if !checked.insert((file.schema_id, file.write_cols.as_ref())) {
+                continue;
+            }
+            let historical = if file.schema_id == current.id() {
+                None
+            } else {
+                Some(self.row_id_file_schema(file).await?)
+            };
+            let schema = historical.as_deref().unwrap_or(current);
+            let fields = match &file.write_cols {
+                Some(columns) => 
super::super::data_evolution_fields::project_by_paths(
+                    schema.fields(),
+                    &columns
+                        .iter()
+                        .filter(|name| !is_system_field(name))
+                        .cloned()
+                        .collect::<Vec<_>>(),
+                )?,
+                None => schema.data_file_fields(None),
+            };
+            let mut written_ids = HashSet::new();
+            collect_field_ids(&fields, &mut written_ids);
+            if !written_ids.is_subset(&current_ids) {
+                return Err(crate::Error::DataInvalid {
+                    message: "Row-id update cannot restore a dropped 
field".into(),
+                    source: None,
+                });
+            }
+        }
+        Ok(())
+    }
+}
+
+fn collect_field_ids(fields: &[DataField], ids: &mut HashSet<i32>) {
+    for field in fields {
+        ids.insert(field.id());
+        collect_nested_ids(field.data_type(), ids);
+    }
+}
+
+fn collect_nested_ids(data_type: &DataType, ids: &mut HashSet<i32>) {
+    match data_type {
+        DataType::Row(row) => collect_field_ids(row.fields(), ids),
+        DataType::Array(array) => collect_nested_ids(array.element_type(), 
ids),
+        DataType::Multiset(multiset) => 
collect_nested_ids(multiset.element_type(), ids),
+        DataType::Map(map) => {
+            collect_nested_ids(map.key_type(), ids);
+            collect_nested_ids(map.value_type(), ids);
+        }
+        _ => {}
+    }
+}
diff --git a/crates/paimon/src/table/table_commit/row_id_schema_tests.rs 
b/crates/paimon/src/table/table_commit/row_id_schema_tests.rs
new file mode 100644
index 00000000..dd6fd9a2
--- /dev/null
+++ b/crates/paimon/src/table/table_commit/row_id_schema_tests.rs
@@ -0,0 +1,430 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+mod row_id_schema {
+    use super::*;
+    use crate::spec::{BlobType, DataField, FloatType, IntType, RowType, 
VectorType};
+    use std::sync::Mutex;
+
+    async fn persist(table: &Table, schema: &TableSchema) {
+        table
+            .file_io()
+            .new_output(&format!(
+                "{}/schema/schema-{}",
+                table.location(),
+                schema.id()
+            ))
+            .unwrap()
+            .write(serde_json::to_vec(schema).unwrap().into())
+            .await
+            .unwrap();
+    }
+
+    fn evolve(table: &Table, recreate: bool) -> TableSchema {
+        let mut schema = serde_json::to_value(table.schema()).unwrap();
+        schema["id"] = 1.into();
+        if recreate {
+            schema["fields"][1]["id"] = 2.into();
+            schema["highestFieldId"] = 2.into();
+        } else {
+            schema["fields"][1]["name"] = "renamed".into();
+        }
+        serde_json::from_value(schema).unwrap()
+    }
+
+    async fn fixture(path: &str) -> TableCommit {
+        let io = test_file_io();
+        setup_dirs(&io, path).await;
+        let commit = setup_data_evolution_commit(&io, path);
+        persist(&commit.table, commit.table.schema()).await;
+        let mut file = test_data_file("base.parquet", 10);
+        file.file_source = Some(0);
+        commit
+            .commit(vec![CommitMessage::new(
+                EMPTY_SERIALIZED_ROW.clone(),
+                0,
+                vec![file],
+            )])
+            .await
+            .unwrap();
+        commit
+    }
+
+    #[tokio::test]
+    async fn standalone_check_tracks_renamed_ids_across_snapshot_schemas() {
+        for overlapping in [false, true] {
+            let path = format!("memory:/cross-schema-check-{overlapping}");
+            let commit = fixture(&path).await;
+            let schema = evolve(&commit.table, false);
+            persist(&commit.table, &schema).await;
+            let latest = commit
+                .table
+                .copy_with_resolved_schema(schema, "main")
+                .unwrap();
+            let mut concurrent = row_id_check_message("concurrent.parquet", 
"renamed");
+            concurrent.new_files[0].schema_id = 1;
+            latest
+                .new_write_builder()
+                .new_commit()
+                .commit(vec![concurrent])
+                .await
+                .unwrap();
+            let staged =
+                row_id_check_message("staged.parquet", if overlapping { "name" 
} else { "id" });
+            let result = commit.check_row_id_conflicts(&[staged], 2, 1).await;
+            if overlapping {
+                assert!(result
+                    .unwrap_err()
+                    .to_string()
+                    .contains("multiple MERGE INTO"));
+            } else {
+                result.unwrap();
+            }
+        }
+    }
+
+    struct EvolveBeforePublication {
+        table: Table,
+        recreate: bool,
+        attempts: Mutex<Vec<Snapshot>>,
+    }
+
+    #[async_trait::async_trait]
+    impl SnapshotCommit for EvolveBeforePublication {
+        async fn commit(
+            &self,
+            _: Option<&str>,
+            snapshot: &Snapshot,
+            _: &str,
+            _: &[PartitionStatistics],
+        ) -> Result<bool> {
+            let first = {
+                let mut attempts = self.attempts.lock().unwrap();
+                attempts.push(snapshot.clone());
+                attempts.len() == 1
+            };
+            if first {
+                let schema = evolve(&self.table, self.recreate);
+                persist(&self.table, &schema).await;
+                let current = self.table.copy_with_resolved_schema(schema, 
"main")?;
+                let mut file = test_data_file("competing-append.parquet", 1);
+                file.schema_id = 1;
+                file.file_source = Some(0);
+                current
+                    .new_write_builder()
+                    .new_commit()
+                    .commit(vec![CommitMessage::new(
+                        EMPTY_SERIALIZED_ROW.clone(),
+                        0,
+                        vec![file],
+                    )])
+                    .await?;
+                return Ok(false);
+            }
+            self.table
+                .snapshot_manager()
+                .commit_snapshot(snapshot)
+                .await
+        }
+    }
+
+    #[tokio::test]
+    async fn 
publication_retry_revalidates_update_ids_for_append_and_overwrite() {
+        for overwrite in [false, true] {
+            for recreate in [false, true] {
+                let path = 
format!("memory:/row-id-schema-retry-{overwrite}-{recreate}");
+                let mut commit = fixture(&path).await;
+                let mut staged = row_id_check_message("staged.parquet", 
"name");
+                if overwrite {
+                    staged
+                        .new_index_files
+                        .push(test_deletion_vector_index_file("delete.dv", 
"base.parquet"));
+                }
+                let staged_path = format!("{path}/bucket-0/staged.parquet");
+                commit
+                    .table
+                    .file_io()
+                    .new_output(&staged_path)
+                    .unwrap()
+                    .write(bytes::Bytes::from_static(b"prepared update"))
+                    .await
+                    .unwrap();
+                let publisher = Arc::new(EvolveBeforePublication {
+                    table: commit.table.clone(),
+                    recreate,
+                    attempts: Mutex::new(vec![]),
+                });
+                commit.snapshot_commit = publisher.clone();
+                commit.commit_min_retry_wait_ms = 0;
+                commit.commit_max_retry_wait_ms = 0;
+                let result = commit.commit(vec![staged]).await;
+                let snapshot = commit
+                    .snapshot_manager
+                    .get_latest_snapshot()
+                    .await
+                    .unwrap()
+                    .unwrap();
+                let attempts = publisher.attempts.lock().unwrap().clone();
+                assert_eq!(attempts[0].schema_id(), 0);
+                assert_eq!(
+                    attempts[0].commit_kind(),
+                    if overwrite {
+                        &CommitKind::OVERWRITE
+                    } else {
+                        &CommitKind::APPEND
+                    }
+                );
+                if recreate {
+                    assert!(result.unwrap_err().to_string().contains("dropped 
field"));
+                    assert_eq!(snapshot.id(), 2);
+                    assert_eq!(attempts.len(), 1, "reject before another 
publication");
+                } else {
+                    result.unwrap();
+                    assert_eq!(snapshot.id(), 3);
+                    assert_eq!(attempts.len(), 2);
+                    assert_eq!(attempts[1].schema_id(), 1);
+                    let entries = active_entries(commit.table.file_io(), 
&path, &snapshot).await;
+                    assert!(entries
+                        .iter()
+                        .any(|entry| entry.file().file_name == "staged.parquet"
+                            && entry.file().schema_id == 0));
+                }
+                
assert!(commit.table.file_io().exists(&staged_path).await.unwrap());
+            }
+        }
+    }
+
+    #[tokio::test]
+    async fn compact_write_cols_exclude_dedicated_field_conflicts() {
+        for nested in [false, true] {
+            let schema = crate::spec::Schema::builder()
+                .column("id", DataType::Int(IntType::new()))
+                .column("payload", DataType::Blob(BlobType::new()))
+                .column(
+                    "embedding",
+                    DataType::Vector(
+                        VectorType::try_new(true, 4, 
DataType::Float(FloatType::new())).unwrap(),
+                    ),
+                )
+                .option("data-evolution.enabled", "true")
+                .option("row-tracking.enabled", "true")
+                .option("data-evolution.write-cols-optimization.enabled", 
"true")
+                .option("data-evolution.nested-field.enabled", 
nested.to_string())
+                .option("vector.file.format", "vortex")
+                .option("write-only", "true")
+                .build()
+                .unwrap();
+            let table = Table::new(
+                test_file_io(),
+                Identifier::new("default", "compact_cols"),
+                "memory:/compact_cols".into(),
+                TableSchema::new(0, &schema),
+                None,
+            );
+            let commit = table.new_write_builder().new_commit();
+            let mut file = test_data_file("normal.parquet", 10);
+            file.first_row_id = Some(0);
+            assert_eq!(
+                commit.write_field_ids(&file).await.unwrap(),
+                HashSet::from([0])
+            );
+            setup_dirs(table.file_io(), table.location()).await;
+            let mut base = test_data_file("base.parquet", 10);
+            base.file_source = Some(0);
+            commit
+                .commit(vec![CommitMessage::new(
+                    EMPTY_SERIALIZED_ROW.clone(),
+                    0,
+                    vec![base],
+                )])
+                .await
+                .unwrap();
+            file.file_source = Some(0);
+            let mut normal_update =
+                CommitMessage::new(EMPTY_SERIALIZED_ROW.clone(), 0, 
vec![file.clone()]);
+            normal_update.check_from_snapshot = Some(1);
+            commit.commit(vec![normal_update]).await.unwrap();
+            for column in ["payload", "embedding"] {
+                file.write_cols = Some(vec![column.into()]);
+                
assert!(!commit.write_field_ids(&file).await.unwrap().contains(&0));
+                let mut staged =
+                    CommitMessage::new(EMPTY_SERIALIZED_ROW.clone(), 0, 
vec![file.clone()]);
+                staged.new_files[0].file_name = if column == "payload" {
+                    "staged.blob"
+                } else {
+                    "staged.vector.vortex"
+                }
+                .into();
+                staged.check_from_snapshot = Some(1);
+                commit
+                    .check_row_id_conflicts(&[staged], 2, 1)
+                    .await
+                    .unwrap();
+            }
+        }
+    }
+
+    #[tokio::test]
+    async fn commits_reject_dropped_descendants_in_written_complex_columns() {
+        for container in ["row", "array", "map", "multiset"] {
+            let child = DataType::Row(RowType::new(vec![DataField::new(
+                0,
+                "value".into(),
+                DataType::Int(IntType::new()),
+            )]));
+            let data_type = match container {
+                "array" => DataType::Array(crate::spec::ArrayType::new(child)),
+                "multiset" => 
DataType::Multiset(crate::spec::MultisetType::new(child)),
+                "map" => DataType::Map(crate::spec::MapType::new(
+                    DataType::Int(IntType::new()),
+                    child,
+                )),
+                _ => child,
+            };
+            let schema = crate::spec::Schema::builder()
+                .column("id", DataType::Int(IntType::new()))
+                .column("profile", data_type)
+                .option("data-evolution.enabled", "true")
+                .option("row-tracking.enabled", "true")
+                .option("write-only", "true")
+                .build()
+                .unwrap();
+            let path = format!("memory:/nested-schema-{container}");
+            let io = test_file_io();
+            setup_dirs(&io, &path).await;
+            let table = Table::new(
+                io,
+                Identifier::new("default", "nested"),
+                path.clone(),
+                TableSchema::new(0, &schema),
+                None,
+            );
+            persist(&table, table.schema()).await;
+            let mut base = test_data_file("base.parquet", 10);
+            base.file_source = Some(0);
+            let commit = table.new_write_builder().new_commit();
+            commit
+                .commit(vec![CommitMessage::new(
+                    EMPTY_SERIALIZED_ROW.clone(),
+                    0,
+                    vec![base],
+                )])
+                .await
+                .unwrap();
+            let mut changed = serde_json::to_value(table.schema()).unwrap();
+            changed["id"] = 1.into();
+            changed["highestFieldId"] = 3.into();
+            let mut ty = &mut changed["fields"][1]["type"];
+            if container == "array" || container == "multiset" {
+                ty = &mut ty["element"];
+            }
+            if container == "map" {
+                ty = &mut ty["value"];
+            }
+            ty["fields"][0]["id"] = 3.into();
+            let changed: TableSchema = 
serde_json::from_value(changed).unwrap();
+            persist(&table, &changed).await;
+            let staged = row_id_check_message("staged.parquet", "profile");
+            let error = commit.commit(vec![staged]).await.unwrap_err();
+            assert!(
+                error.to_string().contains("dropped field"),
+                "{container}: {error}"
+            );
+            assert_eq!(
+                commit
+                    .snapshot_manager
+                    .get_latest_snapshot_id()
+                    .await
+                    .unwrap(),
+                Some(1)
+            );
+            // Dropping a descendant in an untouched column must not prevent
+            // an independent partial update from publishing.
+            commit
+                .commit(vec![row_id_check_message("id-only.parquet", "id")])
+                .await
+                .unwrap();
+            assert_eq!(
+                commit
+                    .snapshot_manager
+                    .get_latest_snapshot_id()
+                    .await
+                    .unwrap(),
+                Some(2)
+            );
+        }
+    }
+
+    #[tokio::test]
+    async fn partial_row_write_ignores_dropped_unwritten_sibling() {
+        let schema = crate::spec::Schema::builder()
+            .column(
+                "profile",
+                DataType::Row(RowType::new(vec![
+                    DataField::new(0, "keep".into(), 
DataType::Int(IntType::new())),
+                    DataField::new(0, "drop".into(), 
DataType::Int(IntType::new())),
+                ])),
+            )
+            .option("data-evolution.enabled", "true")
+            .option("row-tracking.enabled", "true")
+            .option("data-evolution.nested-field.enabled", "true")
+            .option("write-only", "true")
+            .build()
+            .unwrap();
+        let path = "memory:/partial-row-drop-sibling";
+        let io = test_file_io();
+        setup_dirs(&io, path).await;
+        let table = Table::new(
+            io,
+            Identifier::new("default", "nested"),
+            path.into(),
+            TableSchema::new(0, &schema),
+            None,
+        );
+        persist(&table, table.schema()).await;
+        let commit = table.new_write_builder().new_commit();
+        let mut base = test_data_file("base.parquet", 10);
+        base.file_source = Some(0);
+        commit
+            .commit(vec![CommitMessage::new(
+                EMPTY_SERIALIZED_ROW.clone(),
+                0,
+                vec![base],
+            )])
+            .await
+            .unwrap();
+        let mut changed = serde_json::to_value(table.schema()).unwrap();
+        changed["id"] = 1.into();
+        changed["fields"][0]["type"]["fields"]
+            .as_array_mut()
+            .unwrap()
+            .pop();
+        persist(&table, &serde_json::from_value(changed).unwrap()).await;
+        commit
+            .commit(vec![row_id_check_message("keep.parquet", "profile.keep")])
+            .await
+            .unwrap();
+        let snapshot = commit
+            .snapshot_manager
+            .get_latest_snapshot()
+            .await
+            .unwrap()
+            .unwrap();
+        assert_eq!(snapshot.id(), 2);
+        assert_eq!(snapshot.schema_id(), 1);
+    }
+}
diff --git a/crates/paimon/tests/historical_table_update_test.rs 
b/crates/paimon/tests/historical_table_update_test.rs
index 2b9466b5..5d2f11a2 100644
--- a/crates/paimon/tests/historical_table_update_test.rs
+++ b/crates/paimon/tests/historical_table_update_test.rs
@@ -515,12 +515,23 @@ async fn 
historical_append_mutations_keep_original_field_ids() {
                 .all(|file| file.schema_id == 0));
             // The committer's historical read schema must not replace the
             // latest schema used for publication or conflict validation.
+            if change == "drop_readd" {
+                let before = rows(&latest).await;
+                let error = historical
+                    .new_write_builder()
+                    .new_commit()
+                    .commit(messages)
+                    .await
+                    .unwrap_err();
+                assert!(
+                    error.to_string().contains("dropped field"),
+                    "{operation}: {error}"
+                );
+                assert_eq!(rows(&latest).await, before);
+                continue;
+            }
             commit(&historical, messages).await;
-            let values = if change == "drop_readd" {
-                [None; 4]
-            } else {
-                [Some(11), Some(20), Some(30), Some(40)]
-            };
+            let values = [Some(11), Some(20), Some(30), Some(40)];
             let expected = vec![
                 vec![Some(1), values[0], Some(100), None],
                 vec![Some(2), values[1], Some(200), None],
@@ -602,7 +613,30 @@ async fn 
historical_partial_files_follow_field_ids_after_schema_changes() {
             .iter()
             .flat_map(|message| &message.new_files)
             .all(|file| file.schema_id == 0 && file.write_cols == 
Some(vec!["value".into()])));
-        commit(&historical, messages).await;
+        if change == "drop_readd" {
+            let before = latest
+                .snapshot_manager()
+                .get_latest_snapshot_id()
+                .await
+                .unwrap();
+            let error = historical
+                .new_write_builder()
+                .new_commit()
+                .commit(messages)
+                .await
+                .unwrap_err();
+            assert!(error.to_string().contains("dropped field"), "{error}");
+            assert_eq!(
+                latest
+                    .snapshot_manager()
+                    .get_latest_snapshot_id()
+                    .await
+                    .unwrap(),
+                before
+            );
+        } else {
+            commit(&historical, messages).await;
+        }
         let expected = if change == "drop_readd" {
             [None, None, None]
         } else {
diff --git a/crates/paimon/tests/rest_catalog/row_id_schema.rs 
b/crates/paimon/tests/rest_catalog/row_id_schema.rs
new file mode 100644
index 00000000..0a393a5e
--- /dev/null
+++ b/crates/paimon/tests/rest_catalog/row_id_schema.rs
@@ -0,0 +1,245 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use super::*;
+
+#[tokio::test]
+async fn row_id_updates_validate_catalog_fields_without_current_schema_files() 
{
+    for change in ["rename", "add", "recreate"] {
+        for advance in ["none", "append", "update"] {
+            let ctx = setup_catalog(vec!["default"]).await;
+            let directory = tempfile::tempdir().unwrap();
+            let name = format!("row_id_schema_{change}_{advance}");
+            let schema = schema_of(
+                &["id", "value"],
+                &[
+                    ("data-evolution.enabled", "true"),
+                    ("row-tracking.enabled", "true"),
+                    ("write-only", "true"),
+                ],
+            );
+            ctx.server.add_table_with_schema(
+                "default",
+                &name,
+                schema.clone(),
+                directory.path().to_str().unwrap(),
+            );
+            let identifier = Identifier::new("default", &name);
+            let table = ctx.catalog.get_table(&identifier).await.unwrap();
+            let check_table = 
ctx.catalog.get_table(&identifier).await.unwrap();
+            let batch = RecordBatch::try_from_iter([
+                (
+                    "id",
+                    Arc::new(Int32Array::from(vec![1])) as 
arrow_array::ArrayRef,
+                ),
+                (
+                    "value",
+                    Arc::new(Int32Array::from(vec![10])) as 
arrow_array::ArrayRef,
+                ),
+            ])
+            .unwrap();
+            let mut writer = table.new_write_builder().new_write().unwrap();
+            writer.write_arrow_batch(&batch).await.unwrap();
+            table
+                .new_write_builder()
+                .new_commit()
+                .commit(writer.prepare_commit().await.unwrap())
+                .await
+                .unwrap();
+            let input = RecordBatch::try_from_iter([
+                (
+                    "_ROW_ID",
+                    Arc::new(Int64Array::from(vec![0])) as 
arrow_array::ArrayRef,
+                ),
+                (
+                    "value",
+                    Arc::new(Int32Array::from(vec![99])) as 
arrow_array::ArrayRef,
+                ),
+            ])
+            .unwrap();
+            let messages = table
+                .new_write_builder()
+                .new_update()
+                .unwrap()
+                .update_by_arrow_with_row_id(vec![input])
+                .await
+                .unwrap();
+            let mut evolved = serde_json::to_value(schema).unwrap();
+            match change {
+                "rename" => evolved["fields"][1]["name"] = "renamed".into(),
+                "recreate" => evolved["fields"][1]["id"] = 2.into(),
+                _ => evolved["fields"]
+                    .as_array_mut()
+                    .unwrap()
+                    .push(serde_json::json!({"id": 2, "name": "extra", "type": 
"INT"})),
+            }
+            ctx.server.set_table_schema_id(
+                "default",
+                &name,
+                serde_json::from_value(evolved).unwrap(),
+                1,
+            );
+            let current = ctx.catalog.get_table(&identifier).await.unwrap();
+            
assert!(current.schema_manager().latest().await.unwrap().is_none());
+            if advance == "append" {
+                let input = RecordBatch::try_new(
+                    
paimon::arrow::build_target_arrow_schema(current.schema().fields()).unwrap(),
+                    current
+                        .schema()
+                        .fields()
+                        .iter()
+                        .map(|field| {
+                            Arc::new(Int32Array::from(vec![if field.name() == 
"id" {
+                                2
+                            } else {
+                                20
+                            }])) as arrow_array::ArrayRef
+                        })
+                        .collect(),
+                )
+                .unwrap();
+                let mut writer = 
current.new_write_builder().new_write().unwrap();
+                writer.write_arrow_batch(&input).await.unwrap();
+                current
+                    .new_write_builder()
+                    .new_commit()
+                    .commit(writer.prepare_commit().await.unwrap())
+                    .await
+                    .unwrap();
+            }
+            if advance == "update" {
+                // The independent schema-1 writer needs the historical source
+                // definition to read schema-0 rows. Keep the current schema
+                // catalog-only, so old committers must resolve it through 
REST.
+                table
+                    .file_io()
+                    .mkdirs(&format!("{}/schema", table.location()))
+                    .await
+                    .unwrap();
+                table
+                    .file_io()
+                    .new_output(&format!("{}/schema/schema-0", 
table.location()))
+                    .unwrap()
+                    .write(serde_json::to_vec(table.schema()).unwrap().into())
+                    .await
+                    .unwrap();
+                let input = RecordBatch::try_from_iter([
+                    (
+                        "_ROW_ID",
+                        Arc::new(Int64Array::from(vec![0])) as 
arrow_array::ArrayRef,
+                    ),
+                    (
+                        "id",
+                        Arc::new(Int32Array::from(vec![123])) as 
arrow_array::ArrayRef,
+                    ),
+                ])
+                .unwrap();
+                let concurrent = current
+                    .new_write_builder()
+                    .new_update()
+                    .unwrap()
+                    .update_by_arrow_with_row_id(vec![input])
+                    .await
+                    .unwrap();
+                current
+                    .new_write_builder()
+                    .new_commit()
+                    .commit(concurrent)
+                    .await
+                    .unwrap();
+            }
+            assert!(!table
+                .file_io()
+                .exists(&format!("{}/schema/schema-1", table.location()))
+                .await
+                .unwrap());
+            let before = table
+                .snapshot_manager()
+                .get_latest_snapshot_id()
+                .await
+                .unwrap()
+                .unwrap();
+            let check = check_table
+                .new_write_builder()
+                .new_commit()
+                .check_row_id_conflicts(&messages, before, 1)
+                .await;
+            // Use an independent old handle so the check cannot populate the
+            // committer's schema cache before its own conflict detection.
+            let result = table
+                .new_write_builder()
+                .new_commit()
+                .commit(messages)
+                .await;
+            if change == "recreate" {
+                assert!(check.unwrap_err().to_string().contains("dropped 
field"));
+                assert!(result.unwrap_err().to_string().contains("dropped 
field"));
+                assert_eq!(
+                    current
+                        .snapshot_manager()
+                        .get_latest_snapshot_id()
+                        .await
+                        .unwrap(),
+                    Some(before)
+                );
+            } else {
+                check.unwrap();
+                result.unwrap();
+                let snapshot = current
+                    .snapshot_manager()
+                    .get_latest_snapshot()
+                    .await
+                    .unwrap()
+                    .unwrap();
+                assert_eq!(snapshot.id(), before + 1);
+                assert_eq!(snapshot.schema_id(), 1);
+                let builder = table.new_read_builder();
+                let plan = builder.new_scan().plan().await.unwrap();
+                let batches: Vec<RecordBatch> = builder
+                    .new_read()
+                    .unwrap()
+                    .to_arrow(plan.splits())
+                    .unwrap()
+                    .try_collect()
+                    .await
+                    .unwrap();
+                let mut rows: Vec<_> = batches
+                    .iter()
+                    .flat_map(|batch| {
+                        column::<Int32Array>(batch, "id")
+                            .values()
+                            .iter()
+                            .copied()
+                            .zip(
+                                column::<Int32Array>(batch, "value")
+                                    .values()
+                                    .iter()
+                                    .copied(),
+                            )
+                    })
+                    .collect();
+                rows.sort_unstable();
+                let expected = match advance {
+                    "append" => vec![(1, 99), (2, 20)],
+                    "update" => vec![(123, 99)],
+                    _ => vec![(1, 99)],
+                };
+                assert_eq!(rows, expected, "{change}: {advance}");
+            }
+        }
+    }
+}
diff --git a/crates/paimon/tests/rest_catalog_test.rs 
b/crates/paimon/tests/rest_catalog_test.rs
index fb7a2835..7f79263c 100644
--- a/crates/paimon/tests/rest_catalog_test.rs
+++ b/crates/paimon/tests/rest_catalog_test.rs
@@ -5975,3 +5975,6 @@ mod read_path_completion;
 #[cfg(not(windows))]
 #[path = "rest_catalog/auto_compact_review.rs"]
 mod auto_compact_review;
+
+#[path = "rest_catalog/row_id_schema.rs"]
+mod row_id_schema;
diff --git a/docs/src/python-binding.md b/docs/src/python-binding.md
index 57b8ac55..3de7e321 100644
--- a/docs/src/python-binding.md
+++ b/docs/src/python-binding.md
@@ -287,6 +287,13 @@ ctx.sql("INSERT INTO paimon.default.my_table VALUES (1, 
'alice'), (2, 'bob')")
 !!! note "Write Builder Consistency"
     The writer and committer must come from the same `BatchWriteBuilder` — 
they share a `commit_user` for duplicate-commit detection. Passing messages 
from one builder's writer to another builder's committer will raise a 
`ValueError`.
 
+Data Evolution updates to existing row IDs retain their original field IDs 
across
+compatible schema changes, including renames and type widening. Each snapshot
+publication attempt, including internal retries, checks those IDs against the
+schema recorded in that snapshot. An update to a dropped field is rejected even
+if its name is reused or DDL has not published a new data snapshot. This check
+includes fields nested inside written ROW, ARRAY, MAP, and MULTISET columns.
+
 ## Column Projection
 
 Use `with_projection` to select specific columns. Only the requested columns 
are read, reducing I/O.

Reply via email to