You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "zhuqi-lucas (via GitHub)" <gi...@apache.org> on 2025/07/01 13:44:27 UTC

[PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

zhuqi-lucas opened a new pull request, #16641:
URL: https://github.com/apache/datafusion/pull/16641

   ## Which issue does this PR close?
   
   - Closes[ #16638](https://github.com/apache/datafusion/issues/16638)
   
   ## Rationale for this change
   
    Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
    so sorting beforehand cannot be relied on. We should not pushdown the sort for anti join.
   
   ## What changes are included in this PR?
   Disable hashjoin with Anti join.
   
   ## Are these changes tested?
   
   Yes, slt testing added.
   
   ## Are there any user-facing changes?
   
   No
   


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2179182492


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   > I mean the limit that's built into the TopK operator
   
   Right @adriangb , i reproduced it in above example.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180473337


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,28 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Only attempt to push down TopK when there is an upstream LIMIT
+    if parent_fetch.is_some() {
+        // 1) Never push a new TopK below an operator that already has its own fetch
+        if plan.fetch().is_some() {
+            return Ok(None);
+        }
+        // 2) Only allow pushdown through operators that do not increase row count
+        //    (equal or lower-equal cardinality). Any other operator (including joins,
+        //    sort-with-limit, or UDTFs that may expand rows) must stop the pushdown.
+        let effect = plan.cardinality_effect();
+        if !matches!(
+            effect,
+            CardinalityEffect::Equal | CardinalityEffect::LowerEqual
+        ) {
+            return Ok(None);
+        }

Review Comment:
   Thank you @adriangb , i think i got it now, even filter exec, we should not pass the push down.
   
   Changed it to equal in latest PR. 



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180411847


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,28 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Only attempt to push down TopK when there is an upstream LIMIT
+    if parent_fetch.is_some() {

Review Comment:
   I guess this code is already assuming that `parent` is some operator that has a limit. So yeah I agree with you not worth refactoring for this change, if there are still issues we can address them later.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb merged PR #16641:
URL: https://github.com/apache/datafusion/pull/16641


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2178965043


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   Thank you @adriangb, exactly you are right. Correct me if i am wrong.
   
   Why Anti‑Joins Are Different
   An anti‑join (LEFT ANTI or RIGHT ANTI) filters out all rows that do have matches, emitting only the non‑matching ones. Although maintains_input_order() still returns true—because if you emitted every probe row in match order, they’d be ordered—the act of dropping rows breaks that guarantee:
   
   Per‑batch filtering
   In a batched execution, each batch is sorted, then some rows are independently discarded by the anti‑join filter.
   
   No final merge
   When you push the sort below the anti‑join, you end up just concatenating each sorted batch’s output. A small key in a later batch can easily slip behind a larger key from an earlier batch, violating the global ORDER BY.
   
   That is why we must short‑circuit and refuse to push the sort beneath any anti‑join: without a final merge or a full sort after filtering, the concatenation of filtered, sorted batches cannot preserve the overall ordering guarantee.
   
   
   
   **Why Anti‑Joins Break Global Ordering: A Batch Example**
   
   Suppose we split the probe-side input into two batches, each sorted by `a`, and then simply concatenate their outputs after filtering. Here’s how the global order can be lost:
   
   ```sql
   -- Batch 1 input (sorted by a)
   a | b | c
   --+---+---
   1 | x | …
   3 | x | …
   
   -- Batch 2 input (sorted by a)
   a | b | c
   --+---+---
   2 | y | …
   4 | y | …
   
   -- Assume the anti‑join filter keeps *all* rows (no actual filtering for simplicity).
   -- So each batch output remains:
   --   Batch 1 → [ (1, x, …), (3, x, …) ]
   --   Batch 2 → [ (2, y, …), (4, y, …) ]
   
   -- Naïvely concatenating Batch 1 then Batch 2:
   1 | x | …  
   3 | x | …   ← (3 > 2) but appears before the row with a=2  
   2 | y | …  
   4 | y | …
   
   -- Final sequence: [1, 3, 2, 4], which is *not* globally sorted by `a`.
   
   -- In contrast, a true global merge of two sorted streams:
   --   merge([1,3], [2,4]) → [1,2,3,4]
   -- would preserve order.
   
   **Key takeaway**:  
   1. Sorting each batch in isolation only guarantees *local* order.  
   2. An anti‑join may filter out rows, but even without filtering, concatenating sorted batches breaks global ordering.  
   3. Therefore, we must *prevent* pushing a sort below an anti‑join unless we perform a final merge or full sort after filtering.
   



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2178965043


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   Thank you @adriangb, exactly you are right. Correct me if i am wrong.
   
   Why Anti‑Joins Are Different
   An anti‑join (LEFT ANTI or RIGHT ANTI) filters out all rows that do have matches, emitting only the non‑matching ones. Although maintains_input_order() still returns true—because if you emitted every probe row in match order, they’d be ordered—the act of dropping rows breaks that guarantee:
   
   Per‑batch filtering
   In a batched execution, each batch is sorted, then some rows are independently discarded by the anti‑join filter.
   
   No final merge
   When you push the sort below the anti‑join, you end up just concatenating each sorted batch’s output. A small key in a later batch can easily slip behind a larger key from an earlier batch, violating the global ORDER BY.
   
   That is why we must short‑circuit and refuse to push the sort beneath any anti‑join: without a final merge or a full sort after filtering, the concatenation of filtered, sorted batches cannot preserve the overall ordering guarantee.
   
   
   
   **Why Anti‑Joins Break Global Ordering: A Batch Example**
   
   Suppose we split the probe-side input into two batches, each sorted by `a`, and then simply concatenate their outputs after filtering. Here’s how the global order can be lost:
   
   ```sql
   -- Batch 1 input (sorted by a)
   a | b | c
   --+---+---
   1 | x | …
   3 | x | …
   
   -- Batch 2 input (sorted by a)
   a | b | c
   --+---+---
   2 | y | …
   4 | y | …
   
   -- Assume the anti‑join filter keeps all rows (no actual filtering for simplicity).
   -- So each batch output remains:
   --   Batch 1 → [ (1, x, …), (3, x, …) ]
   --   Batch 2 → [ (2, y, …), (4, y, …) ]
   
   -- Naively concatenating Batch 1 then Batch 2:
   1 | x | …  
   3 | x | …   ← (3 > 2) but appears before the row with a=2  
   2 | y | …  
   4 | y | …
   
   -- Final sequence: [1, 3, 2, 4], which is *not* globally sorted by `a`.
   
   -- In contrast, a true global merge of two sorted streams:
   --   merge([1,3], [2,4]) → [1,2,3,4]
   -- would preserve order.
   
   1. Sorting each batch in isolation only guarantees local order.  
   2. An anti‑join may filter out rows, but even without filtering, concatenating sorted batches breaks global ordering.  
   3. Therefore, we must prevent pushing a sort below an anti‑join unless we perform a final merge or full sort after filtering.
   



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180419834


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,28 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Only attempt to push down TopK when there is an upstream LIMIT
+    if parent_fetch.is_some() {
+        // 1) Never push a new TopK below an operator that already has its own fetch
+        if plan.fetch().is_some() {
+            return Ok(None);
+        }
+        // 2) Only allow pushdown through operators that do not increase row count
+        //    (equal or lower-equal cardinality). Any other operator (including joins,
+        //    sort-with-limit, or UDTFs that may expand rows) must stop the pushdown.
+        let effect = plan.cardinality_effect();
+        if !matches!(
+            effect,
+            CardinalityEffect::Equal | CardinalityEffect::LowerEqual
+        ) {
+            return Ok(None);
+        }

Review Comment:
   Hmm but if `FilterExec` is `LowerEqual` aren't you saying "if the cardinality effect is not one of Equal or LowerEqual allow pushdown" which is equivalent to "if the cardinality effect is either of Equal or LowerEqual do allow pushdown", which would be the opposite of what we want? I think we *only* want to allow pushdown if the cardinality effect is `Equal`



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2181454354


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,25 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Only attempt to push down TopK when there is an upstream LIMIT
+    if parent_fetch.is_some() {
+        // 1) Never push a new TopK below an operator that already has its own fetch
+        if plan.fetch().is_some() {
+            return Ok(None);
+        }
+        // 2) Only allow pushdown through operators that do not increase row count
+        //    (equal cardinality). Any other operator (including joins, filter,
+        //    sort-with-limit, or UDTFs that may expand rows) must stop the pushdown.
+        let effect = plan.cardinality_effect();
+        if !matches!(effect, CardinalityEffect::Equal) {
+            return Ok(None);
+        }
+        // At this point, only single-input, non-expanding operators
+        // such as ProjectionExec, CoalesceBatchesExec, are allowed to receive TopK.
+    }

Review Comment:
   Thank you @adriangb ,  exactly more concise and accurate solution!  Merged your suggestion now.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180242562


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   Thank you @adriangb for confirming, addressed it in latest PR.
   
   Now, we will not pushdown Topk for anti join. 
   
   But for normal sort without fetch, we should support push down, also added the related slt testing.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2181487323


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,25 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Only attempt to push down TopK when there is an upstream LIMIT
+    if parent_fetch.is_some() {
+        // 1) Never push a new TopK below an operator that already has its own fetch
+        if plan.fetch().is_some() {
+            return Ok(None);
+        }
+        // 2) Only allow pushdown through operators that do not increase row count
+        //    (equal cardinality). Any other operator (including joins, filter,
+        //    sort-with-limit, or UDTFs that may expand rows) must stop the pushdown.
+        let effect = plan.cardinality_effect();
+        if !matches!(effect, CardinalityEffect::Equal) {
+            return Ok(None);
+        }
+        // At this point, only single-input, non-expanding operators
+        // such as ProjectionExec, CoalesceBatchesExec, are allowed to receive TopK.
+    }

Review Comment:
   After testing,  this is not enough, for example, the unionexec support limit push down, but the topk should not pushdown through UnionExec.
   ```rust
    // If there is a limit on the parent plan we cannot push it down through operators that change the cardinality.
       // E.g. consider if LIMIT 2 is applied below a FilteExec that filters out 1/2 of the rows we'll end up with 1 row instead of 2.
       // If the LIMIT is applied after the FilterExec and the FilterExec returns > 2 rows we'll end up with 2 rows (correct).
       if parent_fetch.is_some() {
           if !plan.supports_limit_pushdown() {
               return Ok(None);
           }
   
           // Note: we still need to check the cardinality effect of the plan here, because the
           // limit pushdown is not always safe, even if the plan supports it. Here's an example:
           //
           // UnionExec advertises `supports_limit_pushdown() == true` because it can
           // forward a LIMIT k to each of its children—i.e. apply “LIMIT k” separately
           // on each branch before merging them together.
           //
           // However, UnionExec’s `cardinality_effect() == GreaterEqual` (it sums up
           // all child row counts), so pushing a global TopK/LIMIT through it would
           // break the semantics of “take the first k rows of the combined result.”
           //
           // For example, with two branches A and B and k = 3:
           //   — Global LIMIT: take the first 3 rows from (A ∪ B) after merging.
           //   — Pushed down: take 3 from A, 3 from B, then merge → up to 6 rows!
           //
           // That’s why we still block on cardinality: even though UnionExec can
           // push a LIMIT to its children, its GreaterEqual effect means it cannot
           // preserve the global TopK semantics.
           match plan.cardinality_effect() {
               CardinalityEffect::Equal => {
                   // safe: only true sources (e.g. CoalesceBatchesExec, ProjectionExec) pass
               }
               _ => return Ok(None),
           }
       }
   ```
   
   Change the code to above @adriangb , thank you !
   
   



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180355482


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   Try to address it in latest PR, and it seems some slt files changes, but it should be right, the unionexec also should not pass the TopK i believe.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2179151489


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   Updated, i checked the code, we will not push down limit for anti join:
   https://github.com/apache/datafusion/blob/25c2a079fc1baacc038e304cb2bcae671338c2d8/datafusion/optimizer/src/push_down_limit.rs#L256
   
   And example:
   
   ```rust
   CREATE TABLE t1 AS VALUES
     (1, 'a'),
     (2, 'b'),
     (3, 'c');
   0 row(s) fetched.
   Elapsed 0.004 seconds.
   
   > CREATE TABLE t2 AS VALUES
     (1, 'a');
   0 row(s) fetched.
   Elapsed 0.003 seconds.
   
   > -- LIMIT potentially pushed down (depends on optimizer)
   SELECT * FROM t1 LEFT ANTI JOIN t2 ON t1.column1 = t2.column1 LIMIT 2;
   +---------+---------+
   | column1 | column2 |
   +---------+---------+
   | 2       | b       |
   | 3       | c       |
   +---------+---------+
   2 row(s) fetched.
   Elapsed 0.003 seconds.
   
   > -- LIMIT applied after anti join (expected)
   SELECT * FROM (
     SELECT * FROM t1 LEFT ANTI JOIN t2 ON t1.column1 = t2.column1
   ) LIMIT 2;
   +---------+---------+
   | column1 | column2 |
   +---------+---------+
   | 2       | b       |
   | 3       | c       |
   +---------+---------+
   2 row(s) fetched.
   Elapsed 0.002 seconds.
   
   > EXPLAIN SELECT * FROM t1 LEFT ANTI JOIN t2 ON t1.column1 = t2.column1 LIMIT 2;
   +---------------+------------------------------------------------------------+
   | plan_type     | plan                                                       |
   +---------------+------------------------------------------------------------+
   | physical_plan | ┌───────────────────────────┐                              |
   |               | │    CoalesceBatchesExec    │                              |
   |               | │    --------------------   │                              |
   |               | │          limit: 2         │                              |
   |               | │                           │                              |
   |               | │     target_batch_size:    │                              |
   |               | │            8192           │                              |
   |               | └─────────────┬─────────────┘                              |
   |               | ┌─────────────┴─────────────┐                              |
   |               | │        HashJoinExec       │                              |
   |               | │    --------------------   │                              |
   |               | │    join_type: RightAnti   │                              |
   |               | │                           ├──────────────┐               |
   |               | │            on:            │              │               |
   |               | │    (column1 = column1)    │              │               |
   |               | └─────────────┬─────────────┘              │               |
   |               | ┌─────────────┴─────────────┐┌─────────────┴─────────────┐ |
   |               | │       DataSourceExec      ││       DataSourceExec      │ |
   |               | │    --------------------   ││    --------------------   │ |
   |               | │        bytes: 1336        ││        bytes: 1336        │ |
   |               | │       format: memory      ││       format: memory      │ |
   |               | │          rows: 1          ││          rows: 1          │ |
   |               | └───────────────────────────┘└───────────────────────────┘ |
   |               |                                                            |
   +---------------+------------------------------------------------------------+
   1 row(s) fetched.
   Elapsed 0.003 seconds.
   ```



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180362694


##########
datafusion/sqllogictest/test_files/order.slt:
##########
@@ -1258,13 +1258,12 @@ logical_plan
 08)--------TableScan: ordered_table projection=[a0, b, c, d]
 physical_plan
 01)SortPreservingMergeExec: [d@4 ASC NULLS LAST, c@1 ASC NULLS LAST, a@2 ASC NULLS LAST, a0@3 ASC NULLS LAST, b@0 ASC NULLS LAST], fetch=2
-02)--UnionExec
-03)----SortExec: TopK(fetch=2), expr=[d@4 ASC NULLS LAST, c@1 ASC NULLS LAST, a@2 ASC NULLS LAST, b@0 ASC NULLS LAST], preserve_partitioning=[false]
+02)--SortExec: TopK(fetch=2), expr=[d@4 ASC NULLS LAST, c@1 ASC NULLS LAST, a@2 ASC NULLS LAST, a0@3 ASC NULLS LAST, b@0 ASC NULLS LAST], preserve_partitioning=[true]

