Skip to content
Closed
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
52 changes: 52 additions & 0 deletions datafusion/core/tests/fuzz_cases/leaf_pushdown_fuzz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ use arrow::datatypes::{DataType, Field, Fields, Int32Type, Schema};
use arrow::util::pretty::pretty_format_batches;
use datafusion::prelude::{ParquetReadOptions, SessionConfig, SessionContext};
use datafusion_common::Result;
use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
use datafusion_datasource::source::DataSourceExec;
use datafusion_physical_plan::displayable;
use parquet::arrow::ArrowWriter;
use rand::rngs::SmallRng;
use rand::{Rng, SeedableRng};
Expand Down Expand Up @@ -786,6 +789,55 @@ async fn leaf_pushdown_parquet_fuzz() {
.await;
}

#[tokio::test]
async fn leaf_pushdown_prunes_filter_only_columns() -> Result<()> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we please also add a non fuzz test for this? Specifically can we add a SLT test that shows the explain plan that changes with / without this change?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@alamb done! 🙇

let dir = TempDir::new()?;
let reference = memory_ctx(false);
for seed in seed()..seed() + env_usize("LEAF_PUSHDOWN_FUZZ_CASES", 64) as u64 {
let mut rng = SmallRng::seed_from_u64(seed);
let mut cfg = config(true, true).with_batch_size(1);
cfg.options_mut().execution.target_partitions = rng.random_range(2..=4);
let ctx = SessionContext::new_with_config(cfg);
let path = dir.path().join(format!("{seed}.parquet"));
write_parquet(&path, &table_batch(0));
ctx.register_parquet("t1", path.to_str().unwrap(), ParquetReadOptions::default())
.await?;

let left = pick(&mut rng, &["b", "s['a']", "t['x']"]);
let right = pick(&mut rng, &["b", "s['a']", "t['x']"]);
let op = pick(&mut rng, &["+", "-", "*"]);
let threshold = rng.random_range(-4..=1);
let sql = format!(
"SELECT {left} {op} {right} AS result, CAST({right} AS BIGINT) AS other \
FROM t1 WHERE a > {threshold} AND lower(s['b']) <> 'never'"
);
let plan = ctx.sql(&sql).await?.create_physical_plan().await?;
let text = displayable(plan.as_ref()).indent(true).to_string();
assert!(
text.contains("RoundRobinBatch"),
"seed {seed}: {sql}\n{text}"
);
let mut scans = 0;
plan.apply(|node| {
if node.downcast_ref::<DataSourceExec>().is_some() {
scans += 1;
assert!(
node.schema().field_with_name("a").is_err(),
"seed {seed}: filter-only column remains: {sql}\n{text}"
);
}
Ok(TreeNodeRecursion::Continue)
})?;
assert_eq!(scans, 1, "seed {seed}: {sql}\n{text}");
assert_eq!(
normalize(&collect(&reference, &sql).await?),
normalize(&collect(&ctx, &sql).await?),
"seed {seed}: {sql}\n{text}"
);
}
Ok(())
}

#[rstest]
#[case::p0(0)]
#[case::p1(1)]
Expand Down
2 changes: 1 addition & 1 deletion datafusion/physical-expr/src/expressions/column.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ impl PhysicalExpr for Column {

/// Evaluate the expression
fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
self.bounds_check(batch.schema().as_ref())?;
self.bounds_check(batch.schema_ref())?;
Ok(ColumnarValue::Array(Arc::clone(batch.column(self.index))))
}

Expand Down
47 changes: 41 additions & 6 deletions datafusion/physical-expr/src/projection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ use datafusion_physical_expr_common::metrics::ExecutionPlanMetricsSet;
use datafusion_physical_expr_common::metrics::ExpressionEvaluatorMetrics;
use datafusion_physical_expr_common::physical_expr::fmt_sql;
use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays_with_metrics;
use indexmap::IndexMap;
use itertools::Itertools;

Expand Down Expand Up @@ -1107,6 +1106,26 @@ pub struct Projector {
}

