Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
277 changes: 250 additions & 27 deletions datafusion/physical-optimizer/src/projection_pushdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use datafusion_common::{JoinSide, JoinType, Result, internal_datafusion_err};
use datafusion_expr::ExpressionPlacement;
use datafusion_physical_expr::expressions::{Column, LambdaExpr, LambdaVariable};
use datafusion_physical_expr::projection::ProjectionExpr;
use datafusion_physical_expr::utils::collect_columns;
use datafusion_physical_expr::{conjunction, split_conjunction};
use datafusion_physical_expr_common::physical_expr::{PhysicalExpr, is_volatile};
use datafusion_physical_plan::joins::NestedLoopJoinExec;
Expand All @@ -30,7 +31,8 @@ use datafusion_physical_plan::projection::{
};
use datafusion_physical_plan::repartition::RepartitionExec;
use datafusion_physical_plan::{
ChildrenPropertiesMode, ExecutionPlan, Partitioning, ReplaceChildrenOptions,
ChildrenPropertiesMode, ExecutionPlan, ExecutionPlanProperties, Partitioning,
ReplaceChildrenOptions,
};

/// This rule inspects `ProjectionExec`'s in the given physical plan and tries to
Expand Down Expand Up @@ -74,13 +76,10 @@ impl PhysicalOptimizerRule for ProjectionPushdown {
// narrows and holds a computed one. `RepartitionExec` declines both, it
// is not removable because it renames, and nothing else moved.
let plan = plan.transform_down(remove_unnecessary_projections).data()?;
plan.transform_down(|plan| {
Ok(match try_split_leaf_projection(&plan)? {
Some(new_plan) => Transformed::yes(new_plan),
None => Transformed::no(plan),
})
})
.data()
// Before `OutputRequirementExec` is removed, it declares the ordering of the
// query. After, an operator that needs a global ordering, such as a sort or a
// merge, declares it, because the round robin repartition loses it.
split_projections(plan, false)
}

