mbutrovich commented on code in PR #6400:
URL: https://github.com/apache/datafusion-comet/pull/6400#discussion_r4135725762


##########
native/spark-expr/src/float_semantics/compare.rs:
##########
@@ -0,0 +1,340 @@
+// 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 super::{compare_floats, has_float_leaf};
+use arrow::array::{make_comparator, Array, AsArray, DynComparator, 
OffsetSizeTrait};
+use arrow::compute::SortOptions;
+use arrow::datatypes::{ArrowPrimitiveType, DataType, Float32Type, Float64Type};
+use datafusion::common::{internal_err, DFSchema, Result};
+use num::Float;
+use std::cmp::Ordering;
+use std::ops::Range;
+
+/// Builds a comparator of `left[i]` against `right[j]` in Spark's SQL 
ordering, in which floats
+/// compare as [`compare_floats`] does at any depth. Inner nulls sort first, 
lists compare element
+/// by element and then by length, and structs compare field by field.
+///
+/// Subtrees without a float leaf use Arrow's comparator, which orders them 
the same way. The two
+/// arrays must have the same type, ignoring field names and nullability.
+pub fn spark_comparator(left: &dyn Array, right: &dyn Array) -> 
Result<DynComparator> {
+    check_types(left, right)?;
+    comparator(left, right, false)
+}
+
+/// Builds a test of whether `left[i]` equals `right[j]` in the ordering of 
[`spark_comparator`].
+/// Lists of different lengths are unequal without comparing their elements.
+pub fn spark_equality(
+    left: &dyn Array,
+    right: &dyn Array,
+) -> Result<Box<dyn Fn(usize, usize) -> bool + Send + Sync>> {
+    check_types(left, right)?;
+    let compare = comparator(left, right, true)?;
+    Ok(Box::new(move |i, j| compare(i, j).is_eq()))
+}
+
+fn check_types(left: &dyn Array, right: &dyn Array) -> Result<()> {
+    if DFSchema::datatype_is_logically_equal(left.data_type(), 
right.data_type()) {
+        Ok(())
+    } else {
+        internal_err!(
+            "Spark comparison requires matching types, got {} and {}",
+            left.data_type(),
+            right.data_type()
+        )
+    }
+}
+
+/// With `equality` set, the comparator only has to tell equal from unequal 
values.
+fn comparator(left: &dyn Array, right: &dyn Array, equality: bool) -> 
Result<DynComparator> {
+    if !has_float_leaf(left.data_type()) {
+        let options = SortOptions {
+            descending: false,
+            nulls_first: true,
+        };
+        return Ok(make_comparator(left, right, options)?);
+    }
+    match left.data_type() {
+        DataType::Float32 => Ok(float_comparator::<Float32Type>(left, right)),
+        DataType::Float64 => Ok(float_comparator::<Float64Type>(left, right)),
+        DataType::List(_) => list_comparator::<i32>(left, right, equality),
+        DataType::LargeList(_) => list_comparator::<i64>(left, right, 
equality),
+        DataType::FixedSizeList(_, _) => fixed_size_list_comparator(left, 
right, equality),
+        DataType::Struct(_) => struct_comparator(left, right, equality),
+        dt => internal_err!("Unsupported type for Spark comparison: {dt}"),

Review Comment:
   The doc on `spark_comparator` says the two arrays must have the same type, 
and `mismatched_types_are_rejected` checks that a mismatch comes back as an 
error. Should `comparator` also check the right side's type before downcasting 
it?
   
   As I read it, `check_types` uses 
[`DFSchema::datatype_is_logically_equal`](https://github.com/apache/datafusion/blob/7d3835c71f30cbd3c3ae4041732267f1f453097a/datafusion/common/src/dfschema.rs#L683-L686),
 which treats `Dictionary(_, Float64)` as equal to `Float64`. So `check_types` 
lets that pair through, and `float_comparator` then calls `as_primitive` on the 
dictionary, which 
[panics](https://github.com/apache/arrow-rs/blob/f90e061326bd821a7af09281d9e92de6f3b603d9/arrow-array/src/cast.rs#L848-L850)
 instead of returning the internal error. I added a scratch test at the head 
commit that calls `spark_equality` with a `Float64Array` and a 
`DictionaryArray<Int32Type>` of `Float64`, and it panics with `primitive array` 
from `arrow-array/src/cast.rs:849`. The old `nested_equality` had the same gap, 
so this isn't new behavior. The difference is that this check now also guards 
`array_min`/`array_max` and will guard the nested ordering work in #6157 and 
#5507.
   
   Matching on both types keeps the error in one place. With the change below, 
a dictionary on either side returns an error, at the top level and inside a 
list. The existing `float_semantics` tests still pass, and I checked it with 
`cargo fmt --check`. What do you think about also adding the dictionary case to 
`mismatched_types_are_rejected`?
   
   ```suggestion
       match (left.data_type(), right.data_type()) {
           (DataType::Float32, DataType::Float32) => 
Ok(float_comparator::<Float32Type>(left, right)),
           (DataType::Float64, DataType::Float64) => 
Ok(float_comparator::<Float64Type>(left, right)),
           (DataType::List(_), DataType::List(_)) => 
list_comparator::<i32>(left, right, equality),
           (DataType::LargeList(_), DataType::LargeList(_)) => {
               list_comparator::<i64>(left, right, equality)
           }
           (DataType::FixedSizeList(_, _), DataType::FixedSizeList(_, _)) => {
               fixed_size_list_comparator(left, right, equality)
           }
           (DataType::Struct(_), DataType::Struct(_)) => 
struct_comparator(left, right, equality),
           (l, r) => internal_err!("Unsupported types for Spark comparison: {l} 
and {r}"),
       }
   ```
   



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