SubhamSinghal commented on code in PR #21621:
URL: https://github.com/apache/datafusion/pull/21621#discussion_r3987922677


##########
datafusion/optimizer/src/push_down_limit/topk_through_join.rs:
##########
@@ -0,0 +1,1185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Sort(fetch) → Join pushdown — a sub-module of `push_down_limit`.
+//!
+//! When a `Sort` with a fetch limit (TopK) sits above a join whose
+//! preserved side is known (LEFT / RIGHT / LeftMark / RightMark / CROSS)
+//! and all sort expressions come from the preserved side, we insert a
+//! copy of the `Sort(fetch)` onto that input to reduce rows entering
+//! the join. The outer `Sort` is kept because a 1-to-many join can
+//! produce more than N output rows from N preserved-side rows.
+//!
+//! Dispatched from `PushDownLimit::rewrite` when the plan node is
+//! `LogicalPlan::Sort` with `fetch.is_some()`.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use crate::utils::{has_all_column_refs, schema_columns};
+
+use datafusion_common::tree_node::{Transformed, TreeNode};
+use datafusion_common::{Column, Result, internal_err};
+use datafusion_expr::logical_plan::{
+    JoinType, LogicalPlan, Projection, Sort as SortPlan, SubqueryAlias,
+};
+use datafusion_expr::{Expr, SortExpr};
+
+/// Which child of a join is being treated as the preserved side.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Side {
+    Left,
+    Right,
+}
+
+/// Top-level pushdown for `Sort(fetch) → ... → Join` patterns. The plan
+/// passed in is guaranteed by the caller to be `LogicalPlan::Sort` with
+/// `fetch.is_some()`; we re-bind to a borrow inside.
+pub(super) fn push_topk_through_join(
+    plan: LogicalPlan,
+) -> Result<Transformed<LogicalPlan>> {
+    let LogicalPlan::Sort(sort) = &plan else {
+        return Ok(Transformed::no(plan));
+    };
+    let Some(fetch) = sort.fetch else {
+        return Ok(Transformed::no(plan));
+    };
+
+    // Don't push if any sort expression is non-deterministic (e.g.
+    // `random()`). Duplicating such expressions would produce different
+    // values at each evaluation point, potentially changing results.
+    if sort.expr.iter().any(|se| se.expr.is_volatile()) {
+        return Ok(Transformed::no(plan));
+    }
+
+    // Peel through transparent nodes (SubqueryAlias, Projection) to
+    // find the Join. Track intermediates so we can reconstruct the tree
+    // and resolve sort expressions through them.
+    let mut current = sort.input.as_ref();
+    let mut intermediates: Vec<&LogicalPlan> = Vec::new();
+    let join = loop {
+        match current {
+            LogicalPlan::Join(join) => break join,
+            LogicalPlan::Projection(proj) => {
+                intermediates.push(current);
+                current = proj.input.as_ref();
+            }
+            LogicalPlan::SubqueryAlias(sq) => {
+                intermediates.push(current);
+                current = sq.input.as_ref();
+            }
+            _ => return Ok(Transformed::no(plan)),
+        }
+    };
+
+    // Determine which side(s) of the join are preserved.
+    //
+    // - LEFT / LeftMark: only left preserved.
+    // - RIGHT / RightMark: symmetric.
+    // - CROSS JOIN (Inner with no `on` keys and no filter):
+    //   every row from both sides appears in the output (Cartesian
+    //   product), so we can push to whichever side has all the sort
+    //   columns.
+    //
+    // For LEFT/RIGHT, non-equijoin filters in the ON clause are safe:
+    // outer joins guarantee all preserved-side rows appear in the
+    // output regardless of the filter. For Inner joins (cross-join
+    // detection), the filter check is strict (`filter.is_none()`) —
+    // any filter on Inner can drop rows from either side.
+    let preserved_candidates: &[Side] = match join.join_type {
+        JoinType::Left | JoinType::LeftMark => &[Side::Left],
+        JoinType::Right | JoinType::RightMark => &[Side::Right],
+        JoinType::Inner if join.on.is_empty() && join.filter.is_none() => {
+            &[Side::Left, Side::Right]
+        }
+        _ => return Ok(Transformed::no(plan)),
+    };
+
+    // Resolve sort expressions through all intermediate nodes
+    // (Projection, SubqueryAlias) so column references match the
+    // join's schema.
+    let mut resolved_sort_exprs = sort.expr.clone();
+    for node in &intermediates {
+        match node {
+            LogicalPlan::Projection(proj) => {
+                resolved_sort_exprs =
+                    
resolve_sort_exprs_through_projection(&resolved_sort_exprs, proj)?;
+            }
+            LogicalPlan::SubqueryAlias(sq) => {
+                resolved_sort_exprs =
+                    
resolve_sort_exprs_through_subquery_alias(&resolved_sort_exprs, sq)?;
+            }
+            _ => {
+                return internal_err!(
+                    "push_topk_through_join: unexpected intermediate node: {}",
+                    node.display()
+                );
+            }
+        }
+    }
+
+    // After resolving through projections, sort expressions may now
+    // contain volatile functions (e.g. `random() AS col`). Duplicating
+    // them would change results.
+    if resolved_sort_exprs.iter().any(|se| se.expr.is_volatile()) {
+        return Ok(Transformed::no(plan));
+    }
+
+    // Pick the first preserved-side candidate whose schema contains all
+    // referenced sort columns. For LEFT/RIGHT this is the fixed side;
+    // for CROSS we try both.
+    let Some(preserved_side) = 
preserved_candidates.iter().copied().find(|&side| {
+        let schema = match side {
+            Side::Left => join.left.schema(),
+            Side::Right => join.right.schema(),
+        };
+        let cols = schema_columns(schema);
+        resolved_sort_exprs
+            .iter()
+            .all(|se| has_all_column_refs(&se.expr, &cols))

Review Comment:
   Addressed in a1bc5af2f45ced9e91fe9878834496659bb1b520



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

To unsubscribe, e-mail: [email protected]

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


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

Reply via email to