Skip to content

Commit c92ba29

Browse files
kumarUjjawalJefffreymartin-gcomphead
authored
perf: Optimize scalar fast path & write() encoding for sha2 (#20116)
## Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123. --> - Closes #20046 . ## Rationale for this change Spark `sha2` currently evaluates scalars via `make_scalar_function(sha2_impl, vec![])`, which expands scalar inputs to size-1 arrays before execution. This adds avoidable overhead for scalar evaluation / constant folding scenarios. In addition, the existing digest-to-hex formatting uses `write!(&mut s, "{b:02x}")` in a loop, which is significantly slower than a LUT-based hex encoder. <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. --> ## What changes are included in this PR? 1) a match-based scalar fast path for `sha2` to avoid scalar→array expansion, and 2) a faster LUT-based hex encoder to replace `write!` formatting. | Benchmark | Before | After | Speedup | |----------|--------|-------|---------| | `sha2/scalar/size=1` | 1.0408 µs | 339.29 ns | **~3.07x** | | `sha2/array_binary_256/size=1024` | 604.13 µs | 295.09 µs | **~2.05x** | | `sha2/array_binary_256/size=4096` | 2.3508 ms | 1.2095 ms | **~1.94x** | | `sha2/array_binary_256/size=8192` | 4.5192 ms | 2.2826 ms | **~1.98x** | <!-- There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR. --> ## Are these changes tested? Yes <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 2. Serve as another way to document the expected behavior of the code If tests are not included in your PR, please explain why (for example, are they covered by existing tests)? --> ## Are there any user-facing changes? No <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. --> <!-- If there are any breaking changes to public APIs, please add the `api change` label. --> --------- Co-authored-by: Jeffrey Vo <jeffrey.vo.australia@gmail.com> Co-authored-by: Martin Grigorov <martin-g@users.noreply.github.com> Co-authored-by: Oleks V <comphead@users.noreply.github.com>
1 parent eb33141 commit c92ba29

File tree

3 files changed

+240
-10
lines changed

3 files changed

+240
-10
lines changed

datafusion/spark/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,7 @@ name = "substring"
9292
[[bench]]
9393
harness = false
9494
name = "unhex"
95+
96+
[[bench]]
97+
harness = false
98+
name = "sha2"

datafusion/spark/benches/sha2.rs

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
extern crate criterion;
19+
20+
use arrow::array::*;
21+
use arrow::datatypes::*;
22+
use criterion::{Criterion, criterion_group, criterion_main};
23+
use datafusion_common::ScalarValue;
24+
use datafusion_common::config::ConfigOptions;
25+
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl};
26+
use datafusion_spark::function::hash::sha2::SparkSha2;
27+
use rand::rngs::StdRng;
28+
use rand::{Rng, SeedableRng};
29+
use std::hint::black_box;
30+
use std::sync::Arc;
31+
32+
fn seedable_rng() -> StdRng {
33+
StdRng::seed_from_u64(42)
34+
}
35+
36+
fn generate_binary_data(size: usize, null_density: f32) -> BinaryArray {
37+
let mut rng = seedable_rng();
38+
let mut builder = BinaryBuilder::new();
39+
for _ in 0..size {
40+
if rng.random::<f32>() < null_density {
41+
builder.append_null();
42+
} else {
43+
let len = rng.random_range::<usize, _>(1..=100);
44+
let bytes: Vec<u8> = (0..len).map(|_| rng.random()).collect();
45+
builder.append_value(&bytes);
46+
}
47+
}
48+
builder.finish()
49+
}
50+
51+
fn run_benchmark(c: &mut Criterion, name: &str, size: usize, args: &[ColumnarValue]) {
52+
let sha2_func = SparkSha2::new();
53+
let arg_fields: Vec<_> = args
54+
.iter()
55+
.enumerate()
56+
.map(|(idx, arg)| Field::new(format!("arg_{idx}"), arg.data_type(), true).into())
57+
.collect();
58+
let config_options = Arc::new(ConfigOptions::default());
59+
60+
c.bench_function(&format!("{name}/size={size}"), |b| {
61+
b.iter(|| {
62+
black_box(
63+
sha2_func
64+
.invoke_with_args(ScalarFunctionArgs {
65+
args: args.to_vec(),
66+
arg_fields: arg_fields.clone(),
67+
number_rows: size,
68+
return_field: Arc::new(Field::new("f", DataType::Utf8, true)),
69+
config_options: Arc::clone(&config_options),
70+
})
71+
.unwrap(),
72+
)
73+
})
74+
});
75+
}
76+
77+
fn criterion_benchmark(c: &mut Criterion) {
78+
// Scalar benchmark (avoid array expansion)
79+
let scalar_args = vec![
80+
ColumnarValue::Scalar(ScalarValue::Binary(Some(b"Spark".to_vec()))),
81+
ColumnarValue::Scalar(ScalarValue::Int32(Some(256))),
82+
];
83+
run_benchmark(c, "sha2/scalar", 1, &scalar_args);
84+
85+
let sizes = vec![1024, 4096, 8192];
86+
let null_density = 0.1;
87+
88+
for &size in &sizes {
89+
let values: ArrayRef = Arc::new(generate_binary_data(size, null_density));
90+
let bit_lengths: ArrayRef = Arc::new(Int32Array::from(vec![256; size]));
91+
92+
let array_args = vec![
93+
ColumnarValue::Array(Arc::clone(&values)),
94+
ColumnarValue::Array(Arc::clone(&bit_lengths)),
95+
];
96+
run_benchmark(c, "sha2/array_binary_256", size, &array_args);
97+
98+
let array_scalar_args = vec![
99+
ColumnarValue::Array(Arc::clone(&values)),
100+
ColumnarValue::Scalar(ScalarValue::Int32(Some(256))),
101+
];
102+
run_benchmark(c, "sha2/array_scalar_binary_256", size, &array_scalar_args);
103+
}
104+
}
105+
106+
criterion_group!(benches, criterion_benchmark);
107+
criterion_main!(benches);