Review Comment:
   Same as above.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2179135590


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   Good point @adriangb, even we don't have sort, but only limit, we will also hit the bug, let me address this point, and add more testing cases.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180361982


##########
datafusion/sqllogictest/test_files/topk.slt:
##########
@@ -53,7 +53,7 @@ query I
 select * from (select * from topk limit 8) order by x limit 3;
 ----
 0

Review Comment:
   This is right, becasue we select * from topk limit 8 but not order, the original case should push down the sort limit to it.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#issuecomment-3032766023

   > left a minor nit to reduce indentation but otherwise approved, great job!
   
   Thank you @adriangb for patient review, addressed it in latest PR.


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "nuno-faria (via GitHub)" <gi...@apache.org>.
nuno-faria commented on PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#issuecomment-3024191112

   Thanks @zhuqi-lucas, it returns the correct result now.


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#issuecomment-3024262064

   Thank you @nuno-faria for checking!


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2178834573


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   Thank you @adriangb for review:
   
   Good point—at first glance it looks like RightAnti would simply fall out at the !maintains_input_order()[1] check below, but in reality we need to short‑circuit before that.
   
   The maintains_input_order method is merely telling us “if you streamed all probe‑side matches you’d get them in input order,” which is true of a RightAnti join (it does process probe rows in sequence). But an anti‑join also drops rows, and that drop can interleave arbitrarily with the sort key, so a pre‑sort + anti‑join does not guarantee globally sorted output.
   
   In other words:
   
   maintains_input_order()[1] == true means “if you output every matching probe row, you’d preserve order.”
   
   Anti‑joins however filter out some rows, so you cannot rely on that to still produce a correctly sorted subset.
   
   That’s why we explicitly bail out on both LeftAnti and RightAnti before ever calling maintains_input_order—we need to prevent any sort‑pushdown for anti‑joins, even though their raw probe phase might look ordered.
   
   And since maintains_input_order is used elsewhere for true order‑preserving cases, we keep it unchanged here.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2178887207


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   Okay interesting. Thank you for the in-depth explenation.
   
   Could you show with a simple table representing a batch how the anti join filtering out rows causes ordering to be lost? I imagine something like this flowing into the anti join:
   
   | a | b | c |
   |---|---|---|
   | 1 | 1 | 2 |
   | 2 | 3 | 5 |
   | 2 | 4 | 1 |
   
   
   For the query `SELECT a, b, c FROM t1 WHERE c NOT IN (SELECT n FROM t2) ORDER BY t1.a, t2.b` I expect the anti join to be created and for it to remove some rows, let's say `SELECT n FROM t2` returns just `5`, then the output would be:
   
   | a | b | c |
   |---|---|---|
   | 1 | 1 | 2 |
   | 2 | 4 | 1 |
   
   Which is still ordered. Are you saying it might be
   
   | a | b | c |
   |---|---|---|
   | 2 | 4 | 1 |
   | 1 | 1 | 2 |
   
   instead?



