Skip to content
Merged
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
147 changes: 147 additions & 0 deletions datafusion/core/tests/physical_optimizer/limit_pushdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ use datafusion_physical_optimizer::PhysicalOptimizerRule;
use datafusion_physical_optimizer::limit_pushdown::LimitPushdown;
use datafusion_physical_plan::aggregates::AggregateExec;
use datafusion_physical_plan::empty::EmptyExec;
use datafusion_physical_plan::execution_plan::{Boundedness, EmissionType};
use datafusion_physical_plan::filter::FilterExec;
use datafusion_physical_plan::joins::NestedLoopJoinExec;
use datafusion_physical_plan::operator_statistics::{
Expand Down Expand Up @@ -516,6 +517,152 @@ impl ExecutionPlan for CombineExec {
}
}

/// A leaf that declares `behavior` as its `limit_behavior`, like a custom scan
/// that returns `true` from the deprecated `supports_limit_pushdown`. It takes
/// a fetch only if `takes_fetch` is set.
#[derive(Debug, Clone)]
struct LeafExec {
behavior: LimitBehavior,
takes_fetch: bool,
fetch: Option<usize>,
properties: Arc<PlanProperties>,
}

impl LeafExec {
fn new(behavior: LimitBehavior, takes_fetch: bool) -> Self {
let properties = Arc::new(PlanProperties::new(
EquivalenceProperties::new(create_schema()),
Partitioning::UnknownPartitioning(1),
EmissionType::Incremental,
Boundedness::Bounded,
));
Self {
behavior,
takes_fetch,
fetch: None,
properties,
}
}
}

impl DisplayAs for LeafExec {
fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "LeafExec: {:?}", self.behavior)?;
if let Some(fetch) = self.fetch {
write!(f, ", fetch={fetch}")?;
}
Ok(())
}
}

impl ExecutionPlan for LeafExec {
fn name(&self) -> &str {
"LeafExec"
}

fn properties(&self) -> &Arc<PlanProperties> {
&self.properties
}

fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![]
}

fn apply_expressions(
&self,
_f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
Ok(TreeNodeRecursion::Continue)
}

fn with_new_children(
self: Arc<Self>,
_children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
Ok(self)
}

fn limit_behavior(&self) -> LimitBehavior {
self.behavior
}

fn with_fetch(&self, fetch: Option<usize>) -> Option<Arc<dyn ExecutionPlan>> {
self.takes_fetch.then(|| {
Arc::new(Self {
fetch,
..self.clone()
}) as _
})
}

fn fetch(&self) -> Option<usize> {
self.fetch
}

fn execute(
&self,
_partition: usize,
_context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
unimplemented!("only planned in these tests")
}
}

#[test]
fn leaf_that_passes_limits_takes_the_limit_as_its_fetch() -> Result<()> {
for behavior in [LimitBehavior::MoveToInput, LimitBehavior::CopyToChildren] {
let leaf: Arc<dyn ExecutionPlan> = Arc::new(LeafExec::new(behavior, true));
let global_limit = global_limit_exec(leaf, 0, Some(5));

let after_optimize =
LimitPushdown::new().optimize(global_limit, &ConfigOptions::new())?;

// A leaf has no input to pass the limit to.
assert_eq!(
format_plan(&after_optimize),
format!("LeafExec: {behavior:?}, fetch=5")
);
}
Ok(())
}

#[test]
fn leaf_that_passes_limits_keeps_offset_above() -> Result<()> {
let leaf: Arc<dyn ExecutionPlan> =
Arc::new(LeafExec::new(LimitBehavior::MoveToInput, true));
let global_limit = global_limit_exec(leaf, 2, Some(3));

let after_optimize =
LimitPushdown::new().optimize(global_limit, &ConfigOptions::new())?;

let optimized = format_plan(&after_optimize);
insta::assert_snapshot!(optimized, @r"
GlobalLimitExec: skip=2, fetch=3
LeafExec: MoveToInput, fetch=5
");
Ok(())
}

#[test]
fn limit_stays_above_leaf_that_passes_limits_but_takes_no_fetch() -> Result<()> {
let leaf: Arc<dyn ExecutionPlan> =
Arc::new(LeafExec::new(LimitBehavior::MoveToInput, false));
let global_limit = global_limit_exec(leaf, 0, Some(5));

let after_optimize =
LimitPushdown::new().optimize(global_limit, &ConfigOptions::new())?;

let optimized = format_plan(&after_optimize);
insta::assert_snapshot!(
optimized,
@r"
GlobalLimitExec: skip=0, fetch=5
LeafExec: MoveToInput
"
);
Ok(())
}

#[test]
fn merge_without_fetch_gets_offset_rows_below() -> Result<()> {
let schema = create_schema();
Expand Down
8 changes: 8 additions & 0 deletions datafusion/physical-optimizer/src/limit_pushdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,14 @@ enum Step {
fn step(plan: &Arc<dyn ExecutionPlan>) -> Step {
match plan.limit_behavior() {
LimitBehavior::Limit { skip, fetch } => Step::Limit(RowBound { skip, fetch }),
// A leaf has no input to pass the bound to, e.g. a custom scan that
// reports the deprecated `supports_limit_pushdown`. Passing it would
// drop the limit.
LimitBehavior::CopyToChildren | LimitBehavior::MoveToInput
if plan.children().is_empty() =>
{
Step::Stop
}
// Below a node whose children have more partitions than it outputs,
// the bound would apply to each of them and keep too many rows. The
// node takes the bound like a merge: it stays above, and each child
Expand Down