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
248 changes: 239 additions & 9 deletions datafusion/core/tests/physical_optimizer/projection_pushdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ use datafusion::datasource::source::DataSourceExec;
use datafusion::prelude::{ParquetReadOptions, SessionContext};
use datafusion_common::config::{ConfigOptions, CsvOptions};
use datafusion_common::metadata::FieldMetadata;
use datafusion_common::{JoinSide, JoinType, NullEquality, Result, ScalarValue};
use datafusion_common::{
JoinSide, JoinType, NullEquality, Result, ScalarValue, assert_batches_eq,
};
use datafusion_datasource::TableSchemaBuilder;
use datafusion_datasource::file_scan_config::FileScanConfigBuilder;
use datafusion_execution::object_store::ObjectStoreUrl;
Expand All @@ -35,6 +37,7 @@ use datafusion_physical_expr_common::sort_expr::{
use datafusion_physical_optimizer::PhysicalOptimizerRule;
use datafusion_physical_optimizer::output_requirements::OutputRequirementExec;
use datafusion_physical_optimizer::projection_pushdown::ProjectionPushdown;
use datafusion_physical_plan::buffer::BufferExec;
use datafusion_physical_plan::coalesce_partitions::CoalescePartitionsExec;
use datafusion_physical_plan::coop::CooperativeExec;
use datafusion_physical_plan::filter::{FilterExec, FilterExecBuilder};
Expand All @@ -43,15 +46,18 @@ use datafusion_physical_plan::joins::{
HashJoinExec, NestedLoopJoinExec, PartitionMode, SortMergeJoinExec,
StreamJoinPartitionMode, SymmetricHashJoinExec,
};
use datafusion_physical_plan::limit::GlobalLimitExec;
use datafusion_physical_plan::projection::{ProjectionExec, ProjectionExpr, update_expr};
use datafusion_physical_plan::repartition::RepartitionExec;
use datafusion_physical_plan::sorts::sort::SortExec;
use datafusion_physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec;
use datafusion_physical_plan::streaming::{PartitionStream, StreamingTableExec};
use datafusion_physical_plan::union::UnionExec;
use datafusion_physical_plan::{ExecutionPlan, displayable};
use datafusion_physical_plan::{ExecutionPlan, collect, displayable};

use insta::assert_snapshot;

use crate::physical_optimizer::test_utils::OptimizationTest;
use itertools::Itertools;

/// Mocked UDF
Expand Down Expand Up @@ -1973,16 +1979,10 @@ async fn split_declines_hash_repartition() -> Result<()> {
true,
),
]));
let config = FileScanConfigBuilder::new(
ObjectStoreUrl::parse("test:///").unwrap(),
Arc::new(ParquetSource::new(Arc::clone(&schema))),
)
.with_file(PartitionedFile::new("x".to_string(), 100))
.build();
// Parquet absorbs a leaf projection, so the split would commit here if the
// partitioning check did not stop it first.
let hash = Arc::new(RepartitionExec::try_new(
DataSourceExec::from_data_source(config),
parquet_scan(&schema),
Partitioning::Hash(vec![col("id", &schema)?], 4),
)?);

Expand Down Expand Up @@ -2035,3 +2035,233 @@ async fn split_declines_hash_repartition() -> Result<()> {
);
Ok(())
}

fn parquet_scan(schema: &SchemaRef) -> Arc<dyn ExecutionPlan> {
let config = FileScanConfigBuilder::new(
ObjectStoreUrl::parse("test:///").unwrap(),
Arc::new(ParquetSource::new(Arc::clone(schema))),
)
.with_file(PartitionedFile::new("x".to_string(), 100))
.build();
DataSourceExec::from_data_source(config)
}

fn limit_split_exprs(schema: &SchemaRef) -> Result<Vec<ProjectionExpr>> {

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.

do we really need 500 lines of rust test ? Why can't we cover all these cases with .slt tests (the end API that is important)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'll check if they can be removed, moved to slt or merged.

let leaf: Arc<dyn PhysicalExpr> = Arc::new(ScalarFunctionExpr::new(
"get_field",
datafusion_functions::core::get_field(),
vec![
col("s", schema)?,
Arc::new(Literal::new(ScalarValue::from("value"))),
],
Arc::new(Field::new("v", DataType::Int64, true)),
Arc::new(ConfigOptions::default()),
));
Ok(vec![
ProjectionExpr {
expr: leaf,
alias: "v".to_string(),
},
ProjectionExpr {
expr: binary(
col("id", schema)?,
Operator::Plus,
Arc::new(Literal::new(ScalarValue::Int64(Some(1)))),
schema,
)?,
alias: "w".to_string(),
},
])
}

