adriangb commented on code in PR #27816:
URL: https://github.com/apache/datafusion/pull/27816#discussion_r4750281332


##########
datafusion/sqllogictest/test_files/sort_pushdown.slt:
##########
@@ -198,9 +198,73 @@ physical_plan
 06)----------LocalLimitExec: fetch=3
 07)------------ExactSortSource
 
+# The custom source keeps a ProjectionExec above it. After the sort is removed,
+# its limit must pass the projection: into the source as a fetch when the
+# source takes one, or as a LocalLimitExec right above it otherwise.
+query TT
+EXPLAIN SELECT group_id, value + 1 AS v
+FROM exact_sort_fetch_source
+ORDER BY group_id, value
+LIMIT 3;
+----
+physical_plan
+01)ProjectionExec: expr=[group_id@0 as group_id, v@1 as v]
+02)--SortPreservingMergeExec: [group_id@0 ASC NULLS LAST, value@2 ASC NULLS 
LAST], fetch=3
+03)----BufferExec: capacity=1073741824
+04)------ProjectionExec: expr=[group_id@0 as group_id, CAST(value@1 AS Int64) 
+ 1 as v, value@1 as value]
+05)--------ExactSortSource: fetch=3
+
+query TT
+EXPLAIN SELECT group_id, value + 1 AS v
+FROM exact_sort_source
+ORDER BY group_id, value
+LIMIT 3;
+----
+physical_plan
+01)ProjectionExec: expr=[group_id@0 as group_id, v@1 as v]
+02)--SortPreservingMergeExec: [group_id@0 ASC NULLS LAST, value@2 ASC NULLS 
LAST], fetch=3
+03)----BufferExec: capacity=1073741824
+04)------ProjectionExec: expr=[group_id@0 as group_id, CAST(value@1 AS Int64) 
+ 1 as v, value@1 as value]
+05)--------LocalLimitExec: fetch=3
+06)----------ExactSortSource
+
+query TT
+EXPLAIN SELECT group_id, value + 1 AS v
+FROM exact_sort_fetch_source
+ORDER BY group_id, value
+LIMIT 3 OFFSET 2;
+----
+physical_plan
+01)ProjectionExec: expr=[group_id@0 as group_id, v@1 as v]
+02)--GlobalLimitExec: skip=2, fetch=3
+03)----SortPreservingMergeExec: [group_id@0 ASC NULLS LAST, value@2 ASC NULLS 
LAST], fetch=5
+04)------BufferExec: capacity=1073741824
+05)--------ProjectionExec: expr=[group_id@0 as group_id, CAST(value@1 AS 
Int64) + 1 as v, value@1 as value]
+06)----------ExactSortSource: fetch=5

Review Comment:
   The PR description says that each case also has an OFFSET test. Could we add 
the one for the source without a fetch? This passes locally.
   
   ```suggestion
   06)----------ExactSortSource: fetch=5
   
   query TT
   EXPLAIN SELECT group_id, value + 1 AS v
   FROM exact_sort_source
   ORDER BY group_id, value
   LIMIT 3 OFFSET 2;
   ----
   physical_plan
   01)ProjectionExec: expr=[group_id@0 as group_id, v@1 as v]
   02)--GlobalLimitExec: skip=2, fetch=3
   03)----SortPreservingMergeExec: [group_id@0 ASC NULLS LAST, value@2 ASC 
NULLS LAST], fetch=5
   04)------BufferExec: capacity=1073741824
   05)--------ProjectionExec: expr=[group_id@0 as group_id, CAST(value@1 AS 
Int64) + 1 as v, value@1 as value]
   06)----------LocalLimitExec: fetch=5
   07)------------ExactSortSource
   ```



##########
datafusion/core/tests/physical_optimizer/test_utils.rs:
##########
@@ -1093,6 +1108,11 @@ impl ExecutionPlan for TestScan {
         self.supports_fetch
     }
 
+    // A leaf: it takes a limit as its own fetch, like `DataSourceExec`.
+    fn limit_behavior(&self) -> LimitBehavior {
+        LimitBehavior::Stops
+    }

Review Comment:
   Nit: could we remove both methods? `DataSourceExec` overrides neither of 
them. It accepts a limit through `with_fetch`, and `TestScan` keeps that 
method. `supports_limit_pushdown` tells the optimizer that a limit can pass 
through to the input, but a leaf has no input. The default `limit_behavior` is 
already `Stops`, so the `pushdown_sort` tests pass with this change:
   
   ```diff
   -    fn supports_limit_pushdown(&self) -> bool {
   -        self.supports_fetch
   -    }
   -
   -    // A leaf: it takes a limit as its own fetch, like `DataSourceExec`.
   -    fn limit_behavior(&self) -> LimitBehavior {
   -        LimitBehavior::Stops
   -    }
   -
   ```
   
   The `LimitBehavior` import is then unused.



##########
datafusion/sqllogictest/test_files/sort_pushdown.slt:
##########
@@ -198,9 +198,73 @@ physical_plan
 06)----------LocalLimitExec: fetch=3
 07)------------ExactSortSource
 
