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 f8da5743 fix(table): treat lone UPDATE_BEFORE as retraction in 
partial-update (#1434)
f8da5743 is described below

commit f8da5743d2eb36a75bdcbbf0afaffadb775cbffd
Author: 龙骑士k <[email protected]>
AuthorDate: Tue Nov 17 15:35:10 2026 +0000

    fix(table): treat lone UPDATE_BEFORE as retraction in partial-update (#1434)
---
 crates/paimon/src/table/compact/primary_key.rs     |  11 +-
 .../paimon/src/table/compact/primary_key/lookup.rs |   2 +-
 crates/paimon/src/table/kv_file_reader.rs          |   7 +-
 crates/paimon/src/table/kv_file_writer.rs          |   7 +-
 crates/paimon/src/table/sort_merge.rs              | 128 +++++++++++++++------
 crates/paimon/tests/pk_compact/merge_engines.rs    |  45 ++++++++
 .../tests/pk_partial_update_delete_state_test.rs   |  72 +++++++++++-
 docs/src/compaction.md                             |   3 +
 8 files changed, 225 insertions(+), 50 deletions(-)

diff --git a/crates/paimon/src/table/compact/primary_key.rs 
b/crates/paimon/src/table/compact/primary_key.rs
index 9c3eca12..cb36c333 100644
--- a/crates/paimon/src/table/compact/primary_key.rs
+++ b/crates/paimon/src/table/compact/primary_key.rs
@@ -193,19 +193,24 @@ impl MergeFunction for CompactReducer {
             });
         }
         Ok(match self.inner.merge(rows, batches, columns, schema)? {
-            MergeResult::MaterializedDeleteRow(_) if self.reject_delete_state 
&& rows.len() > 1 => {
+            MergeResult::MaterializedRetractRow(_, RowKind::Delete)
+                if self.reject_delete_state && rows.len() > 1 =>
+            {
                 // A partial-update reducer initializes from the first retract
                 // and then retracts its payload. Replaying an accumulated
                 // DELETE can cancel its own state. First-value aggregators
                 // also carry an initialized flag that DELETE payloads do not
-                // serialize. Keep the sources until replay is safe.
+                // serialize. Keep the sources until replay is safe. An
+                // UPDATE_BEFORE state only comes from remove-record-on-delete
+                // without sequence groups, where a replayed UPDATE_BEFORE
+                // writes its non-null fields like an INSERT.
                 return Err(crate::Error::Unsupported {
                     message:
                         "Compaction cannot preserve DELETE aggregate state for 
this merge engine"
                             .into(),
                 });
             }
-            MergeResult::MaterializedDeleteRow(batch) => 
MergeResult::MaterializedRow(batch),
+            MergeResult::MaterializedRetractRow(batch, _) => 
MergeResult::MaterializedRow(batch),
             result => result,
         })
     }
