viirya commented on code in PR #7717:
URL: https://github.com/apache/datafusion-comet/pull/7717#discussion_r4699816558


##########
native/spark-expr/src/array_funcs/array_position.rs:
##########
@@ -15,300 +15,108 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use std::sync::Arc;
+
+use super::array_match::{invoke_match, MatchOperation, MatchRows};
+use crate::float_semantics::spark_equality_by_ordinal;
 use arrow::array::{
-    make_comparator, Array, ArrayRef, AsArray, BooleanArray, GenericListArray, 
Int64Array,
-    OffsetSizeTrait,
-};
-use arrow::buffer::{NullBuffer, ScalarBuffer};
-use arrow::compute::SortOptions;
-use arrow::datatypes::{
-    ArrowPrimitiveType, DataType, Date32Type, Decimal128Type, Float32Type, 
Float64Type, Int16Type,
-    Int32Type, Int64Type, Int8Type, TimestampMicrosecondType,
+    Array, ArrayRef, AsArray, BooleanArray, Date32Array, Decimal128Array, 
GenericListArray,
+    Int16Array, Int32Array, Int64Array, Int8Array, LargeStringArray, 
OffsetSizeTrait, StringArray,
+    TimestampMicrosecondArray,
 };
-use datafusion::common::{exec_err, DataFusionError, Result as 
DataFusionResult, ScalarValue};
+use arrow::datatypes::{DataType, TimeUnit};
+use datafusion::common::{exec_err, Result};
 use datafusion::logical_expr::{
     ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, 
TypeSignature, Volatility,
 };
