← Back to Pull requests

[AURON #2624] Support Spark's array_except natively #2648

Open
zoddtheimmortal opened this pull request with 750 lines diff across 7 files
View on GitHub
zoddtheimmortal zoddtheimmortal commented on Oct 31, 2026 19:14 UTC
Author

Which issue does this PR close?

Closes #2624

Rationale for this change

Spark's array_except currently falls back to Spark.

What changes are included in this PR?

  • Convert Spark's ArrayExcept to a new native Spark_ArrayExcept function.

  • For each row, seed a hash set with the second array, then keep each element of the first array that the set has not seen. This preserves first-occurrence order and removes duplicates in one pass.

  • Time complexity: O(n + m) expected per row, where n and m are the two array lengths. Each element is hashed once. Only the visible value range of each list is row-encoded, so sliced inputs don't pay for hidden values.

  • Preserve Spark semantics:

  • - null arrays give null;
    - a single null element is kept unless the second array contains null;
    - NaN equals NaN;
    - -0.0 and 0.0 stay distinct; Spark 4.2 normalizes them before this function.
  • Move the element-type check from ArrayDistinct into isSupportedSetArrayType, shared by both functions.

  • Move array_distinct's NaN canonicalization into canonicalize_nans, shared by both functions.

  • Add Rust tests for scalar and array inputs, slices, NaN and signed zero, field metadata, and invalid arguments, plus Spark result and native-plan checks.
  • Are there any user-facing changes?

    array_except can execute natively for supported atomic element types. Nested element type keeps the fallback, and so does floating point arrays on Spark 3.0.

    How was this patch tested?

    cargo test -p datafusion-ext-functions --lib spark_array
    cargo clippy -p datafusion-ext-functions --all-targets -- -D warnings
    cargo fmt --all -- --check
    ./dev/reformat --check
    ./dev/mvn-build-helper/build-native.sh pre
    ./build/mvn -Ppre -Pspark-3.0 -Pscala-2.12 -pl spark-extension-shims-spark -am test -DskipBuildNative -DskipTests=false -DwildcardSuites=org.apache.auron.AuronFunctionSuite
    ./build/mvn -Ppre -Pspark-3.5 -Pscala-2.12 -pl spark-extension-shims-spark -am test -DskipBuildNative -DskipTests=false -DwildcardSuites=org.apache.auron.AuronFunctionSuite
    ./build/mvn -Ppre -Pspark-4.2 -Pscala-2.13 -pl spark-extension-shims-spark -am test -DskipBuildNative -DskipTests=false -DwildcardSuites=org.apache.auron.AuronFunctionSuite
    

    All passed. AuronFunctionSuite: 97 succeeded, 0 failed on each Spark version.

    Was this patch authored or co-authored using generative AI tooling?


  • Yes

  • No
  • Generated-by: Claude Opus 5.5 on GitHub Copilot CLI 1.0.105

    ASF guidance: https://www.apache.org/legal/generative-tooling.html

    Diff: 750 lines (+693 / -57) across 7 files Reviewer: robreeves Review duration: 33872m
    All Vouch review confidence checks passed
    Residual risk 0.04 = Change Risk (0.51) × (1 − Review Confidence (0.91)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.51 · 750 lines diff across 7 files
    0.51
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.91 · 5 substantive comment(s)
    0.91
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    91%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.396
    Real PR Conversation Timeline
    20 items
    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 31, 2026 19:17 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟢 Approval recommended

    No active review issues block approval of the native array_except implementation.

    No open issues 🎉

    <details>
    <summary><strong>What changed in this PR</strong></summary>

    Adds native execution of Spark’s array_except in Auron, reducing fallback for supported atomic element types while preserving Spark’s ordering, deduplication, null, and floating-point semantics.

    Changes:

  • Connects Spark expression conversion to the new native function, retaining fallback for unsupported types and Spark 3.0 floating-point arrays.

  • Implements hash-based array subtraction and shares type checks and NaN canonicalization with array_distinct.

  • Adds Rust unit tests and Spark result, native-plan, and fallback checks.
  • | File | Description |
    | ---- | ----------- |
    | spark-extension/​src/​main/​scala/​org/​apache/​spark/​sql/​auron/​NativeConverters.scala | Adds ArrayExcept conversion and shared set-array type checks. |
    | spark-extension-shims-spark/​src/​test/​scala/​org/​apache/​auron/​AuronFunctionSuite.scala | Tests Spark-compatible results, native execution, and fallback behavior. |
    | native-engine/​datafusion-ext-functions/​src/​spark_array.rs | Implements native array subtraction, extracts NaN handling, and adds unit tests. |
    | native-engine/​datafusion-ext-functions/​src/​lib.rs | Registers Spark_ArrayExcept in the native function dispatcher. |
    </details>

    <sub>Review effort: Balanced</sub>

    Copilot Copilot commented on code on Nov 08, 2026 10:03 UTC
    Code Review
    native-engine/datafusion-ext-functions/src/spark_array.rs:1
    @@ -38,6 +38,24 @@ use datafusion_ext_commons::{
         spark_float::spark_float_cmp,
     };
     
    +// Spark canonicalizes NaNs but keeps signed zeros distinct before Spark 4.2's
    +// normalization.
    +fn canonicalize_nans(values: &ArrayRef) -> Result<ArrayRef> {
    +    Ok(match values.data_type() {
    +        DataType::Float32 => Arc::new(Float32Array::from_iter(
    +            downcast_any!(values, Float32Array)?
    +                .iter()
    +                .map(|v| v.map(|v| if v.is_nan() { f32::NAN } else { v })),
    +        )),
    +        DataType::Float64 => Arc::new(Float64Array::from_iter(
    +            downcast_any!(values, Float64Array)?
    +                .iter()
    +                .map(|v| v.map(|v| if v.is_nan() { f64::NAN } else { v })),
    +        )),
    +        _ => Arc::clone(values),
    +    })
    +}

    The helper (and its call sites in array_distinct/union/except) only canonicalizes NaNs but never applies Spark 4.2+ signed-zero normalization. Your Spark test explicitly expects different -0.0 behavior when SPARK_RUNTIME_VERSION >= 4.2, so the native implementation will likely diverge on Spark 4.2+. Consider extending the float canonicalization step to also normalize signed zeros when targeting Spark 4.2+ (e.g., map -0.0 to 0.0 conditionally), or apply the existing Spark_NormalizeNanAndZero semantics to float array set ops for Spark 4.2+ so native results match Spark across versions.

    Copilot Copilot commented on code on Nov 08, 2026 10:03 UTC
    Code Review
    native-engine/datafusion-ext-functions/src/spark_array.rs:1
    @@ -172,6 +176,100 @@ pub fn array_union(args: &[ColumnarValue]) -> Result<ColumnarValue> {
         }
     }
     
    +pub fn array_except(args: &[ColumnarValue]) -> Result<ColumnarValue> {
    +    if args.len() != 2 {
    +        return df_execution_err!("array_except requires exactly 2 arguments");
    +    }
    +    let left_is_scalar = matches!(args[0], ColumnarValue::Scalar(_));
    +    let right_is_scalar = matches!(args[1], ColumnarValue::Scalar(_));
    +    // Scalar lists stay one row to avoid copying their elements per input row.
    +    let left = columnar_value_to_list_array(&args[0])?;
    +    let right = columnar_value_to_list_array(&args[1])?;
    +    let num_rows = match (left_is_scalar, right_is_scalar) {
    +        (true, _) => right.len(),
    +        (_, true) => left.len(),
    +        _ if left.len() == right.len() => left.len(),
    +        _ => return df_execution_err!("array_except requires matching array lengths"),
    +    };
    +    if left.value_type() != right.value_type() {
    +        return df_execution_err!("array_except requires matching element types");
    +    }
    +    if left.value_type().is_nested() {
    +        return df_execution_err!("array_except does not support nested element types");
    +    }
    +    let DataType::List(field) = left.data_type() else {
    +        return df_execution_err!("array_except requires a list");
    +    };
    +
    +    let (left_base, left_values) = visible_values(&left)?;
    +    let (right_base, right_values) = visible_values(&right)?;
    +    let converter = RowConverter::new(vec![SortField::new(left_values.data_type().clone())])?;
    +    let left_rows = converter.convert_columns(&[Arc::clone(&left_values)])?;
    +    let right_rows = converter.convert_columns(&[right_values])?;
    +    let data = left_values.to_data();
    +    let mut output = MutableArrayData::new(vec![&data], false, left_values.len());
    +    let mut offsets = Vec::with_capacity(num_rows + 1);
    +    let mut valids = Vec::with_capacity(num_rows);
    +    // Seeded with the right elements, so each left element needs one lookup.
    +    let mut seen = HashSet::new();

    Within the per-row loop, seen is repeatedly repopulated from the right-side elements but is created with the default capacity and may rehash as right sizes vary by row. Consider ensuring capacity before inserting (e.g., seen.reserve(right_end - right_start) after seen.clear()), or initializing with a reasonable capacity derived from the first row, to reduce rehash overhead on wide arrays.

    Copilot Copilot commented on code on Nov 08, 2026 10:03 UTC
    Code Review
    native-engine/datafusion-ext-functions/src/spark_array.rs:1
    @@ -172,6 +176,100 @@ pub fn array_union(args: &[ColumnarValue]) -> Result<ColumnarValue> {
         }
     }
     
    +pub fn array_except(args: &[ColumnarValue]) -> Result<ColumnarValue> {
    +    if args.len() != 2 {
    +        return df_execution_err!("array_except requires exactly 2 arguments");
    +    }
    +    let left_is_scalar = matches!(args[0], ColumnarValue::Scalar(_));
    +    let right_is_scalar = matches!(args[1], ColumnarValue::Scalar(_));
    +    // Scalar lists stay one row to avoid copying their elements per input row.
    +    let left = columnar_value_to_list_array(&args[0])?;
    +    let right = columnar_value_to_list_array(&args[1])?;
    +    let num_rows = match (left_is_scalar, right_is_scalar) {
    +        (true, _) => right.len(),
    +        (_, true) => left.len(),
    +        _ if left.len() == right.len() => left.len(),
    +        _ => return df_execution_err!("array_except requires matching array lengths"),
    +    };
    +    if left.value_type() != right.value_type() {
    +        return df_execution_err!("array_except requires matching element types");
    +    }
    +    if left.value_type().is_nested() {
    +        return df_execution_err!("array_except does not support nested element types");
    +    }
    +    let DataType::List(field) = left.data_type() else {
    +        return df_execution_err!("array_except requires a list");
    +    };
    +
    +    let (left_base, left_values) = visible_values(&left)?;
    +    let (right_base, right_values) = visible_values(&right)?;
    +    let converter = RowConverter::new(vec![SortField::new(left_values.data_type().clone())])?;
    +    let left_rows = converter.convert_columns(&[Arc::clone(&left_values)])?;
    +    let right_rows = converter.convert_columns(&[right_values])?;
    +    let data = left_values.to_data();
    +    let mut output = MutableArrayData::new(vec![&data], false, left_values.len());
    +    let mut offsets = Vec::with_capacity(num_rows + 1);
    +    let mut valids = Vec::with_capacity(num_rows);
    +    // Seeded with the right elements, so each left element needs one lookup.
    +    let mut seen = HashSet::new();
    +    offsets.push(0i32);
    +    for row in 0..num_rows {
    +        let l = if left_is_scalar { 0 } else { row };
    +        let r = if right_is_scalar { 0 } else { row };
    +        let valid = left.is_valid(l) && right.is_valid(r);
    +        valids.push(valid);
    +        if valid {
    +            seen.clear();
    +            let right_start = right.value_offsets()[r] as usize - right_base;
    +            let right_end = right.value_offsets()[r + 1] as usize - right_base;

    Within the per-row loop, seen is repeatedly repopulated from the right-side elements but is created with the default capacity and may rehash as right sizes vary by row. Consider ensuring capacity before inserting (e.g., seen.reserve(right_end - right_start) after seen.clear()), or initializing with a reasonable capacity derived from the first row, to reduce rehash overhead on wide arrays.

    Copilot Copilot commented on code on Nov 08, 2026 10:03 UTC
    Code Review
    spark-extension/src/main/scala/org/apache/spark/sql/auron/NativeConverters.scala:1
    @@ -117,6 +117,16 @@ object NativeConverters extends Logging {
         }
       }
     
    +  private def isSupportedSetArrayType(dataType: DataType): Boolean = dataType match {
    +    // Spark 3.0 has different NaN deduplication behavior.
    +    case ArrayType(FloatType | DoubleType, _) =>
    +      SparkVersionUtil.SPARK_RUNTIME_VERSION >= "3.1"

    Comparing Spark versions as strings is not a correct version ordering in general (e.g., \"3.10\" would compare less than \"3.2\"). It’s safer to use a numeric/semantic version comparator (or an existing SparkVersionUtil boolean like isSparkV31OrGreater, if available) to avoid incorrect feature gating as versions evolve.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 08, 2026 10:03 UTC
    Reviewer

    [!NOTE]

    Copilot was unable to run its full agentic suite in this review.

    <!-- ccr-overview-v2 -->

    Copilot review overview

    <details open>
    <summary><strong>4 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> The helper (and its call sites in array_distinct/union/except) only canonicalizes NaNs but never… · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Within the per-row loop, seen is repeatedly repopulated from the right-side elements but is… · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Within the per-row loop, seen is repeatedly repopulated from the right-side elements but is… · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Comparing Spark versions as strings is not a correct version ordering in general (e.g., \\&quot;3.10\\&quot;… · New

  • </details>

    <sub>Review effort: Lite</sub>

    robreeves robreeves commented on code on Nov 13, 2026 23:19 UTC
    Code Review
    native-engine/datafusion-ext-functions/src/spark_array.rs:1
    @@ -38,6 +38,24 @@ use datafusion_ext_commons::{
         spark_float::spark_float_cmp,
     };
     
    +// Spark canonicalizes NaNs but keeps signed zeros distinct before Spark 4.2's
    +// normalization.
    +fn canonicalize_nans(values: &ArrayRef) -> Result<ArrayRef> {

    /native-engine/datafusion-ext-commons/src/spark_float.rs contains Spark float specific behavior. Could this be added there since it is not specific to these operators?

    robreeves robreeves commented on code on Nov 14, 2026 00:27 UTC
    Code Review
    spark-extension/src/main/scala/org/apache/spark/sql/auron/NativeConverters.scala:1
    @@ -117,6 +117,16 @@ object NativeConverters extends Logging {
         }
       }
     
    +  private def isSupportedSetArrayType(dataType: DataType): Boolean = dataType match {
    +    // Spark 3.0 has different NaN deduplication behavior.
    +    case ArrayType(FloatType | DoubleType, _) =>
    +      SparkVersionUtil.SPARK_RUNTIME_VERSION >= "3.1"

    Instead of checking the runtime most other cases I have seen add Spark version specific logic to /spark-extension-shims-spark/src/main/scala/org/apache/spark/sql/auron/ShimsImpl.scala and @sparkver. Can you use that pattern here? I know you didn't add this in the PR, but since it is being refactored now seems like a good time to do it.

    robreeves robreeves commented on code on Nov 14, 2026 00:33 UTC
    Code Review
    native-engine/datafusion-ext-functions/src/spark_array.rs:1
    @@ -853,6 +951,252 @@ mod test {
             Ok(())
         }
     
    +    fn int_lists(rows: Vec<Option<Vec<Option<i32>>>>) -> ArrayRef {
    +        Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(rows))
    +    }
    +
    +    #[test]
    +    fn test_array_except_int() -> Result<()> {
    +        let left = int_lists(vec![
    +            Some(vec![Some(1), Some(2), Some(3), Some(2), Some(4)]),
    +            Some(vec![Some(1), None, Some(3), None]),
    +            Some(vec![Some(1), None]),
    +            Some(vec![]),
    +            Some(vec![Some(1), Some(1)]),
    +            None,
    +            Some(vec![Some(1)]),
    +        ]);
    +        let right = int_lists(vec![
    +            Some(vec![Some(2), Some(5)]),
    +            Some(vec![Some(3)]),
    +            Some(vec![None]),
    +            Some(vec![Some(1)]),
    +            Some(vec![]),
    +            Some(vec![Some(1)]),
    +            None,
    +        ]);
    +        let result = array_except(&[ColumnarValue::Array(left), ColumnarValue::Array(right)])?
    +            .into_array(7)?;
    +        let expected = int_lists(vec![
    +            Some(vec![Some(1), Some(3), Some(4)]),
    +            Some(vec![Some(1), None]),
    +            Some(vec![Some(1)]),
    +            Some(vec![]),
    +            Some(vec![Some(1)]),
    +            None,
    +            None,
    +        ]);
    +        assert_eq!(&result, &expected);
    +        Ok(())
    +    }
    +
    +    #[test]
    +    fn test_array_except_scalar_arguments() -> Result<()> {
    +        let column = int_lists(vec![
    +            Some(vec![Some(1), Some(2), Some(1)]),
    +            Some(vec![Some(3), None, None]),
    +            None,
    +        ]);
    +        let scalar_source = int_lists(vec![
    +            Some(vec![Some(1), None]),
    +            Some(vec![Some(1), Some(2), None, Some(2)]),
    +        ]);
    +        let small = ScalarValue::try_from_array(&scalar_source, 0)?;
    +        let big = ScalarValue::try_from_array(&scalar_source, 1)?;
    +
    +        let result = array_except(&[
    +            ColumnarValue::Array(Arc::clone(&column)),
    +            ColumnarValue::Scalar(small.clone()),
    +        ])?
    +        .into_array(3)?;
    +        let expected = int_lists(vec![Some(vec![Some(2)]), Some(vec![Some(3)]), None]);
    +        assert_eq!(&result, &expected);
    +
    +        let result = array_except(&[
    +            ColumnarValue::Scalar(big.clone()),
    +            ColumnarValue::Array(column),
    +        ])?
    +        .into_array(3)?;
    +        let expected = int_lists(vec![Some(vec![None]), Some(vec![Some(1), Some(2)]), None]);
    +        assert_eq!(&result, &expected);
    +
    +        let result = array_except(&[ColumnarValue::Scalar(big), ColumnarValue::Scalar(small)])?;
    +        assert!(matches!(result, ColumnarValue::Scalar(_)));
    +        assert_eq!(
    +            &result.into_array(1)?,
    +            &int_lists(vec![Some(vec![Some(2)])])
    +        );
    +        Ok(())
    +    }
    +
    +    #[test]
    +    fn test_array_except_sliced_values_and_field() -> Result<()> {
    +        // Offsets do not start at 0, so hidden values precede the visible ones.
    +        let field = Arc::new(Field::new("element", DataType::Int32, true).with_metadata(
    +            std::collections::HashMap::from([("key".into(), "value".into())]),
    +        ));
    +        let left: ArrayRef = Arc::new(ListArray::try_new(
    +            Arc::clone(&field),
    +            OffsetBuffer::new(vec![1, 4, 6].into()),
    +            Arc::new(Int32Array::from(vec![99, 1, 2, 1, 3, 3, 99])),
    +            None,
    +        )?);
    +        let right: ArrayRef = Arc::new(ListArray::try_new(
    +            Arc::new(Field::new_list_field(DataType::Int32, true)),
    +            OffsetBuffer::new(vec![2, 3, 4].into()),
    +            Arc::new(Int32Array::from(vec![1, 3, 2, 3, 1])),
    +            None,
    +        )?);
    +        let result = array_except(&[ColumnarValue::Array(left), ColumnarValue::Array(right)])?
    +            .into_array(2)?;
    +        let expected: ArrayRef = Arc::new(ListArray::try_new(
    +            field,
    +            OffsetBuffer::new(vec![0, 1, 1].into()),
    +            Arc::new(Int32Array::from(vec![1])),
    +            None,
    +        )?);
    +        assert_eq!(&result, &expected);
    +
    +        // Sliced ListArray (non-zero array offset) on both sides.
    +        let left = int_lists(vec![
    +            Some(vec![Some(9)]),
    +            Some(vec![Some(1), Some(2), Some(3)]),
    +            Some(vec![Some(4), Some(4)]),
    +        ])
    +        .slice(1, 2);
    +        let right = int_lists(vec![
    +            Some(vec![Some(1), Some(3), Some(4)]),
    +            Some(vec![Some(2)]),
    +            Some(vec![]),
    +        ])
    +        .slice(1, 2);
    +        let result = array_except(&[ColumnarValue::Array(left), ColumnarValue::Array(right)])?
    +            .into_array(2)?;
    +        let expected = int_lists(vec![Some(vec![Some(1), Some(3)]), Some(vec![Some(4)])]);
    +        assert_eq!(&result, &expected);
    +        Ok(())
    +    }
    +
    +    #[test]
    +    fn test_array_except_strings() -> Result<()> {
    +        let field = Arc::new(Field::new_list_field(DataType::Utf8, true));
    +        let left: ArrayRef = Arc::new(ListArray::try_new(
    +            Arc::clone(&field),
    +            OffsetBuffer::new(vec![0, 4].into()),
    +            Arc::new(StringArray::from(vec![
    +                Some("a"),
    +                Some("b"),
    +                None,
    +                Some("a"),
    +            ])),
    +            None,
    +        )?);
    +        let right: ArrayRef = Arc::new(ListArray::try_new(
    +            Arc::clone(&field),
    +            OffsetBuffer::new(vec![0, 1].into()),
    +            Arc::new(StringArray::from(vec![Some("b")])),
    +            None,
    +        )?);
    +        let result = array_except(&[ColumnarValue::Array(left), ColumnarValue::Array(right)])?
    +            .into_array(1)?;
    +        let expected: ArrayRef = Arc::new(ListArray::try_new(
    +            field,
    +            OffsetBuffer::new(vec![0, 2].into()),
    +            Arc::new(StringArray::from(vec![Some("a"), None])),
    +            None,
    +        )?);
    +        assert_eq!(&result, &expected);
    +        Ok(())
    +    }
    +
    +    macro_rules! test_array_except_float {
    +        ($name:ident, $arrow_type:ty, $array_type:ty, $float_type:ty, $nan_bits:expr) => {
    +            #[test]
    +            fn $name() -> Result<()> {
    +                let non_canonical_nan = <$float_type>::from_bits($nan_bits);
    +                let left: ArrayRef =
    +                    Arc::new(ListArray::from_iter_primitive::<$arrow_type, _, _>(vec![
    +                        Some(vec![
    +                            Some(-0.0),
    +                            Some(0.0),
    +                            Some(non_canonical_nan),
    +                            Some(<$float_type>::NAN),
    +                            Some(-<$float_type>::NAN),
    +                            Some(1.0),
    +                            Some(1.0),
    +                        ]),
    +                        Some(vec![Some(non_canonical_nan), Some(2.0)]),
    +                    ]));
    +                let right: ArrayRef =
    +                    Arc::new(ListArray::from_iter_primitive::<$arrow_type, _, _>(vec![
    +                        Some(vec![Some(0.0)]),

    Can you also add some of the tricky cases (non_canonical_nan, -0.0, etc) on the right to verify both sides get the same handling?

    robreeves robreeves commented on Nov 14, 2026 00:35 UTC
    Reviewer

    Overall the logic LGTM. Just a few minor comments.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 15, 2026 06:10 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟢 Approval recommended

    The review reports no active issues with the native array_except change.

    <details open>
    <summary><strong>3 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> The helper (and its call sites in array_distinct/union/except) only canonicalizes NaNs but never…

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Within the per-row loop, seen is repeatedly repopulated from the right-side elements but is…

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Within the per-row loop, seen is repeatedly repopulated from the right-side elements but is…

  • </details>

    <details>
    <summary><strong>1 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Comparing Spark versions as strings is not a correct version ordering in general (e.g., \\&quot;3.10\\&quot;…

  • </details>

    <sub>Review effort: Balanced</sub>

    zoddtheimmortal zoddtheimmortal commented on code on Nov 15, 2026 06:34 UTC
    Code Review
    native-engine/datafusion-ext-functions/src/spark_array.rs:1
    @@ -38,6 +38,24 @@ use datafusion_ext_commons::{
         spark_float::spark_float_cmp,
     };
     
    +// Spark canonicalizes NaNs but keeps signed zeros distinct before Spark 4.2's
    +// normalization.
    +fn canonicalize_nans(values: &ArrayRef) -> Result<ArrayRef> {

    Good call, moved canonicalize_nans to spark_float.rs so other functions can share this impl. Updated array_distinct, array_except and arrays_overlap to use it.

    zoddtheimmortal zoddtheimmortal commented on code on Nov 15, 2026 06:36 UTC
    Code Review
    spark-extension/src/main/scala/org/apache/spark/sql/auron/NativeConverters.scala:1
    @@ -117,6 +117,16 @@ object NativeConverters extends Logging {
         }
       }
     
    +  private def isSupportedSetArrayType(dataType: DataType): Boolean = dataType match {
    +    // Spark 3.0 has different NaN deduplication behavior.
    +    case ArrayType(FloatType | DoubleType, _) =>
    +      SparkVersionUtil.SPARK_RUNTIME_VERSION >= "3.1"

    Moved the check to Shims.hasNaNAwareArraySetOps with @sparkver

    zoddtheimmortal zoddtheimmortal commented on code on Nov 15, 2026 06:40 UTC
    Code Review
    native-engine/datafusion-ext-functions/src/spark_array.rs:1
    @@ -853,6 +951,252 @@ mod test {
             Ok(())
         }
     
    +    fn int_lists(rows: Vec<Option<Vec<Option<i32>>>>) -> ArrayRef {
    +        Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(rows))
    +    }
    +
    +    #[test]
    +    fn test_array_except_int() -> Result<()> {
    +        let left = int_lists(vec![
    +            Some(vec![Some(1), Some(2), Some(3), Some(2), Some(4)]),
    +            Some(vec![Some(1), None, Some(3), None]),
    +            Some(vec![Some(1), None]),
    +            Some(vec![]),
    +            Some(vec![Some(1), Some(1)]),
    +            None,
    +            Some(vec![Some(1)]),
    +        ]);
    +        let right = int_lists(vec![
    +            Some(vec![Some(2), Some(5)]),
    +            Some(vec![Some(3)]),
    +            Some(vec![None]),
    +            Some(vec![Some(1)]),
    +            Some(vec![]),
    +            Some(vec![Some(1)]),
    +            None,
    +        ]);
    +        let result = array_except(&[ColumnarValue::Array(left), ColumnarValue::Array(right)])?
    +            .into_array(7)?;
    +        let expected = int_lists(vec![
    +            Some(vec![Some(1), Some(3), Some(4)]),
    +            Some(vec![Some(1), None]),
    +            Some(vec![Some(1)]),
    +            Some(vec![]),
    +            Some(vec![Some(1)]),
    +            None,
    +            None,
    +        ]);
    +        assert_eq!(&result, &expected);
    +        Ok(())
    +    }
    +
    +    #[test]
    +    fn test_array_except_scalar_arguments() -> Result<()> {
    +        let column = int_lists(vec![
    +            Some(vec![Some(1), Some(2), Some(1)]),
    +            Some(vec![Some(3), None, None]),
    +            None,
    +        ]);
    +        let scalar_source = int_lists(vec![
    +            Some(vec![Some(1), None]),
    +            Some(vec![Some(1), Some(2), None, Some(2)]),
    +        ]);
    +        let small = ScalarValue::try_from_array(&scalar_source, 0)?;
    +        let big = ScalarValue::try_from_array(&scalar_source, 1)?;
    +
    +        let result = array_except(&[
    +            ColumnarValue::Array(Arc::clone(&column)),
    +            ColumnarValue::Scalar(small.clone()),
    +        ])?
    +        .into_array(3)?;
    +        let expected = int_lists(vec![Some(vec![Some(2)]), Some(vec![Some(3)]), None]);
    +        assert_eq!(&result, &expected);
    +
    +        let result = array_except(&[
    +            ColumnarValue::Scalar(big.clone()),
    +            ColumnarValue::Array(column),
    +        ])?
    +        .into_array(3)?;
    +        let expected = int_lists(vec![Some(vec![None]), Some(vec![Some(1), Some(2)]), None]);
    +        assert_eq!(&result, &expected);
    +
    +        let result = array_except(&[ColumnarValue::Scalar(big), ColumnarValue::Scalar(small)])?;
    +        assert!(matches!(result, ColumnarValue::Scalar(_)));
    +        assert_eq!(
    +            &result.into_array(1)?,
    +            &int_lists(vec![Some(vec![Some(2)])])
    +        );
    +        Ok(())
    +    }
    +
    +    #[test]
    +    fn test_array_except_sliced_values_and_field() -> Result<()> {
    +        // Offsets do not start at 0, so hidden values precede the visible ones.
    +        let field = Arc::new(Field::new("element", DataType::Int32, true).with_metadata(
    +            std::collections::HashMap::from([("key".into(), "value".into())]),
    +        ));
    +        let left: ArrayRef = Arc::new(ListArray::try_new(
    +            Arc::clone(&field),
    +            OffsetBuffer::new(vec![1, 4, 6].into()),
    +            Arc::new(Int32Array::from(vec![99, 1, 2, 1, 3, 3, 99])),
    +            None,
    +        )?);
    +        let right: ArrayRef = Arc::new(ListArray::try_new(
    +            Arc::new(Field::new_list_field(DataType::Int32, true)),
    +            OffsetBuffer::new(vec![2, 3, 4].into()),
    +            Arc::new(Int32Array::from(vec![1, 3, 2, 3, 1])),
    +            None,
    +        )?);
    +        let result = array_except(&[ColumnarValue::Array(left), ColumnarValue::Array(right)])?
    +            .into_array(2)?;
    +        let expected: ArrayRef = Arc::new(ListArray::try_new(
    +            field,
    +            OffsetBuffer::new(vec![0, 1, 1].into()),
    +            Arc::new(Int32Array::from(vec![1])),
    +            None,
    +        )?);
    +        assert_eq!(&result, &expected);
    +
    +        // Sliced ListArray (non-zero array offset) on both sides.
    +        let left = int_lists(vec![
    +            Some(vec![Some(9)]),
    +            Some(vec![Some(1), Some(2), Some(3)]),
    +            Some(vec![Some(4), Some(4)]),
    +        ])
    +        .slice(1, 2);
    +        let right = int_lists(vec![
    +            Some(vec![Some(1), Some(3), Some(4)]),
    +            Some(vec![Some(2)]),
    +            Some(vec![]),
    +        ])
    +        .slice(1, 2);
    +        let result = array_except(&[ColumnarValue::Array(left), ColumnarValue::Array(right)])?
    +            .into_array(2)?;
    +        let expected = int_lists(vec![Some(vec![Some(1), Some(3)]), Some(vec![Some(4)])]);
    +        assert_eq!(&result, &expected);
    +        Ok(())
    +    }
    +
    +    #[test]
    +    fn test_array_except_strings() -> Result<()> {
    +        let field = Arc::new(Field::new_list_field(DataType::Utf8, true));
    +        let left: ArrayRef = Arc::new(ListArray::try_new(
    +            Arc::clone(&field),
    +            OffsetBuffer::new(vec![0, 4].into()),
    +            Arc::new(StringArray::from(vec![
    +                Some("a"),
    +                Some("b"),
    +                None,
    +                Some("a"),
    +            ])),
    +            None,
    +        )?);
    +        let right: ArrayRef = Arc::new(ListArray::try_new(
    +            Arc::clone(&field),
    +            OffsetBuffer::new(vec![0, 1].into()),
    +            Arc::new(StringArray::from(vec![Some("b")])),
    +            None,
    +        )?);
    +        let result = array_except(&[ColumnarValue::Array(left), ColumnarValue::Array(right)])?
    +            .into_array(1)?;
    +        let expected: ArrayRef = Arc::new(ListArray::try_new(
    +            field,
    +            OffsetBuffer::new(vec![0, 2].into()),
    +            Arc::new(StringArray::from(vec![Some("a"), None])),
    +            None,
    +        )?);
    +        assert_eq!(&result, &expected);
    +        Ok(())
    +    }
    +
    +    macro_rules! test_array_except_float {
    +        ($name:ident, $arrow_type:ty, $array_type:ty, $float_type:ty, $nan_bits:expr) => {
    +            #[test]
    +            fn $name() -> Result<()> {
    +                let non_canonical_nan = <$float_type>::from_bits($nan_bits);
    +                let left: ArrayRef =
    +                    Arc::new(ListArray::from_iter_primitive::<$arrow_type, _, _>(vec![
    +                        Some(vec![
    +                            Some(-0.0),
    +                            Some(0.0),
    +                            Some(non_canonical_nan),
    +                            Some(<$float_type>::NAN),
    +                            Some(-<$float_type>::NAN),
    +                            Some(1.0),
    +                            Some(1.0),
    +                        ]),
    +                        Some(vec![Some(non_canonical_nan), Some(2.0)]),
    +                    ]));
    +                let right: ArrayRef =
    +                    Arc::new(ListArray::from_iter_primitive::<$arrow_type, _, _>(vec![
    +                        Some(vec![Some(0.0)]),

    Added some tricky cases on the right side, these verify that both sides get the same handling

    zoddtheimmortal zoddtheimmortal commented on Nov 15, 2026 06:43 UTC
    Author

    Thanks for the review @robreeves ! Addressed all the comments

    @slfan1989 could you please approve the workflow runs for this PR as well? Thanks!

    robreeves robreeves commented on code on Nov 15, 2026 17:13 UTC
    Code Review
    native-engine/datafusion-ext-functions/src/spark_array.rs:1
    @@ -172,6 +157,100 @@ pub fn array_union(args: &[ColumnarValue]) -> Result<ColumnarValue> {
         }
     }
     
    +pub fn array_except(args: &[ColumnarValue]) -> Result<ColumnarValue> {
    +    if args.len() != 2 {
    +        return df_execution_err!("array_except requires exactly 2 arguments");
    +    }
    +    let left_is_scalar = matches!(args[0], ColumnarValue::Scalar(_));
    +    let right_is_scalar = matches!(args[1], ColumnarValue::Scalar(_));
    +    // Scalar lists stay one row to avoid copying their elements per input row.
    +    let left = columnar_value_to_list_array(&args[0])?;
    +    let right = columnar_value_to_list_array(&args[1])?;
    +    let num_rows = match (left_is_scalar, right_is_scalar) {
    +        (true, _) => right.len(),
    +        (_, true) => left.len(),
    +        _ if left.len() == right.len() => left.len(),
    +        _ => return df_execution_err!("array_except requires matching array lengths"),
    +    };
    +    if left.value_type() != right.value_type() {
    +        return df_execution_err!("array_except requires matching element types");
    +    }
    +    if left.value_type().is_nested() {
    +        return df_execution_err!("array_except does not support nested element types");
    +    }
    +    let DataType::List(field) = left.data_type() else {
    +        return df_execution_err!("array_except requires a list");
    +    };
    +
    +    let (left_base, left_values) = visible_values(&left)?;
    +    let (right_base, right_values) = visible_values(&right)?;

    Could it canonicalize floats inline when constructing the hash set keys, rather than upfront? This would avoid a separate pass over both inputs. Since seen currently uses row-encoded keys, could it instead use native value keys with canonicalized float bits for floats and avoid row encoding altogether?

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 17, 2026 19:57 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟢 Approval recommended

    The native array_except change has no active review issues blocking approval.

    <details open>
    <summary><strong>3 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> The helper (and its call sites in array_distinct/union/except) only canonicalizes NaNs but never…

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Within the per-row loop, seen is repeatedly repopulated from the right-side elements but is…

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Within the per-row loop, seen is repeatedly repopulated from the right-side elements but is…

  • </details>

    <sub>Review effort: Balanced</sub>

    zoddtheimmortal zoddtheimmortal commented on code on Nov 17, 2026 19:58 UTC
    Code Review
    native-engine/datafusion-ext-functions/src/spark_array.rs:1
    @@ -172,6 +157,100 @@ pub fn array_union(args: &[ColumnarValue]) -> Result<ColumnarValue> {
         }
     }
     
    +pub fn array_except(args: &[ColumnarValue]) -> Result<ColumnarValue> {
    +    if args.len() != 2 {
    +        return df_execution_err!("array_except requires exactly 2 arguments");
    +    }
    +    let left_is_scalar = matches!(args[0], ColumnarValue::Scalar(_));
    +    let right_is_scalar = matches!(args[1], ColumnarValue::Scalar(_));
    +    // Scalar lists stay one row to avoid copying their elements per input row.
    +    let left = columnar_value_to_list_array(&args[0])?;
    +    let right = columnar_value_to_list_array(&args[1])?;
    +    let num_rows = match (left_is_scalar, right_is_scalar) {
    +        (true, _) => right.len(),
    +        (_, true) => left.len(),
    +        _ if left.len() == right.len() => left.len(),
    +        _ => return df_execution_err!("array_except requires matching array lengths"),
    +    };
    +    if left.value_type() != right.value_type() {
    +        return df_execution_err!("array_except requires matching element types");
    +    }
    +    if left.value_type().is_nested() {
    +        return df_execution_err!("array_except does not support nested element types");
    +    }
    +    let DataType::List(field) = left.data_type() else {
    +        return df_execution_err!("array_except requires a list");
    +    };
    +
    +    let (left_base, left_values) = visible_values(&left)?;
    +    let (right_base, right_values) = visible_values(&right)?;

    Good point, had explored it during design and was planning to add it in a follow up PR, but added it here

    Floats now are canonicalized inline and keyed by their bits, so they skip the separate canonicalisation pass and row encoding.

    robreeves robreeves approved these changes on Nov 24, 2026 04:50 UTC
    Approved Reviewer

    LGTM. @slfan1989 PTAL

    Reviewers
    Assignees
    zoddtheimmortal zoddtheimmortal
    Labels
    risk: low confidence: 91.3% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 51.4% (MEDIUM) · Higher = larger blast radius
    51.4%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 91.3% · Lower = rushed or shallow review
    91.3%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 4.5% · Safe to merge
    4.5%
    Repository