diff --git a/crates/paimon/src/table/compact/primary_key/lookup.rs 
b/crates/paimon/src/table/compact/primary_key/lookup.rs
index 4be6e90c..0465e84c 100644
--- a/crates/paimon/src/table/compact/primary_key/lookup.rs
+++ b/crates/paimon/src/table/compact/primary_key/lookup.rs
@@ -133,7 +133,7 @@ fn result_row(
         MergeResult::SourceRow { batch_idx, row_idx } => {
             source_row(*batch_idx, *row_idx, batches, columns, 
schema).map(Some)
         }
-        MergeResult::MaterializedRow(batch) | 
MergeResult::MaterializedDeleteRow(batch) => {
+        MergeResult::MaterializedRow(batch) | 
MergeResult::MaterializedRetractRow(batch, _) => {
             Ok(Some(batch.clone()))
         }
         MergeResult::Omit => Ok(None),
diff --git a/crates/paimon/src/table/kv_file_reader.rs 
b/crates/paimon/src/table/kv_file_reader.rs
index ce59ed26..7f05c3dc 100644
--- a/crates/paimon/src/table/kv_file_reader.rs
+++ b/crates/paimon/src/table/kv_file_reader.rs
@@ -4154,11 +4154,10 @@ mod tests {
             vec![10]
         );
 
+        // Java PR 11178: a lone UPDATE_BEFORE removes the row.
         write_commit(&table, &make(Some(99), 1)).await;
-        assert_eq!(
-            int_column(&read_rows(&table, None, None).await, "value"),
-            vec![10]
-        );
+        let rows = read_rows(&table, None, None).await;
+        assert!(rows.iter().all(|batch| batch.num_rows() == 0), "{rows:?}");
 
         write_commit(&table, &make(Some(20), 2)).await;
         assert_eq!(
diff --git a/crates/paimon/src/table/kv_file_writer.rs 
b/crates/paimon/src/table/kv_file_writer.rs
index 4c174144..f2915be5 100644
--- a/crates/paimon/src/table/kv_file_writer.rs
+++ b/crates/paimon/src/table/kv_file_writer.rs
@@ -718,9 +718,9 @@ impl KeyValueFileWriter {
                     merged_kinds.push(RowKind::Insert as i8);
                     last_indices.push(sorted_indices.value(end - 1));
                 }
-                MergeResult::MaterializedDeleteRow(row) => {
+                MergeResult::MaterializedRetractRow(row, kind) => {
                     merged.push(row);
-                    merged_kinds.push(RowKind::Delete as i8);
+                    merged_kinds.push(kind as i8);
                     last_indices.push(sorted_indices.value(end - 1));
                 }
                 MergeResult::Omit => {}
@@ -852,7 +852,8 @@ impl KeyValueFileWriter {
                     match first_row_merge.merge(&rows, &[], &[], &schema)? {
                         MergeResult::SourceRow { row_idx, .. } => 
result.push(row_idx as u32),
                         MergeResult::Omit => {}
-                        MergeResult::MaterializedRow(_) | 
MergeResult::MaterializedDeleteRow(_) => {
+                        MergeResult::MaterializedRow(_)
+                        | MergeResult::MaterializedRetractRow(..) => {
                             unreachable!("first-row merge must return an input 
row")
                         }
                     }
diff --git a/crates/paimon/src/table/sort_merge.rs 
b/crates/paimon/src/table/sort_merge.rs
index b6365fed..a773d1db 100644
--- a/crates/paimon/src/table/sort_merge.rs
+++ b/crates/paimon/src/table/sort_merge.rs
@@ -142,8 +142,9 @@ pub(crate) enum MergeResult {
     SourceRow { batch_idx: usize, row_idx: usize },
     /// Emit a synthesized one-row batch matching the merge output schema.
     MaterializedRow(RecordBatch),
-    /// Persist a synthesized tombstone during a write; scans omit it.
-    MaterializedDeleteRow(RecordBatch),
+    /// Persist a synthesized DELETE or UPDATE_BEFORE during a write; scans
+    /// omit it.
+    MaterializedRetractRow(RecordBatch, RowKind),
     /// Omit this key from the output.
     Omit,
 }
@@ -453,7 +454,7 @@ fn is_merged_metadata_field(field: &arrow_schema::Field) -> 
bool {
 fn merged_metadata_column(
     field: &arrow_schema::Field,
     row: &MergeRow,
-    deleted: bool,
+    kind: RowKind,
 ) -> Option<ArrayRef> {
     match field.name().as_str() {
         crate::spec::SEQUENCE_NUMBER_FIELD_NAME => {
@@ -462,11 +463,6 @@ fn merged_metadata_column(
             ])))
         }
         crate::spec::VALUE_KIND_FIELD_NAME => {
-            let kind = if deleted {
-                RowKind::Delete
-            } else {
-                RowKind::Insert
-            };
             Some(std::sync::Arc::new(Int8Array::from(vec![kind as i8])))
         }
         _ => None,
@@ -505,6 +501,39 @@ impl PartialUpdateMergeFunction {
         Ok(())
     }
 
+    /// Java `updateNonNullFields`: ungrouped fields take the row's non-null
+    /// values, or feed their aggregator.
+    fn update_non_null_fields(
+        &self,
+        selected_by_col: &mut [Option<(usize, usize)>],
+        mut aggregators: Option<&mut [Option<Box<dyn FieldAggregator>>]>,
+        row: &MergeRow,
+        batch_buffer: &[BufferedBatch],
+        source_output_col_indices: &[usize],
+    ) -> crate::Result<()> {
+        for (output_col_idx, selected) in 
selected_by_col.iter_mut().enumerate() {
+            if self.grouped_fields.contains(&output_col_idx) {
+                continue;
+            }
+            let source_array = batch_buffer[row.batch_idx]
+                .column_for_output(output_col_idx, source_output_col_indices);
+            if let Some(aggregator) = aggregators
+                .as_mut()
+                .and_then(|aggregators| aggregators.get_mut(output_col_idx))
+                .and_then(Option::as_mut)
+            {
+                aggregator.agg_array(
+                    batch_buffer[row.batch_idx]
+                        .column_ref_for_output(output_col_idx, 
source_output_col_indices),
+                    row.row_idx,
+                )?;
+            } else if !source_array.is_null(row.row_idx) {
+                *selected = Some((row.batch_idx, row.row_idx));
+            }
+        }
+        Ok(())
+    }
+
     #[cfg(test)]
     pub(crate) fn new(
         table_options: &HashMap<String, String>,
@@ -739,6 +768,8 @@ impl PartialUpdateMergeFunction {
         }
         let mut saw_add = false;
         let mut current_delete_row = false;
+        // Whether a DELETE re-initialized the row, see the result kind below.
+        let mut meet_delete = false;
         let mut initialized = false;
         let mut latest_row = None;
 
@@ -824,6 +855,7 @@ impl PartialUpdateMergeFunction {
                     }
                     if full_delete {
                         current_delete_row = true;
+                        meet_delete = true;
                         Self::replace_with_source(
                             &mut selected_by_col,
                             aggregators.as_mut().map(|guard| 
guard.as_mut_slice()),
@@ -837,8 +869,9 @@ impl PartialUpdateMergeFunction {
                     continue;
                 }
                 if self.remove_record_on_delete {
+                    current_delete_row = true;
                     if kind == RowKind::Delete {
-                        current_delete_row = true;
+                        meet_delete = true;
                         Self::replace_with_source(
                             &mut selected_by_col,
                             aggregators.as_mut().map(|guard| 
guard.as_mut_slice()),
@@ -847,6 +880,18 @@ impl PartialUpdateMergeFunction {
                             batch_buffer,
                             source_output_col_indices,
                         )?;
+                    } else {
+                        // Java PR 11178: an UPDATE_BEFORE is a retraction. It
+                        // marks the row removed without re-initializing it, so
+                        // a later add keeps the fields of other writers, and
+                        // it applies its own non-null fields like an add.
+                        self.update_non_null_fields(
+                            &mut selected_by_col,
+                            aggregators.as_mut().map(|guard| 
guard.as_mut_slice()),
+                            row,
+                            batch_buffer,
+                            source_output_col_indices,
+                        )?;
                     }
                     continue;
                 }
@@ -861,26 +906,13 @@ impl PartialUpdateMergeFunction {
             }
             latest_row = Some(row);
 
-            for (output_col_idx, selected) in 
selected_by_col.iter_mut().enumerate() {
-                if self.grouped_fields.contains(&output_col_idx) {
-                    continue;
-                }
-                let source_array = batch_buffer[row.batch_idx]
-                    .column_for_output(output_col_idx, 
source_output_col_indices);
-                if let Some(aggregator) = aggregators
-                    .as_mut()
-                    .and_then(|aggregators| 
aggregators.get_mut(output_col_idx))
-                    .and_then(Option::as_mut)
-                {
-                    aggregator.agg_array(
-                        batch_buffer[row.batch_idx]
-                            .column_ref_for_output(output_col_idx, 
source_output_col_indices),
-                        row.row_idx,
-                    )?;
-                } else if !source_array.is_null(row.row_idx) {
-                    *selected = Some((row.batch_idx, row.row_idx));
-                }
-            }
+            self.update_non_null_fields(
+                &mut selected_by_col,
+                aggregators.as_mut().map(|guard| guard.as_mut_slice()),
+                row,
+                batch_buffer,
+                source_output_col_indices,
+            )?;
 
             for (group_idx, group) in self.sequence_groups.iter().enumerate() {
                 let sequence_is_empty = 
group.sequence_indices.iter().all(|&output_col_idx| {
@@ -945,7 +977,21 @@ impl PartialUpdateMergeFunction {
         if !initialized {
             return Ok(PickedMerge::Result(MergeResult::Omit));
         }
-        let deleted = current_delete_row || !saw_add;
+        // A row removed only by UPDATE_BEFORE stays UPDATE_BEFORE, so merging
+        // a pre-merged result again does not re-initialize the row like a
+        // DELETE would. This also covers keys with only UPDATE_BEFORE rows.
+        let result_kind = if current_delete_row {
+            if meet_delete {
+                RowKind::Delete
+            } else {
+                RowKind::UpdateBefore
+            }
+        } else if saw_add {
+            RowKind::Insert
+        } else {
+            RowKind::Delete
+        };
+        let deleted = result_kind != RowKind::Insert;
         // Ignored legacy retracts seed the value but do not advance Java's
         // latestSequenceNumber, whose reset value is zero.
         let ignored_retract_metadata = latest_row.is_none().then(|| MergeRow {
@@ -987,7 +1033,7 @@ impl PartialUpdateMergeFunction {
             .iter()
             .enumerate()
             .map(|(output_col_idx, field)| {
-                if let Some(column) = merged_metadata_column(field, 
latest_row, deleted) {
+                if let Some(column) = merged_metadata_column(field, 
latest_row, result_kind) {
                     return Ok(column);
                 }
                 let column = match aggregators
@@ -1024,8 +1070,10 @@ impl PartialUpdateMergeFunction {
         })?;
 
         if deleted {
-            Ok(PickedMerge::Result(MergeResult::MaterializedDeleteRow(
+            debug_assert!(result_kind.is_retract());
+            Ok(PickedMerge::Result(MergeResult::MaterializedRetractRow(
                 batch,
+                result_kind,
             )))
         } else {
             Ok(PickedMerge::Result(MergeResult::MaterializedRow(batch)))
@@ -1245,7 +1293,11 @@ impl AggregateMergeFunction {
                 if let Some(column) = merged_metadata_column(
                     output_schema.field(col_idx),
                     pk_source,
-                    current_delete_row,
+                    if current_delete_row {
+                        RowKind::Delete
+                    } else {
+                        RowKind::Insert
+                    },
                 ) {
                     return Ok(column);
                 }
@@ -1324,7 +1376,7 @@ impl MergeFunction for AggregateMergeFunction {
             output_schema,
         )?;
         Ok(if delete {
-            MergeResult::MaterializedDeleteRow(batch)
+            MergeResult::MaterializedRetractRow(batch, RowKind::Delete)
         } else {
             MergeResult::MaterializedRow(batch)
         })
@@ -1886,7 +1938,7 @@ fn sort_merge_stream(
                     batch_buffer.push(BufferedBatch::Materialized(batch));
                     output_indices.push((batch_idx, 0));
                 }
-                MergeResult::Omit | MergeResult::MaterializedDeleteRow(_) => {}
+                MergeResult::Omit | MergeResult::MaterializedRetractRow(..) => 
{}
             }
 
             if let Some(changelog) = changelog {
@@ -4230,7 +4282,7 @@ mod tests {
                 &schema,
             )
             .unwrap();
-        let MergeResult::MaterializedDeleteRow(deleted) = result else {
+        let MergeResult::MaterializedRetractRow(deleted, RowKind::Delete) = 
result else {
             panic!("expected a materialized delete row");
         };
         assert_eq!(
@@ -4258,7 +4310,9 @@ mod tests {
                 .downcast_ref::<StringArray>()
                 .unwrap()
                 .value(0),
-            "deleted"
+            // Java PR 11178: the UPDATE_BEFORE after the DELETE applies its
+            // non-null fields and keeps the DELETE result kind.
+            "before"
         );
     }
 
diff --git a/crates/paimon/tests/pk_compact/merge_engines.rs 
b/crates/paimon/tests/pk_compact/merge_engines.rs
index 37ec8fc1..eb484024 100644
--- a/crates/paimon/tests/pk_compact/merge_engines.rs
+++ b/crates/paimon/tests/pk_compact/merge_engines.rs
@@ -225,6 +225,51 @@ async fn 
partial_update_compaction_keeps_sequence_group_delete_and_payload() {
     assert_eq!(state(&table).await, vec![(None, Some(20), Some(40))]);
 }
 
+#[tokio::test]
+async fn partial_update_compaction_keeps_update_before_state() {
+    // Java PR 11178: with remove-record-on-delete, a -U marks the row removed
+    // without re-initializing it, and a merge result removed only by -U stays
+    // UPDATE_BEFORE. Compaction must write that state, so the following +U
+    // brings the row back with `other` from another writer. With a field
+    // aggregator a DELETE state is rejected by compaction; without one a
+    // DELETE state would re-initialize the row and drop `other`.
+    for aggregate in [Some("last_non_null_value"), None] {
+        for producer in ["none", "lookup"] {
+            for same_commit in [true, false] {
+                let mut options = vec![
+                    ("partial-update.remove-record-on-delete", "true"),
+                    ("changelog-producer", producer),
+                ];
+                if let Some(function) = aggregate {
+                    options.push(("fields.value.aggregate-function", 
function));
+                }
+                let table = partial(&options).await;
+                let case = format!("{aggregate:?} {producer} {same_commit}");
+                write_batch(&table, &update(None, None, Some(20), 0)).await;
+                let insert = update(None, Some(10), None, 0);
+                let before = update(None, Some(10), None, 1);
+                if same_commit {
+                    let batch =
+                        arrow_select::concat::concat_batches(&insert.schema(), 
&[insert, before])
+                            .unwrap();
+                    write_batch(&table, &batch).await;
+                } else {
+                    write_batch(&table, &insert).await;
+                    write_batch(&table, &before).await;
+                }
+                compact(&table).await;
+                assert!(state(&table).await.is_empty(), "{case}");
+                write_batch(&table, &update(None, Some(11), None, 2)).await;
+                assert_eq!(
+                    state(&table).await,
+                    vec![(None, Some(11), Some(20))],
+                    "{case}"
+                );
+            }
+        }
+    }
+}
+
 #[tokio::test]
 async fn aggregation_compaction_keeps_accumulators_for_later_updates() {
     for (function, before, after) in [
diff --git a/crates/paimon/tests/pk_partial_update_delete_state_test.rs 
b/crates/paimon/tests/pk_partial_update_delete_state_test.rs
index 9ffc819f..f8b91c00 100644
--- a/crates/paimon/tests/pk_partial_update_delete_state_test.rs
+++ b/crates/paimon/tests/pk_partial_update_delete_state_test.rs
@@ -274,7 +274,10 @@ async fn delete_state_survives_subsequent_retractions() {
 }
 
 #[tokio::test]
-async fn whole_row_delete_ignores_update_before_payload() {
+async fn whole_row_delete_keeps_update_before_payload() {
+    // Java PR 11178: after a DELETE, an UPDATE_BEFORE keeps the row removed
+    // and still applies its non-null fields, so they are the baseline of the
+    // restored row.
     let before = event(
         RowKind::UpdateBefore,
         (Some(9), Some(99)),
@@ -286,7 +289,72 @@ async fn whole_row_delete_ignores_update_before_payload() {
         &[("partial-update.remove-record-on-delete", "true")],
         &[INITIAL, DELETED, before],
         restored,
-        [Some(1), Some(2), Some(10), Some(3), Some(30), Some(1)],
+        [Some(1), Some(9), Some(99), Some(3), Some(30), Some(9)],
+    )
+    .await;
+}
+
+// Java PR 11178 handles an UPDATE_BEFORE under remove-record-on-delete as a
+// retraction: it marks the row removed without re-initializing it and applies
+// its own non-null fields, and a merge result removed only by UPDATE_BEFORE
+// stays UPDATE_BEFORE. Every split of the events into commits, each flushed
+// through the writer's pre-merge, must read the same row. One writer owns
+// left_value, another writer owns right_value.
+const OTHER_WRITER: Event = Event {
+    values: [Some(1), None, None, None, Some(20), None],
+    kind: RowKind::Insert,
+};
+
+fn left(kind: RowKind, value: i32) -> Event {
+    event(kind, (None, Some(value)), (None, None), None)
+}
+
+#[tokio::test]
+async fn update_before_pair_keeps_other_writer_fields() {
+    // The +U brings the row back on top of the kept right_value = 20.
+    assert_all_layouts(
+        &[("partial-update.remove-record-on-delete", "true")],
+        &[
+            OTHER_WRITER,
+            left(RowKind::Insert, 10),
+            left(RowKind::UpdateBefore, 10),
+            left(RowKind::UpdateAfter, 11),
+        ],
+        [Some(1), None, Some(11), None, Some(20), None],
+    )
+    .await;
+}
+
+#[tokio::test]
+async fn lone_update_before_removes_row_until_restored() {
+    // A key that ends with a lone -U reads no row. When the other writer
+    // restores it, the kept left_value = 10 comes back, as after a DELETE.
+    assert_deleted_then_restored(
+        &[("partial-update.remove-record-on-delete", "true")],
+        &[
+            OTHER_WRITER,
+            left(RowKind::Insert, 10),
+            left(RowKind::UpdateBefore, 10),
+        ],
+        event(RowKind::Insert, (None, None), (None, Some(30)), None),
+        [Some(1), None, Some(10), None, Some(30), None],
+    )
+    .await;
+}
+
+#[tokio::test]
+async fn update_before_only_merge_keeps_older_fields() {
+    // Two -U merged without an add stay UPDATE_BEFORE rather than DELETE, so a
+    // later merge does not re-initialize the row and drop right_value = 20.
+    assert_deleted_then_restored(
+        &[("partial-update.remove-record-on-delete", "true")],
+        &[
+            OTHER_WRITER,
+            left(RowKind::UpdateBefore, 10),
+            left(RowKind::UpdateBefore, 11),
+        ],
+        left(RowKind::Insert, 12),
+        [Some(1), None, Some(12), None, Some(20), None],
     )
     .await;
 }
diff --git a/docs/src/compaction.md b/docs/src/compaction.md
index 4497ac37..1fc57d63 100644
--- a/docs/src/compaction.md
+++ b/docs/src/compaction.md
@@ -522,6 +522,9 @@ legitimately ignored, compaction can remove the selected 
files without
 creating an output file. Key bounds, sequence bounds, delete counts and file
 indexes are regenerated, using metadata statistics options for the output 
level.
 Compound `partial-update` DELETE states with field aggregators are rejected.
+Compound UPDATE_BEFORE states, which `partial-update.remove-record-on-delete`
+produces when only UPDATE_BEFORE records removed the row, are compacted
+because a later merge only replays their non-null fields.
 For both reducer engines, compound groups containing retracts are also rejected
 when they use `first_value`, `first_non_null_value`, `collect`, `listagg`,
 `nested_update` or `nested_partial_update`. These states may carry 
initialization

Reply via email to