diff --git a/vortex-datafusion/src/convert/exprs/mod.rs b/vortex-datafusion/src/convert/exprs/mod.rs index 5e5602e32e6..cb74fa3a621 100644 --- a/vortex-datafusion/src/convert/exprs/mod.rs +++ b/vortex-datafusion/src/convert/exprs/mod.rs @@ -7,6 +7,7 @@ //! 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 projection_fields; use std::sync::Arc; use arrow_schema::DataType; @@ -40,6 +41,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; +pub(crate) use projection_fields::push_down_projection_fields; use vortex::VortexSessionDefault; use vortex::aggregate_fn::NumericalAggregateOpts; use vortex::array::VortexSessionExecute; @@ -173,6 +175,14 @@ pub trait ExpressionConverter: Send + Sync { }) } + /// Allow scans to refine the raw fallback returned by [`Self::split_projection`]. + /// + /// Defaults to `false`. Opt in if scans may replace whole struct inputs with the plain fields + /// the remaining DataFusion projection needs. + fn allows_projection_field_pushdown(&self) -> bool { + false + } + /// Create a projection that reads only the required columns without pushing down /// any expressions. All projection logic is applied after the scan. fn no_pushdown_projection( @@ -914,6 +924,10 @@ impl ExpressionConverter for DefaultExpressionConverter { Err(Unconverted::Failed(error)) => Err(error), } } + + fn allows_projection_field_pushdown(&self) -> bool { + true + } } /// Whether evaluating `expr` cannot fail, so Vortex may evaluate it on rows DataFusion skips. diff --git a/vortex-datafusion/src/convert/exprs/projection_fields.rs b/vortex-datafusion/src/convert/exprs/projection_fields.rs new file mode 100644 index 00000000000..ba76e9468fd --- /dev/null +++ b/vortex-datafusion/src/convert/exprs/projection_fields.rs @@ -0,0 +1,286 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Prunes struct fields from the raw inputs of a DataFusion projection. +//! +//! DataFusion still evaluates the projection. The scan substitutes columns only for field reads +//! whose Arrow field and values are the same as in the raw projection. + +use std::iter; +use std::sync::Arc; + +use arrow_schema::DataType; +use arrow_schema::FieldRef; +use arrow_schema::Schema; +use datafusion_common::tree_node::Transformed; +use datafusion_common::tree_node::TreeNode; +use datafusion_common::tree_node::TreeNodeRecursion; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_physical_expr::PhysicalExprRef; +use datafusion_physical_expr::ScalarFunctionExpr; +use datafusion_physical_expr::expressions as df_expr; +use datafusion_physical_expr::utils::reassign_expr_columns; +use itertools::Itertools; +use vortex::dtype::DType; +use vortex::dtype::Nullability; +use vortex::dtype::StructFields; +use vortex::error::VortexResult; +use vortex::expr::Expression; +use vortex::expr::get_item; +use vortex::expr::pack; +use vortex::expr::root; +use vortex::layout::layouts::row_idx; +use vortex::scalar_fn::fns::get_item::GetItem; +use vortex::scalar_fn::fns::pack::Pack; +use vortex_arrow::ArrowSession; +use vortex_utils::aliases::hash_map::HashMap; + +use super::ExpressionConverter; +use super::ProcessedProjection; + +/// Refine a raw fallback if it can omit at least one whole struct column. Resolve the actual scan +/// dtype lazily because the Arrow reference schema can describe stricter nullability than the data. +pub(crate) fn push_down_projection_fields( + projection: ProcessedProjection, + converter: &dyn ExpressionConverter, + scan_dtype: impl FnOnce(&Expression) -> VortexResult, + arrow: &ArrowSession, +) -> ProcessedProjection { + if !converter.allows_projection_field_pushdown() { + return projection; + } + + try_push_down_fields(&projection, converter, scan_dtype, arrow).unwrap_or(projection) +} + +fn try_push_down_fields( + projection: &ProcessedProjection, + converter: &dyn ExpressionConverter, + scan_dtype: impl FnOnce(&Expression) -> VortexResult, + arrow: &ArrowSession, +) -> Option { + let raw_schema = &projection.scan_reference_schema; + let raw_fields = raw_schema.fields(); + let raw_columns = projection.scan_projection.children(); + let options = projection.scan_projection.as_opt::()?; + if options.nullability.is_nullable() + || options.names.len() != raw_fields.len() + || raw_columns.len() != raw_fields.len() + || !raw_fields + .iter() + .any(|field| matches!(field.data_type(), DataType::Struct(_))) + || !raw_fields.iter().map(|field| field.name()).all_unique() + || !options + .names + .iter() + .zip(raw_fields) + .zip(raw_columns) + .all(|((name, field), expr)| { + name.as_ref() == field.name() + && (expr.as_opt::() == Some(name) && expr.child(0) == &root() + || *expr == row_idx::row_idx()) + }) + { + return None; + } + + let leftover = &projection.leftover_projection; + if !leftover.iter().map(|output| &output.alias).all_unique() { + return None; + } + + let mut has_field_read = false; + for output in leftover.iter() { + if output + .expr + .exists(|expr| { + has_field_read |= get_field_function(expr).is_some(); + Ok(!can_rewrite(expr)) + }) + .ok()? + { + return None; + } + } + if !has_field_read { + return None; + } + + let DType::Struct(scan_fields, _) = scan_dtype(&projection.scan_projection).ok()? else { + return None; + }; + + let mut fields = raw_fields.to_vec(); + let mut columns = raw_columns.to_vec(); + let mut indices: HashMap = fields + .iter() + .enumerate() + .map(|(index, field)| (field.name().clone(), index)) + .collect(); + let leftover = leftover + .clone() + .try_map_exprs(|expr| { + // The fallback keeps the original column indices until the caller remaps by name. + // Assign indices before adding columns so rebuilding a CASE sees distinct inputs. + reassign_expr_columns(expr, raw_schema)? + .transform_down(|expr| { + if get_field_function(&expr).is_none() { + return Ok(Transformed::no(expr)); + } + + let keep = + || Transformed::new(Arc::clone(&expr), false, TreeNodeRecursion::Jump); + let Some((field, read)) = + convert_field_read(&expr, raw_schema, &scan_fields, converter, arrow) + else { + return Ok(keep()); + }; + + // UDFs receive the argument's full Arrow field. Its name must survive the + // rewrite, so a collision with a different read keeps the original expression. + let index = if let Some(&index) = indices.get(field.name()) { + if index < raw_fields.len() || columns[index] != read { + return Ok(keep()); + } + index + } else { + let index = columns.len(); + indices.insert(field.name().clone(), index); + fields.push(Arc::clone(&field)); + columns.push(read); + index + }; + + Ok(Transformed::yes( + Arc::new(df_expr::Column::new(field.name(), index)) as _, + )) + }) + .map(|transformed| transformed.data) + }) + .ok()?; + + let used = leftover.column_indices(); + let retained_raw = used.partition_point(|&index| index < raw_fields.len()); + if retained_raw == raw_fields.len() || retained_raw == used.len() { + return None; + } + + let schema = Schema::new_with_metadata(fields, raw_schema.metadata().clone()); + let scan_reference_schema = schema.project(&used).ok()?; + let scan_projection = pack( + used.iter() + .map(|&index| (schema.field(index).name().clone(), columns[index].clone())), + Nullability::NonNullable, + ); + Some(ProcessedProjection { + scan_projection, + scan_reference_schema, + leftover_projection: leftover, + }) +} + +/// Allow only expressions whose children describe their input bindings. A lambda or a physical +/// expression with its own bindings needs the original fallback layout. +fn can_rewrite(expr: &PhysicalExprRef) -> bool { + if let Some(function) = expr.downcast_ref::() { + // DataFusion passes return fields to UDFs, and the default return field uses the + // expression's display name. These argument types preserve their fields when remapped. + return function.args().iter().all(|arg| { + arg.is::() + || arg.is::() + || arg.is::() + }); + } + + expr.is::() + || expr.is::() + || expr.is::() + || expr.is::() + || expr.is::() + || expr.is::() + || expr.is::() + || expr.is::() +} + +fn get_field_function(expr: &PhysicalExprRef) -> Option<&ScalarFunctionExpr> { + ScalarFunctionExpr::try_downcast_func::(expr.as_ref()) +} + +fn convert_field_read( + expr: &PhysicalExprRef, + schema: &Schema, + scan_fields: &StructFields, + converter: &dyn ExpressionConverter, + arrow: &ArrowSession, +) -> Option<(FieldRef, Expression)> { + let (field, dtype, read) = struct_field_path(expr, schema, scan_fields)?; + // Importing an Arrow field can erase dictionary and run-end encoding. Check the Arrow + // type directly, since a UDF can observe that encoding even when the values are equivalent. + let arrow_type = field.data_type(); + let plain_type = arrow_type.is_integer() + || arrow_type.is_floating() + || arrow_type.is_string() + || matches!( + arrow_type, + DataType::Boolean | DataType::Binary | DataType::LargeBinary | DataType::BinaryView + ); + if !plain_type + || field.extension_type_name().is_some() + || arrow.from_arrow_field(&field).ok()? != dtype + { + return None; + } + + // A custom converter may reject the read or give it different semantics. + let converted = converter.try_convert(expr, schema).ok().flatten()?; + (converted == read).then_some((field, read)) +} + +/// Resolve both flattened and nested get_field calls. Vortex applies parent validity to a child, +/// so every traversed parent must be a non-nullable struct in both schemas. +fn struct_field_path( + expr: &PhysicalExprRef, + schema: &Schema, + scan_fields: &StructFields, +) -> Option<(FieldRef, DType, Expression)> { + if let Some(column) = expr.downcast_ref::() { + let field = schema.fields().get(column.index())?; + let dtype = scan_fields.field(field.name())?; + let read = get_item(field.name().as_str(), root()); + return Some((Arc::clone(field), dtype, read)); + } + + let function = get_field_function(expr)?; + let [source, first, rest @ ..] = function.args() else { + return None; + }; + let (mut field, mut dtype, mut read) = struct_field_path(source, schema, scan_fields)?; + + for path in iter::once(first).chain(rest) { + if field.is_nullable() || field.extension_type_name().is_some() { + return None; + } + let (DataType::Struct(fields), DType::Struct(children, Nullability::NonNullable)) = + (field.data_type(), &dtype) + else { + return None; + }; + let name = path + .downcast_ref::()? + .value() + .try_as_str() + .flatten() + .filter(|name| !name.is_empty())?; + let mut matching = fields.iter().filter(|field| field.name() == name); + let child = matching.next()?; + if matching.next().is_some() { + return None; + } + + field = Arc::clone(child); + dtype = children.field(name)?; + read = get_item(name, read); + } + + (expr.return_field(schema).ok()? == field).then_some((field, dtype, read)) +} diff --git a/vortex-datafusion/src/persistent/opener.rs b/vortex-datafusion/src/persistent/opener.rs index 3ba227d6ca5..4b9ebcfd052 100644 --- a/vortex-datafusion/src/persistent/opener.rs +++ b/vortex-datafusion/src/persistent/opener.rs @@ -72,6 +72,7 @@ use vortex_utils::parallelism::get_available_parallelism; use crate::VortexAccessPlan; use crate::convert::exprs::ExpressionConverter; use crate::convert::exprs::ProcessedProjection; +use crate::convert::exprs::push_down_projection_fields; use crate::convert::exprs::raw_projection; use crate::convert::schema::calculate_physical_schema; use crate::convert::to_record_batch; @@ -434,11 +435,17 @@ impl FileOpener for VortexOpener { indices.dedup(); raw_projection(&indices, &this_file_schema, projection)? } else if projection_pushdown { - expr_converter.split_projection( + let projection = expr_converter.split_projection( projection, &this_file_schema, output_schema.as_ref(), - )? + )?; + push_down_projection_fields( + projection, + expr_converter.as_ref(), + |expr| expr.return_dtype(vxf.dtype()), + &session.arrow(), + ) } else { expr_converter.no_pushdown_projection(projection, &this_file_schema)? }; diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index cefefb0f696..712434c9482 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -142,6 +142,7 @@ use super::dynamic_filters::convert_dynamic_filter; use crate::convert::exprs::DefaultExpressionConverter; use crate::convert::exprs::ExpressionConverter; use crate::convert::exprs::ProcessedProjection; +use crate::convert::exprs::push_down_projection_fields; use crate::convert::schema::calculate_physical_schema; use crate::convert::stats::stats_set_to_df; use crate::convert::to_record_batch; @@ -873,15 +874,28 @@ impl DataSource for VortexDataSource { let converter = &self.expression_converter; let input_schema = self.initial_schema.as_ref(); let projected_schema = projection.project_schema(input_schema)?; + let arrow = self.session.arrow(); // Use the shared ExpressionConverter to split the projection into a Vortex // scan_projection and a leftover DataFusion projection for expressions that // can't be pushed down (e.g., unsupported scalar functions, decimal binary). + let processed = + converter.split_projection(projection.clone(), input_schema, &projected_schema)?; let ProcessedProjection { scan_projection, scan_reference_schema, leftover_projection, - } = converter.split_projection(projection.clone(), input_schema, &projected_schema)?; + } = push_down_projection_fields( + processed, + converter.as_ref(), + |expr| { + let initial_dtype = self + .initial_projection + .return_dtype(self.data_source.dtype())?; + expr.return_dtype(&initial_dtype) + }, + &arrow, + ); // Compose with the initial projection so the scan operates on the original // source columns, not the initial projection's output columns. @@ -894,7 +908,7 @@ impl DataSource for VortexDataSource { let scan_output_schema = Arc::new(calculate_physical_schema( &scan_dtype, &scan_reference_schema, - &self.session.arrow(), + &arrow, )?); // Remap the leftover column references to match the scan output schema. diff --git a/vortex-datafusion/src/v2/tests.rs b/vortex-datafusion/src/v2/tests.rs index 8ad23de2b4a..a82102679c2 100644 --- a/vortex-datafusion/src/v2/tests.rs +++ b/vortex-datafusion/src/v2/tests.rs @@ -4,9 +4,12 @@ use std::sync::Arc; use anyhow::anyhow; +use arrow_array::Array; use arrow_array::ArrayRef; use arrow_array::Int32Array; use arrow_array::RecordBatch; +use arrow_array::StringArray; +use arrow_array::StructArray; use arrow_array::cast::AsArray; use arrow_array::types::Int32Type; use arrow_schema::DataType; @@ -16,7 +19,9 @@ use arrow_schema::extension::Json as ArrowJson; use arrow_schema::extension::Uuid as ArrowUuid; use datafusion::assert_batches_eq; use datafusion::prelude::SessionContext; +use datafusion_common::Result as DFResult; use datafusion_common::ScalarValue; +use datafusion_common::arrow::buffer::NullBuffer; use datafusion_common::arrow::compute::concat_batches; use datafusion_common::config::ConfigOptions; use datafusion_common::stats::Precision; @@ -25,11 +30,17 @@ use datafusion_common::tree_node::TreeNodeRecursion; use datafusion_datasource::source::DataSource; use datafusion_datasource::source::DataSourceExec; use datafusion_expr::Operator; +use datafusion_expr::ScalarUDF; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_functions::string::upper::UpperFunc; use datafusion_physical_expr::PhysicalExpr; +use datafusion_physical_expr::PhysicalExprRef; +use datafusion_physical_expr::ScalarFunctionExpr; use datafusion_physical_expr::expressions::DynamicFilterPhysicalExpr; use datafusion_physical_expr::projection::ProjectionExpr; use datafusion_physical_expr::projection::ProjectionExprs; use datafusion_physical_plan::ExecutionPlan; +use datafusion_physical_plan::displayable; use datafusion_physical_plan::expressions as df_expr; use datafusion_physical_plan::filter::FilterExec; use datafusion_physical_plan::filter_pushdown::PushedDown; @@ -37,6 +48,7 @@ use futures::TryStreamExt; use rstest::rstest; use vortex::VortexSessionDefault; use vortex::buffer::ByteBufferMut; +use vortex::expr::Expression; use vortex::file::OpenOptionsSessionExt; use vortex::file::WriteOptionsSessionExt; use vortex::scan::DataSourceRef; @@ -44,6 +56,10 @@ use vortex::session::VortexSession; use vortex_arrow::ArrowSessionExt; use super::VortexDataSource; +use crate::convert::DefaultExpressionConverter; +use crate::convert::ExpressionConverter; +use crate::convert::ProcessedProjection; +use crate::row_index; async fn vortex_source() -> anyhow::Result { let batch = @@ -84,6 +100,209 @@ async fn data_source_from_batch( Ok(file.data_source()?) } +#[rstest] +#[case::non_nullable(false, false, false)] +#[case::nullable_outer(true, true, false)] +#[case::nullable_outer_in_storage(true, false, false)] +#[case::nullable_inner(false, false, true)] +#[tokio::test] +async fn test_partial_projection_reads_struct_leaf( + #[case] stored_outer_nullable: bool, + #[case] declared_outer_nullable: bool, + #[case] inner_nullable: bool, +) -> anyhow::Result<()> { + let label_field = Field::new("label", DataType::Utf8, true) + .with_metadata([("source".to_owned(), "test".to_owned())].into()); + let inner = StructArray::try_new( + vec![ + label_field.clone(), + Field::new("unused", DataType::Int32, false), + ] + .into(), + vec![ + Arc::new(StringArray::from(vec![Some("x"), Some("20"), None])), + Arc::new(Int32Array::from(vec![10, 20, 30])), + ], + inner_nullable.then(|| NullBuffer::from(vec![false, true, true])), + )?; + let outer = StructArray::try_new( + vec![Field::new( + "inner", + inner.data_type().clone(), + inner_nullable, + )] + .into(), + vec![Arc::new(inner)], + stored_outer_nullable.then(|| NullBuffer::from(vec![false, true, true])), + )?; + let batch = RecordBatch::try_from_iter([ + ("id", Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef), + ("s", Arc::new(outer) as ArrayRef), + ])?; + let schema = Arc::new(Schema::new(vec![ + batch.schema().field(0).clone(), + batch + .schema() + .field(1) + .clone() + .with_nullable(declared_outer_nullable), + ])); + let session = VortexSession::default(); + let data_source = data_source_from_batch(batch, &session).await?; + let source = VortexDataSource::builder(data_source, session) + .with_arrow_schema(Arc::clone(&schema)) + .build() + .await?; + + let function = |udf: ScalarUDF, args| -> anyhow::Result { + Ok(Arc::new(ScalarFunctionExpr::try_new( + Arc::new(udf), + args, + &schema, + Arc::new(ConfigOptions::new()), + )?)) + }; + let id: PhysicalExprRef = Arc::new(df_expr::Column::new("id", 0)); + let label = function( + GetFieldFunc::new().into(), + vec![ + Arc::new(df_expr::Column::new("s", 1)), + df_expr::lit("inner"), + df_expr::lit("label"), + ], + )?; + let upper = function(UpperFunc::new().into(), vec![Arc::clone(&label)])?; + // The cast would fail on "x" if the scan evaluated it before the CASE selected rows. + let parse_label = Arc::new(df_expr::CastExpr::new( + Arc::clone(&label), + DataType::Int32, + None, + )); + let format_label: PhysicalExprRef = + Arc::new(df_expr::CastExpr::new(parse_label, DataType::Utf8, None)); + let is_second_row: PhysicalExprRef = Arc::new(df_expr::BinaryExpr::new( + Arc::clone(&id), + Operator::Eq, + df_expr::lit(2i32), + )); + let formatted = Arc::new(df_expr::CaseExpr::try_new( + None, + vec![(is_second_row, format_label)], + Some(upper), + )?); + let inner = function( + GetFieldFunc::new().into(), + vec![ + Arc::new(df_expr::Column::new("s", 1)), + df_expr::lit("inner"), + ], + )?; + let original = function( + GetFieldFunc::new().into(), + vec![inner, df_expr::lit("label")], + )?; + let projection = ProjectionExprs::from(vec![ + ProjectionExpr::new(id, "id"), + ProjectionExpr::new(formatted, "formatted"), + ProjectionExpr::new(original, "original"), + ProjectionExpr::new(row_index(), "position"), + ]); + let projected = source + .try_swapping_with_projection(&projection)? + .ok_or_else(|| anyhow!("projection was not swapped"))?; + let plan = Arc::new(DataSourceExec::new(projected)) as Arc; + let display = displayable(plan.as_ref()).one_line().to_string(); + let expected_scan = if stored_outer_nullable || inner_nullable { + "projection=pack(id: $.id, s: $.s, __vortex_row_index: #row_idx)" + } else { + "projection=pack(id: $.id, __vortex_row_index: #row_idx, label: $.s.inner.label)" + }; + assert!(display.contains(expected_scan), "{display}"); + + let batches = datafusion_physical_plan::collect(plan, SessionContext::new().task_ctx()).await?; + assert_batches_eq!( + [ + "+----+-----------+----------+----------+", + "| id | formatted | original | position |", + "+----+-----------+----------+----------+", + "| 1 | X | x | 0 |", + "| 2 | 20 | 20 | 1 |", + "| 3 | | | 2 |", + "+----+-----------+----------+----------+", + ], + &batches + ); + for batch in batches { + assert_eq!(batch.schema().field(2).metadata(), label_field.metadata()); + } + + Ok(()) +} + +#[derive(Default)] +struct RawProjectionConverter(DefaultExpressionConverter); + +impl ExpressionConverter for RawProjectionConverter { + fn try_convert(&self, expr: &PhysicalExprRef, schema: &Schema) -> DFResult> { + self.0.try_convert(expr, schema) + } + + fn split_projection( + &self, + projection: ProjectionExprs, + input_schema: &Schema, + _output_schema: &Schema, + ) -> DFResult { + self.no_pushdown_projection(projection, input_schema) + } +} + +#[tokio::test] +async fn test_custom_converter_keeps_raw_projection() -> anyhow::Result<()> { + let input = StructArray::try_new( + vec![ + Field::new("value", DataType::Int32, false), + Field::new("unused", DataType::Int32, false), + ] + .into(), + vec![ + Arc::new(Int32Array::from(vec![1, 2])), + Arc::new(Int32Array::from(vec![10, 20])), + ], + None, + )?; + let batch = RecordBatch::try_from_iter([("s", Arc::new(input) as ArrayRef)])?; + let schema = batch.schema(); + let field: PhysicalExprRef = Arc::new(ScalarFunctionExpr::try_new( + Arc::new(GetFieldFunc::new().into()), + vec![ + Arc::new(df_expr::Column::new("s", 0)), + df_expr::lit("value"), + ], + &schema, + Arc::new(ConfigOptions::new()), + )?); + let converter = RawProjectionConverter::default(); + assert!(converter.try_convert(&field, &schema)?.is_some()); + + let session = VortexSession::default(); + let data_source = data_source_from_batch(batch, &session).await?; + let source = VortexDataSource::builder(data_source, session) + .with_arrow_schema(schema) + .with_expression_converter(Arc::new(converter)) + .build() + .await?; + let projection = vec![ProjectionExpr::new(field, "value")].into(); + let projected = source + .try_swapping_with_projection(&projection)? + .ok_or_else(|| anyhow!("projection was not swapped"))?; + let plan = DataSourceExec::new(projected); + let display = displayable(&plan).one_line().to_string(); + assert!(display.contains("projection=pack(s: $.s)"), "{display}"); + + Ok(()) +} + #[tokio::test] async fn projection_filters_use_scan_schema() -> anyhow::Result<()> { let source = vortex_source().await?;