JingsongLi commented on code in PR #1378:
URL: https://github.com/apache/paimon-rust/pull/1378#discussion_r4662277125


##########
crates/paimon/src/table/kv_file_writer.rs:
##########
@@ -524,12 +525,56 @@ impl KeyValueFileWriter {
         }
     }
 
+    /// Reject NaN key-times and NULL ROW map values for every column that uses
+    /// `merge_map_with_keytime`, before singleton or multi-row flush merging.
+    fn reject_merge_map_with_keytime_write_inputs(&self, batch: &RecordBatch) 
-> Result<()> {
+        let config = AggregationConfig::new(&self.config.table_options);
+        let pk: std::collections::HashSet<&str> = self
+            .config
+            .primary_keys
+            .iter()
+            .map(String::as_str)
+            .collect();
+        let sequence_fields: std::collections::HashSet<String> =
+            CoreOptions::new(&self.config.table_options)
+                .sequence_fields()
+                .into_iter()
+                .map(str::to_string)
+                .collect();
+        for field in &self.config.value_fields {
+            let name = field.name();
+            if pk.contains(name) || sequence_fields.contains(name) {
+                continue;
+            }
+            let agg_name = config
+                .agg_function_for_field(name)
+                .or_else(|| config.default_agg_function())
+                .unwrap_or("last_non_null_value");
+            if canonical_aggregator_name(agg_name) != "merge_map_with_keytime" 
{
+                continue;
+            }
+            let Some(column) = batch.column_by_name(name) else {
+                continue;
+            };
+            validate_merge_map_with_keytime_write_values(
+                name,
+                field.data_type(),
+                &self.config.table_options,
+                column.as_ref(),
+            )?;
+        }
+        Ok(())
+    }
+
     fn merge_aggregation_rows(
         &self,
         batch: &RecordBatch,
         seq_array: &dyn Array,
         sorted_indices: &UInt32Array,
     ) -> Result<(RecordBatch, Arc<dyn Array>)> {
+        // Shared write-entry checks for merge_map_with_keytime: must run 
before
+        // the singleton shortcut so NaN / NULL ROW cannot bypass aggregation.
+        self.reject_merge_map_with_keytime_write_inputs(batch)?;

Review Comment:
   **[P1] Validate key-time values before the partial-update singleton path**
   
   The check runs only in `merge_aggregation_rows`. A table with 
`merge-engine=partial-update`, `fields.seq.sequence-group=updates`, and 
`fields.updates.aggregate-function=merge_map_with_keytime` accepts FLOAT 
key-time. I wrote a singleton map row with a NaN key-time under this 
configuration, and `commit` returned success. The partial-update singleton path 
bypasses the aggregator, so the invalid value can be materialized and later 
rejected by a merged read.
   
   Apply the input validation before both flush paths take their singleton 
shortcuts, or reject the new type on partial-update until that path can enforce 
the contract.



##########
crates/paimon/src/table/aggregator/merge_map.rs:
##########
@@ -396,11 +436,359 @@ impl FieldAggregator for MergeMapAgg {
     }
 }
 
