Skip to content

Commit 51e5c98

Browse files
authored
fix null handling for nanvl & implement fast path (#20205)
## 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. --> - Part of apache/datafusion-comet#2986 ## Rationale for this change `nanvl` currently evaluates scalar inputs via `make_scalar_function(nanvl, vec![])`, which converts scalar values into size‑1 arrays before execution and then converts back. This adds unnecessary overhead for constant folding / scalar evaluation Also fix bug where `null` was being returned if `y` was null, even if `x` was not `nan` - We treat nulls as normal values; we return `x` if and only if `x` is not `nan`, otherwise return `y` <!-- 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? - Add match-based scalar fast path for `ColumnarValue::Scalar + ColumnarValue::Scalar` - Add Criterion benchmarks: - `nanvl/scalar_f64` - `nanvl/scalar_f32` Benchmark | Before | After | Speedup ━━━━━━━━━━━━━━━━━━━━━━━ nanvl/scalar_f64 | ~240.1 ns | 50.104 ns ~4.79x nanvl/scalar_f32 |~237.1 ns | 49.284 ns ~4.81x <!-- 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. -->
1 parent a3d4651 commit 51e5c98

5 files changed

Lines changed: 181 additions & 40 deletions

File tree

datafusion/functions/Cargo.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,11 @@ harness = false
132132
name = "gcd"
133133
required-features = ["math_expressions"]
134134

135+
[[bench]]
136+
harness = false
137+
name = "nanvl"
138+
required-features = ["math_expressions"]
139+
135140
[[bench]]
136141
harness = false
137142
name = "uuid"
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
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::{ArrayRef, Float32Array, Float64Array};
21+
use arrow::datatypes::{DataType, Field};
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};
26+
use datafusion_functions::math::nanvl;
27+
use std::hint::black_box;
28+
use std::sync::Arc;
29+
30+
fn criterion_benchmark(c: &mut Criterion) {
31+
let nanvl_fn = nanvl();
32+
let config_options = Arc::new(ConfigOptions::default());
33+
34+
// Scalar benchmarks
35+
c.bench_function("nanvl/scalar_f64", |b| {
36+
let args = ScalarFunctionArgs {
37+
args: vec![
38+
ColumnarValue::Scalar(ScalarValue::Float64(Some(f64::NAN))),
39+
ColumnarValue::Scalar(ScalarValue::Float64(Some(1.0))),
40+
],
41+
arg_fields: vec![
42+
Field::new("a", DataType::Float64, true).into(),
43+
Field::new("b", DataType::Float64, true).into(),
44+
],
45+
number_rows: 1,
46+
return_field: Field::new("f", DataType::Float64, true).into(),
47+
config_options: Arc::clone(&config_options),
48+
};
49+
50+
b.iter(|| black_box(nanvl_fn.invoke_with_args(args.clone()).unwrap()))
51+
});
52+
53+
c.bench_function("nanvl/scalar_f32", |b| {
54+
let args = ScalarFunctionArgs {
55+
args: vec![
56+
ColumnarValue::Scalar(ScalarValue::Float32(Some(f32::NAN))),
57+
ColumnarValue::Scalar(ScalarValue::Float32(Some(1.0))),
58+
],
59+
arg_fields: vec![
60+
Field::new("a", DataType::Float32, true).into(),
61+
Field::new("b", DataType::Float32, true).into(),
62+
],
63+
number_rows: 1,
64+
return_field: Field::new("f", DataType::Float32, true).into(),
65+
config_options: Arc::clone(&config_options),
66+
};
67+
68+
b.iter(|| black_box(nanvl_fn.invoke_with_args(args.clone()).unwrap()))
69+
});
70+
71+
// Array benchmarks
72+
for size in [1024, 4096, 8192] {
73+
let a64: ArrayRef = Arc::new(Float64Array::from(vec![f64::NAN; size]));
74+
let b64: ArrayRef = Arc::new(Float64Array::from(vec![1.0; size]));
75+
c.bench_function(&format!("nanvl/array_f64/{size}"), |bench| {
76+
let args = ScalarFunctionArgs {
77+
args: vec![
78+
ColumnarValue::Array(Arc::clone(&a64)),
79+
ColumnarValue::Array(Arc::clone(&b64)),
80+
],
81+
arg_fields: vec![
82+
Field::new("a", DataType::Float64, true).into(),
83+
Field::new("b", DataType::Float64, true).into(),
84+
],
85+
number_rows: size,
86+
return_field: Field::new("f", DataType::Float64, true).into(),
87+
config_options: Arc::clone(&config_options),
88+
};
89+
bench.iter(|| black_box(nanvl_fn.invoke_with_args(args.clone()).unwrap()))
90+
});
91+
92+
let a32: ArrayRef = Arc::new(Float32Array::from(vec![f32::NAN; size]));
93+
let b32: ArrayRef = Arc::new(Float32Array::from(vec![1.0; size]));
94+
c.bench_function(&format!("nanvl/array_f32/{size}"), |bench| {
95+
let args = ScalarFunctionArgs {
96+
args: vec![
97+
ColumnarValue::Array(Arc::clone(&a32)),
98+
ColumnarValue::Array(Arc::clone(&b32)),
99+
],
100+
arg_fields: vec![
101+
Field::new("a", DataType::Float32, true).into(),
102+
Field::new("b", DataType::Float32, true).into(),
103+
],
104+
number_rows: size,
105+
return_field: Field::new("f", DataType::Float32, true).into(),
106+
config_options: Arc::clone(&config_options),
107+
};
108+
bench.iter(|| black_box(nanvl_fn.invoke_with_args(args.clone()).unwrap()))
109+
});
110+
}
111+
}
112+
113+
criterion_group!(benches, criterion_benchmark);
114+
criterion_main!(benches);

