From 58e3c1a301f53a832a05a4226828ee8d8173e61b Mon Sep 17 00:00:00 2001 From: Qi Zhu Date: Tue, 1 Dec 2026 15:12:16 +0800 Subject: [PATCH] fix: don't drop a limit above a leaf in LimitPushdown --- .../physical_optimizer/limit_pushdown.rs | 147 ++++++++++++++++++ .../physical-optimizer/src/limit_pushdown.rs | 8 + 2 files changed, 155 insertions(+) diff --git a/datafusion/core/tests/physical_optimizer/limit_pushdown.rs b/datafusion/core/tests/physical_optimizer/limit_pushdown.rs index 1d05d326e03ae..00e094df49855 100644 --- a/datafusion/core/tests/physical_optimizer/limit_pushdown.rs +++ b/datafusion/core/tests/physical_optimizer/limit_pushdown.rs @@ -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::{ @@ -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, + properties: Arc, +} + +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 { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + vec![] + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + _children: Vec>, + ) -> Result> { + Ok(self) + } + + fn limit_behavior(&self) -> LimitBehavior { + self.behavior + } + + fn with_fetch(&self, fetch: Option) -> Option> { + self.takes_fetch.then(|| { + Arc::new(Self { + fetch, + ..self.clone() + }) as _ + }) + } + + fn fetch(&self) -> Option { + self.fetch + } + + fn execute( + &self, + _partition: usize, + _context: Arc, + ) -> Result { + 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 = 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 = + 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 = + 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(); diff --git a/datafusion/physical-optimizer/src/limit_pushdown.rs b/datafusion/physical-optimizer/src/limit_pushdown.rs index 740553280d72c..a0c83a030156c 100644 --- a/datafusion/physical-optimizer/src/limit_pushdown.rs +++ b/datafusion/physical-optimizer/src/limit_pushdown.rs @@ -169,6 +169,14 @@ enum Step { fn step(plan: &Arc) -> 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