datafusion/spark/src/function/hash/sha2.rs

Lines changed: 129 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,22 @@
1515
// specific language governing permissions and limitations
1616
// under the License.
1717

18-
use arrow::array::{ArrayRef, AsArray, BinaryArrayType, Int32Array, StringArray};
18+
use arrow::array::{
19+
ArrayRef, AsArray, BinaryArrayType, Int32Array, StringArray, new_null_array,
20+
};
1921
use arrow::datatypes::{DataType, Int32Type};
2022
use datafusion_common::types::{
2123
NativeType, logical_binary, logical_int32, logical_string,
2224
};
2325
use datafusion_common::utils::take_function_args;
24-
use datafusion_common::{Result, internal_err};
26+
use datafusion_common::{Result, ScalarValue, internal_err};
2527
use datafusion_expr::{
2628
Coercion, ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature,
2729
TypeSignatureClass, Volatility,
2830
};
2931
use datafusion_functions::utils::make_scalar_function;
3032
use sha2::{self, Digest};
3133
use std::any::Any;
32-
use std::fmt::Write;
3334
use std::sync::Arc;
3435

3536
/// Differs from DataFusion version in allowing array input for bit lengths, and
@@ -87,7 +88,97 @@ impl ScalarUDFImpl for SparkSha2 {
8788
}
8889

