Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
- Spark 3.5.8 (audited 2026-05-27): identical to 3.4.3.
- Spark 4.0.1 (audited 2026-05-27): the replacement is wrapped in `KnownNotContainsNull(...)` (analysis-only hint, no semantic change).
- Spark 4.1.1 (audited 2026-05-27): identical to 4.0.1.
- Performance (tuned 2026-07-15, PR #4934): added a no-op fast path to `spark_array_compact` that returns the input unchanged (zero-copy) when the values buffer has no null elements, skipping the per-element `MutableArrayData::extend` loop. ~1000x faster on null-free arrays; sparse/dense element-null shapes are unchanged (same code path). Benchmark: `benches/array_compact.rs`.

## array_contains

Expand Down
4 changes: 4 additions & 0 deletions native/spark-expr/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,7 @@ harness = false
[[bench]]
name = "to_json"
harness = false

[[bench]]
name = "array_compact"
harness = false
119 changes: 119 additions & 0 deletions native/spark-expr/benches/array_compact.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// 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 arrow::array::{ArrayRef, Int32Array, ListArray};
use arrow::buffer::{NullBuffer, OffsetBuffer};
use arrow::datatypes::{DataType, Field};
use criterion::{criterion_group, criterion_main, Criterion};
use datafusion::common::config::ConfigOptions;
use datafusion::logical_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl};
use datafusion_comet_spark_expr::SparkArrayCompact;
use std::hint::black_box;
use std::sync::Arc;

/// Build a `ListArray` of `rows` lists, each with `elems_per_row` Int32 elements.
///
/// - `elem_null_every`: insert a null element every Nth element (0 = no element nulls).
/// - `row_null_every`: mark every Nth row null (0 = no null rows).
fn build(
rows: usize,
elems_per_row: usize,
elem_null_every: usize,
row_null_every: usize,
) -> ArrayRef {
let total = rows * elems_per_row;

let values: Int32Array = (0..total)
.map(|i| {
if elem_null_every != 0 && i % elem_null_every == 0 {
None
} else {
Some(i as i32)
}
})
.collect();

let mut offsets = Vec::with_capacity(rows + 1);
offsets.push(0i32);
for i in 1..=rows {
offsets.push((i * elems_per_row) as i32);
}

let row_nulls = if row_null_every == 0 {
None
} else {
Some(NullBuffer::from(
(0..rows)
.map(|i| i % row_null_every != 0)
.collect::<Vec<bool>>(),
))
};

let field = Arc::new(Field::new("item", DataType::Int32, true));
Arc::new(ListArray::new(
field,
OffsetBuffer::new(offsets.into()),
Arc::new(values),
row_nulls,
))
}

