From 77814f3c83a9a3a7ddceb24b5f9c49c80e4ac154 Mon Sep 17 00:00:00 2001 From: Daniel King Date: Thu, 12 Nov 2026 14:55:38 -0500 Subject: [PATCH 1/2] Lower mixed DataFusion expressions into Vortex scans Signed-off-by: Daniel King --- Cargo.lock | 1 + vortex-datafusion/Cargo.toml | 1 + .../src/convert/exprs/fallback.rs | 264 ++++++++++ .../src/convert/exprs/mixed_tests.rs | 493 ++++++++++++++++++ vortex-datafusion/src/convert/exprs/mod.rs | 225 ++++++-- vortex-datafusion/src/convert/exprs/tests.rs | 119 ++--- vortex-datafusion/src/v2/tests.rs | 88 +++- 7 files changed, 1068 insertions(+), 123 deletions(-) create mode 100644 vortex-datafusion/src/convert/exprs/fallback.rs create mode 100644 vortex-datafusion/src/convert/exprs/mixed_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 265d4b24ebd..a31abc4281a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11824,6 +11824,7 @@ dependencies = [ "insta", "itertools 0.14.0", "object_store 0.13.2", + "parking_lot", "rstest", "tempfile", "tokio", diff --git a/vortex-datafusion/Cargo.toml b/vortex-datafusion/Cargo.toml index fa73a69b0e9..e4d046a523d 100644 --- a/vortex-datafusion/Cargo.toml +++ b/vortex-datafusion/Cargo.toml @@ -32,6 +32,7 @@ datafusion-pruning = { workspace = true } futures = { workspace = true } itertools = { workspace = true } object_store = { workspace = true } +parking_lot = { workspace = true } tokio = { workspace = true, features = ["rt-multi-thread", "fs"] } tokio-stream = { workspace = true } tracing = { workspace = true, features = ["std", "attributes"] } diff --git a/vortex-datafusion/src/convert/exprs/fallback.rs b/vortex-datafusion/src/convert/exprs/fallback.rs new file mode 100644 index 00000000000..b0a1ead578a --- /dev/null +++ b/vortex-datafusion/src/convert/exprs/fallback.rs @@ -0,0 +1,264 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Lower one DF region, extracting native subtrees without changing evaluation domains. + +use std::sync::Arc; + +use arrow_schema::DataType; +use arrow_schema::FieldRef; +use arrow_schema::Schema; +use datafusion_common::HashMap; +use datafusion_expr::Operator; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_physical_expr::PhysicalExpr; +use datafusion_physical_expr::ScalarFunctionExpr; +use datafusion_physical_plan::expressions::BinaryExpr; +use datafusion_physical_plan::expressions::CastExpr; +use datafusion_physical_plan::expressions::Column; +use datafusion_physical_plan::expressions::IsNotNullExpr; +use datafusion_physical_plan::expressions::IsNullExpr; +use datafusion_physical_plan::expressions::Literal; +use datafusion_physical_plan::expressions::NegativeExpr; +use datafusion_physical_plan::expressions::NotExpr; +use datafusion_physical_plan::expressions::TryCastExpr; +use datafusion_physical_plan::joins::HashExpr; +use datafusion_physical_plan::joins::HashTableLookupExpr; +use vortex::expr::Expression; +use vortex::expr::get_item; +use vortex::expr::root; + +use super::Conversion; +use super::DefaultExpressionConverter; +use super::Unconverted; +use super::is_infallible; + +pub(super) fn eager(expression: &Arc) -> bool { + expression.is::() || expression.is::() || expression.is::() + || expression.is::() || expression.is::() + || expression.is::() || expression.is::() || expression.is::() + // These concrete DF implementations evaluate all children over the input batch. + || expression.is::() || expression.is::() || expression.is::() + || expression.downcast_ref::().is_some_and(|binary| !matches!(binary.op(), Operator::And | Operator::Or)) +} + +pub(super) fn compatible(expression: &Arc, schema: &Schema) -> Conversion { + if let Some(binary) = expression.downcast_ref::() { + let left = binary.left().data_type(schema)?; + let right = binary.right().data_type(schema)?; + let floating = |dtype: &DataType| match dtype { + DataType::Dictionary(_, values) => values.is_floating(), + other => other.is_floating(), + }; + if matches!( + binary.op(), + Operator::Eq + | Operator::NotEq + | Operator::Lt + | Operator::LtEq + | Operator::Gt + | Operator::GtEq + ) && (floating(&left) || floating(&right)) + { + return Ok(false); + } + // DF may wrap integer arithmetic; the Vortex operation is checked. DF does + // not expose that expression option, so preserve either behavior in DF. + if matches!( + binary.op(), + Operator::Plus | Operator::Minus | Operator::Multiply + ) && (left.is_integer() || right.is_integer()) + { + return Ok(false); + } + } + // Native extraction is equivalent only when every parent struct is non-null. + if let Some(function) = expression.downcast_ref::() + && ScalarFunctionExpr::try_downcast_func::(function).is_some() + { + let [source, paths @ ..] = function.args() else { + return Ok(true); + }; + let mut dtype = source.data_type(schema)?; + let mut nullable = source.nullable(schema)?; + for path in paths { + let Some(name) = path + .downcast_ref::() + .and_then(|literal| literal.value().try_as_str()) + .flatten() + else { + return Ok(true); + }; + let DataType::Struct(fields) = &dtype else { + return Ok(true); + }; + let Some((_, field)) = fields.find(name) else { + return Ok(true); + }; + if nullable { + return Ok(false); + } + nullable = field.is_nullable(); + dtype = field.data_type().clone(); + } + } + Ok(true) +} + +pub(super) fn lower( + converter: &DefaultExpressionConverter, + expression: &Arc, + schema: &Schema, + advisory: bool, +) -> Conversion { + super::validate_columns(expression, schema)?; + if !crate::df_expression::eligible(expression) { + return Err(Unconverted::Unsupported); + } + if crate::df_expression::contains_higher_order_function(expression) { + return crate::df_expression::raw_expression( + Arc::clone(expression), + schema, + &converter.session, + advisory, + )? + .ok_or(Unconverted::Unsupported); + } + let native = converter.native_only(); + let mut extraction = Extraction { + native: &native, + schema, + advisory, + inputs: vec![], + fields: vec![], + originals: vec![], + columns: HashMap::default(), + arrays: HashMap::default(), + }; + let expression = extraction.rewrite(expression, true, false)?; + crate::df_expression::from_inputs( + expression, + Arc::new(Schema::new(extraction.fields)), + extraction.inputs, + &converter.session, + advisory, + )? + .ok_or(Unconverted::Unsupported) +} + +struct Extraction<'a> { + native: &'a DefaultExpressionConverter, + schema: &'a Schema, + advisory: bool, + inputs: Vec, + fields: Vec, + originals: Vec>, + columns: HashMap, + arrays: HashMap, +} +impl Extraction<'_> { + fn has_columns(&mut self, expression: &Arc) -> bool { + let key = Arc::as_ptr(expression) as *const () as usize; + if let Some(value) = self.columns.get(&key) { + return *value; + } + let value = expression.is::() + || expression + .children() + .iter() + .any(|child| self.has_columns(child)); + self.columns.insert(key, value); + value + } + // DF may return Scalar from short-circuit expressions, conditional regions, + // or arbitrary UDFs even when they reference a column. Extract only concrete + // operators whose evaluator preserves Array shape from an Array operand. + fn array_valued(&mut self, expression: &Arc) -> bool { + let key = Arc::as_ptr(expression) as *const () as usize; + if let Some(value) = self.arrays.get(&key) { + return *value; + } + let preserves_array = expression.is::() + || expression.is::() + || expression.is::() + || expression.is::() + || expression.is::() + || expression.is::() + || expression + .downcast_ref::() + .is_some_and(|binary| !matches!(binary.op(), Operator::And | Operator::Or)); + let value = expression.is::() + || preserves_array + && expression + .children() + .iter() + .any(|child| self.array_valued(child)); + self.arrays.insert(key, value); + value + } + fn input( + &mut self, + original: &Arc, + native: Expression, + ) -> Conversion> { + let index = if let Some(index) = self + .originals + .iter() + .position(|existing| existing.eq(original)) + { + index + } else { + let index = self.inputs.len(); + self.fields.push(original.return_field(self.schema)?); + self.originals.push(Arc::clone(original)); + self.inputs.push(native); + index + }; + Ok(Arc::new(Column::new(self.fields[index].name(), index))) + } + fn rewrite( + &mut self, + expression: &Arc, + eager_region: bool, + child: bool, + ) -> Conversion> { + if let Some(column) = expression.downcast_ref::() { + return self.input(expression, get_item(column.name(), root())); + } + // Keep scalar-producing constant regions in DF: turning them into + // input columns changes ColumnarValue::Scalar into Array for a UDF. + if expression.is::() || !self.has_columns(expression) { + return Ok(Arc::clone(expression)); + } + if child && self.array_valued(expression) { + match self.native.convert_checked(expression, self.schema) { + Ok(native) + if (eager_region || is_infallible(&native)) + && (!self.advisory || is_infallible(&native)) => + { + // DF UDFs observe the original Field, including nullability. + let field = expression.return_field(self.schema)?; + if field.is_nullable() == expression.nullable(self.schema)? { + return self.input(expression, native); + } + } + Ok(_) | Err(Unconverted::Unsupported) => {} + Err(error) => return Err(error), + } + } + let allow = eager_region && eager(expression); + let children = expression + .children() + .into_iter() + .map(|child| self.rewrite(child, allow, true)) + .collect::>>()?; + let rewritten = Arc::clone(expression).with_new_children(children)?; + crate::df_expression::preserve_field( + expression, + rewritten, + self.schema, + &Schema::new(self.fields.clone()), + ) + .map_err(Unconverted::Failed) + } +} diff --git a/vortex-datafusion/src/convert/exprs/mixed_tests.rs b/vortex-datafusion/src/convert/exprs/mixed_tests.rs new file mode 100644 index 00000000000..6ac3fb33d6d --- /dev/null +++ b/vortex-datafusion/src/convert/exprs/mixed_tests.rs @@ -0,0 +1,493 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::Arc; + +use arrow_array::ArrayRef; +use arrow_array::BooleanArray; +use arrow_array::Float64Array; +use arrow_array::Int64Array; +use arrow_array::ListArray; +use arrow_array::RecordBatch; +use arrow_array::StringArray; +use arrow_array::types::Int64Type; +use arrow_schema::DataType; +use arrow_schema::Field; +use arrow_schema::Schema; +use datafusion_common::config::ConfigOptions; +use datafusion_common::hash_utils::create_hashes; +use datafusion_expr::Operator as DFOperator; +use datafusion_expr::ScalarUDF; +use datafusion_functions::core::named_struct::NamedStructFunc; +use datafusion_functions::string::lower::LowerFunc; +use datafusion_physical_expr::PhysicalExpr; +use datafusion_physical_expr::ScalarFunctionExpr; +use datafusion_physical_plan::expressions::BinaryExpr; +use datafusion_physical_plan::expressions::CaseExpr; +use datafusion_physical_plan::expressions::CastExpr; +use datafusion_physical_plan::expressions::Column; +use datafusion_physical_plan::expressions::NotExpr; +use datafusion_physical_plan::expressions::lit; +use datafusion_physical_plan::joins::HashExpr; +use datafusion_physical_plan::joins::HashTableLookupExpr; +use datafusion_physical_plan::joins::Map; +use datafusion_physical_plan::joins::SeededRandomState; +use datafusion_physical_plan::joins::join_hash_map::JoinHashMapU32; +use datafusion_physical_plan::joins::utils::JoinHashMapType; +use vortex::VortexSessionDefault; +use vortex::array::VortexSessionExecute; +use vortex::expr::Expression; +use vortex::scalar_fn::fns::binary::Binary; +use vortex::scalar_fn::fns::operators::Operator; +use vortex::session::VortexSession; +use vortex_arrow::ArrowSessionExt; +use vortex_arrow::ExecuteArrowExt; + +use super::DefaultExpressionConverter; +use super::ExpressionConverter; +use super::is_infallible; + +pub(crate) fn lookup( + values: ArrayRef, + key: Arc, +) -> anyhow::Result> { + let state = SeededRandomState::with_seed(17); + let mut hashes = vec![0; values.len()]; + create_hashes(&[values], state.random_state(), &mut hashes)?; + let mut map = JoinHashMapU32::with_capacity(hashes.len()); + map.update_from_iter(Box::new(hashes.iter().enumerate()), 0); + Ok(Arc::new(HashTableLookupExpr::new( + vec![key], + state, + Arc::new(Map::HashMap(Box::new(map))), + "membership".into(), + ))) +} +fn evaluate( + expression: &Expression, + batch: &RecordBatch, + output: &Field, + session: &VortexSession, +) -> anyhow::Result { + let input = session + .arrow() + .from_arrow_record_batch(batch.clone(), &batch.schema())?; + Ok(input + .apply(expression)? + .execute_arrow(Some(output), &mut session.create_execution_ctx())?) +} + +#[test] +fn df_expression_keeps_native_outer_and_inner_sums() -> anyhow::Result<()> { + let batch = RecordBatch::try_from_iter(vec![ + ( + "x", + Arc::new(Float64Array::from(vec![1., 2., 4.])) as ArrayRef, + ), + ( + "y", + Arc::new(Float64Array::from(vec![2., 2., 1.])) as ArrayRef, + ), + ( + "z", + Arc::new(Float64Array::from(vec![10., 20., 30.])) as ArrayRef, + ), + ])?; + let inner: Arc = Arc::new(BinaryExpr::new( + Arc::new(Column::new("x", 0)), + DFOperator::Plus, + Arc::new(Column::new("y", 1)), + )); + let membership = lookup(Arc::new(Float64Array::from(vec![3., 5.])), inner)?; + let outer: Arc = Arc::new(BinaryExpr::new( + Arc::new(CastExpr::new(membership, DataType::Float64, None)), + DFOperator::Plus, + Arc::new(Column::new("z", 2)), + )); + let session = VortexSession::default(); + let converter = DefaultExpressionConverter::new(session.clone()); + let converted = converter.try_convert(&outer, &batch.schema())?.unwrap(); + assert_eq!(converted.as_opt::(), Some(&Operator::Add)); + let display = converted.to_string(); + assert_eq!( + display.matches("datafusion.df_expression").count(), + 1, + "{display}" + ); + // The single DF fragment receives the native x+y result, not x and y. + assert!(display.contains("opts=membership"), "{display}"); + let expected = outer + .evaluate(&batch)? + .into_array_of_size(batch.num_rows())?; + let actual = evaluate( + &converted, + &batch, + outer.return_field(&batch.schema())?.as_ref(), + &session, + )?; + assert_eq!(&actual, &expected); + Ok(()) +} + +#[test] +fn df_expression_groups_wrapping_operators_and_preserves_lazy_errors() -> anyhow::Result<()> { + let batch = RecordBatch::try_from_iter(vec![( + "id", + Arc::new(Int64Array::from(vec![0, 1])) as ArrayRef, + )])?; + let column = Arc::new(Column::new("id", 0)) as Arc; + let wrapped: Arc = Arc::new(BinaryExpr::new( + Arc::new(BinaryExpr::new( + Arc::clone(&column), + DFOperator::Plus, + lit(i64::MAX), + )), + DFOperator::Plus, + lit(1_i64), + )); + let key: Arc = Arc::new(BinaryExpr::new( + lit(1_i64), + DFOperator::Divide, + Arc::clone(&column), + )); + let membership = lookup(Arc::new(Int64Array::from(vec![1])), key)?; + let conditional: Arc = Arc::new(CaseExpr::try_new( + None, + vec![(lit(false), Arc::clone(&membership))], + Some(lit(true)), + )?); + let session = VortexSession::default(); + let converter = DefaultExpressionConverter::new(session.clone()); + for expression in [wrapped, conditional] { + let converted = converter + .try_convert(&expression, &batch.schema())? + .unwrap(); + assert_eq!( + converted + .to_string() + .matches("datafusion.df_expression") + .count(), + 1 + ); + let expected = expression + .evaluate(&batch)? + .into_array_of_size(batch.num_rows())?; + let actual = evaluate( + &converted, + &batch, + expression.return_field(&batch.schema())?.as_ref(), + &session, + )?; + assert_eq!(&actual, &expected); + } + let negated: Arc = Arc::new(NotExpr::new(membership)); + let hint = converter + .try_convert_dynamic(&negated, &batch.schema())? + .unwrap(); + assert!(is_infallible(&hint)); + let actual = evaluate( + &hint, + &batch, + &Field::new("hint", DataType::Boolean, false), + &session, + )?; + assert_eq!( + &actual, + &(Arc::new(BooleanArray::from(vec![true, true])) as ArrayRef) + ); + Ok(()) +} + +pub(crate) fn routed(key: Arc) -> anyhow::Result> { + let route: Arc = Arc::new(BinaryExpr::new( + Arc::new(HashExpr::new( + vec![Arc::clone(&key)], + SeededRandomState::with_seed(0), + "route".into(), + )), + DFOperator::Modulo, + lit(2_u64), + )); + let first = lookup(Arc::new(Int64Array::from(vec![1, 3])), Arc::clone(&key))?; + let second = lookup(Arc::new(Int64Array::from(vec![2, 4])), key)?; + Ok(Arc::new(CaseExpr::try_new( + Some(route), + vec![(lit(0_u64), first), (lit(1_u64), second)], + Some(lit(false)), + )?)) +} +#[test] +fn df_expression_accepts_partition_routing_case_as_a_whole_hint() -> anyhow::Result<()> { + let batch = RecordBatch::try_from_iter(vec![( + "id", + Arc::new(Int64Array::from(vec![ + Some(1), + Some(2), + None, + Some(3), + Some(4), + ])) as ArrayRef, + )])?; + let expression = routed(Arc::new(Column::new("id", 0)))?; + let session = VortexSession::default(); + let converter = DefaultExpressionConverter::new(session.clone()); + let converted = converter + .try_convert_dynamic(&expression, &batch.schema())? + .unwrap(); + assert!(is_infallible(&converted)); + let expected = expression + .evaluate(&batch)? + .into_array_of_size(batch.num_rows())?; + let actual = evaluate( + &converted, + &batch, + &Field::new("hint", DataType::Boolean, true), + &session, + )?; + assert_eq!(&actual, &expected); + Ok(()) +} + +#[derive(Debug, PartialEq, Eq, Hash)] +struct ObserveArgument { + signature: datafusion_expr::Signature, + name: String, + nullable: bool, + scalar: bool, +} +impl datafusion_expr::ScalarUDFImpl for ObserveArgument { + fn name(&self) -> &str { + "observe_argument" + } + fn signature(&self) -> &datafusion_expr::Signature { + &self.signature + } + fn return_type(&self, _: &[DataType]) -> datafusion_common::Result { + Ok(DataType::Boolean) + } + fn invoke_with_args( + &self, + args: datafusion_expr::ScalarFunctionArgs, + ) -> datafusion_common::Result { + Ok(datafusion_expr::ColumnarValue::Scalar( + datafusion_common::ScalarValue::Boolean(Some( + args.arg_fields[0].name() == &self.name + && args.arg_fields[0].is_nullable() == self.nullable + && matches!(args.args[0], datafusion_expr::ColumnarValue::Scalar(_)) + == self.scalar, + )), + )) + } +} +#[test] +fn df_expression_preserves_udf_argument_fields_and_scalar_shape() -> anyhow::Result<()> { + let batch = RecordBatch::try_from_iter(vec![ + ("unused", Arc::new(Int64Array::from(vec![0, 0])) as ArrayRef), + ( + "x", + Arc::new(arrow_array::Float32Array::from(vec![Some(1.), None])) as ArrayRef, + ), + ])?; + let cast: Arc = Arc::new(CastExpr::new_with_target_field( + Arc::new(Column::new("x", 1)), + Arc::new(Field::new("original", DataType::Float64, false)), + None, + )); + let lower: Arc = Arc::new(ScalarFunctionExpr::try_new( + Arc::new(ScalarUDF::from(LowerFunc::new())), + vec![lit("ABC")], + &batch.schema(), + Arc::new(ConfigOptions::new()), + )?); + let session = VortexSession::default(); + let converter = DefaultExpressionConverter::new(session.clone()); + let short_circuit: Arc = Arc::new(BinaryExpr::new( + lit(false), + DFOperator::And, + Arc::new(datafusion_physical_plan::expressions::IsNotNullExpr::new( + Arc::new(Column::new("x", 1)), + )), + )); + for (child, scalar) in [(cast, false), (lower, true), (short_circuit, true)] { + let field = child.return_field(&batch.schema())?; + let fun = ScalarUDF::from(ObserveArgument { + signature: datafusion_expr::Signature::any(1, datafusion_expr::Volatility::Immutable), + name: field.name().clone(), + nullable: field.is_nullable(), + scalar, + }); + let expression: Arc = Arc::new(ScalarFunctionExpr::try_new( + Arc::new(fun), + vec![child], + &batch.schema(), + Arc::new(ConfigOptions::new()), + )?); + let mixed = converter + .try_convert(&expression, &batch.schema())? + .unwrap(); + let raw = + crate::df_expression(Arc::clone(&expression), &batch.schema(), &session)?.unwrap(); + let expected = expression + .evaluate(&batch)? + .into_array_of_size(batch.num_rows())?; + for converted in [mixed, raw] { + let actual = evaluate( + &converted, + &batch, + expression.return_field(&batch.schema())?.as_ref(), + &session, + )?; + assert_eq!(&actual, &expected); + assert_eq!( + &actual, + &(Arc::new(BooleanArray::from(vec![true, true])) as ArrayRef) + ); + } + } + Ok(()) +} + +#[test] +fn df_expression_advisory_rejects_invalid_original_column_bindings() -> anyhow::Result<()> { + let converter = DefaultExpressionConverter::default(); + let duplicate = Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("id", DataType::Int64, false), + ]); + let predicate: Arc = Arc::new(BinaryExpr::new( + Arc::new(Column::new("id", 1)), + DFOperator::Eq, + lit(2_i64), + )); + assert!( + converter + .try_convert_dynamic(&predicate, &duplicate)? + .is_none() + ); + let distinct = Schema::new(vec![ + Field::new("a", DataType::Int64, false), + Field::new("id", DataType::Int64, false), + ]); + for index in [0, 2] { + let invalid: Arc = Arc::new(BinaryExpr::new( + Arc::new(Column::new("id", index)), + DFOperator::Eq, + lit(2_i64), + )); + assert!(converter.try_convert_dynamic(&invalid, &distinct).is_err()); + } + Ok(()) +} + +#[test] +fn df_expression_preserves_lambda_input_positions() -> anyhow::Result<()> { + let batch = RecordBatch::try_from_iter(vec![ + ( + "x", + Arc::new(Float64Array::from(vec![10., 20.])) as ArrayRef, + ), + ( + "list", + Arc::new(ListArray::from_iter_primitive::([ + Some(vec![Some(1), Some(2)]), + Some(vec![Some(3), None]), + ])) as ArrayRef, + ), + ])?; + let transform = super::tests::array_transform_expr( + Arc::new(Column::new("list", 1)), + "u", + 2, + |u| Ok(Arc::new(BinaryExpr::new(u, DFOperator::Modulo, lit(2_i64)))), + &batch.schema(), + )?; + let sum: Arc = Arc::new(BinaryExpr::new( + Arc::new(Column::new("x", 0)), + DFOperator::Plus, + lit(1_f64), + )); + let product: Arc = Arc::new(BinaryExpr::new( + Arc::new(Column::new("x", 0)), + DFOperator::Multiply, + lit(2_f64), + )); + let named: Arc = Arc::new(ScalarFunctionExpr::try_new( + Arc::new(ScalarUDF::from(NamedStructFunc::new())), + vec![ + lit("sum"), + sum, + lit("product"), + product, + lit("list"), + Arc::clone(&transform), + ], + &batch.schema(), + Arc::new(ConfigOptions::new()), + )?); + let session = VortexSession::default(); + let converter = DefaultExpressionConverter::new(session.clone()); + for expression in [transform, named] { + let mixed = converter + .try_convert(&expression, &batch.schema())? + .unwrap(); + let raw = + crate::df_expression(Arc::clone(&expression), &batch.schema(), &session)?.unwrap(); + let expected = expression + .evaluate(&batch)? + .into_array_of_size(batch.num_rows())?; + for converted in [mixed, raw] { + let actual = evaluate( + &converted, + &batch, + expression.return_field(&batch.schema())?.as_ref(), + &session, + )?; + assert_eq!(&actual, &expected); + } + } + Ok(()) +} + +#[test] +fn df_expression_preserves_fields_through_datafusion_case_projection() -> anyhow::Result<()> { + let batch = RecordBatch::try_from_iter(vec![ + ("s", Arc::new(StringArray::from(vec!["a", "b"])) as ArrayRef), + ( + "flag", + Arc::new(BooleanArray::from(vec![true, false])) as ArrayRef, + ), + ("n", Arc::new(Int64Array::from(vec![10, 20])) as ArrayRef), + ])?; + let case: Arc = Arc::new(CaseExpr::try_new( + None, + vec![( + Arc::new(Column::new("flag", 1)) as Arc, + Arc::new(Column::new("n", 2)) as Arc, + )], + Some(lit(0_i64)), + )?); + let expression: Arc = Arc::new(ScalarFunctionExpr::try_new( + Arc::new(ScalarUDF::from(NamedStructFunc::new())), + vec![lit("s"), Arc::new(Column::new("s", 0)), lit("v"), case], + &batch.schema(), + Arc::new(ConfigOptions::new()), + )?); + let session = VortexSession::default(); + let mixed = DefaultExpressionConverter::new(session.clone()) + .try_convert(&expression, &batch.schema())? + .unwrap(); + let raw = crate::df_expression(Arc::clone(&expression), &batch.schema(), &session)?.unwrap(); + let expected = expression + .evaluate(&batch)? + .into_array_of_size(batch.num_rows())?; + for converted in [mixed, raw] { + let actual = evaluate( + &converted, + &batch, + expression.return_field(&batch.schema())?.as_ref(), + &session, + )?; + assert_eq!(&actual, &expected); + } + Ok(()) +} diff --git a/vortex-datafusion/src/convert/exprs/mod.rs b/vortex-datafusion/src/convert/exprs/mod.rs index f73ba102aa3..90c686dd30e 100644 --- a/vortex-datafusion/src/convert/exprs/mod.rs +++ b/vortex-datafusion/src/convert/exprs/mod.rs @@ -1,12 +1,16 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Converts DataFusion physical expressions for native Vortex evaluation. +//! Converts DataFusion physical expressions into mixed Vortex/DF evaluation. //! -//! Unsupported expressions stay in DataFusion. Comparison and membership literals retain their own +//! Eligible non-native fragments run in a typed DF callback inside the Vortex scan. Comparison and membership literals retain their own //! extension metadata, or inherit missing metadata from the operand they are compared with. This //! supplies the logical dtype that Vortex requires without adding implicit casts. +mod fallback; +#[cfg(test)] +pub(crate) mod mixed_tests; + use std::sync::Arc; use arrow_schema::DataType; @@ -15,6 +19,7 @@ use arrow_schema::Schema; use arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY; use arrow_schema::extension::EXTENSION_TYPE_NAME_KEY; use datafusion_common::DataFusionError; +use datafusion_common::HashMap; use datafusion_common::Result as DFResult; use datafusion_common::ScalarValue; use datafusion_common::exec_datafusion_err; @@ -38,6 +43,7 @@ use datafusion_physical_expr::projection::ProjectionExprs; use datafusion_physical_expr::utils::collect_columns; use datafusion_physical_plan::expressions as df_expr; use itertools::Itertools; +use parking_lot::Mutex; use vortex::VortexSessionDefault; use vortex::aggregate_fn::NumericalAggregateOpts; use vortex::array::VortexSessionExecute; @@ -89,8 +95,7 @@ pub struct ProcessedProjection { /// Trait for converting DataFusion expressions to Vortex ones. /// /// Custom converters implement a single schema-aware decision. Conversion should preserve -/// DataFusion values, nulls, and evaluation errors; see [`DefaultExpressionConverter`] for -/// the arithmetic and nested field access exceptions. Unsupported expressions remain in +/// DataFusion values, nulls, and evaluation errors. Unsupported expressions remain in /// DataFusion, including when a file's schema adapter introduces them. /// /// # Implementing a custom converter @@ -230,14 +235,13 @@ type Conversion = Result; /// The default [`ExpressionConverter`] implementation. /// -/// Supported arithmetic is pushed down using Vortex semantics, including its checked -/// integer arithmetic. Matching DataFusion's overflow behavior is deferred to a future patch. -/// Nested struct field access also uses Vortex semantics: a null parent produces a null child, -/// whereas DataFusion extracts the child without applying parent validity. These differences -/// are accepted for both filters and projections. +/// Compatible subtrees execute natively; remaining synchronous non-volatile fragments +/// use a typed DataFusion callback. Integer wrapping arithmetic, float binary comparisons +/// and struct extraction with different null semantics retain DataFusion evaluation. /// Searched `CASE WHEN` expressions preserve short-circuit evaluation: conditions and /// branch values only execute on the rows that reach them, including fallible branches. /// Other expressions require compatible SQL semantics or remain in DataFusion. +#[derive(Clone)] pub struct DefaultExpressionConverter { /// Session used to resolve Arrow → Vortex dtypes through the extension /// plugin registry, so registered extension types (e.g. UUID ⇄ @@ -246,9 +250,50 @@ pub struct DefaultExpressionConverter { session: VortexSession, /// What `$` is in the expressions this converts. scope: Scope, + df_fallback: bool, + native_cache: Option>>, +} + +fn validate_columns(expr: &Arc, schema: &Schema) -> Conversion> { + let columns = collect_columns(expr); + let mut column_indices = Vec::with_capacity(columns.len()); + for column in columns { + let field = schema.fields().get(column.index()).ok_or_else(|| { + exec_datafusion_err!( + "Column {}@{} is out of bounds", + column.name(), + column.index() + ) + })?; + if field.name() != column.name() { + return Err(exec_datafusion_err!( + "Column {}@{} refers to field {}", + column.name(), + column.index(), + field.name() + ) + .into()); + } + if schema + .fields() + .iter() + .filter(|field| field.name() == column.name()) + .count() + != 1 + { + return Err(Unconverted::Unsupported); + } + column_indices.push(column.index()); + } + column_indices.sort_unstable(); + column_indices.dedup(); + Ok(column_indices) } +type NativeCache = HashMap<(usize, usize, bool), (Arc, Option)>; + /// What `$` is where an expression is converted. +#[derive(Clone)] enum Scope { /// Outside any lambda, the scan's columns: a column `c` reads `$.c`. Global, @@ -264,12 +309,27 @@ impl Default for DefaultExpressionConverter { } impl DefaultExpressionConverter { + fn native_only(&self) -> Self { + Self { + df_fallback: false, + ..self.clone() + } + } + fn conversion_context(&self) -> Self { + Self { + native_cache: Some(Arc::new(Mutex::new(HashMap::default()))), + ..self.clone() + } + } + /// Create a converter that resolves Arrow extension types using `session`'s /// dtype registry. pub fn new(session: VortexSession) -> Self { Self { session, scope: Scope::Global, + df_fallback: true, + native_cache: None, } } @@ -287,29 +347,20 @@ impl DefaultExpressionConverter { expr: &Arc, schema: &Schema, ) -> Conversion { - let columns = collect_columns(expr); - let mut column_indices = Vec::with_capacity(columns.len()); - for column in columns { - let field = schema.fields().get(column.index()).ok_or_else(|| { - exec_datafusion_err!( - "Column {}@{} is out of bounds", - column.name(), - column.index() - ) - })?; - if field.name() != column.name() { - return Err(exec_datafusion_err!( - "Column {}@{} refers to field {}", - column.name(), - column.index(), - field.name() - ) - .into()); - } - column_indices.push(column.index()); + self.memoized_native(expr, schema, true, || { + self.convert_checked_uncached(expr, schema) + }) + } + + fn convert_checked_uncached( + &self, + expr: &Arc, + schema: &Schema, + ) -> Conversion { + let mut column_indices = validate_columns(expr, schema)?; + if crate::df_expression::contains_higher_order_function(expr) { + column_indices = (0..schema.fields().len()).collect(); } - column_indices.sort_unstable(); - column_indices.dedup(); let input_dtype = self .session .arrow() @@ -320,14 +371,8 @@ impl DefaultExpressionConverter { ) .map_err(|_| Unconverted::Unsupported)?; let converted = self.convert_expr(expr, schema, &input_dtype)?; - // `return_field` names the field by formatting the whole expression. For the IN list of a - // hash join filter, with thousands of keys, that costs more than the conversion. A - // predicate has no field metadata, so its type and nullability are enough. - let expected_dtype = if expr.data_type(schema)? == DataType::Boolean { - DType::Bool(expr.nullable(schema)?.into()) - } else { - self.arrow_dtype(expr.return_field(schema)?.as_ref())? - }; + // Preserve extension metadata even for Boolean outputs. + let expected_dtype = self.arrow_dtype(expr.return_field(schema)?.as_ref())?; if !converted_dtype(&converted, &input_dtype)?.eq_ignore_nullability(&expected_dtype) { return Err(Unconverted::Unsupported); } @@ -339,6 +384,81 @@ impl DefaultExpressionConverter { expr: &Arc, schema: &Schema, input_dtype: &DType, + ) -> Conversion { + self.memoized_native(expr, schema, false, || { + self.convert_expr_uncached(expr, schema, input_dtype) + }) + } + + fn memoized_native( + &self, + expr: &Arc, + schema: &Schema, + checked: bool, + convert: impl FnOnce() -> Conversion, + ) -> Conversion { + let cache = if !self.df_fallback && matches!(self.scope, Scope::Global) { + self.native_cache.as_ref() + } else { + None + }; + let key = ( + Arc::as_ptr(expr) as *const () as usize, + schema as *const Schema as usize, + checked, + ); + if let Some(cache) = cache + && let Some((_, cached)) = cache.lock().get(&key) + { + return cached.clone().ok_or(Unconverted::Unsupported); + } + let result = convert(); + if let Some(cache) = cache { + let value = match &result { + Ok(value) => Some(value.clone()), + Err(Unconverted::Unsupported) => None, + Err(_) => return result, + }; + cache.lock().insert(key, (Arc::clone(expr), value)); + } + result + } + + fn convert_expr_uncached( + &self, + expr: &Arc, + schema: &Schema, + input_dtype: &DType, + ) -> Conversion { + let mut result = if !fallback::compatible(expr, schema)? { + Err(Unconverted::Unsupported) + } else if self.df_fallback && !fallback::eager(expr) { + self.native_only() + .convert_native_expr(expr, schema, input_dtype) + } else { + self.convert_native_expr(expr, schema, input_dtype) + }; + if let Ok(converted) = &result { + let expected = self.arrow_dtype(expr.return_field(schema)?.as_ref())?; + if !converted_dtype(converted, input_dtype)?.eq_ignore_nullability(&expected) { + result = Err(Unconverted::Unsupported); + } + } + match result { + Err(Unconverted::Unsupported) + if self.df_fallback && matches!(self.scope, Scope::Global) => + { + fallback::lower(self, expr, schema, false) + } + other => other, + } + } + + fn convert_native_expr( + &self, + expr: &Arc, + schema: &Schema, + input_dtype: &DType, ) -> Conversion { if let Some(binary_expr) = expr.downcast_ref::() { let operator = @@ -821,6 +941,8 @@ impl DefaultExpressionConverter { let body_converter = Self { session: self.session.clone(), scope: Scope::Lambda(params), + df_fallback: false, + native_cache: None, }; // DataFusion also types the body against the outer schema: a lambda variable carries its // own field. @@ -870,12 +992,35 @@ impl ExpressionConverter for DefaultExpressionConverter { if DynamicFilterTracking::classify(expr).contains_dynamic_filter() { return Ok(None); } - match self.convert_checked(expr, schema) { + if !crate::df_expression::eligible(expr) { + return Ok(None); + } + match self.conversion_context().convert_checked(expr, schema) { Ok(converted) => Ok(Some(converted)), Err(Unconverted::Unsupported) => Ok(None), Err(Unconverted::Failed(error)) => Err(error), } } + fn try_convert_dynamic( + &self, + expr: &Arc, + schema: &Schema, + ) -> DFResult> { + if !crate::df_expression::eligible(expr) || expr.data_type(schema)? != DataType::Boolean { + return Ok(None); + } + let converter = self.conversion_context(); + match converter.convert_checked(expr, schema) { + Ok(value) if is_infallible(&value) => return Ok(Some(value)), + Err(Unconverted::Failed(error)) => return Err(error), + _ => {} + } + match fallback::lower(&converter, expr, schema, true) { + Ok(value) => Ok(Some(value)), + Err(Unconverted::Unsupported) => Ok(None), + Err(Unconverted::Failed(error)) => Err(error), + } + } } /// Whether evaluating `expr` cannot fail, so Vortex may evaluate it on rows DataFusion skips. diff --git a/vortex-datafusion/src/convert/exprs/tests.rs b/vortex-datafusion/src/convert/exprs/tests.rs index e5c652bf58a..32758b2049b 100644 --- a/vortex-datafusion/src/convert/exprs/tests.rs +++ b/vortex-datafusion/src/convert/exprs/tests.rs @@ -18,6 +18,7 @@ use arrow_array::StructArray; use arrow_array::UInt8Array; use arrow_array::UInt32Array; use arrow_array::UInt64Array; +use arrow_array::cast::AsArray; use arrow_array::types::Float64Type; use arrow_array::types::Int32Type; use arrow_array::types::Int64Type; @@ -59,7 +60,6 @@ use rstest::rstest; use vortex::array::Canonical; use vortex::array::IntoArray; use vortex::array::arrays::ConstantArray; -use vortex::array::arrays::PrimitiveArray; use vortex::array::builtins::ArrayBuiltins; use vortex::dtype::PType; use vortex::encodings::uuid::Uuid; @@ -72,6 +72,7 @@ use vortex::scalar_fn::fns::cast::Cast; use vortex::scalar_fn::fns::list_contains::ListContains; use vortex::scalar_fn::fns::literal::Literal; use vortex_array::assert_arrays_eq; +use vortex_arrow::ExecuteArrowExt; use super::*; use crate::common_tests::TestSessionContext; @@ -144,7 +145,7 @@ fn array_sum_expr(list: Arc, schema: &Schema) -> DFResult body)` as DataFusion does: the parameter is the list's /// element field, numbered after the columns of `schema` and any enclosing lambda's parameters. -fn array_transform_expr( +pub(super) fn array_transform_expr( list: Arc, param: &str, index: usize, @@ -189,6 +190,7 @@ fn get_field_expr( /// Whether the default converter accepts `expr` for native evaluation against `schema`. fn converts(expr: &Arc, schema: &Schema) -> DFResult { Ok(DefaultExpressionConverter::default() + .native_only() .try_convert(expr, schema)? .is_some()) } @@ -196,6 +198,7 @@ fn converts(expr: &Arc, schema: &Schema) -> DFResult { /// Convert `expr` natively, failing the test if the converter declines it. fn convert(expr: Arc, schema: &Schema) -> DFResult { DefaultExpressionConverter::default() + .native_only() .try_convert(&expr, schema)? .ok_or_else(|| exec_datafusion_err!("Expected native conversion for {expr}")) } @@ -209,7 +212,7 @@ fn assert_in_list_matches( ) -> anyhow::Result<()> { let expr = df_expr::InListExpr::try_new(value, list, negated, &batch.schema())?; expr.evaluate(&batch)?; - assert_native_matches(Arc::new(expr), batch) + assert_conversion_matches(Arc::new(expr), batch) } fn int_literals(values: impl IntoIterator>) -> Vec> { @@ -867,7 +870,7 @@ fn test_comparison_inherits_complete_extension_metadata() -> anyhow::Result<()> Arc::new(literal), )); - assert_native_matches(predicate, batch) + assert_conversion_matches(predicate, batch) } #[test] @@ -957,7 +960,7 @@ fn test_like_preserves_nullable_input_through_non_nullable_cast() -> anyhow::Res )))) as Arc; let like = Arc::new(df_expr::LikeExpr::new(false, false, cast, pattern)); - assert_native_matches(like, batch) + assert_conversion_matches(like, batch) } #[rstest] @@ -1104,13 +1107,13 @@ fn test_literal_ignores_unreferenced_malformed_decimal() -> DFResult<()> { #[test] fn test_projection_ignores_unreferenced_unsupported_field() -> DFResult<()> { let schema = Schema::new(vec![ - Field::new("a", DataType::Int32, false), + Field::new("a", DataType::Float64, false), Field::new( "unsupported", DataType::Duration(ArrowTimeUnit::Second), true, ), - Field::new("b", DataType::Int32, false), + Field::new("b", DataType::Float64, false), ]); let projection = ProjectionExprs::from(vec![ProjectionExpr::new( Arc::new(df_expr::BinaryExpr::new( @@ -1472,10 +1475,13 @@ fn test_case_when_datafusion_vortex_equivalence() -> anyhow::Result<()> { vec![(greater_than(10), int32(100)), (greater_than(5), int32(50))], Some(int32(0)), )?; - assert_native_matches(Arc::new(case_expr), batch) + assert_conversion_matches(Arc::new(case_expr), batch) } -fn assert_native_matches(expr: Arc, batch: RecordBatch) -> anyhow::Result<()> { +fn assert_conversion_matches( + expr: Arc, + batch: RecordBatch, +) -> anyhow::Result<()> { let session = VortexSession::default(); let converted = DefaultExpressionConverter::new(session.clone()) .try_convert(&expr, &batch.schema())? @@ -1494,12 +1500,23 @@ fn assert_native_matches(expr: Arc, batch: RecordBatch) -> any if constant { input = ConstantArray::new(input.execute_scalar(0, &mut ctx)?, 1).into_array(); } + // Struct scalarization drops hidden children under null parents. In + // constant cases, compare DF on the actual supplied representation; + // ordinary arrays retain the original Arrow reference unchanged. + let reference = if constant { + let field = + Field::new("", DataType::Struct(batch.schema().fields().clone()), false); + let arrow = input.clone().execute_arrow(Some(&field), &mut ctx)?; + RecordBatch::from(arrow.as_struct()) + } else { + batch.clone() + }; let actual = input .apply(&converted)? .execute::(&mut ctx) .map(IntoArray::into_array); let expected = expr - .evaluate(&batch) + .evaluate(&reference) .and_then(|value| value.into_array(batch.num_rows())); match (actual, expected) { (Ok(actual), Ok(expected)) => { @@ -1535,7 +1552,7 @@ fn test_native_integer_division( #[case] denominators: Vec, ) -> anyhow::Result<()> { let batch = arrow_array::record_batch!(("a", Int32, values), ("b", Int32, denominators))?; - assert_native_matches( + assert_conversion_matches( Arc::new(df_expr::BinaryExpr::new( Arc::new(df_expr::Column::new("a", 0)), DFOperator::Divide, @@ -1565,7 +1582,7 @@ fn test_native_float_arithmetic(#[case] operator: DFOperator) -> anyhow::Result< ), ("b", Float64, vec![0.0, f64::NEG_INFINITY, 0.0, 2.0, 0.0]) )?; - assert_native_matches( + assert_conversion_matches( Arc::new(df_expr::BinaryExpr::new( Arc::new(df_expr::Column::new("a", 0)), operator, @@ -1584,7 +1601,7 @@ fn test_native_integer_cast(#[case] target: DataType) -> anyhow::Result<()> { Int32, vec![Some(i32::MIN), Some(i32::MAX), Some(0), None] ))?; - assert_native_matches( + assert_conversion_matches( Arc::new(df_expr::CastExpr::new( Arc::new(df_expr::Column::new("a", 0)), target, @@ -1607,7 +1624,7 @@ fn test_native_float_cast() -> anyhow::Result<()> { None ] ))?; - assert_native_matches( + assert_conversion_matches( Arc::new(df_expr::CastExpr::new( Arc::new(df_expr::Column::new("a", 0)), DataType::Float64, @@ -1647,7 +1664,7 @@ fn test_native_numeric_cast( #[case] target: DataType, ) -> anyhow::Result<()> { let batch = RecordBatch::try_from_iter([("a", values)])?; - assert_native_matches( + assert_conversion_matches( Arc::new(df_expr::CastExpr::new( Arc::new(df_expr::Column::new("a", 0)), target, @@ -1678,7 +1695,7 @@ fn test_native_list_cast_to_float64( Some(vec![Some(0), Some(1)]), ]); let batch = RecordBatch::try_from_iter([("xs", cast(&lists, &list_type(element))?)])?; - assert_native_matches( + assert_conversion_matches( Arc::new(df_expr::CastExpr::new( Arc::new(df_expr::Column::new("xs", 0)), list_type(DataType::Float64), @@ -1879,7 +1896,7 @@ fn test_string_functions_match_datafusion( let session = VortexSession::default(); let serialized = native.serialize_proto()?; assert_eq!(Expression::from_proto(&serialized, &session)?, native); - assert_native_matches(expr, batch)?; + assert_conversion_matches(expr, batch)?; } Ok(()) } @@ -1949,7 +1966,7 @@ fn test_large_string_position_matches_datafusion() -> anyhow::Result<()> { ("s", LargeUtf8, vec![Some("é📊hello"), None, Some("")]), ("needle", LargeUtf8, vec![Some("h"), Some(""), Some("x")]) )?; - assert_native_matches(plan_predicate("strpos(s, needle)", &batch.schema())?, batch) + assert_conversion_matches(plan_predicate("strpos(s, needle)", &batch.schema())?, batch) } /// Regression test for #10634: coercion casts `REE>` columns to `Dict` before @@ -2046,7 +2063,7 @@ fn test_ree_dict_comparison_matches_datafusion(#[case] predicate: &str) -> anyho true, )])); let batch = RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(ree)])?; - assert_native_matches(plan_predicate(predicate, &schema)?, batch) + assert_conversion_matches(plan_predicate(predicate, &schema)?, batch) } #[rstest] @@ -2054,7 +2071,7 @@ fn test_ree_dict_comparison_matches_datafusion(#[case] predicate: &str) -> anyho #[case::sub(DFOperator::Minus)] #[case::mul(DFOperator::Multiply)] #[case::div(DFOperator::Divide)] -fn test_integer_arithmetic_pushdown_ignores_overflow_mode( +fn test_integer_arithmetic_uses_native_division_and_df_overflow_modes( #[case] op: DFOperator, #[values(false, true)] checked: bool, ) -> DFResult<()> { @@ -2067,7 +2084,7 @@ fn test_integer_arithmetic_pushdown_ignores_overflow_mode( ) .with_fail_on_overflow(checked), ); - assert!(converts(&expr, &schema)?); + assert_eq!(converts(&expr, &schema)?, op == DFOperator::Divide); Ok(()) } @@ -2084,7 +2101,7 @@ fn test_native_integer_arithmetic( ("a", Int32, vec![Some(-12), Some(0), Some(12), None]), ("b", Int32, vec![-2, 2, 2, 0]) )?; - assert_native_matches( + assert_conversion_matches( Arc::new( df_expr::BinaryExpr::new( Arc::new(df_expr::Column::new("a", 0)), @@ -2119,7 +2136,7 @@ fn test_native_decimal_arithmetic(#[case] op: DFOperator) -> anyhow::Result<()> ) as arrow_array::ArrayRef, ), ])?; - assert_native_matches( + assert_conversion_matches( Arc::new(df_expr::BinaryExpr::new( Arc::new(df_expr::Column::new("a", 0)), op, @@ -2175,7 +2192,7 @@ fn test_native_case_short_circuit( }; let expr: Arc = Arc::new(df_expr::CaseExpr::try_new(None, pairs, otherwise)?); assert_eq!(expr.evaluate(&batch).is_err(), branch == "error"); - assert_native_matches(expr, batch) + assert_conversion_matches(expr, batch) } #[rstest] @@ -2229,20 +2246,18 @@ fn test_case_unsupported_child_falls_back(#[values(0, 1, 2)] child: usize) -> DF Some(vec![true, true, false, true]), vec![Some(10), None, None, Some(40)], )] -fn test_native_nested_get_field( +fn test_nested_get_field_matches_datafusion( #[case] outer_validity: Option>, #[case] inner_validity: Option>, - #[case] mut expected: Vec>, + #[case] _historical_parent_nulls: Vec>, #[values(false, true)] nullable_leaf: bool, #[values(false, true)] flattened: bool, ) -> anyhow::Result<()> { - let parents_all_valid = expected.iter().all(Option::is_some); let nullable_outer = outer_validity.is_some(); let nullable_inner = inner_validity.is_some(); let mut values = vec![Some(10), Some(20), Some(30), Some(40)]; if nullable_leaf { values[3] = None; - expected[3] = None; } let inner = Arc::new(StructArray::new( vec![Field::new("leaf", DataType::Int32, nullable_leaf)].into(), @@ -2275,25 +2290,7 @@ fn test_native_nested_get_field( &batch.schema(), )? }; - let converted = convert(Arc::clone(&expr), &batch.schema())?; - assert_eq!( - converted, - get_item("leaf", get_item("inner", get_item("outer", root()))) - ); - if parents_all_valid { - return assert_native_matches(expr, batch); - } - - let session = VortexSession::default(); - let input = session - .arrow() - .from_arrow_record_batch(batch.clone(), &batch.schema())?; - assert_arrays_eq!( - input.apply(&converted)?, - PrimitiveArray::from_option_iter(expected), - &mut session.create_execution_ctx() - ); - Ok(()) + assert_conversion_matches(expr, batch) } #[rstest] @@ -2427,21 +2424,7 @@ fn test_native_nested_list_length( Arc::new(ConfigOptions::new()), )?); let length = array_length_expr(vec![get_field], &batch.schema()); - if nullable_parent { - let converted = convert(length, &batch.schema())?; - let session = VortexSession::default(); - let input = session - .arrow() - .from_arrow_record_batch(batch.clone(), &batch.schema())?; - assert_arrays_eq!( - input.apply(&converted)?, - PrimitiveArray::from_option_iter([Some(1u64), None, None]), - &mut session.create_execution_ctx() - ); - Ok(()) - } else { - assert_native_matches(length, batch) - } + assert_conversion_matches(length, batch) } #[rstest] @@ -2460,7 +2443,7 @@ fn test_native_array_sum( let data_type = DataType::new_list(element, true); let batch = RecordBatch::try_from_iter([("xs", cast(&lists, &data_type)?)])?; let expr = array_sum_expr(Arc::new(df_expr::Column::new("xs", 0)), &batch.schema())?; - assert_native_matches(expr, batch) + assert_conversion_matches(expr, batch) } #[test] @@ -2542,7 +2525,7 @@ fn test_native_array_transform( if summed { expr = array_sum_expr(expr, &schema)?; } - assert_native_matches(expr, batch) + assert_conversion_matches(expr, batch) } /// `100 / x` never sees the zero under a null list, as DataFusion drops the values under nulls. @@ -2570,7 +2553,7 @@ fn test_native_array_transform_skips_values_under_null_lists() -> anyhow::Result &schema, )?; expr.evaluate(&batch)?; - assert_native_matches(expr, batch) + assert_conversion_matches(expr, batch) } /// `array_transform(xss, (x) -> array_transform(x, (y) -> y IS NOT NULL))`, and the same with the @@ -2600,7 +2583,7 @@ fn test_native_nested_array_transform(#[case] inner_param: &str) -> anyhow::Resu |x| array_transform_expr(x, inner_param, 2, is_not_null_body, &schema), &schema, )?; - assert_native_matches(expr, batch) + assert_conversion_matches(expr, batch) } /// A body may read only its own parameter: a column, even one named like the parameter, or an @@ -2663,7 +2646,7 @@ fn test_native_case_null_conditions() -> anyhow::Result<()> { )], None, )?); - assert_native_matches(expr, batch) + assert_conversion_matches(expr, batch) } #[rstest] @@ -2673,7 +2656,7 @@ fn test_native_not(#[values(false, true)] nested: bool) -> anyhow::Result<()> { if nested { expr = Arc::new(df_expr::NotExpr::new(expr)); } - assert_native_matches(Arc::new(df_expr::NotExpr::new(expr)), batch) + assert_conversion_matches(Arc::new(df_expr::NotExpr::new(expr)), batch) } #[test] diff --git a/vortex-datafusion/src/v2/tests.rs b/vortex-datafusion/src/v2/tests.rs index 13079028338..867335306de 100644 --- a/vortex-datafusion/src/v2/tests.rs +++ b/vortex-datafusion/src/v2/tests.rs @@ -22,6 +22,7 @@ use datafusion::prelude::SessionContext; use datafusion_common::Result as DFResult; use datafusion_common::ScalarValue; use datafusion_common::arrow::compute::concat_batches; +use datafusion_common::arrow::compute::filter_record_batch; use datafusion_common::config::ConfigOptions; use datafusion_common::stats::Precision; use datafusion_common::tree_node::TreeNode; @@ -51,6 +52,8 @@ use vortex_arrow::ArrowSessionExt; use super::VortexDataSource; use crate::convert::ExpressionConverter; +use crate::convert::exprs::mixed_tests::lookup; +use crate::convert::exprs::mixed_tests::routed; async fn vortex_source() -> anyhow::Result { let batch = @@ -104,17 +107,16 @@ async fn projection_filters_use_scan_schema() -> anyhow::Result<()> { Operator::Gt, Arc::new(df_expr::Literal::new(ScalarValue::Int32(Some(15)))), )); - let unsupported: Arc = Arc::new(df_expr::BinaryExpr::new( + let modular: Arc = Arc::new(df_expr::BinaryExpr::new( Arc::new(df_expr::Column::new("odd", 1)), Operator::Eq, Arc::new(df_expr::Literal::new(ScalarValue::Int32(Some(1)))), )); - let pushed = - projected.try_pushdown_filters(vec![supported, unsupported], &ConfigOptions::new())?; + let pushed = projected.try_pushdown_filters(vec![supported, modular], &ConfigOptions::new())?; assert!(matches!( pushed.filters.as_slice(), - [PushedDown::Yes, PushedDown::No] + [PushedDown::Yes, PushedDown::Yes] )); let updated = pushed .updated_node @@ -222,14 +224,15 @@ async fn statistics_follow_filter_and_fetch() -> anyhow::Result<()> { } #[rstest] -#[case(Operator::And, vec![30, 20], vec![30], vec![20])] -#[case(Operator::Or, vec![30, 10, 20], vec![30, 20], vec![30, 20])] +#[case(Operator::And, vec![30, 20], vec![30], vec![20], vec![])] +#[case(Operator::Or, vec![30, 10, 20], vec![30, 20], vec![30, 20], vec![30, 20])] #[tokio::test] async fn dynamic_filters_refresh_projected_bounds_and_keep_residuals( #[case] operator: Operator, #[case] unrestricted: Vec, #[case] above_bound: Vec, #[case] equal_bound: Vec, + #[case] modular_bound: Vec, ) -> anyhow::Result<()> { let source = vortex_source() .await? @@ -269,8 +272,9 @@ async fn dynamic_filters_refresh_projected_bounds_and_keep_residuals( }) })?; assert!(visited); - // An unsupported dynamic predicate must not erase the static AND restriction. - let unsupported = Arc::new(df_expr::BinaryExpr::new( + // A non-native dynamic predicate now runs in the DF callback, retaining the + // static restriction and the outer Boolean operator. + let modular = Arc::new(df_expr::BinaryExpr::new( Arc::new(df_expr::BinaryExpr::new( Arc::clone(&column), Operator::Modulo, @@ -290,7 +294,7 @@ async fn dynamic_filters_refresh_projected_bounds_and_keep_residuals( )) as Arc, equal_bound, ), - (unsupported as Arc, unrestricted), + (modular as Arc, modular_bound), ] { let stream = source.open(0, SessionContext::new().task_ctx())?; let schema = stream.schema(); @@ -495,7 +499,7 @@ async fn test_dynamic_extension_literals_refresh_and_keep_residuals( let source = pushed .updated_node .ok_or_else(|| anyhow!("dynamic filter was not pushed"))?; - let unsupported = Arc::new(df_expr::BinaryExpr::new( + let distinct = Arc::new(df_expr::BinaryExpr::new( fixture.column(), Operator::IsNotDistinctFrom, fixture.literal(1), @@ -507,11 +511,7 @@ async fn test_dynamic_extension_literals_refresh_and_keep_residuals( (fixture.comparison(2), vec![3], vec![3]), // (fixture.comparison(3), vec![], vec![]), // (fixture.membership()?, vec![2], vec![2]), // - ( - unsupported as Arc, - vec![1, 2, 3, 4], - vec![2], - ), // + (distinct as Arc, vec![2], vec![2]), // ] { bound.update(predicate)?; let scan = Arc::new(DataSourceExec::new(Arc::clone(&source))) as Arc; @@ -602,3 +602,61 @@ async fn dynamic_filter_uses_advisory_conversion_and_keeps_residual() -> anyhow: assert_eq!(calls.load(Ordering::Relaxed), 1); Ok(()) } + +#[tokio::test] +async fn dynamic_df_expression_case_refreshes_after_projection() -> anyhow::Result<()> { + let batch = RecordBatch::try_from_iter(vec![( + "id", + Arc::new(arrow_array::Int64Array::from(vec![ + Some(1), + Some(2), + None, + Some(3), + Some(4), + ])) as ArrayRef, + )])?; + let source = vortex_source_from_batch(batch.clone()) + .await? + .try_swapping_with_projection(&ProjectionExprs::from(vec![ProjectionExpr::new( + Arc::new(df_expr::Column::new("id", 0)), + "value", + )]))? + .unwrap(); + let reference = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "value", + DataType::Int64, + true, + )])), + batch.columns().to_vec(), + )?; + let column = Arc::new(df_expr::Column::new("value", 0)) as Arc; + let bound = Arc::new(DynamicFilterPhysicalExpr::new( + vec![Arc::clone(&column)], + df_expr::lit(true), + )); + let pushed = source.try_pushdown_filters( + vec![Arc::clone(&bound) as Arc], + &ConfigOptions::new(), + )?; + assert!(matches!(pushed.filters.as_slice(), [PushedDown::No])); + let source = pushed.updated_node.unwrap(); + for predicate in [ + lookup( + Arc::new(arrow_array::Int64Array::from(vec![1])), + Arc::clone(&column), + )?, + routed(column)?, + ] { + let expected = predicate + .evaluate(&reference)? + .into_array_of_size(reference.num_rows())?; + let expected = filter_record_batch(&reference, expected.as_boolean())?; + let stream = source.open(0, SessionContext::new().task_ctx())?; + let schema = stream.schema(); + bound.update(predicate)?; + let actual = concat_batches(&schema, &stream.try_collect::>().await?)?; + assert_eq!(actual, expected); + } + Ok(()) +} From d87741492c9d9e63d1f1ce5d2543086536f33c32 Mon Sep 17 00:00:00 2001 From: Daniel King Date: Thu, 19 Nov 2026 16:17:40 -0500 Subject: [PATCH 2/2] Limit import cleanup to new expression conversion code Signed-off-by: Daniel King --- .../src/convert/exprs/fallback.rs | 25 +++--- .../src/convert/exprs/mixed_tests.rs | 76 ++++++++++--------- vortex-datafusion/src/convert/exprs/mod.rs | 20 +++-- 3 files changed, 65 insertions(+), 56 deletions(-) diff --git a/vortex-datafusion/src/convert/exprs/fallback.rs b/vortex-datafusion/src/convert/exprs/fallback.rs index b0a1ead578a..cbd6e45667e 100644 --- a/vortex-datafusion/src/convert/exprs/fallback.rs +++ b/vortex-datafusion/src/convert/exprs/fallback.rs @@ -32,6 +32,12 @@ use super::Conversion; use super::DefaultExpressionConverter; use super::Unconverted; use super::is_infallible; +use super::validate_columns; +use crate::df_expression::contains_higher_order_function; +use crate::df_expression::eligible; +use crate::df_expression::from_inputs; +use crate::df_expression::preserve_field; +use crate::df_expression::raw_expression; pub(super) fn eager(expression: &Arc) -> bool { expression.is::() || expression.is::() || expression.is::() @@ -111,18 +117,13 @@ pub(super) fn lower( schema: &Schema, advisory: bool, ) -> Conversion { - super::validate_columns(expression, schema)?; - if !crate::df_expression::eligible(expression) { + validate_columns(expression, schema)?; + if !eligible(expression) { return Err(Unconverted::Unsupported); } - if crate::df_expression::contains_higher_order_function(expression) { - return crate::df_expression::raw_expression( - Arc::clone(expression), - schema, - &converter.session, - advisory, - )? - .ok_or(Unconverted::Unsupported); + if contains_higher_order_function(expression) { + return raw_expression(Arc::clone(expression), schema, &converter.session, advisory)? + .ok_or(Unconverted::Unsupported); } let native = converter.native_only(); let mut extraction = Extraction { @@ -136,7 +137,7 @@ pub(super) fn lower( arrays: HashMap::default(), }; let expression = extraction.rewrite(expression, true, false)?; - crate::df_expression::from_inputs( + from_inputs( expression, Arc::new(Schema::new(extraction.fields)), extraction.inputs, @@ -253,7 +254,7 @@ impl Extraction<'_> { .map(|child| self.rewrite(child, allow, true)) .collect::>>()?; let rewritten = Arc::clone(expression).with_new_children(children)?; - crate::df_expression::preserve_field( + preserve_field( expression, rewritten, self.schema, diff --git a/vortex-datafusion/src/convert/exprs/mixed_tests.rs b/vortex-datafusion/src/convert/exprs/mixed_tests.rs index 6ac3fb33d6d..577f5cb91a8 100644 --- a/vortex-datafusion/src/convert/exprs/mixed_tests.rs +++ b/vortex-datafusion/src/convert/exprs/mixed_tests.rs @@ -3,8 +3,10 @@ use std::sync::Arc; +use anyhow::Result; use arrow_array::ArrayRef; use arrow_array::BooleanArray; +use arrow_array::Float32Array; use arrow_array::Float64Array; use arrow_array::Int64Array; use arrow_array::ListArray; @@ -14,10 +16,17 @@ use arrow_array::types::Int64Type; use arrow_schema::DataType; use arrow_schema::Field; use arrow_schema::Schema; +use datafusion_common::Result as DFResult; +use datafusion_common::ScalarValue; use datafusion_common::config::ConfigOptions; use datafusion_common::hash_utils::create_hashes; +use datafusion_expr::ColumnarValue; use datafusion_expr::Operator as DFOperator; +use datafusion_expr::ScalarFunctionArgs; use datafusion_expr::ScalarUDF; +use datafusion_expr::ScalarUDFImpl; +use datafusion_expr::Signature; +use datafusion_expr::Volatility; use datafusion_functions::core::named_struct::NamedStructFunc; use datafusion_functions::string::lower::LowerFunc; use datafusion_physical_expr::PhysicalExpr; @@ -26,6 +35,7 @@ use datafusion_physical_plan::expressions::BinaryExpr; use datafusion_physical_plan::expressions::CaseExpr; use datafusion_physical_plan::expressions::CastExpr; use datafusion_physical_plan::expressions::Column; +use datafusion_physical_plan::expressions::IsNotNullExpr; use datafusion_physical_plan::expressions::NotExpr; use datafusion_physical_plan::expressions::lit; use datafusion_physical_plan::joins::HashExpr; @@ -46,11 +56,13 @@ use vortex_arrow::ExecuteArrowExt; use super::DefaultExpressionConverter; use super::ExpressionConverter; use super::is_infallible; +use super::tests::array_transform_expr; +use crate::df_expression::df_expression; pub(crate) fn lookup( values: ArrayRef, key: Arc, -) -> anyhow::Result> { +) -> Result> { let state = SeededRandomState::with_seed(17); let mut hashes = vec![0; values.len()]; create_hashes(&[values], state.random_state(), &mut hashes)?; @@ -68,7 +80,7 @@ fn evaluate( batch: &RecordBatch, output: &Field, session: &VortexSession, -) -> anyhow::Result { +) -> Result { let input = session .arrow() .from_arrow_record_batch(batch.clone(), &batch.schema())?; @@ -78,7 +90,7 @@ fn evaluate( } #[test] -fn df_expression_keeps_native_outer_and_inner_sums() -> anyhow::Result<()> { +fn df_expression_keeps_native_outer_and_inner_sums() -> Result<()> { let batch = RecordBatch::try_from_iter(vec![ ( "x", @@ -130,7 +142,7 @@ fn df_expression_keeps_native_outer_and_inner_sums() -> anyhow::Result<()> { } #[test] -fn df_expression_groups_wrapping_operators_and_preserves_lazy_errors() -> anyhow::Result<()> { +fn df_expression_groups_wrapping_operators_and_preserves_lazy_errors() -> Result<()> { let batch = RecordBatch::try_from_iter(vec![( "id", Arc::new(Int64Array::from(vec![0, 1])) as ArrayRef, @@ -198,7 +210,7 @@ fn df_expression_groups_wrapping_operators_and_preserves_lazy_errors() -> anyhow Ok(()) } -pub(crate) fn routed(key: Arc) -> anyhow::Result> { +pub(crate) fn routed(key: Arc) -> Result> { let route: Arc = Arc::new(BinaryExpr::new( Arc::new(HashExpr::new( vec![Arc::clone(&key)], @@ -217,7 +229,7 @@ pub(crate) fn routed(key: Arc) -> anyhow::Result anyhow::Result<()> { +fn df_expression_accepts_partition_routing_case_as_a_whole_hint() -> Result<()> { let batch = RecordBatch::try_from_iter(vec![( "id", Arc::new(Int64Array::from(vec![ @@ -250,42 +262,36 @@ fn df_expression_accepts_partition_routing_case_as_a_whole_hint() -> anyhow::Res #[derive(Debug, PartialEq, Eq, Hash)] struct ObserveArgument { - signature: datafusion_expr::Signature, + signature: Signature, name: String, nullable: bool, scalar: bool, } -impl datafusion_expr::ScalarUDFImpl for ObserveArgument { +impl ScalarUDFImpl for ObserveArgument { fn name(&self) -> &str { "observe_argument" } - fn signature(&self) -> &datafusion_expr::Signature { + fn signature(&self) -> &Signature { &self.signature } - fn return_type(&self, _: &[DataType]) -> datafusion_common::Result { + fn return_type(&self, _: &[DataType]) -> DFResult { Ok(DataType::Boolean) } - fn invoke_with_args( - &self, - args: datafusion_expr::ScalarFunctionArgs, - ) -> datafusion_common::Result { - Ok(datafusion_expr::ColumnarValue::Scalar( - datafusion_common::ScalarValue::Boolean(Some( - args.arg_fields[0].name() == &self.name - && args.arg_fields[0].is_nullable() == self.nullable - && matches!(args.args[0], datafusion_expr::ColumnarValue::Scalar(_)) - == self.scalar, - )), - )) + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> DFResult { + Ok(ColumnarValue::Scalar(ScalarValue::Boolean(Some( + args.arg_fields[0].name() == &self.name + && args.arg_fields[0].is_nullable() == self.nullable + && matches!(args.args[0], ColumnarValue::Scalar(_)) == self.scalar, + )))) } } #[test] -fn df_expression_preserves_udf_argument_fields_and_scalar_shape() -> anyhow::Result<()> { +fn df_expression_preserves_udf_argument_fields_and_scalar_shape() -> Result<()> { let batch = RecordBatch::try_from_iter(vec![ ("unused", Arc::new(Int64Array::from(vec![0, 0])) as ArrayRef), ( "x", - Arc::new(arrow_array::Float32Array::from(vec![Some(1.), None])) as ArrayRef, + Arc::new(Float32Array::from(vec![Some(1.), None])) as ArrayRef, ), ])?; let cast: Arc = Arc::new(CastExpr::new_with_target_field( @@ -304,14 +310,12 @@ fn df_expression_preserves_udf_argument_fields_and_scalar_shape() -> anyhow::Res let short_circuit: Arc = Arc::new(BinaryExpr::new( lit(false), DFOperator::And, - Arc::new(datafusion_physical_plan::expressions::IsNotNullExpr::new( - Arc::new(Column::new("x", 1)), - )), + Arc::new(IsNotNullExpr::new(Arc::new(Column::new("x", 1)))), )); for (child, scalar) in [(cast, false), (lower, true), (short_circuit, true)] { let field = child.return_field(&batch.schema())?; let fun = ScalarUDF::from(ObserveArgument { - signature: datafusion_expr::Signature::any(1, datafusion_expr::Volatility::Immutable), + signature: Signature::any(1, Volatility::Immutable), name: field.name().clone(), nullable: field.is_nullable(), scalar, @@ -325,8 +329,7 @@ fn df_expression_preserves_udf_argument_fields_and_scalar_shape() -> anyhow::Res let mixed = converter .try_convert(&expression, &batch.schema())? .unwrap(); - let raw = - crate::df_expression(Arc::clone(&expression), &batch.schema(), &session)?.unwrap(); + let raw = df_expression(Arc::clone(&expression), &batch.schema(), &session)?.unwrap(); let expected = expression .evaluate(&batch)? .into_array_of_size(batch.num_rows())?; @@ -348,7 +351,7 @@ fn df_expression_preserves_udf_argument_fields_and_scalar_shape() -> anyhow::Res } #[test] -fn df_expression_advisory_rejects_invalid_original_column_bindings() -> anyhow::Result<()> { +fn df_expression_advisory_rejects_invalid_original_column_bindings() -> Result<()> { let converter = DefaultExpressionConverter::default(); let duplicate = Schema::new(vec![ Field::new("id", DataType::Int64, false), @@ -380,7 +383,7 @@ fn df_expression_advisory_rejects_invalid_original_column_bindings() -> anyhow:: } #[test] -fn df_expression_preserves_lambda_input_positions() -> anyhow::Result<()> { +fn df_expression_preserves_lambda_input_positions() -> Result<()> { let batch = RecordBatch::try_from_iter(vec![ ( "x", @@ -394,7 +397,7 @@ fn df_expression_preserves_lambda_input_positions() -> anyhow::Result<()> { ])) as ArrayRef, ), ])?; - let transform = super::tests::array_transform_expr( + let transform = array_transform_expr( Arc::new(Column::new("list", 1)), "u", 2, @@ -430,8 +433,7 @@ fn df_expression_preserves_lambda_input_positions() -> anyhow::Result<()> { let mixed = converter .try_convert(&expression, &batch.schema())? .unwrap(); - let raw = - crate::df_expression(Arc::clone(&expression), &batch.schema(), &session)?.unwrap(); + let raw = df_expression(Arc::clone(&expression), &batch.schema(), &session)?.unwrap(); let expected = expression .evaluate(&batch)? .into_array_of_size(batch.num_rows())?; @@ -449,7 +451,7 @@ fn df_expression_preserves_lambda_input_positions() -> anyhow::Result<()> { } #[test] -fn df_expression_preserves_fields_through_datafusion_case_projection() -> anyhow::Result<()> { +fn df_expression_preserves_fields_through_datafusion_case_projection() -> Result<()> { let batch = RecordBatch::try_from_iter(vec![ ("s", Arc::new(StringArray::from(vec!["a", "b"])) as ArrayRef), ( @@ -476,7 +478,7 @@ fn df_expression_preserves_fields_through_datafusion_case_projection() -> anyhow let mixed = DefaultExpressionConverter::new(session.clone()) .try_convert(&expression, &batch.schema())? .unwrap(); - let raw = crate::df_expression(Arc::clone(&expression), &batch.schema(), &session)?.unwrap(); + let raw = df_expression(Arc::clone(&expression), &batch.schema(), &session)?.unwrap(); let expected = expression .evaluate(&batch)? .into_array_of_size(batch.num_rows())?; diff --git a/vortex-datafusion/src/convert/exprs/mod.rs b/vortex-datafusion/src/convert/exprs/mod.rs index 90c686dd30e..3adab84b3d2 100644 --- a/vortex-datafusion/src/convert/exprs/mod.rs +++ b/vortex-datafusion/src/convert/exprs/mod.rs @@ -82,6 +82,12 @@ use vortex::scalar_fn::fns::operators::Operator; use vortex::session::VortexSession; use vortex_arrow::ArrowSessionExt; +use self::fallback::compatible as native_compatible; +use self::fallback::eager as evaluates_children_eagerly; +use self::fallback::lower as lower_df_expression; +use crate::df_expression::contains_higher_order_function; +use crate::df_expression::eligible; + /// Result of splitting a projection into Vortex expressions and leftover DataFusion projections. pub struct ProcessedProjection { /// Projection evaluated by the Vortex scan. @@ -358,7 +364,7 @@ impl DefaultExpressionConverter { schema: &Schema, ) -> Conversion { let mut column_indices = validate_columns(expr, schema)?; - if crate::df_expression::contains_higher_order_function(expr) { + if contains_higher_order_function(expr) { column_indices = (0..schema.fields().len()).collect(); } let input_dtype = self @@ -430,9 +436,9 @@ impl DefaultExpressionConverter { schema: &Schema, input_dtype: &DType, ) -> Conversion { - let mut result = if !fallback::compatible(expr, schema)? { + let mut result = if !native_compatible(expr, schema)? { Err(Unconverted::Unsupported) - } else if self.df_fallback && !fallback::eager(expr) { + } else if self.df_fallback && !evaluates_children_eagerly(expr) { self.native_only() .convert_native_expr(expr, schema, input_dtype) } else { @@ -448,7 +454,7 @@ impl DefaultExpressionConverter { Err(Unconverted::Unsupported) if self.df_fallback && matches!(self.scope, Scope::Global) => { - fallback::lower(self, expr, schema, false) + lower_df_expression(self, expr, schema, false) } other => other, } @@ -992,7 +998,7 @@ impl ExpressionConverter for DefaultExpressionConverter { if DynamicFilterTracking::classify(expr).contains_dynamic_filter() { return Ok(None); } - if !crate::df_expression::eligible(expr) { + if !eligible(expr) { return Ok(None); } match self.conversion_context().convert_checked(expr, schema) { @@ -1006,7 +1012,7 @@ impl ExpressionConverter for DefaultExpressionConverter { expr: &Arc, schema: &Schema, ) -> DFResult> { - if !crate::df_expression::eligible(expr) || expr.data_type(schema)? != DataType::Boolean { + if !eligible(expr) || expr.data_type(schema)? != DataType::Boolean { return Ok(None); } let converter = self.conversion_context(); @@ -1015,7 +1021,7 @@ impl ExpressionConverter for DefaultExpressionConverter { Err(Unconverted::Failed(error)) => return Err(error), _ => {} } - match fallback::lower(&converter, expr, schema, true) { + match lower_df_expression(&converter, expr, schema, true) { Ok(value) => Ok(Some(value)), Err(Unconverted::Unsupported) => Ok(None), Err(Unconverted::Failed(error)) => Err(error),