+/// Schema/runtime type check shared with [`MergeMapAgg::new_with_keytime`].
+pub(crate) fn validate_merge_map_with_keytime(
+    field_name: &str,
+    data_type: &DataType,
+    options: &HashMap<String, String>,
+) -> crate::Result<()> {
+    resolve_keytime_config(field_name, data_type, options).map(|_| ())
+}
+
+/// Reject NaN FLOAT/DOUBLE key-times and NULL ROW map values on the shared
+/// write/flush path (covers both singleton and multi-row key groups) so a
+/// snapshot cannot be published with these inputs.
+pub(crate) fn validate_merge_map_with_keytime_write_values(
+    field_name: &str,
+    data_type: &DataType,
+    options: &HashMap<String, String>,
+    array: &dyn Array,
+) -> crate::Result<()> {
+    let (timestamp_index, keytime_kind, _) =
+        resolve_keytime_config(field_name, data_type, options)?;
+    if array.is_empty() {
+        return Ok(());
+    }
+    let map = array
+        .as_any()
+        .downcast_ref::<MapArray>()
+        .ok_or_else(|| Error::DataInvalid {
+            message: format!(
+                "merge_map_with_keytime field '{field_name}' requires Arrow 
Map, got {:?}",
+                array.data_type()
+            ),
+            source: None,
+        })?;
+    let values = map.entries().column(1);
+    for row_idx in 0..map.len() {
+        if map.is_null(row_idx) {
+            continue;
+        }
+        let start =
+            usize::try_from(map.value_offsets()[row_idx]).map_err(|_| 
Error::DataInvalid {
+                message: "Negative Arrow Map offset".into(),
+                source: None,
+            })?;
+        let end =
+            usize::try_from(map.value_offsets()[row_idx + 1]).map_err(|_| 
Error::DataInvalid {
+                message: "Negative Arrow Map offset".into(),
+                source: None,
+            })?;
+        if end > values.len() || start > end {
+            return Err(Error::DataInvalid {
+                message: "Arrow Map offsets exceed entries".into(),
+                source: None,
+            });
+        }
+        for entry_idx in start..end {
+            if values.is_null(entry_idx) {
+                return Err(Error::DataInvalid {
+                    message: format!(
+                        "merge_map_with_keytime field '{field_name}' rejects 
NULL ROW map values \
+                         on write; key tombstones are not supported because a 
partially \
+                         aggregated delete can be lost across later merges"
+                    ),
+                    source: None,
+                });
+            }
+            let value = values.slice(entry_idx, 1);
+            let row = value
+                .as_any()
+                .downcast_ref::<StructArray>()
+                .ok_or_else(|| Error::DataInvalid {
+                    message: format!(
+                        "merge_map_with_keytime field '{field_name}' requires 
ROW values"
+                    ),
+                    source: None,
+                })?;
+            let ts = row.column(timestamp_index);
+            if ts.is_null(0) {
+                continue;
+            }
+            reject_nan_keytime_value(&keytime_kind, ts.as_ref(), field_name)?;
+        }
+    }
+    Ok(())
+}
+
+fn resolve_keytime_config(
+    field_name: &str,
+    data_type: &DataType,
+    options: &HashMap<String, String>,
+) -> crate::Result<(usize, KeytimeKind, bool)> {
+    let DataType::Map(map_type) = data_type else {
+        return Err(unsupported_type_error(
+            "merge_map_with_keytime",
+            field_name,
+            data_type,
+        ));
+    };
+    let DataType::Row(value_type) = map_type.value_type() else {
+        return Err(unsupported_type_error(
+            "merge_map_with_keytime",
+            field_name,
+            data_type,
+        ));
+    };
+    if value_type.fields().len() < 2 {
+        return Err(unsupported_type_error(
+            "merge_map_with_keytime",
+            field_name,
+            data_type,
+        ));
+    }
+    let timestamp_index = match 
options.get(&format!("fields.{field_name}.ts-field")) {
+        Some(name) => value_type
+            .fields()
+            .iter()
+            .position(|field| field.name() == name)
+            .ok_or_else(|| Error::ConfigInvalid {
+                message: format!(
+                    "Timestamp field '{name}' not found in ROW type for field 
'{field_name}'"
+                ),
+            })?,
+        None => value_type.fields().len() - 1,
+    };
+    let ts_field = &value_type.fields()[timestamp_index];
+    let keytime_kind = keytime_kind_for_type(field_name, ts_field.name(), 
ts_field.data_type())?;
+    let overwrite_on_equal_ts = parse_overwrite_on_equal_ts(field_name, 
options)?;
+    if overwrite_on_equal_ts

Review Comment:
   **[P1] Preserve default equal-keytime winners across flush groups**
   
   The new guard covers `overwrite-on-equal-ts=true`. The default false policy 
also loses per-entry sequence provenance. With INT key-time and 
`sequence.field=seq`, I committed `(seq, payload, keytime)` values `(1,11,5)`, 
`(3,33,0)`, and `(2,22,5)` for the same primary key and map key. One flush 
returned `11`. Flushing the first two together and then the last returned `22`. 
The first aggregate stores payload `11` with group sequence `3`, so sequence 
`2` appears earlier on read and wins the false tie.
   
   Please preserve the sequence of the winning map entry or reject the newly 
supported configuration for both tie policies until it is deterministic.



##########
crates/paimon/src/table/aggregator/merge_map.rs:
##########
@@ -396,11 +436,359 @@ impl FieldAggregator for MergeMapAgg {
     }
 }
 
+/// Schema/runtime type check shared with [`MergeMapAgg::new_with_keytime`].
+pub(crate) fn validate_merge_map_with_keytime(
+    field_name: &str,
+    data_type: &DataType,
+    options: &HashMap<String, String>,
+) -> crate::Result<()> {
+    resolve_keytime_config(field_name, data_type, options).map(|_| ())
+}
+
+/// Reject NaN FLOAT/DOUBLE key-times and NULL ROW map values on the shared
+/// write/flush path (covers both singleton and multi-row key groups) so a
+/// snapshot cannot be published with these inputs.
+pub(crate) fn validate_merge_map_with_keytime_write_values(
+    field_name: &str,
+    data_type: &DataType,
+    options: &HashMap<String, String>,
+    array: &dyn Array,
+) -> crate::Result<()> {
+    let (timestamp_index, keytime_kind, _) =
+        resolve_keytime_config(field_name, data_type, options)?;
+    if array.is_empty() {
+        return Ok(());
+    }
+    let map = array
+        .as_any()
+        .downcast_ref::<MapArray>()
+        .ok_or_else(|| Error::DataInvalid {
+            message: format!(
+                "merge_map_with_keytime field '{field_name}' requires Arrow 
Map, got {:?}",
+                array.data_type()
+            ),
+            source: None,
+        })?;
+    let values = map.entries().column(1);
+    for row_idx in 0..map.len() {
+        if map.is_null(row_idx) {
+            continue;
+        }
+        let start =
+            usize::try_from(map.value_offsets()[row_idx]).map_err(|_| 
Error::DataInvalid {
+                message: "Negative Arrow Map offset".into(),
+                source: None,
+            })?;
+        let end =
+            usize::try_from(map.value_offsets()[row_idx + 1]).map_err(|_| 
Error::DataInvalid {
+                message: "Negative Arrow Map offset".into(),
+                source: None,
+            })?;
+        if end > values.len() || start > end {
+            return Err(Error::DataInvalid {
+                message: "Arrow Map offsets exceed entries".into(),
+                source: None,
+            });
+        }
+        for entry_idx in start..end {
+            if values.is_null(entry_idx) {

Review Comment:
   **[P2] Preserve key deletion for existing VARCHAR key-time tables**
   
   On `ea90bef2`, I wrote a VARCHAR key-time map entry, then committed a NULL 
ROW for that map key in a separate write. The resulting map was empty. The same 
two commits on `61741baf` reject the second write during `prepare_commit`. This 
changes an existing Rust write contract, including callers that submit one 
update per key per commit.
   
   Please preserve delete markers through partial aggregation, or scope the new 
rejection to newly enabled configurations and provide a compatibility path for 
existing VARCHAR tables.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to