You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "Brijesh-Thakkar (via GitHub)" <gi...@apache.org> on 2026/05/28 20:42:12 UTC
[PR] feat: add SparkPow UDF returning Infinity for pow(0, negative) [datafusion]
Brijesh-Thakkar opened a new pull request, #22605:
URL: https://github.com/apache/datafusion/pull/22605
## Which issue does this PR close?
Closes #22598
## Rationale for this change
In Apache Spark, the `pow(base, exp)` function follows IEEE 754 semantics where raising `0` (or `-0.0`) to a negative exponent yields positive `Infinity`.
Currently, DataFusion's default core `PowerFunc` mimics PostgreSQL behavior, throwing an explicit error (`"zero raised to a negative power is undefined"`). To support standard Spark compatibility without breaking core DataFusion expectations, this PR introduces a specialized `SparkPow` UDF inside the `datafusion-spark` crate.
## What changes are included in this PR?
This PR introduces the following changes within the `datafusion-spark` integration crate:
* **Added `SparkPow` UDF** (`datafusion/spark/src/function/math/pow.rs`): Overrides the `Float64` execution path to evaluate `base == 0.0 && exp < 0.0` as `f64::INFINITY` (safely catching both `0.0` and `-0.0` due to IEEE 754 equality rules).
* **Decimal Delegation**: Preserves correctness by delegating non-float types (like decimals) back to the standard `PowerFunc`, as decimals cannot represent infinity.
* **Function Registration** (`datafusion/spark/src/function/math/mod.rs`): Registers the new `pow` function and establishes `power` as a valid alias.
* **SQL Integration Tests** (`datafusion/sqllogictest/test_files/spark/math/pow.slt`): Updates and adds test coverage ensuring `pow(0, -1)`, `power(0, -1)`, and `pow(0.0, -1.0)` successfully return `Infinity`.
## Are these changes tested?
Yes, the changes are covered via both unit and integration tests:
1. **Unit Tests**: Added `test_spark_pow_zero_negative_returns_infinity` and `test_spark_pow_normal_cases` within `pow.rs` to validate the core scalar execution logic.
2. **Integration Tests**: Extended `datafusion/sqllogictest/test_files/spark/math/pow.slt` to verify the end-to-end SQL evaluation behavior.
## Are there any user-facing changes?
Yes, but only for users utilizing the `datafusion-spark` compatibility features. When the Spark dialect/crate is active, evaluating `pow(0, <negative>)` will now return `Infinity` instead of throwing an evaluation error. Core DataFusion behavior remains completely unchanged.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: add SparkPow UDF returning Infinity for pow(0, negative) [datafusion]
Posted by "Brijesh-Thakkar (via GitHub)" <gi...@apache.org>.
Brijesh-Thakkar commented on PR #22605:
URL: https://github.com/apache/datafusion/pull/22605#issuecomment-4571566154
> Thanks @Brijesh-Thakkar this a solid PR, please remove tests from `pow.rs`, those are repetitive.
>
> for the `pow.slt` lets have more double edgecases, specifically, nulls, nans, -0, +0, -inf, +Inf
@comphead Removed tests from pow.rs file as you sugegested and also added more edge cases
Thank you
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: add SparkPow UDF returning Infinity for pow(0, negative) [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #22605:
URL: https://github.com/apache/datafusion/pull/22605#discussion_r3326281585
##########
datafusion/spark/src/function/math/pow.rs:
##########
@@ -0,0 +1,152 @@
+// 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.
+
+//! Spark-compatible `pow` / `power` function.
+//!
+//! Unlike the default DataFusion (PostgreSQL) implementation, Spark returns
+//! `Infinity` for `pow(0, <negative>)` rather than raising an error.
+
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, Float64Array};
+use arrow::datatypes::DataType;
+
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{Result, ScalarValue};
+use datafusion_expr::{
+ ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
+};
+use datafusion_functions::math::power::PowerFunc;
+
+/// Spark-compatible implementation of `pow` / `power`.
+///
+/// Behavioural difference from the DataFusion default:
+/// - `pow(0, <negative>)` → `Infinity` (IEEE 754 / Spark semantics)
+/// The default raises `"zero raised to a negative power is undefined"` to
+/// match PostgreSQL.
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkPow {
+ inner: PowerFunc,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkPow {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkPow {
+ pub fn new() -> Self {
+ Self {
+ inner: PowerFunc::new(),
+ // SparkPow is named "pow"; expose "power" as an alias so that
+ // both names resolve to Spark semantics when this crate is active.
+ aliases: vec!["power".to_string()],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkPow {
+ fn name(&self) -> &str {
+ "pow"
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn signature(&self) -> &Signature {
+ self.inner.signature()
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+ self.inner.return_type(arg_types)
+ }
+
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
+ // Only Float64 × Float64 needs the Spark override.
+ // Decimal / integer / mixed-type paths are delegated to the standard
+ // PowerFunc which already handles them correctly (decimal can't
+ // represent Infinity anyway).
+ match args.args.as_slice() {
+ [base, exponent]
+ if matches!(base.data_type(), DataType::Float64)
+ && matches!(exponent.data_type(), DataType::Float64) => {}
+ _ => return self.inner.invoke_with_args(args),
+ }
+
+ let num_rows = args.number_rows;
+
+ // ── Scalar × Scalar fast path ────────────────────────────────────────
+ // Pattern-match on the slice to avoid any ownership issues.
+ if let [
+ ColumnarValue::Scalar(ScalarValue::Float64(b)),
+ ColumnarValue::Scalar(ScalarValue::Float64(e)),
+ ] = args.args.as_slice()
+ {
+ // b and e are &Option<f64>; Option<f64> is Copy.
+ let result = (*b).zip(*e).map(|(b, e)| {
+ if b == 0.0 && e < 0.0 {
+ f64::INFINITY
+ } else {
+ b.powf(e)
+ }
+ });
+ return Ok(ColumnarValue::Scalar(ScalarValue::Float64(result)));
+ }
+
+ // ── Array path ───────────────────────────────────────────────────────
+ let [base, exponent] = take_function_args(self.name(), &args.args)?;
+
+ let base_arr: ArrayRef = base.to_array(num_rows)?;
+ let exp_arr: ArrayRef = exponent.to_array(num_rows)?;
+
+ let base_f64 = base_arr
+ .as_any()
+ .downcast_ref::<Float64Array>()
+ .expect("base must be Float64Array");
+ let exp_f64 = exp_arr
+ .as_any()
+ .downcast_ref::<Float64Array>()
+ .expect("exponent must be Float64Array");
+
+ // Spark: 0^negative = +Infinity (covers both 0.0 and -0.0)
+ // IEEE 754: 0.0^-1.0 = +Infinity, -0.0^-1.0 = -Infinity
+ // Thus we need an explicit guard for b == 0.0 to ensure +Infinity.
+ let result: Float64Array = base_f64
+ .iter()
+ .zip(exp_f64.iter())
+ .map(|(b, e)| match (b, e) {
Review Comment:
same
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: add SparkPow UDF returning Infinity for pow(0, negative) [datafusion]
Posted by "Brijesh-Thakkar (via GitHub)" <gi...@apache.org>.
Brijesh-Thakkar commented on PR #22605:
URL: https://github.com/apache/datafusion/pull/22605#issuecomment-4578716642
@comphead I will fix this and commit the changes
Thanks for review
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: add SparkPow UDF returning Infinity for pow(0, negative) [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead merged PR #22605:
URL: https://github.com/apache/datafusion/pull/22605
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: add SparkPow UDF returning Infinity for pow(0, negative) [datafusion]
Posted by "Brijesh-Thakkar (via GitHub)" <gi...@apache.org>.
Brijesh-Thakkar commented on PR #22605:
URL: https://github.com/apache/datafusion/pull/22605#issuecomment-4578965875
@comphead All requested changes have been addressed and checks are passing. Could you please approve the PR when you get a chance? Thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: add SparkPow UDF returning Infinity for pow(0, negative) [datafusion]
Posted by "Brijesh-Thakkar (via GitHub)" <gi...@apache.org>.
Brijesh-Thakkar commented on PR #22605:
URL: https://github.com/apache/datafusion/pull/22605#issuecomment-4578771612
@comphead I have done the changes as you suggested and commited them as well
Thanks
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: add SparkPow UDF returning Infinity for pow(0, negative) [datafusion]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #22605:
URL: https://github.com/apache/datafusion/pull/22605#discussion_r3320529943
##########
datafusion/spark/src/function/math/pow.rs:
##########
@@ -0,0 +1,195 @@
+// 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.
+
+//! Spark-compatible `pow` / `power` function.
+//!
+//! Unlike the default DataFusion (PostgreSQL) implementation, Spark returns
+//! `Infinity` for `pow(0, <negative>)` rather than raising an error.
+
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, Float64Array};
+use arrow::datatypes::DataType;
+
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{Result, ScalarValue};
+use datafusion_expr::{
+ ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
+};
+use datafusion_functions::math::power::PowerFunc;
+
+/// Spark-compatible implementation of `pow` / `power`.
+///
+/// Behavioural difference from the DataFusion default:
+/// - `pow(0, <negative>)` → `Infinity` (IEEE 754 / Spark semantics)
+/// The default raises `"zero raised to a negative power is undefined"` to
+/// match PostgreSQL.
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkPow {
+ inner: PowerFunc,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkPow {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkPow {
+ pub fn new() -> Self {
+ Self {
+ inner: PowerFunc::new(),
+ // SparkPow is named "pow"; expose "power" as an alias so that
+ // both names resolve to Spark semantics when this crate is active.
+ aliases: vec!["power".to_string()],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkPow {
+ fn name(&self) -> &str {
+ "pow"
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn signature(&self) -> &Signature {
+ self.inner.signature()
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+ self.inner.return_type(arg_types)
+ }
+
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
+ // Only Float64 needs the Spark override.
+ // Decimal / integer paths are delegated to the standard PowerFunc which
+ // already handles them correctly (decimal can't represent Infinity anyway).
+ if !matches!(args.args[0].data_type(), DataType::Float64) {
+ return self.inner.invoke_with_args(args);
Review Comment:
The Float64 override gate only checks the first argument’s type, but the implementation later assumes *both* base and exponent are Float64 (downcasts with `expect`). If base is Float64 but exponent is a different numeric type (possible with coercions/mixed inputs), this can panic. Consider checking both arg types up-front (base and exponent) and delegating to `inner` unless both are Float64, or explicitly casting the exponent to Float64 before downcasting.
##########
datafusion/sqllogictest/test_files/spark/math/pow.slt:
##########
@@ -22,6 +22,27 @@
# https://github.com/apache/datafusion/issues/15914
## Original Query: SELECT pow(2, 3);
-## PySpark 3.5.5 Result: {'pow(2, 3)': 8.0, 'typeof(pow(2, 3))': 'double', 'typeof(2)': 'int', 'typeof(3)': 'int'}
-#query
-#SELECT pow(2::int, 3::int);
+## PySpark 3.5.5 Result: {'pow(2, 3)': 8.0, 'typeof(pow(2, 3))': 'double'}
+query R
+SELECT pow(2::int, 3::int);
+----
+8
Review Comment:
This SLT expectation appears inconsistent with the documented PySpark result (`8.0` as a double). With `query R`, results are regex-matched per value; `8` typically won’t match `8.0` unless written as a regex that allows the decimal part. If the engine returns a double-formatted value, update the expected output to match (e.g., `8.0`) or use a regex that allows either representation (e.g., `8(\\.0)?`) so the test matches Spark’s double semantics.
##########
datafusion/spark/src/function/math/pow.rs:
##########
@@ -0,0 +1,195 @@
+// 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.
+
+//! Spark-compatible `pow` / `power` function.
+//!
+//! Unlike the default DataFusion (PostgreSQL) implementation, Spark returns
+//! `Infinity` for `pow(0, <negative>)` rather than raising an error.
+
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, Float64Array};
+use arrow::datatypes::DataType;
+
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{Result, ScalarValue};
+use datafusion_expr::{
+ ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
+};
+use datafusion_functions::math::power::PowerFunc;
+
+/// Spark-compatible implementation of `pow` / `power`.
+///
+/// Behavioural difference from the DataFusion default:
+/// - `pow(0, <negative>)` → `Infinity` (IEEE 754 / Spark semantics)
+/// The default raises `"zero raised to a negative power is undefined"` to
+/// match PostgreSQL.
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkPow {
+ inner: PowerFunc,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkPow {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkPow {
+ pub fn new() -> Self {
+ Self {
+ inner: PowerFunc::new(),
+ // SparkPow is named "pow"; expose "power" as an alias so that
+ // both names resolve to Spark semantics when this crate is active.
+ aliases: vec!["power".to_string()],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkPow {
+ fn name(&self) -> &str {
+ "pow"
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn signature(&self) -> &Signature {
+ self.inner.signature()
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+ self.inner.return_type(arg_types)
+ }
+
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
+ // Only Float64 needs the Spark override.
+ // Decimal / integer paths are delegated to the standard PowerFunc which
+ // already handles them correctly (decimal can't represent Infinity anyway).
+ if !matches!(args.args[0].data_type(), DataType::Float64) {
+ return self.inner.invoke_with_args(args);
+ }
+
+ let num_rows = args.number_rows;
+
+ // ── Scalar × Scalar fast path ────────────────────────────────────────
+ // Pattern-match on the slice to avoid any ownership issues.
+ if let [
+ ColumnarValue::Scalar(ScalarValue::Float64(b)),
+ ColumnarValue::Scalar(ScalarValue::Float64(e)),
+ ] = args.args.as_slice()
+ {
+ // b and e are &Option<f64>; Option<f64> is Copy.
+ let result = (*b).zip(*e).map(|(b, e)| {
+ // Spark: 0^negative = +Infinity (covers both 0.0 and -0.0)
+ if b == 0.0 && e < 0.0 {
+ f64::INFINITY
+ } else {
+ b.powf(e)
+ }
+ });
+ return Ok(ColumnarValue::Scalar(ScalarValue::Float64(result)));
+ }
+
+ // ── Array path ───────────────────────────────────────────────────────
+ let [base, exponent] = take_function_args(self.name(), &args.args)?;
+
+ let base_arr: ArrayRef = base.to_array(num_rows)?;
+ let exp_arr: ArrayRef = exponent.to_array(num_rows)?;
Review Comment:
Unit tests currently cover only the scalar×scalar fast path. The array path (and mixed scalar/array cases) is newly introduced behavior and should be exercised to prevent regressions, especially around `0 ^ negative` and null handling. Add tests that pass `ColumnarValue::Array` inputs (and ideally a mixed scalar/array case) and assert `Infinity` for base=0 and exponent<0.
##########
datafusion/spark/src/function/math/pow.rs:
##########
@@ -0,0 +1,195 @@
+// 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.
+
+//! Spark-compatible `pow` / `power` function.
+//!
+//! Unlike the default DataFusion (PostgreSQL) implementation, Spark returns
+//! `Infinity` for `pow(0, <negative>)` rather than raising an error.
+
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, Float64Array};
+use arrow::datatypes::DataType;
+
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{Result, ScalarValue};
+use datafusion_expr::{
+ ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
+};
+use datafusion_functions::math::power::PowerFunc;
+
+/// Spark-compatible implementation of `pow` / `power`.
+///
+/// Behavioural difference from the DataFusion default:
+/// - `pow(0, <negative>)` → `Infinity` (IEEE 754 / Spark semantics)
+/// The default raises `"zero raised to a negative power is undefined"` to
+/// match PostgreSQL.
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkPow {
+ inner: PowerFunc,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkPow {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkPow {
+ pub fn new() -> Self {
+ Self {
+ inner: PowerFunc::new(),
+ // SparkPow is named "pow"; expose "power" as an alias so that
+ // both names resolve to Spark semantics when this crate is active.
+ aliases: vec!["power".to_string()],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkPow {
+ fn name(&self) -> &str {
+ "pow"
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn signature(&self) -> &Signature {
+ self.inner.signature()
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+ self.inner.return_type(arg_types)
+ }
+
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
+ // Only Float64 needs the Spark override.
+ // Decimal / integer paths are delegated to the standard PowerFunc which
+ // already handles them correctly (decimal can't represent Infinity anyway).
+ if !matches!(args.args[0].data_type(), DataType::Float64) {
+ return self.inner.invoke_with_args(args);
+ }
+
+ let num_rows = args.number_rows;
+
+ // ── Scalar × Scalar fast path ────────────────────────────────────────
+ // Pattern-match on the slice to avoid any ownership issues.
+ if let [
+ ColumnarValue::Scalar(ScalarValue::Float64(b)),
+ ColumnarValue::Scalar(ScalarValue::Float64(e)),
+ ] = args.args.as_slice()
+ {
+ // b and e are &Option<f64>; Option<f64> is Copy.
+ let result = (*b).zip(*e).map(|(b, e)| {
+ // Spark: 0^negative = +Infinity (covers both 0.0 and -0.0)
+ if b == 0.0 && e < 0.0 {
+ f64::INFINITY
+ } else {
+ b.powf(e)
+ }
+ });
+ return Ok(ColumnarValue::Scalar(ScalarValue::Float64(result)));
+ }
+
+ // ── Array path ───────────────────────────────────────────────────────
+ let [base, exponent] = take_function_args(self.name(), &args.args)?;
+
+ let base_arr: ArrayRef = base.to_array(num_rows)?;
+ let exp_arr: ArrayRef = exponent.to_array(num_rows)?;
+
+ let base_f64 = base_arr
+ .as_any()
+ .downcast_ref::<Float64Array>()
+ .expect("base must be Float64Array");
+ let exp_f64 = exp_arr
+ .as_any()
+ .downcast_ref::<Float64Array>()
+ .expect("exponent must be Float64Array");
+
+ // b.powf(e) follows IEEE 754: 0.0_f64.powf(-1.0) == f64::INFINITY.
+ // No explicit guard needed — the default Rust behaviour is exactly
+ // what Spark requires.
+ let result: Float64Array = base_f64
+ .iter()
+ .zip(exp_f64.iter())
+ .map(|(b, e)| match (b, e) {
+ (Some(b), Some(e)) => {
+ if b == 0.0 && e < 0.0 {
+ Some(f64::INFINITY)
+ } else {
+ Some(b.powf(e))
+ }
+ }
Review Comment:
The comment says no explicit guard is needed for `0 ^ negative`, but the code still includes an explicit guard. This is internally inconsistent and could confuse future maintainers. Either remove the guard (since `powf` already yields `Infinity`) or update the comment to explain why the explicit branch is intentionally retained (e.g., clarity/consistency with scalar path).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: add SparkPow UDF returning Infinity for pow(0, negative) [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #22605:
URL: https://github.com/apache/datafusion/pull/22605#discussion_r3326276148
##########
datafusion/spark/src/function/math/pow.rs:
##########
@@ -0,0 +1,152 @@
+// 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.
+
+//! Spark-compatible `pow` / `power` function.
+//!
+//! Unlike the default DataFusion (PostgreSQL) implementation, Spark returns
+//! `Infinity` for `pow(0, <negative>)` rather than raising an error.
+
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, Float64Array};
+use arrow::datatypes::DataType;
+
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{Result, ScalarValue};
+use datafusion_expr::{
+ ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
+};
+use datafusion_functions::math::power::PowerFunc;
+
+/// Spark-compatible implementation of `pow` / `power`.
+///
+/// Behavioural difference from the DataFusion default:
+/// - `pow(0, <negative>)` → `Infinity` (IEEE 754 / Spark semantics)
+/// The default raises `"zero raised to a negative power is undefined"` to
+/// match PostgreSQL.
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkPow {
+ inner: PowerFunc,
+ aliases: Vec<String>,
+}
+
+impl Default for SparkPow {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkPow {
+ pub fn new() -> Self {
+ Self {
+ inner: PowerFunc::new(),
+ // SparkPow is named "pow"; expose "power" as an alias so that
+ // both names resolve to Spark semantics when this crate is active.
+ aliases: vec!["power".to_string()],
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkPow {
+ fn name(&self) -> &str {
+ "pow"
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn signature(&self) -> &Signature {
+ self.inner.signature()
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+ self.inner.return_type(arg_types)
+ }
+
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
+ // Only Float64 × Float64 needs the Spark override.
+ // Decimal / integer / mixed-type paths are delegated to the standard
+ // PowerFunc which already handles them correctly (decimal can't
+ // represent Infinity anyway).
+ match args.args.as_slice() {
+ [base, exponent]
+ if matches!(base.data_type(), DataType::Float64)
+ && matches!(exponent.data_type(), DataType::Float64) => {}
+ _ => return self.inner.invoke_with_args(args),
+ }
+
+ let num_rows = args.number_rows;
+
+ // ── Scalar × Scalar fast path ────────────────────────────────────────
+ // Pattern-match on the slice to avoid any ownership issues.
+ if let [
+ ColumnarValue::Scalar(ScalarValue::Float64(b)),
+ ColumnarValue::Scalar(ScalarValue::Float64(e)),
+ ] = args.args.as_slice()
+ {
+ // b and e are &Option<f64>; Option<f64> is Copy.
+ let result = (*b).zip(*e).map(|(b, e)| {
Review Comment:
lets call it base, exp instead of b, e
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org