datafusion/functions/src/math/nanvl.rs

Lines changed: 59 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,10 @@
1818
use std::any::Any;
1919
use std::sync::Arc;
2020

21-
use crate::utils::make_scalar_function;
22-
2321
use arrow::array::{ArrayRef, AsArray, Float16Array, Float32Array, Float64Array};
2422
use arrow::datatypes::DataType::{Float16, Float32, Float64};
2523
use arrow::datatypes::{DataType, Float16Type, Float32Type, Float64Type};
26-
use datafusion_common::{DataFusionError, Result, exec_err};
24+
use datafusion_common::{Result, ScalarValue, exec_err, utils::take_function_args};
2725
use datafusion_expr::TypeSignature::Exact;
2826
use datafusion_expr::{
2927
ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
@@ -101,7 +99,24 @@ impl ScalarUDFImpl for NanvlFunc {
10199
}
102100

103101
fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
104-
make_scalar_function(nanvl, vec![])(&args.args)
102+
let [x, y] = take_function_args(self.name(), args.args)?;
103+
104+
match (x, y) {
105+
(ColumnarValue::Scalar(ScalarValue::Float16(Some(v))), y) if v.is_nan() => {
106+
Ok(y)
107+
}
108+
(ColumnarValue::Scalar(ScalarValue::Float32(Some(v))), y) if v.is_nan() => {
109+
Ok(y)
110+
}
111+
(ColumnarValue::Scalar(ScalarValue::Float64(Some(v))), y) if v.is_nan() => {
112+
Ok(y)
113+
}
114+
(x @ ColumnarValue::Scalar(_), _) => Ok(x),
115+
(x, y) => {
116+
let args = ColumnarValue::values_to_arrays(&[x, y])?;
117+
Ok(ColumnarValue::Array(nanvl(&args)?))
118+
}
119+
}
105120
}
106121