impl Projector {
/// Replace expressions after a rewrite that preserves output field names,
/// types, nullability, and metadata. Expression metrics are reset.
///
/// # Public Only for Internal Use:
///
/// This is not a public API and is for internal use only; see [API policy] for details.
///
/// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis
#[doc(hidden)]
pub fn with_new_projection_preserving_schema(
&self,
projection: ProjectionExprs,
) -> Self {
Self {
projection,
output_schema: Arc::clone(&self.output_schema),
expression_metrics: None,
}
}

/// Construct the projector with metrics. After execution, related metrics will
/// be tracked inside `ExecutionPlanMetricsSet`
///
Expand All @@ -1133,11 +1152,27 @@ impl Projector {
/// or if the output schema of the resulting record batch does not match
/// the pre-computed output schema of the projector.
pub fn project_batch(&self, batch: &RecordBatch) -> Result<RecordBatch> {
let arrays = evaluate_expressions_to_arrays_with_metrics(
self.projection.exprs.iter().map(|p| &p.expr),
batch,
self.expression_metrics.as_ref(),
)?;
let arrays = self
.projection
.exprs
.iter()
.enumerate()
.map(|(position, projection)| {
let _timer = self
.expression_metrics
.as_ref()
.and_then(|metrics| metrics.scoped_timer(position));
if let Some(column) = projection.expr.downcast_ref::<Column>()
&& let Some(array) = batch.columns().get(column.index())
{
return Ok(Arc::clone(array));
}
projection
.expr
.evaluate(batch)?
.into_array_of_size(batch.num_rows())
})
.collect::<Result<Vec<_>>>()?;

if arrays.is_empty() {
let options =
Expand Down
28 changes: 28 additions & 0 deletions datafusion/physical-plan/src/projection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,34 @@ impl ProjectionExec {
Self::try_from_projector(projector, input, overrides_metadata)
}

pub(crate) fn with_pruned_input(
&self,
exprs: Vec<ProjectionExpr>,
input: Arc<dyn ExecutionPlan>,
) -> Result<Self> {
// Input pruning must preserve output values, metadata, ordering, and partitioning.
let projector = self
.projector
.with_new_projection_preserving_schema(ProjectionExprs::new(exprs));
debug_assert_eq!(
projector.output_schema(),
projector
.projection()
.make_projector_with_schema_metadata(
&input.schema(),
self.schema().as_ref()
)?
.output_schema()
);
Ok(Self {
projector,
input,
metrics: ExecutionPlanMetricsSet::new(),
cache: Arc::clone(&self.cache),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The rewrite can remove an ordering that an ancestor needs. The query then fails to plan.

SET datafusion.execution.target_partitions = 4;
SET datafusion.execution.parquet.pushdown_filters = true;
COPY (SELECT value * 2 AS c, value AS a, value AS b FROM range(0, 1000) ORDER BY c)
  TO 'ordered.parquet' STORED AS PARQUET;
CREATE EXTERNAL TABLE ordered STORED AS PARQUET LOCATION 'ordered.parquet' WITH ORDER (c ASC);

SELECT a + b AS k FROM ordered WHERE c = a + b ORDER BY k LIMIT 2;
Result
main 0, 2
this PR SanityCheckPlan: order and distribution requirements stopped holding after physical optimizer rule 'ProjectionPushdown'

The file is sorted by c, and the predicate makes c equal to a + b. The plan therefore does not sort k. No expression reads c, so the rewrite prunes it, and the input can no longer show that k is sorted.

The projection keeps its cached properties here, so the rewrite does not see the loss. A possible fix is to recompute the properties and to compare the output orderings before and after the rewrite. If an ordering is lost, the rewrite can keep the columns that the input is sorted by.

Could you add this query as an SLT case?

overrides_metadata: self.overrides_metadata,
})
}

fn try_from_projector(
projector: Projector,
input: Arc<dyn ExecutionPlan>,
Expand Down
36 changes: 35 additions & 1 deletion datafusion/physical-plan/src/repartition/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ use crate::coalesce::LimitedBatchCoalescer;
use crate::execution_plan::{CardinalityEffect, EvaluationType, SchedulingType};
use crate::hash_utils::create_hashes;
use crate::metrics::{BaselineMetrics, SpillMetrics};
use crate::projection::{ProjectionExec, all_columns, make_with_child, update_expr};
use crate::projection::{
ProjectionExec, ProjectionExpr, ProjectionExprs, all_columns, make_with_child,
update_expr,
};
use crate::sorts::streaming_merge::StreamingMergeBuilder;
use crate::spill::spill_manager::SpillManager;
use crate::spill::spill_pool::{self, SpillPoolSink, SpillPoolWriter};
Expand Down Expand Up @@ -1951,6 +1954,37 @@ impl ExecutionPlan for RepartitionExec {
&self,
projection: &ProjectionExec,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
if !all_columns(projection.expr())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The inserted ProjectionExec can move get_field below the round robin, where it runs on one partition.

SET datafusion.execution.target_partitions = 4;
CREATE TABLE t AS
  SELECT value AS c, named_struct('v', value, 'w', 1) AS s FROM range(0, 50000);

EXPLAIN FORMAT INDENT
SELECT s['v'] + 1 AS v, rn FROM (SELECT s, row_number() OVER (ORDER BY c) AS rn FROM t);

The window column is shortened to rn:

-ProjectionExec: expr=[get_field(s@1, v) + 1 as v, rn@2 as rn]
+ProjectionExec: expr=[__datafusion_leaf_0@1 + 1 as v, rn@0 as rn]
   RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
-    BoundedWindowAggExec
+    ProjectionExec: expr=[rn@2 as rn, get_field(s@1, v) as __datafusion_leaf_0]
+      BoundedWindowAggExec

I think that the leaf split from #27152 sees the inserted projection as an operator that absorbs the leaf. I did not measure the cost, and it is probably small for get_field. A possible fix is to not let a leaf split merge into this projection.

&& matches!(self.partitioning(), Partitioning::RoundRobinBatch(_))
{
let indices = projection.projection_expr().column_indices();
if indices.len() >= self.input().schema().fields().len() {
return Ok(None);
}

// Keep computations above repartitioning so they retain its parallelism.
let columns = ProjectionExprs::from_indices(&indices, &self.input().schema());
let mut exprs = Vec::with_capacity(projection.expr().len());
for expr in projection.expr() {
let Some(rewritten) = update_expr(&expr.expr, columns.as_ref(), false)?
else {
return Ok(None);
};
exprs.push(ProjectionExpr::new(rewritten, expr.alias.clone()));
}
let input = Arc::new(ProjectionExec::try_new(
columns.iter().cloned(),
Arc::clone(self.input()),
)?);
let repartition = Arc::new(self.clone()).replace_children(
vec![input],
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
)?;
return Ok(Some(Arc::new(
projection.with_pruned_input(exprs, repartition)?,
)));
}

// If the projection does not narrow the schema, we should not try to push it down.
if projection.expr().len() >= projection.input().schema().fields().len() {
return Ok(None);
Expand Down
22 changes: 22 additions & 0 deletions datafusion/sqllogictest/test_files/projection_pushdown.slt
Original file line number Diff line number Diff line change
Expand Up @@ -2864,6 +2864,28 @@ physical_plan
statement ok
DROP TABLE leaf_split_mem;

# https://github.com/apache/datafusion/issues/27776
# The predicate still reads id, but the scan must not output it through repartition.
query TT
EXPLAIN SELECT s['value'] + 1 AS v FROM leaf_split WHERE id > 2;
----
logical_plan
01)Projection: __datafusion_extracted_1 + Int64(1) AS v
02)--Filter: leaf_split.id > Int64(2)
03)----Projection: get_field(leaf_split.s, Utf8("value")) AS __datafusion_extracted_1, leaf_split.id
04)------TableScan: leaf_split projection=[id, s], partial_filters=[leaf_split.id > Int64(2)]
physical_plan
01)ProjectionExec: expr=[__datafusion_extracted_1@0 + 1 as v]
02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_split.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1], file_type=parquet, predicate=id@0 > 2, pruning_predicate=id_null_count@1 != row_count@2 AND id_max@0 > 2, required_guarantees=[]

query I rowsort
SELECT s['value'] + 1 AS v FROM leaf_split WHERE id > 2;
----
151
251
301

statement ok
SET datafusion.execution.batch_size = 8192;

Expand Down