+# The custom source keeps a ProjectionExec above it. After the sort is removed,
+# its limit must pass the projection: into the source as a fetch when the
+# source takes one, or as a LocalLimitExec right above it otherwise.
+query TT
+EXPLAIN SELECT group_id, value + 1 AS v
+FROM exact_sort_fetch_source
+ORDER BY group_id, value
+LIMIT 3;
+----
+physical_plan
+01)ProjectionExec: expr=[group_id@0 as group_id, v@1 as v]
+02)--SortPreservingMergeExec: [group_id@0 ASC NULLS LAST, value@2 ASC NULLS 
LAST], fetch=3
+03)----BufferExec: capacity=1073741824
+04)------ProjectionExec: expr=[group_id@0 as group_id, CAST(value@1 AS Int64) 
+ 1 as v, value@1 as value]
+05)--------ExactSortSource: fetch=3
+
+query TT
+EXPLAIN SELECT group_id, value + 1 AS v
+FROM exact_sort_source
+ORDER BY group_id, value
+LIMIT 3;
+----
+physical_plan
+01)ProjectionExec: expr=[group_id@0 as group_id, v@1 as v]
+02)--SortPreservingMergeExec: [group_id@0 ASC NULLS LAST, value@2 ASC NULLS 
LAST], fetch=3
+03)----BufferExec: capacity=1073741824
+04)------ProjectionExec: expr=[group_id@0 as group_id, CAST(value@1 AS Int64) 
+ 1 as v, value@1 as value]
+05)--------LocalLimitExec: fetch=3
+06)----------ExactSortSource
+
+query TT
+EXPLAIN SELECT group_id, value + 1 AS v
+FROM exact_sort_fetch_source
+ORDER BY group_id, value
+LIMIT 3 OFFSET 2;
+----
+physical_plan
+01)ProjectionExec: expr=[group_id@0 as group_id, v@1 as v]
+02)--GlobalLimitExec: skip=2, fetch=3
+03)----SortPreservingMergeExec: [group_id@0 ASC NULLS LAST, value@2 ASC NULLS 
LAST], fetch=5
+04)------BufferExec: capacity=1073741824
+05)--------ProjectionExec: expr=[group_id@0 as group_id, CAST(value@1 AS 
Int64) + 1 as v, value@1 as value]
+06)----------ExactSortSource: fetch=5
+
 statement ok
 RESET datafusion.explain.physical_plan_only;
 
+query II
+SELECT group_id, value + 1 AS v
+FROM exact_sort_fetch_source
+ORDER BY group_id, value
+LIMIT 3;
+----
+0 1
+0 2
+0 3
+
+query II
+SELECT group_id, value + 1 AS v
+FROM exact_sort_fetch_source
+ORDER BY group_id, value
+LIMIT 3 OFFSET 2;
+----
+0 3
+0 4
+0 5

Review Comment:
   Could we also check the rows for the `LocalLimitExec` path? These queries 
pass locally.
   
   ```suggestion
   0 5
   
   query II
   SELECT group_id, value + 1 AS v
   FROM exact_sort_source
   ORDER BY group_id, value
   LIMIT 3;
   ----
   0 1
   0 2
   0 3
   
   query II
   SELECT group_id, value + 1 AS v
   FROM exact_sort_source
   ORDER BY group_id, value
   LIMIT 3 OFFSET 2;
   ----
   0 3
   0 4
   0 5
   ```



##########
datafusion/core/tests/physical_optimizer/pushdown_sort.rs:
##########
@@ -1205,3 +1209,349 @@ fn 
test_sort_pushdown_exact_preserves_fetch_with_source_support() {
     "
     );
 }
+
+/// A scan that answers `Exact` for any ordering, with `partitions` output
+/// partitions, that takes a fetch when `supports_fetch`.
+fn exact_scan(partitions: usize, supports_fetch: bool) -> Arc<dyn 
ExecutionPlan> {
+    Arc::new(
+        TestScan::new(schema(), vec![])
+            .with_exact_pushdown(true)
+            .with_supports_fetch(supports_fetch)
+            .with_partition_count(partitions),
+    )
+}
+
+#[test]
+fn test_sort_pushdown_exact_pushes_fetch_through_projection() {
+    // The limit of the eliminated SortExec passes the projection and goes
+    // into the source, instead of staying above the projection.

Review Comment:
   Nit: the comment can describe only the current behavior.
   
   ```suggestion
       // The limit of the eliminated SortExec passes the projection and goes
       // into the source.
   ```



##########
datafusion/core/tests/physical_optimizer/pushdown_sort.rs:
##########
@@ -1205,3 +1209,349 @@ fn 
test_sort_pushdown_exact_preserves_fetch_with_source_support() {
     "
     );
 }