/// A real five-row Parquet file and the scan the planner builds over it, so a
/// hand-built chain above it can be *run*, not only formatted.
async fn five_row_parquet(
dir: &tempfile::TempDir,
) -> Result<(SessionContext, Arc<dyn ExecutionPlan>)> {
let path = dir.path().join("leaf_split_rows.parquet");
let path = path.to_str().expect("temp path is not utf-8");
let ctx = SessionContext::new();
ctx.sql(&format!(
"COPY (SELECT column1 AS id, column2 AS s FROM VALUES \
(1, {{value: 100}}), (2, {{value: 200}}), (3, {{value: 150}}), \
(4, {{value: 300}}), (5, {{value: 250}})) \
TO '{path}' STORED AS PARQUET"
))
.await?
.collect()
.await?;
ctx.register_parquet("t", path, ParquetReadOptions::default())
.await?;
let scan = ctx.table("t").await?.create_physical_plan().await?;
Ok((ctx, scan))
}

/// The marker from #27494: `invoke_with_args` is an `exec_err!`, so it returns
/// rows only if the split put it inside the scan.
fn marker_exprs() -> Vec<ProjectionExpr> {
vec![ProjectionExpr {
expr: Arc::new(ScalarFunctionExpr::new(
"file_row_index",
datafusion_functions::core::file_row_index(),
vec![],
Arc::new(Field::new("r", DataType::Int64, true)),
Arc::new(ConfigOptions::default()),
)),
alias: "r".to_string(),
}]
}

/// Each node in the chain keeps its own `skip` and `fetch` across the rebuild.
/// A lost `skip` comes back as the wrong rows; a lost `fetch` on the
/// `CoalescePartitionsExec` only costs it an early stop, which no row can
/// show, so that one is read back off the rebuilt node instead.
///
/// Neither shape is reachable from SQL: an `OFFSET` with no `LIMIT` is absorbed
/// by the scan before any limit exists, and the fetch on a
/// `CoalescePartitionsExec` is put there by `LimitPushdown`, which runs after
/// this rule's first pass.
#[tokio::test]
async fn split_keeps_each_chain_node_fetch() -> Result<()> {
let dir = tempfile::tempdir()?;
let (ctx, scan) = five_row_parquet(&dir).await?;
let limit: Arc<dyn ExecutionPlan> =
Arc::new(GlobalLimitExec::new(Arc::clone(&scan), 2, None));
let projection: Arc<dyn ExecutionPlan> =
Arc::new(ProjectionExec::try_new(marker_exprs(), limit)?);
let optimized =
ProjectionPushdown::new().optimize(projection, &ConfigOptions::default())?;
assert_batches_eq!(
[
"+---+", "| r |", "+---+", "| 2 |", "| 3 |", "| 4 |", "+---+"
],
&collect(optimized, ctx.task_ctx()).await?
);

// The same leaf two nodes down, so one pass has to walk the whole chain.
let coalesce: Arc<dyn ExecutionPlan> =
Arc::new(CoalescePartitionsExec::new(scan).with_fetch(Some(4)));
let limit: Arc<dyn ExecutionPlan> =
Arc::new(GlobalLimitExec::new(coalesce, 1, Some(3)));
let projection: Arc<dyn ExecutionPlan> =
Arc::new(ProjectionExec::try_new(marker_exprs(), limit)?);
let optimized =
ProjectionPushdown::new().optimize(projection, &ConfigOptions::default())?;

assert_batches_eq!(
[
"+---+", "| r |", "+---+", "| 1 |", "| 2 |", "| 3 |", "+---+"
],
&collect(Arc::clone(&optimized), ctx.task_ctx()).await?
);

// Dropping the coalesce's own fetch costs it an early stop and nothing
// else, so no row above can show it: read it back off the rebuilt node.
let rebuilt_limit = Arc::clone(optimized.children()[0]);
let rebuilt_coalesce = Arc::clone(rebuilt_limit.children()[0]);
let rebuilt_limit = rebuilt_limit
.downcast_ref::<GlobalLimitExec>()
.expect("the rebuild keeps the node itself, not only its numbers");
assert_eq!((rebuilt_limit.skip(), rebuilt_limit.fetch()), (1, Some(3)));
assert_eq!(rebuilt_coalesce.fetch(), Some(4));
Ok(())
}

