andygrove commented on code in PR #7722: URL: https://github.com/apache/datafusion-comet/pull/7722#discussion_r4745901169
########## native/spark-expr/src/map_funcs/float_map.rs: ########## @@ -0,0 +1,510 @@ +// 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 std::{hash::Hash, sync::Arc}; + +use arrow::array::{ + make_array, Array, ArrayRef, AsArray, Int32Array, ListArray, MapArray, MutableArrayData, + NullBufferBuilder, PrimitiveArray, StructArray, +}; +use arrow::buffer::{NullBuffer, OffsetBuffer}; +use arrow::compute::take; +use arrow::datatypes::{ArrowPrimitiveType, DataType, Field, FieldRef, Float32Type, Float64Type}; +use datafusion::common::cast::{as_list_array, as_struct_array}; +use datafusion::common::{exec_err, internal_err, HashMap, Result, ScalarValue}; +use datafusion::logical_expr::function::Hint; +use datafusion::logical_expr::{ + ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature, + Volatility, +}; +use datafusion_functions::utils::make_scalar_function; +use datafusion_spark::function::map::{ + map_from_arrays::MapFromArrays, map_from_entries::MapFromEntries, +}; + +use crate::conversion_funcs::{java_float_string, JavaFloatString}; +use crate::float_semantics::{canonicalize_nan, normalize_float}; +use crate::SparkError; + +/// Spark map construction for a top-level FLOAT or DOUBLE key. +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkFloatMap { + signature: Signature, +} + +impl Default for SparkFloatMap { + fn default() -> Self { + Self { + signature: Signature::one_of( + vec![TypeSignature::Any(3), TypeSignature::Any(4)], + Volatility::Immutable, + ), + } + } +} + +impl SparkFloatMap { + fn build(&self, args: &[ArrayRef], normalize: bool, last_win: bool) -> Result<ArrayRef> { + let input = match args { + [keys, values] => { + let keys = as_list_array(keys)?; + let values = as_list_array(values)?; + MapInput { + key_rows: keys, + value_rows: values, + keys: keys.values(), + values: values.values(), + entry_nulls: None, + from_arrays: true, + } + } + [rows] => { + let rows = as_list_array(rows)?; + let entries = as_struct_array(rows.values())?; + let [keys, values] = entries.columns() else { + return exec_err!("{}: expected key-value pairs", self.name()); + }; + MapInput { + key_rows: rows, + value_rows: rows, + keys, + values, + entry_nulls: entries.nulls(), + from_arrays: false, + } + } + _ => return exec_err!("{}: expected one or two arguments", self.name()), + }; + match input.keys.data_type() { + DataType::Float32 => { + Self::build_typed::<Float32Type, _>(input, normalize, last_win, f32::to_bits) + } + DataType::Float64 => { + Self::build_typed::<Float64Type, _>(input, normalize, last_win, f64::to_bits) + } + dt => exec_err!("{}: expected floating-point keys, got {dt}", self.name()), + } + } + + fn build_typed<T, Bits>( + input: MapInput, + normalize: bool, + last_win: bool, + bits: impl Fn(T::Native) -> Bits, + ) -> Result<ArrayRef> + where + T: ArrowPrimitiveType, + T::Native: JavaFloatString, + Bits: Eq + Hash, + { + let keys = input.keys.as_primitive::<T>(); + let key_offsets = input.key_rows.value_offsets(); + let value_offsets = input.value_rows.value_offsets(); + let first_key = key_offsets[0] as usize; + let first_value = value_offsets[0]; + let raw_keys = &keys.values()[first_key..]; + let num_rows = match input.key_rows.len() { + 1 => input.value_rows.len(), + n => n, + }; + + // Both outputs start as slices of the input. Materialize each independently once + // a changed key or a non-contiguous value breaks that invariant. + let mut output_keys = None; + let mut value_indices = None; + let mut len = 0; + let mut offsets = Vec::with_capacity(num_rows + 1); + let mut nulls = NullBufferBuilder::new(num_rows); + let mut positions = HashMap::new(); + for row in 0..num_rows { + let key_row = if input.key_rows.len() == 1 { 0 } else { row }; + let value_row = if input.value_rows.len() == 1 { 0 } else { row }; + let start = len; + offsets.push(start as i32); + let key_range = key_offsets[key_row] as usize..key_offsets[key_row + 1] as usize; + let value_range = value_offsets[value_row]..value_offsets[value_row + 1]; + let count = key_range.len(); + if input.key_rows.is_null(key_row) + || input.value_rows.is_null(value_row) + || input + .entry_nulls + .is_some_and(|nulls| nulls.slice(key_range.start, count).null_count() != 0) + { + nulls.append_null(); + continue; + } + nulls.append_non_null(); + if count != value_range.len() { + return Err(SparkError::MapKeyValueDiffSizes.into()); + } + + if count == 0 { + continue; + } + + positions.clear(); + // Reuse the table across varied row sizes but bound clear costs after an outlier. + if positions.capacity() > count.saturating_mul(8) { + positions.shrink_to(count); + } + for (i, value_index) in key_range.zip(value_range) { + if keys.is_null(i) { + return Err(SparkError::NullMapKey.into()); + } + let key = keys.value(i); + let compared = if normalize { + normalize_float(key) + } else { + canonicalize_nan(key) + }; + let slot = *positions.entry(bits(compared)).or_insert(len); + let prefix_len = len; + if slot == len { + let stored = if normalize && !input.from_arrays { + compared + } else { + key + }; + if i != first_key + len || bits(stored) != bits(key) { + output_keys.get_or_insert_with(|| raw_keys[..len].to_vec()); + } + if let Some(keys) = &mut output_keys { + keys.push(stored); + } + len += 1; + } else if !last_win { + return Err(SparkError::DuplicatedMapKey { + key: java_float_string(key), + key_type: T::DATA_TYPE.to_string(), + } + .into()); + } + + if value_indices.is_some() || (value_index - first_value) as usize != slot { + let indices = value_indices.get_or_insert_with(|| { + (first_value..first_value + prefix_len as i32).collect::<Vec<_>>() + }); + indices.resize(len, value_index); + indices[slot] = value_index; + } + } + // ArrayBasedMapBuilder.from returns the original arrays if all keys are unique. + // Once LAST_WIN collapses a duplicate, it builds the entire row with normalized keys. + if input.from_arrays && normalize && len - start < count { + let out = output_keys.get_or_insert_with(|| raw_keys[..len].to_vec()); + for key in &mut out[start..] { + *key = normalize_float(*key); + } + } + } + offsets.push(len as i32); + let keys = match output_keys { + Some(keys) => PrimitiveArray::<T>::new(keys.into(), None), + None => keys.slice(first_key, len), + }; + let values = match value_indices { + // take_list assumes the child offsets fit i32 and sizes its buffer using even + // discarded values. For repeated lists, copy only the selected ranges with + // checked offsets at each nesting level. + Some(indices) + if input.value_rows.len() == 1 + && num_rows > 1 + && matches!(input.values.data_type(), DataType::List(_)) => + { + let list = input.values.as_list::<i32>(); + let count: usize = indices + .iter() + .map(|&i| list.value_length(i as usize) as usize) + .sum(); + if count > i32::MAX as usize { + return Err(arrow::error::ArrowError::OffsetOverflowError(count).into()); + } + let data = list.to_data(); + let mut out = MutableArrayData::new(vec![&data], false, indices.len()); + for i in indices { + let i = i as usize; + out.try_extend(0, i, i + 1)?; + } + make_array(out.freeze()) + } + Some(indices) => take(input.values, &Int32Array::from(indices), None)?, + None => input.values.slice(first_value as usize, len), + }; + let fields = vec![ + Field::new("key", keys.data_type().clone(), false), + Field::new("value", values.data_type().clone(), true), + ]; + let entries = StructArray::try_new(fields.into(), vec![Arc::new(keys), values], None)?; + Ok(Arc::new(MapArray::try_new( + Arc::new(Field::new("entries", entries.data_type().clone(), false)), + OffsetBuffer::new(offsets.into()), + entries, + nulls.finish(), + false, + )?)) + } +} + +struct MapInput<'a> { + from_arrays: bool, + key_rows: &'a ListArray, + value_rows: &'a ListArray, + keys: &'a ArrayRef, + values: &'a ArrayRef, + entry_nulls: Option<&'a NullBuffer>, +} + +impl ScalarUDFImpl for SparkFloatMap { + fn name(&self) -> &str { + "spark_float_map" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _: &[DataType]) -> Result<DataType> { + internal_err!("return_field_from_args should be used instead") + } + + fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> { + let [fields @ .., _, _] = args.arg_fields else { + return exec_err!("{}: missing map settings", self.name()); + }; + let args = ReturnFieldArgs { + arg_fields: fields, + scalar_arguments: args + .scalar_arguments + .get(..fields.len()) + .unwrap_or_default(), + }; + match fields { + [_] => MapFromEntries::default().return_field_from_args(args), + [_, _] => MapFromArrays::default().return_field_from_args(args), + _ => exec_err!("{}: expected one or two arguments", self.name()), + } + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { + use ColumnarValue::Scalar; + use ScalarValue::Boolean; + + let [inputs @ .., Scalar(Boolean(Some(normalize))), Scalar(Boolean(Some(last_win)))] = + args.args.as_slice() + else { + return exec_err!("{}: expected constant boolean map settings", self.name()); + }; + if inputs.iter().any( + |arg| matches!(arg, ColumnarValue::Array(array) if array.len() != args.number_rows), + ) { + return exec_err!("{}: expected length {}", self.name(), args.number_rows); + } + // Reuse the scalar list across rows so LAST_WIN only copies surviving values. + make_scalar_function( + |args| self.build(args, *normalize, *last_win), + vec![Hint::AcceptsSingular; inputs.len()], + )(inputs) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow::array::{Float32Array, Float64Array, StringArray}; + use datafusion::common::utils::SingleRowListArrayBuilder; + + fn sliced_rows(values: ArrayRef, lengths: [usize; 4]) -> ArrayRef { + let rows = ListArray::new( + Arc::new(Field::new("item", values.data_type().clone(), true)), + OffsetBuffer::from_lengths(lengths), + values, + None, + ); + Arc::new(rows.slice(1, 3)) + } + + #[test] + fn scalar_values_are_shared_until_gathering_surviving_entries() { + let strings = StringArray::from(vec!["first", "last"]); + let values = SingleRowListArrayBuilder::new(Arc::new(strings.clone())).build_list_scalar(); + let keys = ListArray::from_iter_primitive::<Float32Type, _, _>([ + Some([Some(1.0), Some(2.0)]), + None, + Some([Some(3.0), Some(3.0)]), + Some([Some(4.0), Some(4.0)]), + ]); + let invoke = |start| { + SparkFloatMap::default() + .invoke_with_args(ScalarFunctionArgs { + args: vec![ + ColumnarValue::Array(Arc::new(keys.slice(start, 2))), + ColumnarValue::Scalar(values.clone()), + ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))), + ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))), + ], + arg_fields: vec![], + number_rows: 2, + return_field: Arc::new(Field::new("result", DataType::Null, true)), + config_options: Default::default(), + }) + .unwrap() + .into_array_of_size(2) + .unwrap() + }; + let result = invoke(0); + let retained = result.as_map().values().as_string::<i32>(); + assert!(retained.values().ptr_eq(strings.values())); + assert!(result.as_map().is_null(1)); + + let result = invoke(2); + assert_eq!( + result.as_map().values().as_string::<i32>(), + &StringArray::from(vec!["last", "last"]) + ); + } + + #[test] + fn repeated_list_values_check_only_surviving_child_offsets() { + // NullArray represents this length without allocating a values buffer. + let list = ListArray::new( + Arc::new(Field::new("item", DataType::Null, true)), + OffsetBuffer::from_lengths([1 << 30, 1]), + Arc::new(arrow::array::NullArray::new((1 << 30) + 1)), + None, + ); + let values: ArrayRef = Arc::new(ListArray::new( + Arc::new(Field::new("item", list.data_type().clone(), true)), + OffsetBuffer::from_lengths([2]), + Arc::new(list), + None, + )); + let build = |second_key| { + let keys = ListArray::from_iter_primitive::<Float32Type, _, _>( + [Some([Some(1.0), Some(second_key)]); 2], + ); + SparkFloatMap::default().build(&[Arc::new(keys), values.clone()], true, true) Review Comment: `cargo clippy --all-targets --workspace -- -D warnings` fails here because `values.clone()` on an `ArrayRef` trips `clippy::clone_on_ref_ptr`, which `native/spark-expr/src/lib.rs` denies. This is what fails `rust-test`. Could this be `Arc::clone(&values)`? ########## spark/src/main/scala/org/apache/comet/serde/maps.scala: ########## @@ -133,34 +135,106 @@ 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. - */ 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]) + def convertFloatMap( + expr: Expression, + inputs: Seq[Attribute], + binding: Boolean): Option[ExprOuterClass.Expr] = { + val normalize = isSpark40Plus && + !SQLConf.get + .getConfString("spark.sql.legacy.disableMapKeyNormalization", "false") + .trim + .toBoolean + val args = + expr.children ++ Seq(Literal(normalize), Literal(MapKeyDedupPolicySupport.isLastWin)) + val native = scalarFunctionExprToProto( + "spark_float_map", + args.map(exprToProtoInternal(_, inputs, binding)): _*) + withNullShortCircuit(expr, native).orElse { + CometScalaUDF.emitJvmCodegenDispatch(expr, inputs, binding) + } + } + + val nestedFloatingPointReason: String = + "Spark compares a `FLOAT` or `DOUBLE` inside a struct or array key using SQL ordering, " + + "where signed zeros are equal and all NaNs are equal. Comet's native map builders " + + "compare their bits for these nested keys." + + def isFloatingPoint(keyType: DataType): Boolean = + keyType == FloatType || keyType == DoubleType + + private def isColumn(expr: Expression): Boolean = expr match { + case _: AttributeReference | _: BoundReference => true + case field: GetStructField => isColumn(field.child) + case _ => false + } + + // Spark codegen emits canonical NaNs for scalar literals. Java serialization does the same + // for the boxed elements of folded GenericArrayData. Protobuf preserves their raw bits. + private def sparkPreservesLiteralBits(value: Any): Boolean = value match { + case f: Float => java.lang.Float.floatToRawIntBits(f) == java.lang.Float.floatToIntBits(f) + case d: Double => + java.lang.Double.doubleToRawLongBits(d) == java.lang.Double.doubleToLongBits(d) + case a: GenericArrayData => a.array.forall(sparkPreservesLiteralBits) + case _ => true + } + + // Constructors evaluate their children across the batch and can broadcast a large value + // before LAST_WIN discards it. Only build entries from fixed-width, eagerly evaluable fields. + private def safeElement(expr: Expression): Boolean = expr match { Review Comment: viirya and comphead both asked what `safeElement` and `safeInput` protect beyond `withNullShortCircuit`, and the thread has no answer yet. For int and string keys `CometMapFromArrays.convert` serializes `expr.left` and `expr.right` with no such check, so the same `map_from_arrays(array(<wide value>, ...), ...)` is native for one key type and dispatched for another. Do you have a measurement that shows the expansion matters, and native against dispatch numbers? Without one, could the restriction be dropped? For the `ArraysZip` case, could `CometArraysZip.convert` evaluate each child once, so the gate and its paragraph in `floating-point.md` can go? ########## spark/src/test/scala/org/apache/comet/CometMapExpressionSuite.scala: ########## @@ -261,6 +294,44 @@ class CometMapExpressionSuite extends CometTestBase { } } + test("float map builders use the settings captured when planning") { + assume(isSpark40Plus) + val policy = SQLConf.MAP_KEY_DEDUP_POLICY.key + val disableNormalization = "spark.sql.legacy.disableMapKeyNormalization" + withParquetTable(Seq((Seq(0.0, -0.0), Seq(1, 2))), "zero_keys") { + withSQLConf( + SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false", + policy -> "LAST_WIN", + disableNormalization -> "false") { + val df = sql( + "SELECT map_values(map_from_arrays(_1, _2)), " + + "map_values(map_from_entries(arrays_zip(_1, _2))) FROM zero_keys") + assertExpressionImpl( + df.queryExecution.executedPlan, + Seq("map_from_arrays", "map_from_entries"), + Seq.empty) + withSQLConf(policy -> "EXCEPTION", disableNormalization -> "true") { + assert(df.collect().toSeq == Seq(Row(Seq(2), Seq(2)))) Review Comment: I ran this against Spark. With the plan built under `LAST_WIN` and normalization on, and the collect run under `EXCEPTION` and `disableMapKeyNormalization=true`, Spark returns `Seq(1, 2)` for both columns where Comet returns `Seq(2)`. The docs call this unsupported, so this assertion makes a known divergence part of the test contract. Could the final `collect` assertion go, keeping the `assertExpressionImpl` check on the planned query, or could the test be renamed to say it pins current behavior? -- 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]
