-
Notifications
You must be signed in to change notification settings - Fork 340
perf: optimize spark_array_compact (no-op fast path for null-free arrays)
#4934
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -139,3 +139,7 @@ harness = false | |
| [[bench]] | ||
| name = "to_json" | ||
| harness = false | ||
|
|
||
| [[bench]] | ||
| name = "array_compact" | ||
| harness = false | ||
| 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); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
| // 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(); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
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. The case worth guarding against is a values child whose type overrides 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()); | ||
|
|
@@ -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]); | ||
|
|
@@ -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![])]); | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The comment justifies
logical_nullsoveris_null/nullsspecifically because aNullArrayvalues child reportsnulls() == Noneyet is logically all-null.array_compact(array(null, null))produces aList<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 tonulls()would pass the suite while silently breaking. This also interacts with finding 1: it is the case that proveslogical_null_countmust be used rather thannull_count.Suggested change: add a test building a
List<Null>(viaListBuilder::new(NullBuilder::new())or an explicitNullArrayvalues child) and assert all-null rows compact to empty rows.