rich7420 commented on code in PR #5854:
URL: https://github.com/apache/datafusion-comet/pull/5854#discussion_r4711092241


##########
native/spark-expr/src/map_funcs/map_builders.rs:
##########
@@ -0,0 +1,873 @@
+// 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.
+
+//! Spark-compatible `map_from_arrays`, `map_from_entries` and `str_to_map`.
+//!
+//! The `datafusion-spark` kernels build the `MapArray` the way Spark's 
`ArrayBasedMapBuilder`
+//! does: row by row, checking a row's key and value lengths and then its keys 
in order, under the
+//! duplicate-key policy in `datafusion.spark.map_key_dedup_policy`. These 
wrappers add the one
+//! check the kernels skip, a `NULL` key, and restate the kernels' errors as 
the `SparkError`s the
+//! JVM side turns back into Spark's own:
+//!
+//! - a row whose key and value arrays differ in length raises 
`SparkError::MapKeyValueDiffSizes`,
+//!   which reaches the user as Spark's `_LEGACY_ERROR_TEMP_2128`;
+//! - a `NULL` key raises `NULL_MAP_KEY` and, under `EXCEPTION`, a duplicate 
key raises
+//!   `DUPLICATED_MAP_KEY` naming the key. Spark inserts entries one at a 
time, so whichever comes
+//!   first in the row decides which of the two it reports.
+//!
+//! `str_to_map` builds its keys by splitting a string, so it needs only the 
duplicate-key
+//! restatement.
+
+use crate::SparkError;
+use arrow::array::{Array, ArrayRef, AsArray, ListArray};
+use arrow::buffer::{NullBuffer, OffsetBuffer};
+use arrow::datatypes::{DataType, FieldRef};
+use datafusion::common::config::MapKeyDedupPolicy;
+use datafusion::common::{exec_err, DataFusionError, HashSet, Result, 
ScalarValue};
+use datafusion::logical_expr::{
+    ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, 
Signature,
+};
+use datafusion_spark::function::map::map_from_arrays::MapFromArrays as 
DataFusionMapFromArrays;
+use datafusion_spark::function::map::map_from_entries::MapFromEntries as 
DataFusionMapFromEntries;
+use datafusion_spark::function::map::str_to_map::SparkStrToMap as 
DataFusionStrToMap;
+use std::sync::Arc;
+
+/// Spark-compatible `map_from_arrays(keys, values)`.
+#[derive(Debug, Default, PartialEq, Eq, Hash)]
+pub struct SparkMapFromArrays {
+    inner: DataFusionMapFromArrays,
+}
+
+impl ScalarUDFImpl for SparkMapFromArrays {
+    fn name(&self) -> &str {
+        self.inner.name()
+    }
+
+    fn signature(&self) -> &Signature {
+        self.inner.signature()
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        self.inner.return_type(arg_types)
+    }
+
+    fn return_field_from_args(&self, args: ReturnFieldArgs) -> 
Result<FieldRef> {
+        self.inner.return_field_from_args(args)
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        invoke_list_builder(&self.inner, args, |args, last_value_wins| match 
args {
+            [ColumnarValue::Array(keys), ColumnarValue::Array(values)] => {
+                validate_map_from_arrays(keys, values, last_value_wins)
+            }
+            other => exec_err!("map_from_arrays expects 2 arguments, got {}", 
other.len()),
+        })
+    }
+}
+
+/// Spark-compatible `map_from_entries(entries)`.
+#[derive(Debug, Default, PartialEq, Eq, Hash)]
+pub struct SparkMapFromEntries {
+    inner: DataFusionMapFromEntries,
+}
+
+impl ScalarUDFImpl for SparkMapFromEntries {
+    fn name(&self) -> &str {
+        self.inner.name()
+    }
+
+    fn signature(&self) -> &Signature {
+        self.inner.signature()
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        self.inner.return_type(arg_types)
+    }
+
+    fn return_field_from_args(&self, args: ReturnFieldArgs) -> 
Result<FieldRef> {
+        self.inner.return_field_from_args(args)
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        invoke_list_builder(&self.inner, args, |args, last_value_wins| match 
args {
+            [ColumnarValue::Array(entries)] => 
validate_map_from_entries(entries, last_value_wins),
+            other => exec_err!("map_from_entries expects 1 argument, got {}", 
other.len()),
+        })
+    }
+}
+
+/// Spark-compatible `str_to_map(text[, pair_delim[, key_value_delim]])`.
+#[derive(Debug, Default, PartialEq, Eq, Hash)]
+pub struct SparkStrToMap {
+    inner: DataFusionStrToMap,
+}
+
+impl ScalarUDFImpl for SparkStrToMap {
+    fn name(&self) -> &str {
+        self.inner.name()
+    }
+
+    fn signature(&self) -> &Signature {
+        self.inner.signature()
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        self.inner.return_type(arg_types)
+    }
+
+    fn return_field_from_args(&self, args: ReturnFieldArgs) -> 
Result<FieldRef> {
+        self.inner.return_field_from_args(args)
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        // Splitting a string cannot produce a NULL key, so only the 
duplicate-key error needs
+        // restating here.
+        self.inner
+            .invoke_with_args(args)
+            .map_err(|error| as_spark_error(error, DuplicateKeyFormat::Quoted))
+    }
+}
+
+/// Runs `map_from_arrays` or `map_from_entries`: `validate` sees the 
arguments as arrays whose
+/// entries start at offset zero and rejects a `NULL` key, which the kernel 
would store without a
+/// word, then the kernel builds the maps and its own errors are restated.
+fn invoke_list_builder(
+    inner: &dyn ScalarUDFImpl,
+    mut args: ScalarFunctionArgs,
+    validate: impl FnOnce(&[ColumnarValue], bool) -> Result<()>,
+) -> Result<ColumnarValue> {
+    // The kernel evaluates an all-scalar call once and returns a scalar, 
which DataFusion then
+    // broadcasts to the batch; build that one row here too rather than 
`number_rows` copies.
+    let all_scalar = args
+        .args
+        .iter()
+        .all(|arg| matches!(arg, ColumnarValue::Scalar(_)));
+    if all_scalar {
+        args.number_rows = 1;
+    }
+    expand_scalars(&mut args)?;
+    rebase_sliced_lists(&mut args)?;
+    let last_value_wins =
+        args.config_options.spark.map_key_dedup_policy == 
MapKeyDedupPolicy::LastWin;
+    validate(&args.args, last_value_wins)?;
+    let result = inner
+        .invoke_with_args(args)
+        .map_err(|error| as_spark_error(error, DuplicateKeyFormat::Bare))?;
+    match (all_scalar, result) {
+        (true, ColumnarValue::Array(array)) => Ok(ColumnarValue::Scalar(
+            ScalarValue::try_from_array(&array, 0)?,
+        )),
+        (_, result) => Ok(result),
+    }
+}
+
+/// Materializes scalar arguments at `number_rows`, so the validation indexes 
rows the same way
+/// the kernel does.
+fn expand_scalars(args: &mut ScalarFunctionArgs) -> Result<()> {
+    let number_rows = args.number_rows;
+    for arg in args.args.iter_mut() {
+        if let ColumnarValue::Scalar(scalar) = arg {
+            *arg = ColumnarValue::Array(scalar.to_array_of_size(number_rows)?);
+        }
+    }
+    Ok(())
+}
+
+/// Rebases a list argument whose entries do not start at offset zero, which 
the kernels mishandle
+/// (apache/datafusion#25419): they read each row's entries at its own offset 
but apply the mask
+/// that selects the surviving keys from the start of the list's values, so a 
list sliced past its
+/// first row pairs values with keys from earlier rows. A `LIMIT ... OFFSET` 
above a projection is
+/// enough to produce one. A slice that only drops trailing rows needs 
nothing, since Arrow's
+/// `filter` accepts a predicate shorter than the array it filters. Shifting 
the offsets and slicing
+/// the values leaves the data where it is.
+///
+/// Delete once Comet moves to a DataFusion release carrying 
apache/datafusion#25431.
+fn rebase_sliced_lists(args: &mut ScalarFunctionArgs) -> Result<()> {
+    for arg in args.args.iter_mut() {
+        let ColumnarValue::Array(array) = arg else {
+            continue;
+        };
+        let (DataType::List(field), Some(list)) = (array.data_type(), 
array.as_list_opt::<i32>())
+        else {
+            continue;
+        };
+        let offsets = list.value_offsets();
+        let (first, last) = (offsets[0], offsets[offsets.len() - 1]);
+        if first == 0 {
+            continue;
+        }
+        let rebased = ListArray::try_new(
+            Arc::clone(field),
+            OffsetBuffer::new(offsets.iter().map(|offset| offset - 
first).collect()),
+            list.values().slice(first as usize, (last - first) as usize),
+            list.nulls().cloned(),
+        )?;
+        *arg = ColumnarValue::Array(Arc::new(rebased));
+    }
+    Ok(())
+}
+
+/// Rejects a `NULL` key in a row `map_from_arrays` builds a map from, raising 
what Spark raises
+/// for that row. The kernel already checks each row's lengths and duplicate 
keys in Spark's order,
+/// so a batch where no such row holds a `NULL` key is left to it. A row whose 
keys or values array
+/// is NULL gives a NULL map before Spark builds anything, so its keys do not 
count.
+fn validate_map_from_arrays(
+    keys: &ArrayRef,
+    values: &ArrayRef,
+    last_value_wins: bool,
+) -> Result<()> {
+    // A `NULL`-typed argument makes every row a NULL map, which never reaches 
the builder.
+    if matches!(keys.data_type(), DataType::Null) || 
matches!(values.data_type(), DataType::Null) {
+        return Ok(());
+    }
+    let (keys, values) = (as_list(keys)?, as_list(values)?);
+    let Some(key_nulls) = key_nulls(keys.values()) else {
+        return Ok(());
+    };
+    let (key_offsets, value_offsets) = (keys.value_offsets(), 
values.value_offsets());
+    let row_is_built = |row: usize| keys.is_valid(row) && values.is_valid(row);
+    let Some(failing_row) = first_row_with_null_key(&key_nulls, key_offsets, 
row_is_built) else {
+        return Ok(());
+    };
+    // `failing_row` fails one way or another, so walk the rows up to it in 
Spark's order: a row's
+    // lengths are checked before any of its keys.
+    let mut seen = HashSet::new();
+    for row in (0..=failing_row).filter(|&row| row_is_built(row)) {
+        let (start, end) = (key_offsets[row] as usize, key_offsets[row + 1] as 
usize);
+        if end - start != (value_offsets[row + 1] - value_offsets[row]) as 
usize {
+            return Err(SparkError::MapKeyValueDiffSizes.into());
+        }
+        check_keys_in_order(
+            keys.values(),
+            start,
+            end,
+            &key_nulls,
+            last_value_wins,
+            &mut seen,
+        )?;
+    }
+    Ok(())
+}
+
+/// Rejects a `NULL` key in a row `map_from_entries` builds a map from, 
raising what Spark raises
+/// for that row. A row is not built when its entries array is NULL or holds a 
NULL `struct`
+/// element: Spark returns a NULL map for both without inserting any entry.
+fn validate_map_from_entries(entries: &ArrayRef, last_value_wins: bool) -> 
Result<()> {
+    if matches!(entries.data_type(), DataType::Null) {
+        return Ok(());
+    }
+    let entries = as_list(entries)?;
+    let Some(structs) = entries.values().as_struct_opt() else {
+        return exec_err!(
+            "map_from_entries: expected array<struct<key, value>>, got {:?}",
+            entries.values().data_type()
+        );
+    };
+    let keys = structs.column(0);
+    let Some(key_nulls) = key_nulls(keys) else {
+        return Ok(());
+    };
+    // Only a `NULL` key inside a non-NULL entry can fail, and one AND and a 
popcount rule that
+    // out, which covers the common batch whose only `NULL` keys sit under 
`NULL` entries.
+    let entry_nulls = structs.nulls();
+    let null_entries = entry_nulls.map_or(0, NullBuffer::null_count);
+    let null_entries_or_keys =
+        NullBuffer::union(Some(&key_nulls), entry_nulls).map_or(0, |nulls| 
nulls.null_count());
+    if null_entries_or_keys == null_entries {
+        return Ok(());
+    }
+    let offsets = entries.value_offsets();
+    let row_is_built = |row: usize| {
+        let (start, end) = (offsets[row] as usize, offsets[row + 1] as usize);
+        entries.is_valid(row)
+            && entry_nulls.is_none_or(|nulls| nulls.slice(start, end - 
start).null_count() == 0)
+    };
+    let Some(failing_row) = first_row_with_null_key(&key_nulls, offsets, 
row_is_built) else {
+        return Ok(());
+    };
+    let mut seen = HashSet::new();
+    for row in (0..=failing_row).filter(|&row| row_is_built(row)) {
+        let (start, end) = (offsets[row] as usize, offsets[row + 1] as usize);
+        check_keys_in_order(keys, start, end, &key_nulls, last_value_wins, 
&mut seen)?;
+    }
+    Ok(())
+}
+
+/// The first row that `row_is_built` accepts and whose keys include a `NULL`.
+fn first_row_with_null_key(
+    key_nulls: &NullBuffer,
+    offsets: &[i32],
+    row_is_built: impl Fn(usize) -> bool,
+) -> Option<usize> {
+    (0..offsets.len() - 1).find(|&row| {
+        let (start, end) = (offsets[row] as usize, offsets[row + 1] as usize);
+        key_nulls.slice(start, end - start).null_count() > 0 && 
row_is_built(row)
+    })
+}
+
+/// Walks one row's keys in the order Spark's `ArrayBasedMapBuilder` inserts 
them, so whichever of
+/// a `NULL` key and a duplicate key comes first is the one reported, as Spark 
reports it.
+fn check_keys_in_order(
+    keys: &ArrayRef,
+    start: usize,
+    end: usize,
+    key_nulls: &NullBuffer,
+    last_value_wins: bool,
+    seen: &mut HashSet<ScalarValue>,
+) -> Result<()> {
+    seen.clear();
+    for index in start..end {
+        if key_nulls.is_null(index) {
+            return Err(SparkError::NullMapKey.into());
+        }
+        // `LAST_WIN` overwrites a duplicate rather than raising, so only the 
`NULL` check is
+        // left to do in that mode.
+        if last_value_wins {
+            continue;
+        }
+        let key = ScalarValue::try_from_array(keys, index)?.compacted();
+        if let Some(duplicate) = seen.replace(key) {
+            return Err(SparkError::DuplicatedMapKey {
+                key: duplicate.to_string(),
+            }
+            .into());
+        }
+    }
+    Ok(())
+}
+
+/// Comet hands every Spark `ArrayType` to native code as a `List`.
+fn as_list(array: &ArrayRef) -> Result<&ListArray> {
+    match array.as_list_opt::<i32>() {
+        Some(list) => Ok(list),
+        None => exec_err!("expected a list argument, got {:?}", 
array.data_type()),
+    }
+}
+
+/// The nulls of a map key array, or `None` when no key is `NULL`. Logical 
nulls, so a `NullArray`
+/// (which has no null buffer) and a dictionary whose values hold a `NULL` 
count too.
+fn key_nulls(keys: &ArrayRef) -> Option<NullBuffer> {
+    keys.logical_nulls().filter(|nulls| nulls.null_count() > 0)
+}
+
+/// How the upstream kernel renders the offending key in its duplicate-key 
message.
+#[derive(Clone, Copy)]
+enum DuplicateKeyFormat {
+    /// The map builders write the key unquoted, as Spark does.
+    Bare,
+    /// `str_to_map` single-quotes it.
+    Quoted,
+}
+
+/// The message the kernels' shared map builder raises for a row whose key and 
value arrays differ
+/// in length.
+const LENGTH_MISMATCH_MESSAGE: &str =
+    "keys and values lists in the same row must have equal lengths";
+
+/// Restates the upstream length-mismatch and duplicate-key errors as 
`SparkError`s, so the JVM
+/// side raises Spark's own errors (naming the same key, for a duplicate). Any 
other error is
+/// passed through. The `*_reports_*` tests pin the wordings parsed here 
against the kernels
+/// themselves, so an upstream rewording fails there rather than silently 
downgrading the error to
+/// a generic execution failure.
+fn as_spark_error(error: DataFusionError, key_format: DuplicateKeyFormat) -> 
DataFusionError {
+    let message = error.to_string();
+    if message.contains(LENGTH_MISMATCH_MESSAGE) {

Review Comment:
   Could we check the duplicate marker first? A duplicate key containing this 
phrase gives me the length error instead of `DUPLICATED_MAP_KEY`.



##########
spark/src/main/scala/org/apache/comet/serde/maps.scala:
##########
@@ -134,97 +135,132 @@ object CometMapExtract extends 
CometExpressionSerde[GetMapValue] {
 }
 
 /**
- * Shared gate for the native map builders, `map_from_arrays` and 
`map_from_entries`, which tell
- * keys apart by their bits. A key type that holds a float at any depth is 
`Incompatible` on every
- * Spark version; `floatingPointReason` explains why.
+ * Shared gate for the native map constructors (`map_from_arrays`, 
`map_from_entries`), which
+ * reproduce Spark's `ArrayBasedMapBuilder`, including 
`spark.sql.mapKeyDedupPolicy`. The
+ * map_funcs expression audit covers how, and where they still differ from 
Spark.
  */
-private object MapBuilderKeySupport {
-  val floatingPointReason: String =
-    "Spark finds duplicate map keys that hold a `FLOAT` or `DOUBLE` by value, 
so NaNs with " +
-      "different bits are one key, and so are `-0.0` and `0.0` inside a struct 
or array key. " +
-      "From Spark 4.0, a `-0.0` key is also normalized to `0.0`, unless " +
-      "`spark.sql.legacy.disableMapKeyNormalization` is set. Comet's native 
map construction " +
-      "compares the keys' bits 
([#6549](https://github.com/apache/datafusion-comet/issues/6549))."
-
-  def hasFloatingPointKey(dataType: MapType): Boolean =
-    SupportLevel.containsType(dataType.keyType, classOf[FloatType], 
classOf[DoubleType])
-}
+private object MapBuilderSupport {
+
+  /** Top-level floating-point keys: see the map_funcs expression audit. */
+  val floatingPointKeyNote: String =
+    "Comet's native map construction compares a `FLOAT` or `DOUBLE` map key by 
its raw bits. " +
+      "On every Spark version, Spark treats `NaN`s with different bit patterns 
as one key, " +
+      "where Comet keeps them apart. On Spark 4.0 and later, 
`ArrayBasedMapBuilder` also " +
+      "normalizes the key before it compares it, so `-0.0` and `+0.0` are one 
key. Where Spark " +
+      "reports a duplicate key, or keeps one entry under `LAST_WIN`, Comet 
keeps both entries. " +
+      "`map_from_entries` on Spark 4.0 and later also stores the normalized 
key, so Spark " +
+      "returns `+0.0` for a `-0.0` key where Comet returns `-0.0`. 
`map_from_arrays` keeps the " +
+      "original keys in both engines when no key repeats. Spark 3.4 and 3.5 do 
not normalize " +
+      "the key, so `-0.0` and `+0.0` are two keys in both engines there. This 
applies to a " +
+      "top-level key only: a struct or array key that contains a 
floating-point field does not " +
+      "run natively by default on any Spark version. Set " +
+      s"`${COMET_EXEC_STRICT_FLOATING_POINT.key}=true` to keep a 
floating-point map key off " +
+      "the native path."
+
+  val strictFloatingPointKeyReason: String =
+    s"When `${COMET_EXEC_STRICT_FLOATING_POINT.key}=true`, map construction on 
a floating-point " +
+      "key is not 100% compatible with Spark"
 
-private object MapKeyDedupPolicySupport {
-  val incompatibleReason: String =
-    s"`${SQLConf.MAP_KEY_DEDUP_POLICY.key}` is set to " +
-      s"`${SQLConf.MapKeyDedupPolicy.LAST_WIN}`; Comet's native map 
construction " +
-      "does not implement LAST_WIN dedup semantics."
-
-  val nullKeyReason: String =
-    "Spark rejects a `NULL` element inside the keys array with a 
`RuntimeException`" +
-      " (`Cannot use null as map key`); Comet's native `map_from_arrays` / 
`map_from_entries`" +
-      " does not detect a per-element `NULL` key and produces a map with a 
`NULL` key instead" +
-      " ([#4680](https://github.com/apache/datafusion-comet/issues/4680))."
-
-  def isLastWin: Boolean =
-    SQLConf.get
-      .getConf(SQLConf.MAP_KEY_DEDUP_POLICY)
-      .toString
-      .equalsIgnoreCase(SQLConf.MapKeyDedupPolicy.LAST_WIN.toString)
+  /**
+   * `ArrayBasedMapBuilder` keys its dedup map on 
`TypeUtils.getInterpretedOrdering` once the key
+   * type contains a string, so under `UTF8_LCASE` the keys `'a'` and `'A'` 
are one key. The
+   * native builders compare the raw Arrow bytes and would keep both, missing 
the duplicate that
+   * Spark reports (or, under `LAST_WIN`, the overwrite Spark performs). 
`MapKeySupport` declines
+   * a collated key for `map_extract` for the same reason.
+   */
+  val collationKeyReason: String =
+    "Comet's native map construction compares string keys as `UTF8_BINARY`, so 
it cannot honour " +
+      "a non-default collation when it looks for a duplicate key."
+
+  /**
+   * On every Spark version, `ArrayBasedMapBuilder` keys its dedup map for a 
struct or array key
+   * type on `TypeUtils.getInterpretedOrdering`, whose 
`SQLOrderingUtil.compareDoubles` and
+   * `compareFloats` treat `-0.0` and `+0.0` as equal and all `NaN`s as equal. 
The native builders
+   * hash the nested values by their bits and would keep both keys, missing 
the duplicate that
+   * Spark reports (or, under `LAST_WIN`, the overwrite Spark performs).
+   */
+  val nestedFloatingPointKeyReason: String =
+    "Spark finds duplicate struct or array keys by interpreted ordering, where 
`-0.0` equals " +
+      "`+0.0` and all `NaN`s are equal; Comet's native map construction 
compares the nested " +
+      "floating-point values bit by bit."
+
+  /** The support level for a map constructor whose result has key type 
`keyType`. */
+  def keySupport(keyType: DataType): SupportLevel =
+    if (hasNonDefaultStringCollation(keyType)) {
+      Incompatible(Some(collationKeyReason))
+    } else if (isComplexType(keyType) &&
+      SupportLevel.containsType(keyType, classOf[FloatType], 
classOf[DoubleType])) {
+      Incompatible(Some(nestedFloatingPointKeyReason))
+    } else {
+      SupportLevel

Review Comment:
   Could we restore #6992's `hasFloatingPointKey` gate, which the 10-18 merge 
dropped? `map_from_arrays` with keys `0.0` and `-0.0` now gives me a map 
instead of `DUPLICATED_MAP_KEY`.



-- 
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]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to