##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   Okay interesting. Thank you for the in-depth explanation.
   
   Could you show with a simple table representing a batch how the anti join filtering out rows causes ordering to be lost? I imagine something like this flowing into the anti join:
   
   | a | b | c |
   |---|---|---|
   | 1 | 1 | 2 |
   | 2 | 3 | 5 |
   | 2 | 4 | 1 |
   
   
   For the query `SELECT a, b, c FROM t1 WHERE c NOT IN (SELECT n FROM t2) ORDER BY t1.a, t2.b` I expect the anti join to be created and for it to remove some rows, let's say `SELECT n FROM t2` returns just `5`, then the output would be:
   
   | a | b | c |
   |---|---|---|
   | 1 | 1 | 2 |
   | 2 | 4 | 1 |
   
   Which is still ordered. Are you saying it might be
   
   | a | b | c |
   |---|---|---|
   | 2 | 4 | 1 |
   | 1 | 1 | 2 |
   
   instead?



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180392641


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,28 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Only attempt to push down TopK when there is an upstream LIMIT
+    if parent_fetch.is_some() {
+        // 1) Never push a new TopK below an operator that already has its own fetch
+        if plan.fetch().is_some() {
+            return Ok(None);
+        }
+        // 2) Only allow pushdown through operators that do not increase row count
+        //    (equal or lower-equal cardinality). Any other operator (including joins,
+        //    sort-with-limit, or UDTFs that may expand rows) must stop the pushdown.
+        let effect = plan.cardinality_effect();
+        if !matches!(
+            effect,
+            CardinalityEffect::Equal | CardinalityEffect::LowerEqual
+        ) {
+            return Ok(None);
+        }

Review Comment:
   Good suggestion! @adriangb 
   
   I was adding CardinalityEffect::LowerEqual, because filterexec is LowerEqual, it should also not passing sort pushdown.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180355482


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   > amazing!
   > 
   > > you can't push down a a limit below any operator that changes the cardinality of the data
   > 
   > one question here: can we push down operators that have a limit (`LIMIT` itself but also `TopK`) past other operators that change cardinality? e.g. `HashJoinExec`? I feel like maybe what we should do is call `ExecutionPlan::cardinality_effect` on the plan we are pushing down and the plan we are pushing through and only allow the pushdown if one of them is `CardinalityEffect::Equal` (I think that'd be correct). In the case of `HashJoinExec` + `TopK` you'd have `Unknown` and `LowerEqual` so you can't push down. `HashJoinExec` + non TopK `SortExec` would have `Unknown` and `Equal` so you can push down. This would generalize to to handle pushing through a `FilterExec`, etc.
   
   
   Great point!
   
   Try to address it in latest PR, and it seems some slt files changes, but it should be right, the unionexec also should not pass the TopK i believe.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180250971


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   amazing!
   
   > you can't push down a a limit below any operator that changes the cardinality of the data
   
   one question here: can we push down operators that have a limit (`LIMIT` itself but also `TopK`) past other operators that change cardinality? e.g. `HashJoinExec`? I feel like maybe what we should do is call `ExecutionPlan::cardinality_effect` on the plan we are pushing down and the plan we are pushing through and only allow the pushdown if they are both `CardinalityEffect::Equal`.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180379264


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,28 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Only attempt to push down TopK when there is an upstream LIMIT
+    if parent_fetch.is_some() {
+        // 1) Never push a new TopK below an operator that already has its own fetch
+        if plan.fetch().is_some() {
+            return Ok(None);
+        }
+        // 2) Only allow pushdown through operators that do not increase row count
+        //    (equal or lower-equal cardinality). Any other operator (including joins,
+        //    sort-with-limit, or UDTFs that may expand rows) must stop the pushdown.
+        let effect = plan.cardinality_effect();
+        if !matches!(
+            effect,
+            CardinalityEffect::Equal | CardinalityEffect::LowerEqual
+        ) {
+            return Ok(None);
+        }

Review Comment:
   Should this be
   
   
   ```suggestion
           let effect = plan.cardinality_effect();
           if !matches!(
               plan.cardinality_effect(),
               CardinalityEffect::Equal
           ) {
               return Ok(None);
           }
   ```



##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,28 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Only attempt to push down TopK when there is an upstream LIMIT
+    if parent_fetch.is_some() {

Review Comment:
   Can we pass down `parent.cardinality_effect()` instead? I would do `if !matches(parent.cardinality_effect(), CardinalityEffect::Equal)`



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2179307292


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   So it seems we need to pushdown sort exec without fetch, so it can avoid the topk cases? 



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2177988731


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   Shouldn't these implement `maintains_input_order` and hit the check a couple lines below?



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#issuecomment-3032778175

   > > left a minor nit to reduce indentation but otherwise approved, great job!
   > 
   > Thank you @adriangb for patient review, addressed it in latest PR.
   
   Btw, I think you mean _latest commit_.


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2179833468


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   Yeah my guess is that you can push down a sort below any operator that preserves order but you can't push down a a limit below any operator that changes the cardinality of the data. I'm surprised we can push TopK down through a HashJoin.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180250971


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   amazing!
   
   > you can't push down a a limit below any operator that changes the cardinality of the data
   
   one question here: can we push down operators that have a limit (`LIMIT` itself but also `TopK`) past other operators that change cardinality? e.g. `HashJoinExec`? I feel like maybe what we should do is call `ExecutionPlan::cardinality_effect` on the plan we are pushing down and the plan we are pushing through and only allow the pushdown if one of them is `CardinalityEffect::Equal` (I think that'd be correct). In the case of `HashJoinExec` + `TopK` you'd have `Unknown` and `LowerEqual` so you can't push down. `HashJoinExec` +  non TopK `SortExec` would have `Unknown` and `Equal` so you can push down. This would generalize to to handle pushing through a `FilterExec`, etc.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180360451


##########
datafusion/sqllogictest/test_files/limit.slt:
##########
@@ -663,15 +663,14 @@ logical_plan
 physical_plan
 01)GlobalLimitExec: skip=4, fetch=10
 02)--SortPreservingMergeExec: [c@0 DESC], fetch=14
-03)----UnionExec
-04)------SortExec: TopK(fetch=14), expr=[c@0 DESC], preserve_partitioning=[true]
+03)----SortExec: TopK(fetch=14), expr=[c@0 DESC], preserve_partitioning=[true]