/// A `BufferExec` is not a chain node, but as the *bottom* of the chain it
/// delegates the swap to its own input, so the leaf still reaches the scan in
/// one pass. Both of its inserters run after this rule's first pass —
/// `HashJoinBuffering` before the second, `PushdownSort` after it — and no
/// query in the suite leaves a leaf above one.
#[tokio::test]
async fn leaf_reaches_the_scan_below_a_pass_through_node() -> Result<()> {
let dir = tempfile::tempdir()?;
let (ctx, scan) = five_row_parquet(&dir).await?;
let buffer: Arc<dyn ExecutionPlan> = Arc::new(BufferExec::new(scan, 4));
let limit: Arc<dyn ExecutionPlan> =
Arc::new(GlobalLimitExec::new(buffer, 1, Some(3)));
let projection: Arc<dyn ExecutionPlan> =
Arc::new(ProjectionExec::try_new(marker_exprs(), limit)?);
let optimized =
ProjectionPushdown::new().optimize(projection, &ConfigOptions::default())?;
assert_batches_eq!(
[
"+---+", "| r |", "+---+", "| 1 |", "| 2 |", "| 3 |", "+---+"
],
&collect(optimized, ctx.task_ctx()).await?
);
Ok(())
}

/// A `FilterExec` at the bottom of the chain takes the lower projection by
/// holding it over its own input, so the leaf reaches the scan only on this
/// rule's second run. Plain SQL does not reach this: the logical optimizer
/// extracts the leaf first, leaving none on the filter. The shape needs
/// `get_field`'s narrowing, and a `get_field` leaf returns the same rows either
/// way, so unlike the two tests above this one can only pin the plan.
#[tokio::test]
async fn leaf_reaches_the_scan_below_a_filter() -> Result<()> {
// Three columns so the lower projection narrows; with two it does not, and
// `FilterExec` declines before reaching the branch this test is about.
let schema: SchemaRef = Arc::new(Schema::new(vec![
Field::new("id", DataType::Int64, true),
Field::new(
"s",
DataType::Struct(vec![Field::new("value", DataType::Int64, true)].into()),
true,
),
Field::new("k", DataType::Int64, true),
]));
let predicate = binary(
col("id", &schema)?,
Operator::Gt,
Arc::new(Literal::new(ScalarValue::Int64(Some(0)))),
&schema,
)?;
let filter: Arc<dyn ExecutionPlan> =
Arc::new(FilterExec::try_new(predicate, parquet_scan(&schema))?);
let limit: Arc<dyn ExecutionPlan> =
Arc::new(GlobalLimitExec::new(filter, 1, Some(3)));
let projection: Arc<dyn ExecutionPlan> =
Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?);

let first = ProjectionPushdown::new()
.optimize(Arc::clone(&projection), &ConfigOptions::default())?;
assert_snapshot!(
OptimizationTest::new(projection, ProjectionPushdown::new(), false),
@r"
OptimizationTest:
input:
- ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w]
- GlobalLimitExec: skip=1, fetch=3
- FilterExec: id@0 > 0
- DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s, k], file_type=parquet
output:
Ok:
- ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w]
- GlobalLimitExec: skip=1, fetch=3
- FilterExec: id@0 > 0
- ProjectionExec: expr=[id@0 as id, get_field(s@1, value) as __datafusion_leaf_0]
- DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s, k], file_type=parquet
"
);

assert_snapshot!(
OptimizationTest::new(first, ProjectionPushdown::new(), false),
@r"
OptimizationTest:
input:
- ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w]
- GlobalLimitExec: skip=1, fetch=3
- FilterExec: id@0 > 0
- ProjectionExec: expr=[id@0 as id, get_field(s@1, value) as __datafusion_leaf_0]
- DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s, k], file_type=parquet
output:
Ok:
- ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w]
- GlobalLimitExec: skip=1, fetch=3
- FilterExec: id@0 > 0
- DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet
"
);
Ok(())
}
Loading