107122
fn documentation(&self) -> Option<&Documentation> {
@@ -110,42 +125,49 @@ impl ScalarUDFImpl for NanvlFunc {
110125
}
111126

112127
/// Nanvl SQL function
128+
///
129+
/// - x is NaN -> output is y (which may itself be NULL)
130+
/// - otherwise -> output is x (which may itself be NULL)
113131
fn nanvl(args: &[ArrayRef]) -> Result<ArrayRef> {
114132
match args[0].data_type() {
115133
Float64 => {
116-
let compute_nanvl = |x: f64, y: f64| {
117-
if x.is_nan() { y } else { x }
118-
};
119-
120-
let x = args[0].as_primitive() as &Float64Array;
121-
let y = args[1].as_primitive() as &Float64Array;
122-
arrow::compute::binary::<_, _, _, Float64Type>(x, y, compute_nanvl)
123-
.map(|res| Arc::new(res) as _)
124-
.map_err(DataFusionError::from)
134+
let x = args[0].as_primitive::<Float64Type>();
135+
let y = args[1].as_primitive::<Float64Type>();
136+
let result: Float64Array = x
137+
.iter()
138+
.zip(y.iter())
139+
.map(|(x_value, y_value)| match x_value {
140+
Some(x_value) if x_value.is_nan() => y_value,
141+
_ => x_value,
142+
})
143+
.collect();
144+
Ok(Arc::new(result) as ArrayRef)
125145
}
126146
Float32 => {
127-
let compute_nanvl = |x: f32, y: f32| {
128-
if x.is_nan() { y } else { x }
129-
};
130-
131-
let x = args[0].as_primitive() as &Float32Array;
132-
let y = args[1].as_primitive() as &Float32Array;
133-
arrow::compute::binary::<_, _, _, Float32Type>(x, y, compute_nanvl)
134-
.map(|res| Arc::new(res) as _)
135-
.map_err(DataFusionError::from)
147+
let x = args[0].as_primitive::<Float32Type>();
148+
let y = args[1].as_primitive::<Float32Type>();
149+
let result: Float32Array = x
150+
.iter()
151+
.zip(y.iter())
152+
.map(|(x_value, y_value)| match x_value {
153+
Some(x_value) if x_value.is_nan() => y_value,
154+
_ => x_value,
155+
})
156+
.collect();
157+
Ok(Arc::new(result) as ArrayRef)
136158
}
137159
Float16 => {
138-
let compute_nanvl =
139-
|x: <Float16Type as arrow::datatypes::ArrowPrimitiveType>::Native,
140-
y: <Float16Type as arrow::datatypes::ArrowPrimitiveType>::Native| {
141-
if x.is_nan() { y } else { x }
142-
};
143-
144-
let x = args[0].as_primitive() as &Float16Array;
145-
let y = args[1].as_primitive() as &Float16Array;
146-
arrow::compute::binary::<_, _, _, Float16Type>(x, y, compute_nanvl)
147-
.map(|res| Arc::new(res) as _)
148-
.map_err(DataFusionError::from)
160+
let x = args[0].as_primitive::<Float16Type>();
161+
let y = args[1].as_primitive::<Float16Type>();
162+
let result: Float16Array = x
163+
.iter()
164+
.zip(y.iter())
165+
.map(|(x_value, y_value)| match x_value {
166+
Some(x_value) if x_value.is_nan() => y_value,
167+
_ => x_value,
168+
})
169+
.collect();
170+
Ok(Arc::new(result) as ArrayRef)
149171
}
150172
other => exec_err!("Unsupported data type {other:?} for function nanvl"),
151173
}
@@ -163,8 +185,8 @@ mod test {
163185
#[test]
164186
fn test_nanvl_f64() {
165187
let args: Vec<ArrayRef> = vec![
166-
Arc::new(Float64Array::from(vec![1.0, f64::NAN, 3.0, f64::NAN])), // y
167-
Arc::new(Float64Array::from(vec![5.0, 6.0, f64::NAN, f64::NAN])), // x
188+
Arc::new(Float64Array::from(vec![1.0, f64::NAN, 3.0, f64::NAN])), // x
189+
Arc::new(Float64Array::from(vec![5.0, 6.0, f64::NAN, f64::NAN])), // y
168190
];
169191

170192
let result = nanvl(&args).expect("failed to initialize function nanvl");
@@ -181,8 +203,8 @@ mod test {
181203
#[test]
182204
fn test_nanvl_f32() {
183205
let args: Vec<ArrayRef> = vec![
184-
Arc::new(Float32Array::from(vec![1.0, f32::NAN, 3.0, f32::NAN])), // y
185-
Arc::new(Float32Array::from(vec![5.0, 6.0, f32::NAN, f32::NAN])), // x
206+
Arc::new(Float32Array::from(vec![1.0, f32::NAN, 3.0, f32::NAN])), // x
207+
Arc::new(Float32Array::from(vec![5.0, 6.0, f32::NAN, f32::NAN])), // y
186208
];
187209

188210
let result = nanvl(&args).expect("failed to initialize function nanvl");

datafusion/sqllogictest/test_files/expr.slt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ SELECT
6060
isnan(NULL),
6161
iszero(NULL)
6262
----
63-
NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
63+
NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 1 NULL NULL NULL
6464

6565
# test_array_cast_invalid_timezone_will_panic
6666
statement error Parser error: Invalid timezone "Foo": failed to parse timezone

datafusion/sqllogictest/test_files/scalar.slt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -765,11 +765,11 @@ select nanvl(null, 64);
765765
----
766766
NULL
767767

768-
# nanvl scalar nulls #1
768+
# nanvl scalar nulls #1 - x is not NaN, so return x even if y is NULL
769769
query R rowsort
770770
select nanvl(2, null);
771771
----
772-
NULL
772+
2
773773

774774
# nanvl scalar nulls #2
775775
query R rowsort

0 commit comments

Comments
 (0)