Review Comment:
   This should be right, we should union then to sort limit.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180401096


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,28 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Only attempt to push down TopK when there is an upstream LIMIT
+    if parent_fetch.is_some() {

Review Comment:
   Sorry @adriangb , i can't understand the parent here, what do you mean parent?
   
   I can't find parent context from current sort pushdown code.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2179165257


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   But we support Topk(sort with limit) pushdown for hash join:
   
   ```rust
    explain
   SELECT *
   FROM t1
   LEFT ANTI JOIN t2 ON t1.k = t2.k
   ORDER BY t1.k
   LIMIT 2;
   +---------------+------------------------------------------------------------+
   | plan_type     | plan                                                       |
   +---------------+------------------------------------------------------------+
   | physical_plan | ┌───────────────────────────┐                              |
   |               | │  SortPreservingMergeExec  │                              |
   |               | │    --------------------   │                              |
   |               | │   k ASC NULLS LASTlimit:  │                              |
   |               | │             2             │                              |
   |               | └─────────────┬─────────────┘                              |
   |               | ┌─────────────┴─────────────┐                              |
   |               | │    CoalesceBatchesExec    │                              |
   |               | │    --------------------   │                              |
   |               | │          limit: 2         │                              |
   |               | │                           │                              |
   |               | │     target_batch_size:    │                              |
   |               | │            8192           │                              |
   |               | └─────────────┬─────────────┘                              |
   |               | ┌─────────────┴─────────────┐                              |
   |               | │        HashJoinExec       │                              |
   |               | │    --------------------   │                              |
   |               | │    join_type: RightAnti   ├──────────────┐               |
   |               | │        on: (k = k)        │              │               |
   |               | └─────────────┬─────────────┘              │               |
   |               | ┌─────────────┴─────────────┐┌─────────────┴─────────────┐ |
   |               | │       DataSourceExec      ││       SortExec(TopK)      │ |
   |               | │    --------------------   ││    --------------------   │ |
   |               | │         bytes: 224        ││     k@0 ASC NULLS LAST    │ |
   |               | │       format: memory      ││                           │ |
   |               | │          rows: 1          ││          limit: 2         │ |
   |               | └───────────────────────────┘└─────────────┬─────────────┘ |
   |               |                              ┌─────────────┴─────────────┐ |
   |               |                              │      RepartitionExec      │ |
   |               |                              │    --------------------   │ |
   |               |                              │ partition_count(in->out): │ |
   |               |                              │          1 -> 14          │ |
   |               |                              │                           │ |
   |               |                              │    partitioning_scheme:   │ |
   |               |                              │    RoundRobinBatch(14)    │ |
   |               |                              └─────────────┬─────────────┘ |
   |               |                              ┌─────────────┴─────────────┐ |
   |               |                              │       DataSourceExec      │ |
   |               |                              │    --------------------   │ |
   |               |                              │        bytes: 80384       │ |
   |               |                              │       format: memory      │ |
   |               |                              │          rows: 2          │ |
   |               |                              └───────────────────────────┘ |
   |               |                                                            |
   +---------------+------------------------------------------------------------+
   1 row(s) fetched.
   Elapsed 0.002 seconds.
   ```



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2179151489


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   Updated, i checked the code, we will not push down limit for anti join:
   https://github.com/apache/datafusion/blob/25c2a079fc1baacc038e304cb2bcae671338c2d8/datafusion/optimizer/src/push_down_limit.rs#L256



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2179159157


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   I mean the limit that's built into the TopK operator



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180363095


##########
datafusion/sqllogictest/test_files/union.slt:
##########
@@ -413,15 +413,14 @@ logical_plan
 06)------TableScan: aggregate_test_100 projection=[c1, c3]
 physical_plan
 01)SortPreservingMergeExec: [c9@1 DESC], fetch=5
