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
4 changes: 4 additions & 0 deletions native/spark-expr/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,10 @@ harness = false
name = "murmur3"
harness = false

[[bench]]
name = "hash_nulls"
harness = false

[[bench]]
name = "xxhash64"
harness = false
Expand Down
131 changes: 131 additions & 0 deletions native/spark-expr/benches/hash_nulls.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// 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.

//! Benchmarks hashing fixed-width columns with nulls, the case shuffle hash partitioning hits on
//! nullable keys such as TPC-DS foreign keys.

use arrow::array::{ArrayRef, Float64Array, Int32Array, Int64Array};
use arrow::buffer::NullBuffer;
use criterion::{criterion_group, criterion_main, Criterion};
use datafusion::common::ScalarValue;
use datafusion::physical_plan::ColumnarValue;
use datafusion_comet_spark_expr::murmur3::create_murmur3_hashes;
use datafusion_comet_spark_expr::spark_xxhash64;
use std::hint::black_box;
use std::sync::Arc;

mod common;

const NUM_ROWS: usize = 8192;

/// Null percentages, from TPC-DS-like to nearly all null.
const SWEEP: [u32; 11] = [3, 10, 25, 50, 60, 70, 75, 80, 85, 90, 99];

/// Pseudo-random values from a fixed-seed xorshift, so runs are comparable.
fn xorshift(seed: u64) -> impl FnMut() -> u64 {
let mut x = seed;
move || {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x
}
}

/// Each row is null with probability `null_fraction`, independently.
fn random_nulls(null_fraction: f64) -> NullBuffer {
let mut next = xorshift(0x2545_f491_4f6c_dd1d);
NullBuffer::from(
(0..NUM_ROWS)
.map(|_| (next() as f64 / u64::MAX as f64) >= null_fraction)
.collect::<Vec<_>>(),
)
}

fn int32(nulls: Option<NullBuffer>) -> ArrayRef {
let mut next = xorshift(1);
Arc::new(Int32Array::new(
(0..NUM_ROWS).map(|_| next() as i32).collect(),
nulls,
))
}

fn int64(nulls: Option<NullBuffer>) -> ArrayRef {
let mut next = xorshift(2);
Arc::new(Int64Array::new(
(0..NUM_ROWS).map(|_| next() as i64).collect(),
nulls,
))
}

fn float64(nulls: Option<NullBuffer>) -> ArrayRef {
let mut next = xorshift(3);
Arc::new(Float64Array::new(
(0..NUM_ROWS).map(|_| next() as f64 * 1e-6).collect(),
nulls,
))
}

fn criterion_benchmark(c: &mut Criterion) {
let mut murmur3 = |name: &str, array: ArrayRef| {
let arrays = [array];
let mut hashes = vec![42u32; NUM_ROWS];
c.bench_function(&format!("murmur3/{name}"), |b| {
b.iter(|| {
create_murmur3_hashes(black_box(&arrays), &mut hashes).unwrap();
black_box(&hashes);
})
});
};
// No nulls, which this path doesn't reach, to show the run's noise.
murmur3("int32/no_nulls", int32(None));
// Every tenth row is null, a pattern the branch predictor learns. Murmur3 costs the same for
// every value, so these values don't need to be random.
murmur3(
"int32/stride_10%",
common::i32_array(NUM_ROWS, 0.1, |i| i as i32),
);
// The rates from 25% to 85% leave about 48 down to 10 valid rows in a 64-row chunk, around
// `MIN_VALID_FOR_DENSE`. Rerun them when changing it.
for percent in SWEEP {
let nulls = random_nulls(percent as f64 / 100.0);
murmur3(&format!("int32/random_{percent}%"), int32(Some(nulls)));
}
for percent in [3, 50, 75] {
let nulls = random_nulls(percent as f64 / 100.0);
murmur3(
&format!("int64/random_{percent}%"),
int64(Some(nulls.clone())),
);
murmur3(&format!("float64/random_{percent}%"), float64(Some(nulls)));
}

// A seed other than 42 keeps xxhash64 on Comet's implementation.
for percent in SWEEP {
let nulls = random_nulls(percent as f64 / 100.0);
let args = vec![
ColumnarValue::Array(int64(Some(nulls))),
ColumnarValue::Scalar(ScalarValue::Int64(Some(7))),
];
c.bench_function(&format!("xxhash64/int64/random_{percent}%"), |b| {
b.iter(|| black_box(spark_xxhash64(black_box(&args)).unwrap()))
});
}
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
45 changes: 44 additions & 1 deletion native/spark-expr/src/hash_funcs/murmur3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ pub fn create_murmur3_hashes<'a>(
}

#[cfg(test)]
mod tests {
pub(crate) mod tests {
/// Produced by the per-element `hash_list_array!` implementation. An empty list and a null
/// list both leave the seed untouched.
const EXPECTED_LIST_OF_STRUCT: [u32; 6] =
Expand All @@ -212,6 +212,49 @@ mod tests {
test_hashes_with_nulls!(create_murmur3_hashes, T, values, expected, u32);
}

/// Arrays of every fixed-width kind the hash loops special-case, plus strings, with and
/// without nulls.
pub(crate) fn length_mismatch_arrays() -> Vec<ArrayRef> {
use arrow::array::{BooleanArray, Decimal128Array, IntervalMonthDayNanoArray};
use arrow::datatypes::IntervalMonthDayNano;
vec![
Arc::new(Int32Array::from(vec![1, 2, 3])),
Arc::new(Int64Array::from(vec![Some(1), None, Some(3)])),
Arc::new(Float64Array::from(vec![1.0, -0.0, f64::NAN])),
Arc::new(StringArray::from(vec!["a", "b", "c"])),
Arc::new(BooleanArray::from(vec![true, false, true])),
Arc::new(IntervalMonthDayNanoArray::from(vec![
IntervalMonthDayNano::new(1, 2, 3_000);
3
])),
Arc::new(
Decimal128Array::from(vec![1, 2, 3])
.with_precision_and_scale(10, 2)
.unwrap(),
),
Arc::new(Int32Array::from(Vec::<i32>::new())),
]
}

#[test]
fn test_hashes_buffer_length_mismatch_is_error() {
for array in length_mismatch_arrays() {
for len in [array.len().saturating_sub(1), array.len() + 1] {
if len == array.len() {
continue;
}
let mut hashes = vec![42u32; len];
let result = create_murmur3_hashes(&[Arc::clone(&array)], &mut hashes);
assert!(
result.is_err(),
"{} array of length {} with {len} hashes",
array.data_type(),
array.len()
);
}
}
}

/// A dictionary array reached through a nested type arrives as the only column of its recursive
/// call, so deciding the dictionary fast path from column position alone treated it as a first
/// column and restarted from the seed, discarding the hash accumulated for earlier elements of
Expand Down
Loading