From f9266b99641da89e6fdbd3036bfbc11377541814 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:56:07 -0600 Subject: [PATCH 1/4] fix: return the TableScan skip from LogicalPlan::skip https://github.com/apache/datafusion/pull/25404 added `TableScan::skip`, but `LogicalPlan::skip()` still returns `None` for a `TableScan`. The guard in `PushDownFilter` uses `LogicalPlan::skip()`, so it does not see the skip, and a filter above a scan with only a skip moves into the scan. Inside the scan the filter runs before the skip, so the scan keeps different rows. `LogicalPlan::skip()` now returns the scan skip. A zero skip returns `None`, the same as for `Limit`. Co-Authored-By: Claude Opus 5.5 --- datafusion/expr/src/logical_plan/plan.rs | 28 +++++++++++++++++--- datafusion/optimizer/src/push_down_filter.rs | 21 +++++++++++++++ 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs index d2467e2346c44..ea175038e5b05 100644 --- a/datafusion/expr/src/logical_plan/plan.rs +++ b/datafusion/expr/src/logical_plan/plan.rs @@ -1702,8 +1702,9 @@ impl LogicalPlan { /// Returns the skip (offset) of this plan node, if it has one. /// - /// Only [`LogicalPlan::Limit`] carries a skip value; all other variants - /// return `Ok(None)`. Returns `Ok(None)` for a zero skip. + /// [`LogicalPlan::Limit`] and [`LogicalPlan::TableScan`] may carry a skip + /// value. All other variants return `Ok(None)`. Returns `Ok(None)` for a + /// zero skip. pub fn skip(&self) -> Result> { match self { LogicalPlan::Limit(limit) => match limit.get_skip_type()? { @@ -1712,7 +1713,7 @@ impl LogicalPlan { SkipType::UnsupportedExpr => Ok(None), }, LogicalPlan::Sort(_) => Ok(None), - LogicalPlan::TableScan(_) => Ok(None), + LogicalPlan::TableScan(TableScan { skip, .. }) => Ok(skip.filter(|&n| n > 0)), LogicalPlan::Projection(_) => Ok(None), LogicalPlan::Filter(_) => Ok(None), LogicalPlan::Window(_) => Ok(None), @@ -7803,4 +7804,25 @@ mod tests { } Ok(()) } + + fn employee_scan() -> Result { + let LogicalPlan::TableScan(scan) = + table_scan(Some("employee_csv"), &employee_schema(), None)?.build()? + else { + unreachable!() + }; + Ok(scan) + } + + #[test] + fn table_scan_skip() -> Result<()> { + for (skip, expected) in [(None, None), (Some(0), None), (Some(3), Some(3))] { + let scan = TableScan { + skip, + ..employee_scan()? + }; + assert_eq!(LogicalPlan::TableScan(scan).skip()?, expected); + } + Ok(()) + } } diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs index efaea281a14e2..b6c6b4daee1e1 100644 --- a/datafusion/optimizer/src/push_down_filter.rs +++ b/datafusion/optimizer/src/push_down_filter.rs @@ -4985,6 +4985,27 @@ mod tests { ) } + #[test] + fn filter_not_pushed_down_through_table_scan_with_skip() -> Result<()> { + let LogicalPlan::TableScan(scan) = test_table_scan()? else { + unreachable!() + }; + let scan_with_skip = LogicalPlan::TableScan(TableScan { + skip: Some(3), + ..scan + }); + let plan = LogicalPlanBuilder::from(scan_with_skip) + .filter(col("a").gt(lit(10i64)))? + .build()?; + assert_optimized_plan_equal!( + plan, + @r" + Filter: test.a > Int64(10) + TableScan: test, skip=3 + " + ) + } + #[test] fn filter_push_down_through_sort_without_fetch() -> Result<()> { let table_scan = test_table_scan()?; From 58b54040829414a9c84b4be8346ae4a876865351 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:57:06 -0600 Subject: [PATCH 2/4] feat: document the TableScan row order and add TableScan::try_with_filters A `TableScan` applies its filters, then its skip, then its fetch. The code does not state this order, so each rule that adds filters to a scan must know it. A filter above a scan with a skip or a fetch cannot move into the scan. The `TableScan` docs now state the row order and its one-way consequence. `TableScan::try_with_filters` is the one method that adds filters safely. It returns the scan unchanged in `Err` when the scan has a nonzero skip or any fetch, so the caller can keep the scan. Co-Authored-By: Claude Opus 5.5 --- datafusion/expr/src/logical_plan/plan.rs | 76 +++++++++++++++++++++++- 1 file changed, 74 insertions(+), 2 deletions(-) diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs index ea175038e5b05..20b57573952c6 100644 --- a/datafusion/expr/src/logical_plan/plan.rs +++ b/datafusion/expr/src/logical_plan/plan.rs @@ -3265,6 +3265,31 @@ impl PartialOrd for Window { } /// Produces rows from a table provider by reference or from the context +/// +/// # Row order +/// +/// A `TableScan` combines several operators in one node. It produces rows in +/// this order: +/// +/// ```text +/// source rows -> filters -> skip -> fetch -> projection +/// ``` +/// +/// The filters step means the filters that the source applies exactly (see +/// [`TableProviderFilterPushDown::Exact`]). The skip and the fetch apply to +/// the rows that pass these filters. +/// +/// This order goes in one direction only: +/// +/// * `Limit(Filter(scan))` can fold into one scan with filters and a fetch. +/// * `Filter(scan)` cannot move into the scan when the scan has a skip or a +/// fetch. Inside the scan, the filter runs before the skip and the fetch, +/// so the scan keeps different rows. +/// +/// Use [`TableScan::try_with_filters`] to add filters to a scan. It refuses +/// a scan with a skip or a fetch. +/// +/// [`TableProviderFilterPushDown::Exact`]: crate::TableProviderFilterPushDown::Exact #[derive(Clone)] pub struct TableScan { /// The name of the table @@ -3277,9 +3302,11 @@ pub struct TableScan { pub projected_schema: DFSchemaRef, /// Optional expressions to be used as filters by the table provider pub filters: Vec, - /// Optional number of rows to read + /// Optional number of rows to read. The fetch applies after the filters + /// and the skip. See [Row order](TableScan#row-order). pub fetch: Option, - /// Optional number of rows to skip + /// Optional number of rows to skip. The skip applies after the filters + /// and before the fetch. See [Row order](TableScan#row-order). pub skip: Option, /// Statistics the planner would like the provider to answer for this /// scan, typically attached by a custom optimizer rule from the @@ -3380,6 +3407,23 @@ impl TableScan { .with_fetch(fetch) .build() } + + /// Returns this scan with its filters replaced by `filters`. + /// + /// Returns `Err(self)` unchanged when the scan has a nonzero skip or any + /// fetch, because the filters apply before both. See + /// [Row order](TableScan#row-order). + #[expect(clippy::result_large_err)] + pub fn try_with_filters( + mut self, + filters: Vec, + ) -> std::result::Result { + if self.fetch.is_some() || self.skip.is_some_and(|n| n > 0) { + return Err(self); + } + self.filters = filters; + Ok(self) + } } /// Builder for [`TableScan`]. @@ -7825,4 +7869,32 @@ mod tests { } Ok(()) } + + #[test] + fn table_scan_try_with_filters() -> Result<()> { + let filters = vec![col("id").gt(lit(1))]; + + let scan = employee_scan()?.try_with_filters(filters.clone()).unwrap(); + assert_eq!(scan.filters, filters); + + // A zero skip removes no rows, so the filters can move in. + let scan = TableScan { + skip: Some(0), + ..employee_scan()? + }; + let scan = scan.try_with_filters(filters.clone()).unwrap(); + assert_eq!(scan.filters, filters); + + for (skip, fetch) in [(Some(3), None), (None, Some(5)), (None, Some(0))] { + let scan = TableScan { + fetch, + skip, + ..employee_scan()? + }; + let scan = scan.try_with_filters(filters.clone()).unwrap_err(); + assert!(scan.filters.is_empty()); + assert_eq!((scan.skip, scan.fetch), (skip, fetch)); + } + Ok(()) + } } From 3ce849de2ff123b6bc44ce6214b35b51851de469 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:59:26 -0600 Subject: [PATCH 3/4] refactor: use TableScan::try_with_filters in PushDownFilter The `TableScan` arm of `PushDownFilter::rewrite` assigns `scan.filters` directly. It is correct only because a general fetch and skip guard runs earlier. Using `TableScan::try_with_filters` puts the row order check next to the write. The general guard stays, because `Sort` and `Limit` also need it. Behavior does not change. Co-Authored-By: Claude Opus 5.5 --- datafusion/optimizer/src/push_down_filter.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs index b6c6b4daee1e1..892941d66d6b8 100644 --- a/datafusion/optimizer/src/push_down_filter.rs +++ b/datafusion/optimizer/src/push_down_filter.rs @@ -1313,7 +1313,7 @@ impl OptimizerRule for PushDownFilter { result.map_data(|plan| Ok(with_filters(keep_predicates, plan))) } - LogicalPlan::TableScan(mut scan) => { + LogicalPlan::TableScan(scan) => { let filter_predicates = split_conjunction(&filter.predicate); // Filters containing scalar subqueries cannot be pushed to // providers because the subquery result is not available @@ -1380,9 +1380,20 @@ impl OptimizerRule for PushDownFilter { predicates_changed || reorder_changed, TreeNodeRecursion::Continue, )); - } else { - scan.filters = new_scan_filters; } + let scan = match scan.try_with_filters(new_scan_filters) { + Ok(scan) => scan, + // The fetch and skip guard above returns before this point + // today. This arm keeps the plan correct if that guard moves. + Err(scan) => { + filter.input = Arc::new(LogicalPlan::TableScan(scan)); + return Ok(Transformed::new( + LogicalPlan::Filter(filter), + predicates_changed || reorder_changed, + TreeNodeRecursion::Continue, + )); + } + }; // Compose predicates to be of `Unsupported` or `Inexact` pushdown type, // and also include volatile and subquery-containing filters From 83775a45e2bd14fb0c6473397d59edc6d8188bc3 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:35:24 -0600 Subject: [PATCH 4/4] fix: include skip in TableScan equality, ordering and hash PartialEq, PartialOrd and Hash for TableScan ignore skip, because https://github.com/apache/datafusion/pull/25404 added the field without them. Two scans that differ only in skip compare equal and hash the same, so code that compares or deduplicates plans can treat them as the same scan. Co-Authored-By: Claude Opus 5.5 --- datafusion/expr/src/logical_plan/plan.rs | 27 ++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs index 20b57573952c6..8bc9be1227b49 100644 --- a/datafusion/expr/src/logical_plan/plan.rs +++ b/datafusion/expr/src/logical_plan/plan.rs @@ -3341,6 +3341,7 @@ impl PartialEq for TableScan { && self.projected_schema == other.projected_schema && self.filters == other.filters && self.fetch == other.fetch + && self.skip == other.skip } } @@ -3360,18 +3361,22 @@ impl PartialOrd for TableScan { pub filters: &'a Vec, /// Optional number of rows to read pub fetch: &'a Option, + /// Optional number of rows to skip + pub skip: &'a Option, } let comparable_self = ComparableTableScan { table_name: &self.table_name, projection: &self.projection, filters: &self.filters, fetch: &self.fetch, + skip: &self.skip, }; let comparable_other = ComparableTableScan { table_name: &other.table_name, projection: &other.projection, filters: &other.filters, fetch: &other.fetch, + skip: &other.skip, }; comparable_self .partial_cmp(&comparable_other) @@ -3387,6 +3392,7 @@ impl Hash for TableScan { self.projected_schema.hash(state); self.filters.hash(state); self.fetch.hash(state); + self.skip.hash(state); } } @@ -7870,6 +7876,27 @@ mod tests { Ok(()) } + #[test] + fn table_scan_skip_in_eq_ord_and_hash() -> Result<()> { + fn hash_of(scan: &TableScan) -> u64 { + let mut hasher = DefaultHasher::new(); + scan.hash(&mut hasher); + hasher.finish() + } + let no_skip = employee_scan()?; + let skip = TableScan { + skip: Some(3), + ..employee_scan()? + }; + + assert_ne!(no_skip, skip); + assert_eq!(no_skip.partial_cmp(&skip), Some(Ordering::Less)); + assert_ne!(hash_of(&no_skip), hash_of(&skip)); + assert_eq!(skip, skip.clone()); + assert_eq!(hash_of(&skip), hash_of(&skip.clone())); + Ok(()) + } + #[test] fn table_scan_try_with_filters() -> Result<()> { let filters = vec![col("id").gt(lit(1))];