+
+/// A scan that answers `Exact` for any ordering, with `partitions` output
+/// partitions, that takes a fetch when `supports_fetch`.
+fn exact_scan(partitions: usize, supports_fetch: bool) -> Arc<dyn 
ExecutionPlan> {
+    Arc::new(
+        TestScan::new(schema(), vec![])
+            .with_exact_pushdown(true)
+            .with_supports_fetch(supports_fetch)
+            .with_partition_count(partitions),
+    )
+}
+
+#[test]
+fn test_sort_pushdown_exact_pushes_fetch_through_projection() {
+    // The limit of the eliminated SortExec passes the projection and goes
+    // into the source, instead of staying above the projection.
+    let schema = schema();
+    let a = sort_expr("a", &schema);
+    let projection = simple_projection_exec(exact_scan(1, true), vec![0, 1]);
+
+    let ordering = LexOrdering::new(vec![a.reverse()]).unwrap();
+    let plan = sort_exec_with_fetch(ordering, Some(10), projection);
+
+    insta::assert_snapshot!(
+        OptimizationTest::new(plan, PushdownSort::new(), true),
+        @r"
+    OptimizationTest:
+      input:
+        - SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST], 
preserve_partitioning=[false]
+        -   ProjectionExec: expr=[a@0 as a, b@1 as b]
+        -     TestScan
+      output:
+        Ok:
+          - ProjectionExec: expr=[a@0 as a, b@1 as b]
+          -   TestScan: requested_ordering=[a@0 DESC NULLS LAST], fetch=10
+    "
+    );
+}
+
+#[test]
+fn test_sort_pushdown_exact_pushes_fetch_through_cooperative_and_projection() {
+    let schema = schema();
+    let a = sort_expr("a", &schema);
+    let cooperative = Arc::new(CooperativeExec::new(exact_scan(1, true)));
+    let projection = simple_projection_exec(cooperative, vec![0, 1]);
+
+    let ordering = LexOrdering::new(vec![a.reverse()]).unwrap();
+    let plan = sort_exec_with_fetch(ordering, Some(10), projection);
+
+    insta::assert_snapshot!(
+        OptimizationTest::new(plan, PushdownSort::new(), true),
+        @r"
+    OptimizationTest:
+      input:
+        - SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST], 
preserve_partitioning=[false]
+        -   ProjectionExec: expr=[a@0 as a, b@1 as b]
+        -     CooperativeExec
+        -       TestScan
+      output:
+        Ok:
+          - ProjectionExec: expr=[a@0 as a, b@1 as b]
+          -   CooperativeExec
+          -     TestScan: requested_ordering=[a@0 DESC NULLS LAST], fetch=10
+    "
+    );
+}
+
+#[test]
+fn test_sort_pushdown_exact_places_limit_below_projection() {
+    // The source can't take a fetch: the limit goes right above it, so the
+    // projection only sees the rows that are kept.
+    let schema = schema();
+    let a = sort_expr("a", &schema);
+    let projection = simple_projection_exec(exact_scan(1, false), vec![0, 1]);
+
+    let ordering = LexOrdering::new(vec![a.reverse()]).unwrap();
+    let plan = sort_exec_with_fetch(ordering, Some(10), projection);
+
+    insta::assert_snapshot!(
+        OptimizationTest::new(plan, PushdownSort::new(), true),
+        @r"
+    OptimizationTest:
+      input:
+        - SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST], 
preserve_partitioning=[false]
+        -   ProjectionExec: expr=[a@0 as a, b@1 as b]
+        -     TestScan
+      output:
+        Ok:
+          - ProjectionExec: expr=[a@0 as a, b@1 as b]
+          -   GlobalLimitExec: skip=0, fetch=10
+          -     TestScan: requested_ordering=[a@0 DESC NULLS LAST]
+    "
+    );
+}
+
+#[test]
+fn test_sort_pushdown_exact_keeps_offset_above_pushed_fetch() {
+    // `OFFSET 5 LIMIT 10`: the outer limit stays, the sort's fetch of 15 goes
+    // into the source.
+    let schema = schema();
+    let a = sort_expr("a", &schema);
+    let projection = simple_projection_exec(exact_scan(1, true), vec![0, 1]);
+
+    let ordering = LexOrdering::new(vec![a.reverse()]).unwrap();
+    let sort = sort_exec_with_fetch(ordering, Some(15), projection);
+    let plan = Arc::new(GlobalLimitExec::new(sort, 5, Some(10)));
+
+    insta::assert_snapshot!(
+        OptimizationTest::new(plan, PushdownSort::new(), true),
+        @r"
+    OptimizationTest:
+      input:
+        - GlobalLimitExec: skip=5, fetch=10
+        -   SortExec: TopK(fetch=15), expr=[a@0 DESC NULLS LAST], 
preserve_partitioning=[false]
+        -     ProjectionExec: expr=[a@0 as a, b@1 as b]
+        -       TestScan
+      output:
+        Ok:
+          - GlobalLimitExec: skip=5, fetch=10
+          -   ProjectionExec: expr=[a@0 as a, b@1 as b]
+          -     TestScan: requested_ordering=[a@0 DESC NULLS LAST], fetch=15
+    "
+    );
+}
+
+#[test]
+fn test_sort_pushdown_exact_partitioned_pushes_fetch_through_projection() {
+    // SPM -> SortExec(preserve_partitioning): each partition keeps its own
+    // fetch, now in the source below the projection.

Review Comment:
   Nit: same here.
   
   ```suggestion
       // fetch, in the source below the projection.
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to