-02)--UnionExec
-03)----SortExec: TopK(fetch=5), expr=[c9@1 DESC], preserve_partitioning=[true]
+02)--SortExec: TopK(fetch=5), expr=[c9@1 DESC], preserve_partitioning=[true]

Review Comment:
   Same as above.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "nuno-faria (via GitHub)" <gi...@apache.org>.
nuno-faria commented on PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#issuecomment-3033037009

   Thanks @zhuqi-lucas and @adriangb.


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180442867


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,28 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Only attempt to push down TopK when there is an upstream LIMIT
+    if parent_fetch.is_some() {
+        // 1) Never push a new TopK below an operator that already has its own fetch
+        if plan.fetch().is_some() {
+            return Ok(None);
+        }
+        // 2) Only allow pushdown through operators that do not increase row count
+        //    (equal or lower-equal cardinality). Any other operator (including joins,
+        //    sort-with-limit, or UDTFs that may expand rows) must stop the pushdown.
+        let effect = plan.cardinality_effect();
+        if !matches!(
+            effect,
+            CardinalityEffect::Equal | CardinalityEffect::LowerEqual
+        ) {
+            return Ok(None);
+        }

Review Comment:
   @adriangb I agree with you, the code here is confused, after i looking into the code:
   
   Here Ok(None) means we not push down current plan...
   
   



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180425799


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,28 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Only attempt to push down TopK when there is an upstream LIMIT
+    if parent_fetch.is_some() {
+        // 1) Never push a new TopK below an operator that already has its own fetch
+        if plan.fetch().is_some() {
+            return Ok(None);
+        }
+        // 2) Only allow pushdown through operators that do not increase row count
+        //    (equal or lower-equal cardinality). Any other operator (including joins,
+        //    sort-with-limit, or UDTFs that may expand rows) must stop the pushdown.
+        let effect = plan.cardinality_effect();
+        if !matches!(
+            effect,
+            CardinalityEffect::Equal | CardinalityEffect::LowerEqual
+        ) {
+            return Ok(None);
+        }

Review Comment:
   But maybe I'm confused about what `plan` is referring to here, etc.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2183060691


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,42 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // If there is a limit on the parent plan we cannot push it down through operators that change the cardinality.
+    // E.g. consider if LIMIT 2 is applied below a FilteExec that filters out 1/2 of the rows we'll end up with 1 row instead of 2.
+    // If the LIMIT is applied after the FilterExec and the FilterExec returns > 2 rows we'll end up with 2 rows (correct).
+    if parent_fetch.is_some() {
+        if !plan.supports_limit_pushdown() {
+            return Ok(None);
+        }

Review Comment:
   ```suggestion
       if parent_fetch.is_some() && !plan.supports_limit_pushdown() {
           return Ok(None);
   ```



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2179100056


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   It makes sense that in that example no global order is guaranteed in the output, there was no sorting being done before the anti-join! I think if you pushed a SortExec you'd get the right order.
   
   Having thought about it a bit I do think this is a real bug that needs fixing, but I'm not sure it's about sorting, it's about limits: if you push the TopK below the anti join is the limit is applied before the anti join filters out rows, which means you'll end up getting less or the wrong rows out. For example, if the batch into the TopK(2) is
   
   | a | b | c |
   |---|---|---|
   | 2 | 3 | 5 |
   | 1 | 1 | 2 |
   | 2 | 4 | 1 |
   
   It will output
   
   | a | b | c |
   |---|---|---|
   | 1 | 1 | 2 |
   | 2 | 3 | 5 |
   
   But then if the anti join filters out `c = 5` we get:
   
   | a | b | c |
   |---|---|---|
   | 1 | 1 | 2 |
   
   Which is a single row despite the `LIMIT 2`.
   
   If instead we apply the anti-join first we get:
   
   | a | b | c |
   |---|---|---|
   | 1 | 1 | 2 |
   | 2 | 4 | 1 |
   
   Which is correct.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2179307292


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -668,6 +668,15 @@ fn handle_hash_join(
     plan: &HashJoinExec,
     parent_required: OrderingRequirements,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Anti-joins (LeftAnti or RightAnti) do not preserve meaningful input order,
+    // so sorting beforehand cannot be relied on. Bail out early for both flavors:
+    match plan.join_type() {
+        JoinType::LeftAnti | JoinType::RightAnti => {
+            return Ok(None);
+        }
+        _ => {}
+    }

Review Comment:
   So it seems we need to pushdown sort exec without fetch, so it can avoid the topk cases? 
   
   
   I need further investigate it, thank you @adriangb !



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180408139


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,28 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Only attempt to push down TopK when there is an upstream LIMIT
+    if parent_fetch.is_some() {
+        // 1) Never push a new TopK below an operator that already has its own fetch
+        if plan.fetch().is_some() {
+            return Ok(None);
+        }
+        // 2) Only allow pushdown through operators that do not increase row count
+        //    (equal or lower-equal cardinality). Any other operator (including joins,
+        //    sort-with-limit, or UDTFs that may expand rows) must stop the pushdown.
+        let effect = plan.cardinality_effect();
+        if !matches!(
+            effect,
+            CardinalityEffect::Equal | CardinalityEffect::LowerEqual
+        ) {
+            return Ok(None);
+        }

Review Comment:
   Updated the code, it seems cause some failures. I will revert it first.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180419834


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,28 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Only attempt to push down TopK when there is an upstream LIMIT
+    if parent_fetch.is_some() {
+        // 1) Never push a new TopK below an operator that already has its own fetch
+        if plan.fetch().is_some() {
+            return Ok(None);
+        }
+        // 2) Only allow pushdown through operators that do not increase row count
+        //    (equal or lower-equal cardinality). Any other operator (including joins,
+        //    sort-with-limit, or UDTFs that may expand rows) must stop the pushdown.
+        let effect = plan.cardinality_effect();
+        if !matches!(
+            effect,
+            CardinalityEffect::Equal | CardinalityEffect::LowerEqual
+        ) {
+            return Ok(None);
+        }

Review Comment:
   Hmm but if `FilterExec` is `LowerEqual` aren't you saying "if the cardinality effect is not one of Equal or LowerEqual` allow pushdown" which is equivalent to "if the cardinality effect is either of Equal or LowerEqual do allow pushdown", which would be the opposite of what we want? I think we *only* want to allow pushdown if the cardinality effect is `Equal`



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180444684


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,28 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Only attempt to push down TopK when there is an upstream LIMIT
+    if parent_fetch.is_some() {
+        // 1) Never push a new TopK below an operator that already has its own fetch
+        if plan.fetch().is_some() {
+            return Ok(None);
+        }
+        // 2) Only allow pushdown through operators that do not increase row count
+        //    (equal or lower-equal cardinality). Any other operator (including joins,
+        //    sort-with-limit, or UDTFs that may expand rows) must stop the pushdown.
+        let effect = plan.cardinality_effect();
+        if !matches!(
+            effect,
+            CardinalityEffect::Equal | CardinalityEffect::LowerEqual
+        ) {
+            return Ok(None);
+        }

Review Comment:
   I may add more testing cases as follow-up.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Fix TopK Sort incorrectly pushed down past Join with anti join [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #16641:
URL: https://github.com/apache/datafusion/pull/16641#discussion_r2180504143


##########
datafusion/physical-optimizer/src/enforce_sorting/sort_pushdown.rs:
##########
@@ -216,7 +218,25 @@ fn pushdown_sorts_helper(
 fn pushdown_requirement_to_children(
     plan: &Arc<dyn ExecutionPlan>,
     parent_required: OrderingRequirements,
+    parent_fetch: Option<usize>,
 ) -> Result<Option<Vec<Option<OrderingRequirements>>>> {
+    // Only attempt to push down TopK when there is an upstream LIMIT
+    if parent_fetch.is_some() {
+        // 1) Never push a new TopK below an operator that already has its own fetch
+        if plan.fetch().is_some() {
+            return Ok(None);
+        }
+        // 2) Only allow pushdown through operators that do not increase row count
+        //    (equal cardinality). Any other operator (including joins, filter,
+        //    sort-with-limit, or UDTFs that may expand rows) must stop the pushdown.
+        let effect = plan.cardinality_effect();
+        if !matches!(effect, CardinalityEffect::Equal) {
+            return Ok(None);
+        }
+        // At this point, only single-input, non-expanding operators
+        // such as ProjectionExec, CoalesceBatchesExec, are allowed to receive TopK.
+    }

Review Comment:
   ```suggestion
       // If there is a limit on the parent plan we cannot push it down through operators that change the cardinality.
       // E.g. consider if LIMIT 2 is applied below a FilteExec that filters out 1/2 of the rows we'll end up with 1 row instead of 2.
       // If the LIMIT is applied after the FilterExec and the FilterExec returns > 2 rows we'll end up with 2 rows (correct).
       if parent_fetch.is_some() && !plan.supports_limit_pushdown() {
           return Ok(None)
       }
   ```
   
   wdyt?



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org