Apache DataFusion SQL Query Engine
Add is_volatile(PhysicalExpr) as a generic public API for volatility (#17351)
Adrian Garcia Badaraccof5bdc2d6a9df
diff --git a/datafusion/physical-expr-common/src/physical_expr.rs b/datafusion/physical-expr-common/src/physical_expr.rsindex 023b697aed..6f7c432c75 100644--- a/datafusion/physical-expr-common/src/physical_expr.rs+++ b/datafusion/physical-expr-common/src/physical_expr.rs@@ -377,6 +377,22 @@ pub trait PhysicalExpr: Any + Send + Sync + Display + Debug + DynEq + DynHash {// static expressions will always return 0.0}++ /// Returns true if the expression node is volatile, i.e. whether it can return+ /// different results when evaluated multiple times with the same input.+ ///+ /// Note: unlike [`is_volatile`], this function does not consider inputs:+ /// - `random()` returns `true`,+ /// - `a + random()` returns `false` (because the operation `+` itself is not volatile.)+ ///+ /// The default to this function was set to `false` when it was created+ /// to avoid imposing API churn on implementers, but this is not a safe default in general.+ /// It is highly recommended that volatile expressions implement this method and return `true`.+ /// This default may be removed in the future if it causes problems or we decide to+ /// eat the cost of the breaking change and require all implementers to make a choice.+ fn is_volatile_node(&self) -> bool {+ false+ }}#[deprecated(@@ -560,3 +576,28 @@ pub fn is_dynamic_physical_expr(expr: &Arc<dyn PhysicalExpr>) -> bool {// If the generation is non-zero, then this `PhysicalExpr` is dynamic.snapshot_generation(expr) != 0}++/// Returns true if the expression is volatile, i.e. whether it can return different+/// results when evaluated multiple times with the same input.+///+/// For example the function call `RANDOM()` is volatile as each call will+/// return a different value.+///+/// This method recursively checks if any sub-expression is volatile, for example+/// `1 + RANDOM()` will return `true`.+pub fn is_volatile(expr: &Arc<dyn PhysicalExpr>) -> bool {+ if expr.is_volatile_node() {+ return true;+ }+ let mut is_volatile = false;+ expr.apply(|e| {+ if e.is_volatile_node() {+ is_volatile = true;+ Ok(TreeNodeRecursion::Stop)+ } else {+ Ok(TreeNodeRecursion::Continue)+ }+ })+ .expect("infallible closure should not fail");+ is_volatile+}diff --git a/datafusion/physical-expr/src/physical_expr.rs b/datafusion/physical-expr/src/physical_expr.rsindex 80dd8ce069..3f063d7a03 100644--- a/datafusion/physical-expr/src/physical_expr.rs+++ b/datafusion/physical-expr/src/physical_expr.rs@@ -204,12 +204,19 @@ pub fn add_offset_to_physical_sort_exprs(mod tests {use super::*;- use crate::expressions::{Column, Literal};+ use crate::expressions::{BinaryExpr, Column, Literal};use crate::physical_expr::{physical_exprs_bag_equal, physical_exprs_contains, physical_exprs_equal,};+ use datafusion_physical_expr_common::physical_expr::is_volatile;- use datafusion_common::ScalarValue;+ use arrow::datatypes::{DataType, Schema};+ use arrow::record_batch::RecordBatch;+ use datafusion_common::{Result, ScalarValue};+ use datafusion_expr::ColumnarValue;+ use datafusion_expr::Operator;+ use std::any::Any;+ use std::fmt;#[test]fn test_physical_exprs_contains() {@@ -322,4 +329,120 @@ mod tests {assert!(physical_exprs_bag_equal(list3.as_slice(), list3.as_slice()));assert!(physical_exprs_bag_equal(list4.as_slice(), list4.as_slice()));}++ #[test]+ fn test_is_volatile_default_behavior() {+ // Test that default PhysicalExpr implementations are not volatile+ let literal =+ Arc::new(Literal::new(ScalarValue::Int32(Some(42)))) as Arc<dyn PhysicalExpr>;+ let column = Arc::new(Column::new("test", 0)) as Arc<dyn PhysicalExpr>;++ // Test is_volatile_node() - should return false by default+ assert!(!literal.is_volatile_node());+ assert!(!column.is_volatile_node());++ // Test is_volatile() - should return false for non-volatile expressions+ assert!(!is_volatile(&literal));+ assert!(!is_volatile(&column));+ }++ /// Mock volatile PhysicalExpr for testing purposes+ #[derive(Debug, Clone, PartialEq, Eq, Hash)]+ struct MockVolatileExpr {+ volatile: bool,+ }++ impl MockVolatileExpr {+ fn new(volatile: bool) -> Self {+ Self { volatile }+ }+ }++ impl fmt::Display for MockVolatileExpr {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "MockVolatile({})", self.volatile)+ }+ }++ impl PhysicalExpr for MockVolatileExpr {+ fn as_any(&self) -> &dyn Any {+ self+ }++ fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {+ Ok(DataType::Boolean)+ }++ fn nullable(&self, _input_schema: &Schema) -> Result<bool> {+ Ok(false)+ }++ fn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> {+ Ok(ColumnarValue::Scalar(ScalarValue::Boolean(Some(+ self.volatile,+ ))))+ }++ fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {+ vec![]+ }++ fn with_new_children(+ self: Arc<Self>,+ _children: Vec<Arc<dyn PhysicalExpr>>,+ ) -> Result<Arc<dyn PhysicalExpr>> {+ Ok(self)+ }++ fn is_volatile_node(&self) -> bool {+ self.volatile+ }++ fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "mock_volatile({})", self.volatile)+ }+ }++ #[test]+ fn test_nested_expression_volatility() {+ // Test that is_volatile() recursively detects volatility in expression trees++ // Create a volatile mock expression+ let volatile_expr =+ Arc::new(MockVolatileExpr::new(true)) as Arc<dyn PhysicalExpr>;+ assert!(volatile_expr.is_volatile_node());+ assert!(is_volatile(&volatile_expr));++ // Create a non-volatile mock expression+ let stable_expr = Arc::new(MockVolatileExpr::new(false)) as Arc<dyn PhysicalExpr>;+ assert!(!stable_expr.is_volatile_node());+ assert!(!is_volatile(&stable_expr));++ // Create a literal (non-volatile)+ let literal =+ Arc::new(Literal::new(ScalarValue::Int32(Some(42)))) as Arc<dyn PhysicalExpr>;+ assert!(!literal.is_volatile_node());+ assert!(!is_volatile(&literal));++ // Test composite expression: volatile_expr AND literal+ // The BinaryExpr itself is not volatile, but contains a volatile child+ let composite_expr = Arc::new(BinaryExpr::new(+ Arc::clone(&volatile_expr),+ Operator::And,+ Arc::clone(&literal),+ )) as Arc<dyn PhysicalExpr>;++ assert!(!composite_expr.is_volatile_node()); // BinaryExpr itself is not volatile+ assert!(is_volatile(&composite_expr)); // But it contains a volatile child++ // Test composite expression with all non-volatile children+ let stable_composite = Arc::new(BinaryExpr::new(+ Arc::clone(&stable_expr),+ Operator::And,+ Arc::clone(&literal),+ )) as Arc<dyn PhysicalExpr>;++ assert!(!stable_composite.is_volatile_node());+ assert!(!is_volatile(&stable_composite)); // No volatile children+ }}diff --git a/datafusion/physical-expr/src/scalar_function.rs b/datafusion/physical-expr/src/scalar_function.rsindex 7a3c463f25..743d5b99cd 100644--- a/datafusion/physical-expr/src/scalar_function.rs+++ b/datafusion/physical-expr/src/scalar_function.rs@@ -46,6 +46,7 @@ use datafusion_expr::sort_properties::ExprProperties;use datafusion_expr::type_coercion::functions::data_types_with_scalar_udf;use datafusion_expr::{expr_vec_fmt, ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDF,+ Volatility,};/// Physical expression of a scalar function@@ -358,4 +359,89 @@ impl PhysicalExpr for ScalarFunctionExpr {}write!(f, ")")}++ fn is_volatile_node(&self) -> bool {+ self.fun.signature().volatility == Volatility::Volatile+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::expressions::Column;+ use arrow::datatypes::{DataType, Field, Schema};+ use datafusion_expr::{ScalarUDF, ScalarUDFImpl, Signature};+ use datafusion_physical_expr_common::physical_expr::is_volatile;+ use std::any::Any;++ /// Test helper to create a mock UDF with a specific volatility+ #[derive(Debug, PartialEq, Eq, Hash)]+ struct MockScalarUDF {+ signature: Signature,+ }++ impl ScalarUDFImpl for MockScalarUDF {+ fn as_any(&self) -> &dyn Any {+ self+ }++ fn name(&self) -> &str {+ "mock_function"+ }++ fn signature(&self) -> &Signature {+ &self.signature+ }++ fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {+ Ok(DataType::Int32)+ }++ fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {+ Ok(ColumnarValue::Scalar(ScalarValue::Int32(Some(42))))+ }+ }++ #[test]+ fn test_scalar_function_volatile_node() {+ // Create a volatile UDF+ let volatile_udf = Arc::new(ScalarUDF::from(MockScalarUDF {+ signature: Signature::uniform(+ 1,+ vec![DataType::Float32],+ Volatility::Volatile,+ ),+ }));++ // Create a non-volatile UDF+ let stable_udf = Arc::new(ScalarUDF::from(MockScalarUDF {+ signature: Signature::uniform(1, vec![DataType::Float32], Volatility::Stable),+ }));++ let schema = Schema::new(vec![Field::new("a", DataType::Float32, false)]);+ let args = vec![Arc::new(Column::new("a", 0)) as Arc<dyn PhysicalExpr>];+ let config_options = Arc::new(ConfigOptions::new());++ // Test volatile function+ let volatile_expr = ScalarFunctionExpr::try_new(+ volatile_udf,+ args.clone(),+ &schema,+ Arc::clone(&config_options),+ )+ .unwrap();++ assert!(volatile_expr.is_volatile_node());+ let volatile_arc: Arc<dyn PhysicalExpr> = Arc::new(volatile_expr);+ assert!(is_volatile(&volatile_arc));++ // Test non-volatile function+ let stable_expr =+ ScalarFunctionExpr::try_new(stable_udf, args, &schema, config_options)+ .unwrap();++ assert!(!stable_expr.is_volatile_node());+ let stable_arc: Arc<dyn PhysicalExpr> = Arc::new(stable_expr);+ assert!(!is_volatile(&stable_arc));+ }}diff --git a/datafusion/physical-optimizer/src/filter_pushdown.rs b/datafusion/physical-optimizer/src/filter_pushdown.rsindex 5aedce06b9..d19e62550e 100644--- a/datafusion/physical-optimizer/src/filter_pushdown.rs+++ b/datafusion/physical-optimizer/src/filter_pushdown.rs@@ -37,8 +37,8 @@ use crate::PhysicalOptimizerRule;use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};use datafusion_common::{config::ConfigOptions, Result};-use datafusion_expr_common::signature::Volatility;use datafusion_physical_expr::PhysicalExpr;+use datafusion_physical_expr_common::physical_expr::is_volatile;use datafusion_physical_plan::filter_pushdown::{ChildFilterPushdownResult, ChildPushdownResult, FilterPushdownPhase,FilterPushdownPropagation, PushedDown,@@ -711,7 +711,7 @@ impl<T: Clone> FilteredVec<T> {fn allow_pushdown_for_expr(expr: &Arc<dyn PhysicalExpr>) -> bool {let mut allow_pushdown = true;expr.apply(|e| {- allow_pushdown = allow_pushdown && allow_pushdown_for_expr_inner(e);+ allow_pushdown = allow_pushdown && !is_volatile(e);if allow_pushdown {Ok(TreeNodeRecursion::Continue)} else {@@ -722,20 +722,6 @@ fn allow_pushdown_for_expr(expr: &Arc<dyn PhysicalExpr>) -> bool {allow_pushdown}-fn allow_pushdown_for_expr_inner(expr: &Arc<dyn PhysicalExpr>) -> bool {- if let Some(scalar_function) =- expr.as_any()- .downcast_ref::<datafusion_physical_expr::ScalarFunctionExpr>()- {- // Check if the function is volatile using the proper volatility API- if scalar_function.fun().signature().volatility == Volatility::Volatile {- // Volatile functions should not be pushed down- return false;- }- }- true-}-#[cfg(test)]mod tests {use super::*;