fn criterion_benchmark(c: &mut Criterion) {
let udf = SparkArrayCompact::default();
let rows = 8192;

let call = |arr: &ArrayRef| {
let return_field = Arc::new(Field::new("array_compact", arr.data_type().clone(), true));
let sfa = ScalarFunctionArgs {
args: vec![ColumnarValue::Array(Arc::clone(arr))],
number_rows: rows,
return_field,
config_options: Arc::new(ConfigOptions::default()),
arg_fields: vec![],
};
udf.invoke_with_args(sfa).unwrap()
};

// Dense column of short lists with no null elements: the common shape where
// nothing is removed.
let no_nulls_short = build(rows, 8, 0, 0);
// No null elements, longer lists.
let no_nulls_long = build(rows, 64, 0, 0);
// No null elements but ~10% of rows are null.
let no_nulls_null_rows = build(rows, 8, 0, 10);
// Sparse element nulls (~6%).
let sparse_nulls = build(rows, 8, 17, 0);
// Dense element nulls (every other element): the shape a run-batching
// approach regressed on.
let dense_nulls = build(rows, 8, 2, 0);

let mut bench = |name: &str, arr: &ArrayRef| {
c.bench_function(name, |b| b.iter(|| black_box(call(black_box(arr)))));
};

bench("array_compact: no nulls short", &no_nulls_short);
bench("array_compact: no nulls long", &no_nulls_long);
bench(
"array_compact: no element nulls, null rows",
&no_nulls_null_rows,
);
bench("array_compact: sparse nulls", &sparse_nulls);
bench("array_compact: dense nulls", &dense_nulls);
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
104 changes: 99 additions & 5 deletions native/spark-expr/src/array_funcs/array_compact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,22 @@ fn compact_list<OffsetSize: OffsetSizeTrait>(
};

let values = list_array.values();

// logical_nulls() (not nulls()) is used so a NullArray, whose elements are

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment justifies logical_nulls over is_null/nulls specifically because a NullArray values child reports nulls() == None yet is logically all-null. array_compact(array(null, null)) produces a List<Null> and is exactly this shape. None of the three new unit tests exercise it, so the branch the comment protects has no direct coverage and a future refactor to nulls() would pass the suite while silently breaking. This also interacts with finding 1: it is the case that proves logical_null_count must be used rather than null_count.

Suggested change: add a test building a List<Null> (via ListBuilder::new(NullBuilder::new()) or an explicit NullArray values child) and assert all-null rows compact to empty rows.

// all logically null, is correctly reported as fully null. NullArray::nulls()
// returns None, which would make is_null() report false for every element.
let value_nulls = values.logical_nulls();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

native/spark-expr/src/array_funcs/array_compact.rs:124,132

let value_nulls = values.logical_nulls();
...
if value_nulls.as_ref().map(|n| n.null_count()).unwrap_or(0) == 0 {
    return Ok(Arc::new(list_array.clone()));
}

For the common element types (primitive, string, struct, list) this is already cheap. Array::logical_nulls() is self.nulls().cloned() (arrow-rs arrow-array/src/array/mod.rs:243-245), and since a NullBuffer wraps an Arc-backed buffer that clone is an O(1) refcount bump, not a bitmap copy, while NullBuffer::null_count() is a precomputed O(1) read. The default logical_null_count() (mod.rs:324-328) is the same clone, so for these types switching changes nothing.

The case worth guarding against is a values child whose type overrides logical_nulls() to compute a fresh buffer: DictionaryArray (dictionary_array.rs:741), RunArray (run_array.rs:717), and NullArray (null_array.rs:117). Each of these also overrides logical_null_count() (dictionary_array.rs:762, run_array.rs:721, null_array.rs:125) to count without materializing, so for those types logical_nulls() is an O(n) allocation on exactly the fast path this PR exists to speed up while logical_null_count() is not. (UnionArray overrides logical_nulls() at union_array.rs:794 but has no logical_null_count() override, so it allocates either way and does not benefit.) Using logical_null_count() makes the fast path allocation-free for the types that have the override and is never worse than the current code.

Suggested change: gate the fast path on the count, and only materialize the buffer on the slow path where it is actually consumed.

let values = list_array.values();

// Fast path: array_compact only removes null elements. When the values buffer
// has no logical null elements there is nothing to remove, so every row is
// returned unchanged and the result is bit-identical to the input. logical_null_count
// (not null_count) is used so a NullArray, whose elements are all logically null,
// is counted correctly; NullArray::nulls() is None.
if values.logical_null_count() == 0 {
    return Ok(Arc::new(list_array.clone()));
}

let value_nulls = values.logical_nulls();

This keeps the slow path byte-for-byte identical and removes the allocation from the common case.


// Fast path: array_compact only removes null elements. When the values buffer
// has no null elements there is nothing to remove, so every row is returned
// unchanged and the result is bit-identical to the input (same offsets, values,
// and row null buffer). This skips the per-element MutableArrayData::extend
// loop below and reuses the input buffers without copying. The null-containing
// path is left untouched, so shapes with dense element nulls do not regress.
if value_nulls.as_ref().map(|n| n.null_count()).unwrap_or(0) == 0 {
return Ok(Arc::new(list_array.clone()));
}

let original_data = values.to_data();
let mut offsets = Vec::<OffsetSize>::with_capacity(list_array.len() + 1);
offsets.push(OffsetSize::zero());
Expand All @@ -127,11 +143,6 @@ fn compact_list<OffsetSize: OffsetSizeTrait>(
);
let mut valid = NullBufferBuilder::new(list_array.len());

// Use logical_nulls() instead of is_null() to correctly handle NullArray.
// NullArray::nulls() returns None (which makes is_null() return false),
// but logical_nulls() correctly reports all elements as null.
let value_nulls = values.logical_nulls();

for (row_index, offset_window) in list_array.offsets().windows(2).enumerate() {
if list_array.is_null(row_index) {
offsets.push(offsets[row_index]);
Expand Down Expand Up @@ -163,3 +174,86 @@ fn compact_list<OffsetSize: OffsetSizeTrait>(
valid.finish(),
)?))
}

#[cfg(test)]
mod tests {
use super::*;
use arrow::array::{Int32Array, Int32Builder, ListArray, ListBuilder};

/// Build a `ListArray<Int32>`. `None` row = null row; inner `None` = null element.
fn i32_list(rows: Vec<Option<Vec<Option<i32>>>>) -> ListArray {
let mut b = ListBuilder::new(Int32Builder::new());
for row in rows {
match row {
None => b.append(false),
Some(elems) => {
for e in elems {
b.values().append_option(e);
}
b.append(true);
}
}
}
b.finish()
}

fn read(arr: &ArrayRef) -> Vec<Option<Vec<Option<i32>>>> {
let list = arr.as_any().downcast_ref::<ListArray>().unwrap();
(0..list.len())
.map(|i| {
if list.is_null(i) {
None
} else {
let v = list.value(i);
let v = v.as_any().downcast_ref::<Int32Array>().unwrap();
Some(
(0..v.len())
.map(|j| (!v.is_null(j)).then(|| v.value(j)))
.collect(),
)
}
})
.collect()
}

#[test]
fn no_element_nulls_returns_input_bit_identical() {
// Includes a null row and an empty row: the fast path must preserve both.
let input = i32_list(vec![
Some(vec![Some(1), Some(2)]),
None,
Some(vec![]),
Some(vec![Some(3)]),
]);
let out = compact_list::<i32>(&input).unwrap();
// Fast path returns the input unchanged, so ArrayData must be identical.
assert_eq!(input.to_data(), out.to_data());
}

#[test]
fn removes_null_elements_preserving_rows() {
let input = i32_list(vec![
Some(vec![Some(1), None, Some(2)]),
Some(vec![None, None]),
None,
Some(vec![Some(3)]),
]);
let out = compact_list::<i32>(&input).unwrap();
assert_eq!(
read(&out),
vec![
Some(vec![Some(1), Some(2)]),
Some(vec![]),
None,
Some(vec![Some(3)]),
]
);
}

#[test]
fn all_null_elements_become_empty_rows() {
let input = i32_list(vec![Some(vec![None, None]), Some(vec![None])]);
let out = compact_list::<i32>(&input).unwrap();
assert_eq!(read(&out), vec![Some(vec![]), Some(vec![])]);
}
}
Loading