fn name(&self) -> &str {
Expand Down Expand Up @@ -507,6 +506,38 @@ fn leaf_column_name(index: usize) -> String {
format!("{LEAF_COLUMN_PREFIX}_{index}")
}

/// Calls [`try_split_leaf_projection`] on each node of `plan`, from the root down.
///
/// `order_matters` is true if something above `plan` can rely on its ordering:
/// an ancestor requires one, and every operator in between maintains it.
#[cfg_attr(feature = "recursive_protection", recursive::recursive)]
fn split_projections(
plan: Arc<dyn ExecutionPlan>,
order_matters: bool,
) -> Result<Arc<dyn ExecutionPlan>> {
let plan = try_split_leaf_projection(&plan, order_matters)?.unwrap_or(plan);

let required = plan.required_input_ordering();
let maintains = plan.maintains_input_order();
let mut changed = false;
let mut children = vec![];
for ((child, required), maintains) in
plan.children().into_iter().zip(required).zip(maintains)
{
let order_matters = required.is_some() || (maintains && order_matters);
let new_child = split_projections(Arc::clone(child), order_matters)?;
changed |= !Arc::ptr_eq(child, &new_child);
children.push(new_child);
}
if !changed {
return Ok(plan);
}
plan.replace_children(
children,
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
)
}

/// Splits a `ProjectionExec` that mixes leaf expressions with ones that must
/// stay in place, moving the leaves into a projection the source absorbs.
///
Expand All @@ -517,6 +548,7 @@ fn leaf_column_name(index: usize) -> String {
/// computation above the repartition, still parallelised.
fn try_split_leaf_projection(
plan: &Arc<dyn ExecutionPlan>,
order_matters: bool,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
let Some(projection) = plan.downcast_ref::<ProjectionExec>() else {
return Ok(None);
Expand All @@ -536,13 +568,80 @@ fn try_split_leaf_projection(
return Ok(None);
}

let child = repartition.input();
let passthrough_indices =
choose_passthrough(plan, projection, child, &leaves, order_matters)?;
let lower_projection = lower_projection(child, &leaves, &passthrough_indices)?;

// Only commit the split if the child really absorbs the leaf projection.
// Otherwise this would just add a projection that helps nobody.
let Some(new_child) = child.try_swapping_with_projection(&lower_projection)? else {
return Ok(None);
};

let split =
rebuild_split(projection, &leaves, &passthrough_indices, child, new_child)?;
// The columns were chosen before the lower projection moved, and the operator
// that absorbs it recomputes its own properties.
Ok((keeps_equivalences(plan, &split)?
&& (!order_matters || keeps_orderings(plan, &split)?))
.then_some(split))
}

/// Returns the sorted indices of the `child` columns that a split passes through.
fn choose_passthrough(
plan: &Arc<dyn ExecutionPlan>,
projection: &ProjectionExec,
child: &Arc<dyn ExecutionPlan>,
leaves: &[Arc<dyn PhysicalExpr>],
order_matters: bool,
) -> Result<Vec<usize>> {
// Pass through only the child columns the outer expressions still need. A
// column used *only* inside an extracted leaf must be dropped, otherwise the
// source keeps reading it: for `s['a'] + 1` that would read the whole struct
// alongside the extracted field, which is worse than not splitting at all.
let child = repartition.input();
let mut indices = collect_outer_columns(projection.expr(), leaves)?;
let properties = plan.equivalence_properties();
let has_ordering = order_matters && !properties.oeq_class().is_empty();
if !has_ordering && properties.eq_group().is_empty() {
return Ok(indices);
}
let lower_projection = Arc::new(lower_projection(child, leaves, &indices)?);
let split = rebuild_split(projection, leaves, &indices, child, lower_projection)?;

// A property of the output can depend on a column that no expression reads.
// With `c = a + b`, input sorted by `c` sorts `a + b`, and a constant `c` makes
// `a + b` constant. An ancestor may rely on either, so also pass through the
// columns that the lost property can come from.
let child_properties = child.equivalence_properties();
let mut add_columns = |expr: &Arc<dyn PhysicalExpr>| {
indices.extend(collect_columns(expr).iter().map(|column| column.index()));
};
if !keeps_equivalences(plan, &split)? {
for class in child_properties.eq_group().iter() {
class.iter().for_each(&mut add_columns);
}
}
if order_matters && !keeps_orderings(plan, &split)? {
for ordering in child_properties.oeq_class().iter() {
for sort_expr in ordering.iter() {
add_columns(&sort_expr.expr);
}
}
}
indices.sort_unstable();
indices.dedup();
Ok(indices)
}

/// Returns the lower part of a split, which outputs the `child` columns at
/// `passthrough_indices` and then `leaves`.
fn lower_projection(
child: &Arc<dyn ExecutionPlan>,
leaves: &[Arc<dyn PhysicalExpr>],
passthrough_indices: &[usize],
) -> Result<ProjectionExec> {
let child_schema = child.schema();
let passthrough_indices = collect_outer_columns(projection.expr(), &leaves)?;
let mut lower_exprs = passthrough_indices
.iter()
.map(|&idx| {
Expand All @@ -559,23 +658,28 @@ fn try_split_leaf_projection(
alias: leaf_column_name(index),
});
}
let lower_projection = ProjectionExec::try_new(lower_exprs, Arc::clone(child))?;

// Only commit the split if the child really absorbs the leaf projection.
// Otherwise this would just add a projection that helps nobody.
let Some(new_child) = child.try_swapping_with_projection(&lower_projection)? else {
return Ok(None);
};
ProjectionExec::try_new(lower_exprs, Arc::clone(child))
}

/// Returns `projection` over its repartition of `new_child`, which outputs what
/// [`lower_projection`] of `child` does.
fn rebuild_split(
projection: &ProjectionExec,
leaves: &[Arc<dyn PhysicalExpr>],
passthrough_indices: &[usize],
child: &Arc<dyn ExecutionPlan>,
new_child: Arc<dyn ExecutionPlan>,
) -> Result<Arc<dyn ExecutionPlan>> {
let child_schema = child.schema();
let new_exprs = projection
.expr()
.iter()
.map(|proj_expr| {
Ok(ProjectionExpr {
expr: rewrite_outer_expr(
Arc::clone(&proj_expr.expr),
&leaves,
&passthrough_indices,
leaves,
passthrough_indices,
child_schema.fields().len(),
)?,
alias: proj_expr.alias.clone(),
Expand All @@ -591,13 +695,62 @@ fn try_split_leaf_projection(
)?;
// `try_new` would derive the output schema from the expressions alone and
// drop the metadata the planner set, which `schema_check` then rejects.
Ok(Some(Arc::new(
ProjectionExec::try_new_with_schema_metadata(
new_exprs,
new_repartition,
projection.schema().as_ref(),
)?,
)))
Ok(Arc::new(ProjectionExec::try_new_with_schema_metadata(
new_exprs,
new_repartition,
projection.schema().as_ref(),
)?))
}

/// Returns true if every constant and every equality that `old_plan` knows about
/// its output also holds for `new_plan`.
///
/// Sorts and repartitions keep both, so an ancestor can rely on them even across
/// an operator that destroys the ordering. Expressions that hold a leaf are not
/// compared: `s['v'] + 1 AS v, s` equates `v` with `s['v'] + 1`, and no split that
/// extracts `s['v']` can keep that.
fn keeps_equivalences(
old_plan: &Arc<dyn ExecutionPlan>,
new_plan: &Arc<dyn ExecutionPlan>,
) -> Result<bool> {
let old_group = old_plan.equivalence_properties().eq_group();
let new_group = new_plan.equivalence_properties().eq_group();
for class in old_group.iter() {
let mut first = None;
for expr in class.iter() {
let holds_leaf = expr.exists(|node| {
Ok(node.placement() == ExpressionPlacement::MoveTowardsLeafNodes)
})?;
if holds_leaf {
continue;
}
let first = first.get_or_insert(expr);
let constant = old_group.is_expr_constant(expr);
if !new_group.exprs_equal(first, expr)
|| (constant.is_some() && new_group.is_expr_constant(expr) != constant)
{
return Ok(false);
}
}
}
Ok(true)
}

/// Returns true if `new_plan` satisfies every output ordering of `old_plan`.
///
/// `RepartitionExec::preserve_order` is not enough to decide this, because a
/// repartition of a single input partition keeps the order without it.
fn keeps_orderings(
old_plan: &Arc<dyn ExecutionPlan>,
new_plan: &Arc<dyn ExecutionPlan>,
) -> Result<bool> {
let new_properties = new_plan.equivalence_properties();
for ordering in old_plan.equivalence_properties().oeq_class().iter() {
if !new_properties.ordering_satisfy(ordering.iter().cloned())? {
return Ok(false);
}
}
Ok(true)
}

/// Collects the distinct outermost [`ExpressionPlacement::MoveTowardsLeafNodes`]
Expand Down Expand Up @@ -702,17 +855,87 @@ fn rewrite_outer_expr(
#[cfg(test)]
mod test {
use super::*;
use crate::output_requirements::OutputRequirementExec;
use arrow::datatypes::{DataType, Field, FieldRef, Schema};
use datafusion_expr_common::operator::Operator;
use datafusion_functions::core::get_field;
use datafusion_functions::math::random;
use datafusion_physical_expr::ScalarFunctionExpr;
use datafusion_physical_expr::expressions::{binary, lit};
use datafusion_physical_expr::{Distribution, ScalarFunctionExpr};
use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
use datafusion_physical_plan::displayable;
use datafusion_physical_plan::empty::EmptyExec;
use datafusion_physical_plan::filter::FilterExec;
use datafusion_physical_plan::sorts::partial_sort::PartialSortExec;
use datafusion_physical_plan::sorts::sort::SortExec;
use insta::assert_snapshot;
use std::sync::Arc;

/// `PartialSortExec` requires that its input is sorted by the common prefix.
#[test]
fn split_keeps_partial_sort_prefix() -> Result<()> {
let v = Field::new("v", DataType::Int32, false);
let schema = Arc::new(Schema::new(vec![
Field::new("c", DataType::Int32, false),
Field::new("a", DataType::Int32, false),
Field::new("b", DataType::Int32, false),
Field::new_struct("s", vec![v], false),
]));
let column = |name: &str, index| -> Arc<dyn PhysicalExpr> {
Arc::new(Column::new(name, index))
};
let sum = binary(column("a", 1), Operator::Plus, column("b", 2), &schema)?;
let predicate = binary(column("c", 0), Operator::Eq, Arc::clone(&sum), &schema)?;
let get_v = Arc::new(ScalarFunctionExpr::try_new(
get_field(),
vec![column("s", 3), lit("v")],
&schema,
Arc::new(ConfigOptions::default()),
)?);
let leaf = binary(get_v, Operator::Plus, lit(1), &schema)?;

let sort_c = [PhysicalSortExpr::new_default(column("c", 0))].into();
let plan = Arc::new(SortExec::new(sort_c, Arc::new(EmptyExec::new(schema))));
let plan = Arc::new(FilterExec::try_new(predicate, plan)?);
// Absorbs the lower part of the split. The rename keeps it from being removed.
let exprs = [("c", "c2"), ("a", "a"), ("b", "b"), ("s", "s")]
.into_iter()
.enumerate()
.map(|(index, (name, alias))| (column(name, index), alias.to_string()));
let plan = Arc::new(ProjectionExec::try_new(exprs, plan)?);
let partitioning = Partitioning::RoundRobinBatch(4);
let plan = Arc::new(RepartitionExec::try_new(plan, partitioning)?);
let exprs = [(sum, "k"), (column("a", 1), "a"), (leaf, "v")]
.map(|(expr, alias)| (expr, alias.to_string()));
let plan = Arc::new(ProjectionExec::try_new(exprs, plan)?);
let sort_k = [("k", 0), ("a", 1)]
.map(|(name, index)| PhysicalSortExpr::new_default(column(name, index)));
let plan =
PartialSortExec::new(sort_k.into(), plan, 1).with_preserve_partitioning(true);

// The query needs no ordering, so only the `PartialSortExec` can protect it.
let plan = OutputRequirementExec::new(
Arc::new(plan),
None,
Distribution::UnspecifiedDistribution,
None,
);
let plan = ProjectionPushdown::new()
.optimize(Arc::new(plan), &ConfigOptions::default())?;
assert_snapshot!(displayable(plan.as_ref()).indent(false), @r"
OutputRequirementExec: order_by=[], dist_by=Unspecified
PartialSortExec: expr=[k@0 ASC, a@1 ASC], common_prefix_length=[1]
ProjectionExec: expr=[a@1 + b@2 as k, a@1 as a, __datafusion_leaf_0@3 + 1 as v]
RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true
ProjectionExec: expr=[c@0 as c2, a@1 as a, b@2 as b, get_field(s@3, v) as __datafusion_leaf_0]
FilterExec: c@0 = a@1 + b@2
SortExec: expr=[c@0 ASC], preserve_partitioning=[false]
EmptyExec
");
Ok(())
}

#[tokio::test]
async fn no_computation_does_not_project() -> Result<()> {
let (left_schema, right_schema) = create_simple_schemas();
Expand Down
Loading