8990
fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
90-
make_scalar_function(sha2_impl, vec![])(&args.args)
91+
let [values, bit_lengths] = take_function_args(self.name(), args.args.iter())?;
92+
93+
match (values, bit_lengths) {
94+
(
95+
ColumnarValue::Scalar(value_scalar),
96+
ColumnarValue::Scalar(ScalarValue::Int32(Some(bit_length))),
97+
) => {
98+
if value_scalar.is_null() {
99+
return Ok(ColumnarValue::Scalar(ScalarValue::Utf8(None)));
100+
}
101+
102+
// Accept both Binary and Utf8 scalars (depending on coercion)
103+
let bytes = match value_scalar {
104+
ScalarValue::Binary(Some(b)) => b.as_slice(),
105+
ScalarValue::LargeBinary(Some(b)) => b.as_slice(),
106+
ScalarValue::BinaryView(Some(b)) => b.as_slice(),
107+
ScalarValue::Utf8(Some(s))
108+
| ScalarValue::LargeUtf8(Some(s))
109+
| ScalarValue::Utf8View(Some(s)) => s.as_bytes(),
110+
other => {
111+
return internal_err!(
112+
"Unsupported scalar datatype for sha2: {}",
113+
other.data_type()
114+
);
115+
}
116+
};
117+
118+
let out = match bit_length {
119+
224 => {
120+
let mut digest = sha2::Sha224::default();
121+
digest.update(bytes);
122+
Some(hex_encode(digest.finalize()))
123+
}
124+
0 | 256 => {
125+
let mut digest = sha2::Sha256::default();
126+
digest.update(bytes);
127+
Some(hex_encode(digest.finalize()))
128+
}
129+
384 => {
130+
let mut digest = sha2::Sha384::default();
131+
digest.update(bytes);
132+
Some(hex_encode(digest.finalize()))
133+
}
134+
512 => {
135+
let mut digest = sha2::Sha512::default();
136+
digest.update(bytes);
137+
Some(hex_encode(digest.finalize()))
138+
}
139+
_ => None,
140+
};
141+
142+
Ok(ColumnarValue::Scalar(ScalarValue::Utf8(out)))
143+
}
144+
// Array values + scalar bit length (common case: sha2(col, 256))
145+
(
146+
ColumnarValue::Array(values_array),
147+
ColumnarValue::Scalar(ScalarValue::Int32(Some(bit_length))),
148+
) => {
149+
let output: ArrayRef = match values_array.data_type() {
150+
DataType::Binary => sha2_binary_scalar_bitlen(
151+
&values_array.as_binary::<i32>(),
152+
*bit_length,
153+
),
154+
DataType::LargeBinary => sha2_binary_scalar_bitlen(
155+
&values_array.as_binary::<i64>(),
156+
*bit_length,
157+
),
158+
DataType::BinaryView => sha2_binary_scalar_bitlen(
159+
&values_array.as_binary_view(),
160+
*bit_length,
161+
),
162+
dt => return internal_err!("Unsupported datatype for sha2: {dt}"),
163+
};
164+
Ok(ColumnarValue::Array(output))
165+
}
166+
(
167+
ColumnarValue::Scalar(_),
168+
ColumnarValue::Scalar(ScalarValue::Int32(None)),
169+
) => Ok(ColumnarValue::Scalar(ScalarValue::Utf8(None))),
170+
(
171+
ColumnarValue::Array(_),
172+
ColumnarValue::Scalar(ScalarValue::Int32(None)),
173+
) => Ok(ColumnarValue::Array(new_null_array(
174+
&DataType::Utf8,
175+
args.number_rows,
176+
))),
177+
_ => {
178+
// Fallback to existing behavior for any array/mixed cases
179+
make_scalar_function(sha2_impl, vec![])(&args.args)
180+
}
181+
}
91182
}
92183
}
93184

@@ -112,10 +203,31 @@ fn sha2_binary_impl<'a, BinaryArrType>(
112203
) -> ArrayRef
113204
where
114205
BinaryArrType: BinaryArrayType<'a>,
206+
{
207+
sha2_binary_bitlen_iter(values, bit_lengths.iter())
208+
}
209+
210+
fn sha2_binary_scalar_bitlen<'a, BinaryArrType>(
211+
values: &BinaryArrType,
212+
bit_length: i32,
213+
) -> ArrayRef
214+
where
215+
BinaryArrType: BinaryArrayType<'a>,
216+
{
217+
sha2_binary_bitlen_iter(values, std::iter::repeat(Some(bit_length)))
218+
}
219+
220+
fn sha2_binary_bitlen_iter<'a, BinaryArrType, I>(
221+
values: &BinaryArrType,
222+
bit_lengths: I,
223+
) -> ArrayRef
224+
where
225+
BinaryArrType: BinaryArrayType<'a>,
226+
I: Iterator<Item = Option<i32>>,
115227
{
116228
let array = values
117229
.iter()
118-
.zip(bit_lengths.iter())
230+
.zip(bit_lengths)
119231
.map(|(value, bit_length)| match (value, bit_length) {
120232
(Some(value), Some(224)) => {
121233
let mut digest = sha2::Sha224::default();
@@ -144,11 +256,18 @@ where
144256
Arc::new(array)
145257
}
146258

259+
const HEX_CHARS: [u8; 16] = *b"0123456789abcdef";
260+
261+
#[inline]
147262
fn hex_encode<T: AsRef<[u8]>>(data: T) -> String {
148-
let mut s = String::with_capacity(data.as_ref().len() * 2);
149-
for b in data.as_ref() {
150-
// Writing to a string never errors, so we can unwrap here.
151-
write!(&mut s, "{b:02x}").unwrap();
263+
let bytes = data.as_ref();
264+
let mut out = Vec::with_capacity(bytes.len() * 2);
265+
for &b in bytes {
266+
let hi = b >> 4;
267+
let lo = b & 0x0F;
268+
out.push(HEX_CHARS[hi as usize]);
269+
out.push(HEX_CHARS[lo as usize]);
152270
}
153-
s
271+
// SAFETY: out contains only ASCII
272+
unsafe { String::from_utf8_unchecked(out) }
154273
}

0 commit comments

Comments
 (0)