-use std::cmp::Ordering;
-use std::sync::Arc;
-
-use crate::float_semantics::{compare_floats, has_float_leaf, 
normalize_nested_floats};
-
-/// Spark array_position() function that returns the 1-based position of an 
element in an array.
-/// Returns 0 if the element is not found (Spark behavior differs from 
DataFusion which returns null).
-fn spark_array_position(args: &[ColumnarValue]) -> Result<ColumnarValue, 
DataFusionError> {
-    if args.len() != 2 {
-        return exec_err!("array_position function takes exactly two 
arguments");
-    }
-
-    let len = args
-        .iter()
-        .fold(Option::<usize>::None, |acc, arg| match arg {
-            ColumnarValue::Scalar(_) => acc,
-            ColumnarValue::Array(a) => Some(a.len()),
-        });
-
-    let is_scalar = len.is_none();
-    let arrays = ColumnarValue::values_to_arrays(args)?;
-
-    let result = array_position_inner(&arrays)?;
-
-    if is_scalar {
-        let scalar = ScalarValue::try_from_array(&result, 0)?;
-        Ok(ColumnarValue::Scalar(scalar))
-    } else {
-        Ok(ColumnarValue::Array(result))
-    }
-}
-
-fn array_position_inner(args: &[ArrayRef]) -> Result<ArrayRef, 
DataFusionError> {
-    let array = &args[0];
-    let element = &args[1];
 
+fn array_position(array: &ArrayRef, needle: &ColumnarValue) -> 
Result<ArrayRef> {
     match array.data_type() {
-        DataType::List(_) => generic_array_position::<i32>(array, element),
-        DataType::LargeList(_) => generic_array_position::<i64>(array, 
element),
+        DataType::List(_) => position(array.as_list::<i32>(), needle),
+        DataType::LargeList(_) => position(array.as_list::<i64>(), needle),
         other => exec_err!("array_position does not support type '{other:?}'"),
     }
 }
 
-/// Searches for an element in a list array using the flat values buffer and 
offsets directly,
-/// avoiding per-row subarray allocation. Dispatches to typed fast paths by 
element data type.
-fn generic_array_position<O: OffsetSizeTrait>(
-    array: &ArrayRef,
-    element: &ArrayRef,
-) -> Result<ArrayRef, DataFusionError> {
-    let list_array = array
-        .as_any()
-        .downcast_ref::<GenericListArray<O>>()
-        .ok_or_else(|| DataFusionError::Internal("expected list 
array".into()))?;
-
-    let values = list_array.values();
-    let offsets = list_array.offsets();
-    let elem_type = values.data_type().clone();
-
-    match &elem_type {
-        DataType::Boolean => position_boolean::<O>(list_array, offsets, 
values, element),
-        DataType::Int8 => position_primitive::<O, Int8Type>(list_array, 
offsets, values, element),
-        DataType::Int16 => position_primitive::<O, Int16Type>(list_array, 
offsets, values, element),
-        DataType::Int32 => position_primitive::<O, Int32Type>(list_array, 
offsets, values, element),
-        DataType::Int64 => position_primitive::<O, Int64Type>(list_array, 
offsets, values, element),
-        DataType::Float32 => position_float::<O, Float32Type>(list_array, 
offsets, values, element),
-        DataType::Float64 => position_float::<O, Float64Type>(list_array, 
offsets, values, element),
-        DataType::Decimal128(_, _) => {
-            position_primitive::<O, Decimal128Type>(list_array, offsets, 
values, element)
-        }
-        DataType::Date32 => {
-            position_primitive::<O, Date32Type>(list_array, offsets, values, 
element)
-        }
-        DataType::Timestamp(arrow::datatypes::TimeUnit::Microsecond, _) => {
-            position_primitive::<O, TimestampMicrosecondType>(list_array, 
offsets, values, element)
-        }
-        DataType::Utf8 => position_string::<O, i32>(list_array, offsets, 
values, element),
-        DataType::LargeUtf8 => position_string::<O, i64>(list_array, offsets, 
values, element),
-        // Fallback to Arrow's comparator for complex types (nested arrays, 
etc.)
-        _ => position_fallback::<O>(list_array, offsets, values, element),
-    }
-}
-
-/// Compute the combined null buffer from list array and element nulls.
-fn combined_nulls(
-    list_array_nulls: Option<&NullBuffer>,
-    element_nulls: Option<&NullBuffer>,
-) -> Option<NullBuffer> {
-    match (list_array_nulls, element_nulls) {
-        (Some(a), Some(b)) => NullBuffer::union(Some(a), Some(b)),
-        (Some(a), None) => Some(a.clone()),
-        (None, Some(b)) => Some(b.clone()),
-        (None, None) => None,
-    }
-}
-
-/// Fast path for primitive types: downcast once, iterate using offsets into 
the flat buffer.
-fn position_primitive<O: OffsetSizeTrait, T: ArrowPrimitiveType>(
-    list_array: &GenericListArray<O>,
-    offsets: &arrow::buffer::OffsetBuffer<O>,
-    values: &ArrayRef,
-    element: &ArrayRef,
-) -> Result<ArrayRef, DataFusionError>
-where
-    T::Native: PartialEq,
-{
-    let values_typed = values.as_primitive::<T>();
-    let element_typed = element.as_primitive::<T>();
-    let num_rows = list_array.len();
-    let nulls = combined_nulls(list_array.nulls(), element.nulls());
-    let mut result = vec![0i64; num_rows];
-
-    for (row_index, w) in offsets.windows(2).enumerate() {
-        if nulls.as_ref().is_some_and(|n| n.is_null(row_index)) {
-            continue;
-        }
-        let start = w[0].as_usize();
-        let end = w[1].as_usize();
-        let search_val = element_typed.value(row_index);
-        for i in start..end {
-            if !values_typed.is_null(i) && values_typed.value(i) == search_val 
{
-                result[row_index] = (i - start + 1) as i64;
-                break;
+fn position<O: OffsetSizeTrait>(
+    array: &GenericListArray<O>,
+    needle: &ColumnarValue,
+) -> Result<ArrayRef> {
+    let rows = MatchRows::new(array, needle)?;
+    let values = array.values();
+
+    // Only position needs typed non-float comparisons: contains and remove 
use DataFusion here.
+    macro_rules! typed_position {
+        ($ty:ty) => {
+            if let (Some(values), Some(needles)) = (
+                values.as_any().downcast_ref::<$ty>(),
+                rows.needles.as_any().downcast_ref::<$ty>(),
+            ) {
+                return SparkArrayPositionFunc::apply(&rows, |i, j| {
+                    values.value(i) == needles.value(j)
+                });
             }
-        }
-    }
-
-    Ok(Arc::new(Int64Array::new(ScalarBuffer::from(result), nulls)))
+        };
+    }
+    match values.data_type() {
+        DataType::Boolean => typed_position!(BooleanArray),
+        DataType::Int8 => typed_position!(Int8Array),
+        DataType::Int16 => typed_position!(Int16Array),
+        DataType::Int32 => typed_position!(Int32Array),
+        DataType::Int64 => typed_position!(Int64Array),
+        DataType::Decimal128(_, _) => typed_position!(Decimal128Array),
+        DataType::Date32 => typed_position!(Date32Array),
+        DataType::Timestamp(TimeUnit::Microsecond, _) => 
typed_position!(TimestampMicrosecondArray),
+        DataType::Utf8 => typed_position!(StringArray),
+        DataType::LargeUtf8 => typed_position!(LargeStringArray),
+        _ => {}
+    }
+    rows.evaluate::<SparkArrayPositionFunc>(spark_equality_by_ordinal)

Review Comment:
   Fair point. `SparkArrayPositionFunc` is public and takes `Any(2)`, so 
keeping the old ordinal matching for structs makes sense. The new comment 
explains it. Resolving.



##########
native/spark-expr/src/array_funcs/array_match.rs:
##########
@@ -0,0 +1,194 @@
+// 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.
+
+//! Element matching for Spark's array_contains, array_position and 
array_remove.
+
+use std::ops::Range;
+use std::sync::Arc;
+
+use crate::float_semantics::{compare_float_array_scalar, compare_floats, 
spark_equality};
+use arrow::array::{
+    Array, ArrayRef, AsArray, BooleanArray, GenericListArray, ListArray, 
OffsetSizeTrait,
+    PrimitiveArray,
+};
+use arrow::buffer::{BooleanBuffer, NullBuffer};
+use arrow::datatypes::{ArrowPrimitiveType, DataType, Float32Type, Float64Type};
+use datafusion::common::{exec_err, utils::take_function_args, Result, 
ScalarValue};
+use datafusion::logical_expr::{ColumnarValue, Operator, ScalarFunctionArgs, 
ScalarUDFImpl};
+use num::Float;
+
+pub(super) fn invoke_match(
+    udf: &impl ScalarUDFImpl,
+    args: ScalarFunctionArgs,
+    evaluate: impl FnOnce(&ArrayRef, &ColumnarValue) -> Result<ArrayRef>,
+) -> Result<ColumnarValue> {
+    let [array, needle] = take_function_args(udf.name(), &args.args)?;
+    let rows = match (array, needle) {
+        (_, ColumnarValue::Array(values)) => Some(values.len()),
+        (ColumnarValue::Array(list), _) => Some(list.len()),
+        _ => None,
+    };
+    let result = evaluate(&array.to_array_of_size(rows.unwrap_or(1))?, 
needle)?;
+    match rows {
+        None => Ok(ColumnarValue::Scalar(ScalarValue::try_from_array(
+            &result, 0,
+        )?)),
+        Some(_) => Ok(ColumnarValue::Array(result)),
+    }
+}
+
+/// Contains and remove can consume a bitmap for a scalar float. `IS [NOT] 
DISTINCT FROM`
+/// applies Spark's float equality and treats null elements as distinct from 
the non-null needle.
+pub(super) fn invoke_with_mask<M: ScalarUDFImpl + MatchOperation<i32>>(
+    udf: &M,
+    args: ScalarFunctionArgs,
+    op: Operator,
+    from_mask: impl FnOnce(&ListArray, &ArrayRef, BooleanBuffer) -> 
Result<ArrayRef>,
+) -> Result<ColumnarValue> {
+    invoke_match(udf, args, |array, needle| {
+        let Some(list) = array.as_list_opt::<i32>() else {
+            return exec_err!("{} takes a list, got {}", udf.name(), 
array.data_type());
+        };
+        // array_contains accepts a null scalar of any type. For array_remove, 
let
+        // the row matcher validate the element type even when the needle is 
null.
+        if op == Operator::IsNotDistinctFrom

Review Comment:
   Thanks, moving the null-scalar case into contains reads much better.



##########
native/spark-expr/src/array_funcs/array_match.rs:
##########
@@ -0,0 +1,194 @@
+// 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.
+
+//! Element matching for Spark's array_contains, array_position and 
array_remove.
+
+use std::ops::Range;
+use std::sync::Arc;
+
+use crate::float_semantics::{compare_float_array_scalar, compare_floats, 
spark_equality};
+use arrow::array::{
+    Array, ArrayRef, AsArray, BooleanArray, GenericListArray, ListArray, 
OffsetSizeTrait,
+    PrimitiveArray,
+};
+use arrow::buffer::{BooleanBuffer, NullBuffer};
+use arrow::datatypes::{ArrowPrimitiveType, DataType, Float32Type, Float64Type};
+use datafusion::common::{exec_err, utils::take_function_args, Result, 
ScalarValue};
+use datafusion::logical_expr::{ColumnarValue, Operator, ScalarFunctionArgs, 
ScalarUDFImpl};
+use num::Float;
+
+pub(super) fn invoke_match(
+    udf: &impl ScalarUDFImpl,
+    args: ScalarFunctionArgs,
+    evaluate: impl FnOnce(&ArrayRef, &ColumnarValue) -> Result<ArrayRef>,
+) -> Result<ColumnarValue> {
+    let [array, needle] = take_function_args(udf.name(), &args.args)?;
+    let rows = match (array, needle) {
+        (_, ColumnarValue::Array(values)) => Some(values.len()),
+        (ColumnarValue::Array(list), _) => Some(list.len()),
+        _ => None,
+    };
+    let result = evaluate(&array.to_array_of_size(rows.unwrap_or(1))?, 
needle)?;
+    match rows {
+        None => Ok(ColumnarValue::Scalar(ScalarValue::try_from_array(
+            &result, 0,
+        )?)),
+        Some(_) => Ok(ColumnarValue::Array(result)),
+    }
+}
+
+/// Contains and remove can consume a bitmap for a scalar float. `IS [NOT] 
DISTINCT FROM`
+/// applies Spark's float equality and treats null elements as distinct from 
the non-null needle.
+pub(super) fn invoke_with_mask<M: ScalarUDFImpl + MatchOperation<i32>>(
+    udf: &M,
+    args: ScalarFunctionArgs,
+    op: Operator,
+    from_mask: impl FnOnce(&ListArray, &ArrayRef, BooleanBuffer) -> 
Result<ArrayRef>,
+) -> Result<ColumnarValue> {
+    invoke_match(udf, args, |array, needle| {
+        let Some(list) = array.as_list_opt::<i32>() else {
+            return exec_err!("{} takes a list, got {}", udf.name(), 
array.data_type());
+        };
+        // array_contains accepts a null scalar of any type. For array_remove, 
let
+        // the row matcher validate the element type even when the needle is 
null.
+        if op == Operator::IsNotDistinctFrom
+            && matches!(needle, ColumnarValue::Scalar(value) if 
value.is_null())
+        {
+            return Ok(Arc::new(BooleanArray::new_null(list.len())));
+        }
+        if let ColumnarValue::Scalar(
+            value @ (ScalarValue::Float32(Some(_)) | 
ScalarValue::Float64(Some(_))),
+        ) = needle
+        {
+            let offsets = list.value_offsets();
+            let elements = list.values().slice(
+                offsets[0] as usize,
+                (offsets[list.len()] - offsets[0]) as usize,
+            );
+            if let Some(mask) = compare_float_array_scalar(op, 
elements.as_ref(), value)? {
+                return from_mask(list, &elements, mask.into_parts().0);
+            }
+        }
+        MatchRows::new(list, needle)?.evaluate::<M>(spark_equality)
+    })
+}
+
+pub(super) type EqualityBuilder =
+    fn(&dyn Array, &dyn Array) -> Result<Box<dyn Fn(usize, usize) -> bool + 
Send + Sync>>;
+
+/// Consume a predicate over non-null element and needle indices. The float 
specialization
+/// lets removal copy the surviving elements directly from the typed buffer.
+pub(super) trait MatchOperation<O: OffsetSizeTrait> {
+    fn apply(rows: &MatchRows<'_, O>, equal: impl Fn(usize, usize) -> bool) -> 
Result<ArrayRef>;
+
+    fn apply_float<T: ArrowPrimitiveType>(
+        rows: &MatchRows<'_, O>,
+        _values: &PrimitiveArray<T>,
+        equal: impl Fn(usize, usize) -> bool,
+    ) -> Result<ArrayRef> {
+        Self::apply(rows, equal)
+    }
+}
+
+pub(super) struct MatchRows<'a, O: OffsetSizeTrait> {
+    pub array: &'a GenericListArray<O>,
+    pub needles: ArrayRef,
+    pub nulls: Option<NullBuffer>,
+}
+
+impl<'a, O: OffsetSizeTrait> MatchRows<'a, O> {
+    pub fn new(array: &'a GenericListArray<O>, needle: &ColumnarValue) -> 
Result<Self> {
+        let (needles, nulls) = match needle {
+            ColumnarValue::Scalar(value) if value.is_null() => {
+                (value.to_array()?, Some(NullBuffer::new_null(array.len())))
+            }
+            ColumnarValue::Scalar(value) => (value.to_array()?, 
array.nulls().cloned()),
+            ColumnarValue::Array(values) => (
+                Arc::clone(values),
+                NullBuffer::union(array.nulls(), 
values.logical_nulls().as_ref()),
+            ),
+        };
+        Ok(Self {
+            array,
+            needles,
+            nulls,
+        })
+    }
+
+    pub fn evaluate<M: MatchOperation<O>>(&self, equality: EqualityBuilder) -> 
Result<ArrayRef> {
+        let elements = self.array.values();
+        match (elements.data_type(), self.needles.data_type()) {
+            (DataType::Float32, DataType::Float32) => self.match_floats::<M, 
Float32Type>(),
+            (DataType::Float64, DataType::Float64) => self.match_floats::<M, 
Float64Type>(),
+            _ => {
+                let equal = equality(elements.as_ref(), 
self.needles.as_ref())?;
+                M::apply(self, equal)
+            }
+        }
+    }
+
+    fn match_floats<M: MatchOperation<O>, T: ArrowPrimitiveType>(&self) -> 
Result<ArrayRef>
+    where
+        T::Native: Float,
+    {
+        let values = self.array.values().as_primitive::<T>();
+        let needles = self.needles.as_primitive::<T>().values();
+        let elements = values.values();
+        M::apply_float(self, values, |i, j| {
+            compare_floats(elements[i], needles[j]).is_eq()
+        })
+    }
+
+    /// Each row's element range in the flattened values and its needle index.
+    /// A null array or needle gives an empty range.
+    pub fn iter(&self) -> impl Iterator<Item = (Range<usize>, usize)> + '_ {
+        let scalar = self.needles.len() == 1;

Review Comment:
   Thanks.



##########
docs/source/contributor-guide/expression-audits/array_funcs.md:
##########
@@ -127,7 +127,8 @@
 - Spark 4.0.1 (audited 2026-05-27): `NullIntolerant` -> `nullIntolerant` field 
refactor.
 - Spark 4.1.1 (audited 2026-05-27): identical to 4.0.1.
 - Current status: `CometArrayRemove` sends arrays whose elements hold a 
`FLOAT` or `DOUBLE` at any depth to the native `spark_array_remove`, which 
compares as Spark's `genEqual` does (`-0.0` equals `0.0`, all NaNs are equal, 
nested elements through `spark_equality`) and keeps the bits of the elements it 
keeps. Other element types use DataFusion's `array_remove_all`. Null elements 
stay, and a null array or value gives null.
-- Performance (tuned 2026-10-01, PR 
[#6518](https://github.com/apache/datafusion-comet/pull/6518)): with a constant 
value, `FLOAT` and `DOUBLE` elements get one keep mask over all the values from 
`BooleanBuffer::collect_bool`, with the inverted validity ORed in, one running 
popcount over the mask's words for each row's kept count, and one `filter`. 
41-76% less time than DataFusion's `array_remove_all` with a constant value, 
and 47-95% less with a value per row. Benchmark: `benches/float_arrays.rs`.
+- For a non-null constant `FLOAT` or `DOUBLE`, `compare_float_array_scalar` 
builds a keep mask using `IS DISTINCT FROM`, which retains null elements. A 
running popcount gives the output offsets, and one `filter` copies the 
survivors.
+- Performance (tuned 2026-10-01, PR 
[#6518](https://github.com/apache/datafusion-comet/pull/6518)): the 
implementation measured in `benches/float_arrays.rs` used 
`BooleanBuffer::collect_bool` for the constant case. It took 41-76% less time 
than DataFusion's `array_remove_all` with a constant value and 47-95% less with 
a value per row.

Review Comment:
   Thanks, looks good.



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