You are viewing a plain text version of this content. The canonical link for it is here.
Posted to gitbox@hive.apache.org by "Indhumathi27 (via GitHub)" <gi...@apache.org> on 2025/11/18 17:53:31 UTC

[PR] Draft: HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning [hive]

Indhumathi27 opened a new pull request, #6202:
URL: https://github.com/apache/hive/pull/6202

   
   
   ### What changes were proposed in this pull request?
   
   This PR updates TopNKeyProcessor to skip creating TopNKeyOperator when ReduceSinkDesc.topN is already set by LIMIT pushdown. This prevents TopNKey from overriding pushdown and ensures the map-side LIMIT optimization is applied correctly.
   
   
   ### Why are the changes needed?
   Currently, when a query includes ORDER BY + LIMIT, LIMIT pushdown is generated during planning but is effectively overridden by the subsequent TopNKey rewrite. As a result, TopNKey operator receives full input rather than a reduced data set, leading to worse performance (e.g., 16M rows forwarded to reducer instead of a few). In cases where global ordering uses a single reducer, LIMIT pushdown is sufficient and far more efficient. This fix prevents unnecessary TopNKey creation so that pushdown can reduce shuffle and significantly improve execution time.
   
   
   ### Does this PR introduce _any_ user-facing change?
   No
   
   ### How was this patch tested?
   Manual testing + existing testcases
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "okumin (via GitHub)" <gi...@apache.org>.
okumin commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2601529807


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -71,6 +71,13 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
       return null;
     }
 
+    // Skip the current optimization when a simple global ORDER BY...LIMIT is present
+    // (topN > -1 and hasOnlyOrderByLimit()).
+    // This plan structure is handled more efficiently by the specialized 'TopN In Reducer' optimization.
+    if (reduceSinkDesc.getTopN() > -1 && reduceSinkDesc.hasOnlyOrderByLimit()) {

Review Comment:
   I'm also curious about the two questions in [the JIRA ticket](https://issues.apache.org/jira/browse/HIVE-29322). I don't have an instant answer on whether it is optimal to reuse Top-N for the global sort. However, in my impression, it is at least suboptimal and might not be so bad.
   Disclaimer: My next response might not be timely because I have to visit a hospital every day.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2597042315


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/LimitPushdownOptimizer.java:
##########
@@ -117,18 +118,31 @@ private static class TopNReducer implements SemanticNodeProcessor {
     @Override
     public Object process(Node nd, Stack<Node> stack,
                           NodeProcessorCtx procCtx, Object... nodeOutputs) throws SemanticException {
+      boolean hasOnlyOrderByLimit = true;
       ReduceSinkOperator rs = null;
+      boolean shouldBreak = false;

Review Comment:
   done. refactored



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3692623262

   @zabetak @okumin Added the analysis in the jira. Please check


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2667114756


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -111,6 +123,50 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
     return null;
   }
 
+  /**
+   * Returns true if the ReduceSink is only under an ORDER BY + LIMIT plan
+   * and has no GroupBy or Join operators in its upstream ancestry.
+   * This is used to disable TopNKey for pure ORDER BY LIMIT queries where
+   * LIMIT pushdown must take precedence.
+   */
+  public static boolean isOrderByLimitPath(ReduceSinkOperator rs) {

Review Comment:
   i took an example from topnkey_windowing.q and generated more data to test this case.
   total rows: 3360768
   topNkey enabled: 116,736 rows selected (13.991 seconds)
   topNkey enabled: 116,736 rows selected (11.805 seconds)
   Note: Num of mappers and reducers are same
   
   with this example, i don't see much performance difference for PTF 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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2664769990


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -111,6 +123,50 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
     return null;
   }
 
+  /**
+   * Returns true if the ReduceSink is only under an ORDER BY + LIMIT plan
+   * and has no GroupBy or Join operators in its upstream ancestry.
+   * This is used to disable TopNKey for pure ORDER BY LIMIT queries where
+   * LIMIT pushdown must take precedence.
+   */
+  public static boolean isOrderByLimitPath(ReduceSinkOperator rs) {

Review Comment:
   If there is no GBY/JOIN below the RS (that is PTF) do we gain something by creating the TopNKey operator? In other words is the TopNKey operator more efficient than the topn filtering in the RS?



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2668499859


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -111,6 +123,50 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
     return null;
   }
 
+  /**
+   * Returns true if the ReduceSink is only under an ORDER BY + LIMIT plan
+   * and has no GroupBy or Join operators in its upstream ancestry.
+   * This is used to disable TopNKey for pure ORDER BY LIMIT queries where
+   * LIMIT pushdown must take precedence.
+   */
+  public static boolean isOrderByLimitPath(ReduceSinkOperator rs) {

Review Comment:
   the jira scope for this PR is for only order by limit queries. hence i haven't went deeper to check for PTF operators. based on the experiment, the performance seems same when topnkey enabled / disabled



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3720982527

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [1 New issue](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3708282134

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [1 New issue](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "deniskuzZ (via GitHub)" <gi...@apache.org>.
deniskuzZ commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2595392690


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/LimitPushdownOptimizer.java:
##########
@@ -117,18 +118,31 @@ private static class TopNReducer implements SemanticNodeProcessor {
     @Override
     public Object process(Node nd, Stack<Node> stack,
                           NodeProcessorCtx procCtx, Object... nodeOutputs) throws SemanticException {
+      boolean hasOnlyOrderByLimit = true;
       ReduceSinkOperator rs = null;
+      boolean shouldBreak = false;

Review Comment:
   Could you please rewrite code without the break flag



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2667951917


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1300,9 +1300,17 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
       return;
     }
 
+    // Restrict TopNKey matching to GROUP BY / JOIN ReduceSinks, except for PTF queries.
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+    String topNKeyRegexPattern = hasPTFReduceSink(procCtx) ? reduceSinkOp :
+            ".*(" + GroupByOperator.getOperatorName() + "|" +

Review Comment:
   Is it necessary to have the match any prefix `.*` at the beginning of the pattern?



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/LimitPushdownOptimizer.java:
##########
@@ -198,6 +198,11 @@ public Object process(Node nd, Stack<Node> stack,
           }
           currentOp = currentOp.getChildOperators().get(0);
         }
+        // Skip RS copy for plans that are already TopNKey-optimized to avoid re-propagating
+        // TopNKey configuration into the same ReduceSink.
+        if (((LimitPushdownContext)procCtx).disallowRSCopy && foundGroupByOperator) {

Review Comment:
   1. Can you provide an example of query/plan/qfile that necessitates this conditional? 
   2. Why do we need this conditional now and we didn't have it before?



##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();

Review Comment:
   Why do we need this? It is usually better if we can keep the optimization/transformation rules independent of the SQL syntax.



##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();
+
+    if (hasPTFReduceSink(procCtx) || !hasOrderOrLimit) {
+      return reduceSinkOp;
+    }
+
+    return "("
+            + GroupByOperator.getOperatorName() + "|"
+            + PTFOperator.getOperatorName() + "|"
+            + JoinOperator.getOperatorName() + "|"
+            + MapJoinOperator.getOperatorName() + "|"
+            + LateralViewJoinOperator.getOperatorName() + "|"
+            + CommonMergeJoinOperator.getOperatorName()
+            + ")"
+            + "(%("
+            + SelectOperator.getOperatorName() + "|"
+            + FilterOperator.getOperatorName()

Review Comment:
   Do we really care what operators are between the join/gby and the RS?



##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1330,15 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  private static boolean hasPTFReduceSink(OptimizeTezProcContext ctx) {
+    for (ReduceSinkOperator rs : ctx.visitedReduceSinks) {
+      if (rs.getConf().isPTFReduceSink()) {
+        return true;
+      }
+    }
+    return false;
+  }
+

Review Comment:
   Not sure if this achieves the desired outcome. Basically, if there is a PTF RS anywhere in the plan we will apply the rule on every RS (no matter if it is PTF or not). 
   
   Moreover, by relying on `ctx.visitedReduceSinks` we make the TopNKeyOptimization highly dependent on stats dependent optimization which is not great.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/LimitPushdownOptimizer.java:
##########
@@ -250,8 +255,12 @@ private static class LimitPushdownContext implements NodeProcessorCtx {
 
     private final float threshold;
 
+    private final boolean disallowRSCopy;
+
     public LimitPushdownContext(HiveConf conf) throws SemanticException {
       threshold = conf.getFloatVar(HiveConf.ConfVars.HIVE_LIMIT_PUSHDOWN_MEMORY_USAGE);
+      disallowRSCopy = conf.getBoolVar(HiveConf.ConfVars.HIVE_OPTIMIZE_TOPNKEY) &&
+              !conf.getBoolVar(HiveConf.ConfVars.HIVE_MAPSIDE_AGGREGATE);

Review Comment:
   Can you please explain how and why is this related to the TopNKey optimization and the map-side aggregation? The connection is not obvious for me.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2669030322


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/LimitPushdownOptimizer.java:
##########
@@ -250,8 +255,12 @@ private static class LimitPushdownContext implements NodeProcessorCtx {
 
     private final float threshold;
 
+    private final boolean disallowRSCopy;
+
     public LimitPushdownContext(HiveConf conf) throws SemanticException {
       threshold = conf.getFloatVar(HiveConf.ConfVars.HIVE_LIMIT_PUSHDOWN_MEMORY_USAGE);
+      disallowRSCopy = conf.getBoolVar(HiveConf.ConfVars.HIVE_OPTIMIZE_TOPNKEY) &&
+              !conf.getBoolVar(HiveConf.ConfVars.HIVE_MAPSIDE_AGGREGATE);

Review Comment:
   will remove these changes, as it is not required



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2669195772


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/LimitPushdownOptimizer.java:
##########
@@ -198,6 +198,11 @@ public Object process(Node nd, Stack<Node> stack,
           }
           currentOp = currentOp.getChildOperators().get(0);
         }
+        // Skip RS copy for plans that are already TopNKey-optimized to avoid re-propagating
+        // TopNKey configuration into the same ReduceSink.
+        if (((LimitPushdownContext)procCtx).disallowRSCopy && foundGroupByOperator) {

Review Comment:
   removed these changes. 



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2678912718


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();

Review Comment:
   I have debugged Windowing queries case and below is the observation.
   
   Testcase (unsorted data):
   `CREATE TABLE topnkey_windowing (tw_code string, tw_value double);
   
   INSERT INTO topnkey_windowing VALUES (NULL, NULL),(NULL, 109),('A', 109),('A', 104),('A', 110),('A', 120),('A', 103),('A', 109),('B', 105),('B', 106),('B', 106),('B', NULL),('B', 106),('A', 109);
   
   SELECT tw_code, ranking
   FROM (
     SELECT tw_code AS tw_code,
       rank() OVER (PARTITION BY tw_code ORDER BY tw_value) AS ranking
     FROM topnkey_windowing) tmp1
     WHERE ranking < 2;
   `
   With TopNkey enabled, 
   Map phase: Input records: 14 Output Records: 9
   With TopNkey disabled, 
   Map phase: Input records: 14 Output Records: 8
   Time Taken : both almost same.
   
   1. In PTF queries, TopNKey creates a separate TopNKeyFilter for every distinct PARTITION BY key and maintains an in-memory Top-N heap per partition.
   2. Each incoming row performs partition-key hashing, map lookup, and heap comparison to decide whether it belongs to that partition’s Top-N.
   3. Rows are eliminated when their sort key compares worse than the current Top-N boundary, so they are not inserted into the partition’s ordered Top-N set.
   4. For ORDER BY … LIMIT queries, TopNKey maintains only a single global Top-N heap per reducer.
   
   I have tested with low-cardinality, monotonic-ordered windowing dataset and high-cardinality, multi-row-per-partition PTF test dataset. In this case, behaviour is similar to ORDER by.. Limit queries, where all the rows are forwarded. But query performance degradation is not observed for PTF operator case, comparing with disabling topnKeyoperator. 
   One such example: 
   [ptf_testcase.txt](https://github.com/user-attachments/files/24545845/ptf_testcase.txt)
   
   From this experiments, with TopNkey enabled / disabled, performance is almost similar for Windowing queries.
   Disabling TopNkey for Windowing queries don't show a drastic difference in performance. Forwarding all rows in PTF TopNKey does not cause the catastrophic shuffle explosion seen in ORDER BY … LIMIT queries, because the shuffle and reducer stages are already needed for window partitioning.
   
   



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3713422325

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [1 New issue](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2668471028


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();
+
+    if (hasPTFReduceSink(procCtx) || !hasOrderOrLimit) {
+      return reduceSinkOp;
+    }
+
+    return "("
+            + GroupByOperator.getOperatorName() + "|"
+            + PTFOperator.getOperatorName() + "|"
+            + JoinOperator.getOperatorName() + "|"
+            + MapJoinOperator.getOperatorName() + "|"
+            + LateralViewJoinOperator.getOperatorName() + "|"
+            + CommonMergeJoinOperator.getOperatorName()
+            + ")"
+            + "(%("
+            + SelectOperator.getOperatorName() + "|"
+            + FilterOperator.getOperatorName()

Review Comment:
   yes. There are some pattern of group by queries, which will have SELECT in between.
   example:
   select sum(key) as sum from src group by concat(key,value,value,value,value,value,value,value,value,value) order by sum limit 100



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2655505625


##########
ql/src/test/results/clientpositive/llap/lateral_view.q.out:
##########
@@ -100,22 +90,17 @@ STAGE PLANS:
               Limit
                 Number of rows: 1
                 Statistics: Num rows: 1 Data size: 178 Basic stats: COMPLETE Column stats: COMPLETE
-                Top N Key Operator
-                  sort order: ++
-                  keys: KEY.reducesinkkey0 (type: string), KEY.reducesinkkey1 (type: int)
-                  null sort order: zz
+                Select Operator
+                  expressions: KEY.reducesinkkey0 (type: string), VALUE._col0 (type: string), KEY.reducesinkkey1 (type: int)
+                  outputColumnNames: _col0, _col1, _col2
                   Statistics: Num rows: 1 Data size: 178 Basic stats: COMPLETE Column stats: COMPLETE
-                  top n: 1
-                  Select Operator
-                    expressions: KEY.reducesinkkey0 (type: string), VALUE._col0 (type: string), KEY.reducesinkkey1 (type: int)
-                    outputColumnNames: _col0, _col1, _col2
+                  Reduce Output Operator
+                    key expressions: _col0 (type: string), _col2 (type: int)
+                    null sort order: zz
+                    sort order: ++
                     Statistics: Num rows: 1 Data size: 178 Basic stats: COMPLETE Column stats: COMPLETE
-                    Reduce Output Operator
-                      key expressions: _col0 (type: string), _col2 (type: int)
-                      null sort order: zz
-                      sort order: ++
-                      Statistics: Num rows: 1 Data size: 178 Basic stats: COMPLETE Column stats: COMPLETE
-                      value expressions: _col1 (type: string)
+                    TopN Hash Memory Usage: 0.1

Review Comment:
   When the plan contains a `Limit` operator all subsequent TopN optimizations in the same mapper/reducer seem redundant. It's out of scope of the current PR but it may be worth logging a separate JIRA ticket as a potential improvement.



##########
ql/src/java/org/apache/hadoop/hive/ql/plan/ReduceSinkDesc.java:
##########
@@ -141,6 +141,9 @@ private ReducerTraits(int trait) {
   // used to decide whether global order is needed
   private transient boolean hasOrderBy = false;
 
+  // used to decide whether topn key optimisation can be applied
+  private transient boolean hasOnlyOrderByLimit = false;

Review Comment:
   Do we really need this new indicator here? IT seems to be a hint about the structure of the plan rather than a property/quality of the `ReduceSink` operator.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -71,6 +71,13 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
       return null;
     }
 
+    // Skip the current optimization when a simple global ORDER BY...LIMIT is present
+    // (topN > -1 and hasOnlyOrderByLimit()).
+    // This plan structure is handled more efficiently by the specialized 'TopN In Reducer' optimization.
+    if (reduceSinkDesc.getTopN() > -1 && reduceSinkDesc.hasOnlyOrderByLimit()) {

Review Comment:
   It seems that we don't want to introduce a `TopNKeyOperator` if the path between TS and RS does not contain a JOIN or GBY operator. We can add such checks at some point here or maybe better modify the respective `RuleRegExp` to only trigger when there is a GBY or JOIN in the path.



##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/LimitPushdownOptimizer.java:
##########
@@ -117,18 +118,29 @@ private static class TopNReducer implements SemanticNodeProcessor {
     @Override
     public Object process(Node nd, Stack<Node> stack,
                           NodeProcessorCtx procCtx, Object... nodeOutputs) throws SemanticException {
+      boolean hasOnlyOrderByLimit = true;
       ReduceSinkOperator rs = null;
       for (int i = stack.size() - 2 ; i >= 0; i--) {
         Operator<?> operator = (Operator<?>) stack.get(i);
-        if (operator.getNumChild() != 1) {
-          return false; // multi-GBY single-RS (TODO)
-        }
-        if (operator instanceof ReduceSinkOperator) {
-          rs = (ReduceSinkOperator) operator;
-          break;
+
+        if (operator instanceof GroupByOperator || operator instanceof JoinOperator) {
+          hasOnlyOrderByLimit = false;

Review Comment:
   The decision to introduce or not a `TopNKeyOperator` is a responsibility of the the `TopNKeyProcessor` so if we need to make decisions based on the structure of the plan it makes more sense to do put the GBY/JOIN checks there.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] Draft: HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3586428689

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "deniskuzZ (via GitHub)" <gi...@apache.org>.
deniskuzZ commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2595392690


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/LimitPushdownOptimizer.java:
##########
@@ -117,18 +118,31 @@ private static class TopNReducer implements SemanticNodeProcessor {
     @Override
     public Object process(Node nd, Stack<Node> stack,
                           NodeProcessorCtx procCtx, Object... nodeOutputs) throws SemanticException {
+      boolean hasOnlyOrderByLimit = true;
       ReduceSinkOperator rs = null;
+      boolean shouldBreak = false;

Review Comment:
   Could you please rewrite code without the break flag
   ````
   if (op instanceof GroupByOperator || op instanceof JoinOperator) {
       hasOnlyOrderByLimit = false;
   
       if (rs != null) {
           break; // RS already seen → stop
       }
   
       // No RS yet, skip RS-handling for this iteration
   } else {
       // Case: not GBY/JOIN and RS not yet found
       if (rs == null) {
           if (op.getNumChild() != 1) {
               return false; // multi-GBY single-RS (TODO)
           }
   
           if (op instanceof ReduceSinkOperator) {
               rs = (ReduceSinkOperator) op;
           } else if (!op.acceptLimitPushdown()) {
               return false;
           }
       }
   }
   ````



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2705187020


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();

Review Comment:
   > PS. The content of the [ptf_testcase.txt](https://github.com/user-attachments/files/24545845/ptf_testcase.txt) file is identical wih the previous run. The screenshots show inputs with 51M rows but the content of the attachment is not aligned.
   
   i have used [ptf_testcase.txt](https://github.com/user-attachments/files/24545845/ptf_testcase.txt) schema and generated more data for testing. I have performed insert overwrite select from same table.
   
   > I don't understand to what we what exactly we refer to by saying global shuffle. I would also like some more clarifications about the "reducer fan-in"
   
   Since there is a partitioning key exist in case of PTF queries, each reducer only receives rows for the partitions it owns. In case of simple order by limit queries, all data will have to go to single reducer.
   
   > Since the number of input records to Reducer 2 differs when TopNKey is enabled and disabled what exactly do you mean that the fan-in is not affected?
   
   The comparison is for PTF queries Vs Simple Order by Limit queries, not PTF TopNkey enabled vs disabled.
   
   



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] Draft: HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3549209541

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2689820106


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();

Review Comment:
   Many thanks for the additional experiments for the PTF case. 
   
   > But query performance degradation is not observed for PTF operator case, comparing with disabling topnKeyoperator
   
   It's difficult to extract safe conclusions from the comparison between ORDER BY and windowing experiments cause dataset size and effective limit differ significantly.
   
   Dataset size:
   * for ORDER BY the dataset has ~10M rows
   * for windowing the dataset has 50K rows
   
   Effective limit/top-n filter:
   * for ORDER BY the limit is 100
   * for windowing the limit is ~6K
   
   It would be great if you can run some experiments where the numbers are closer.
    
   > Disabling TopNkey for Windowing queries don't show a drastic difference in performance
   
   I still believe that this depends on the use-case. The example that you crafted for ORDER BY was clearly showing the downsides of the Top-N operator. The answer/benchmarks above imply that this will never happen for windowing functions but I don't understand why.
   
   > because the shuffle and reducer stages are already needed for window partitioning.
   
   I don't fully understand the statement about the shuffle and reducer stages. Can you elaborate a bit more?



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2675903847


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1300,9 +1300,17 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
       return;
     }
 
+    // Restrict TopNKey matching to GROUP BY / JOIN ReduceSinks, except for PTF queries.
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+    String topNKeyRegexPattern = hasPTFReduceSink(procCtx) ? reduceSinkOp :
+            ".*(" + GroupByOperator.getOperatorName() + "|" +

Review Comment:
   Resolving this as it is not relevant on latest patch.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2668488039


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1300,9 +1300,17 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
       return;
     }
 
+    // Restrict TopNKey matching to GROUP BY / JOIN ReduceSinks, except for PTF queries.
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+    String topNKeyRegexPattern = hasPTFReduceSink(procCtx) ? reduceSinkOp :
+            ".*(" + GroupByOperator.getOperatorName() + "|" +

Review Comment:
   yes. Some queries with Group by not matching current Regex pattern without the prefix



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2669025866


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/LimitPushdownOptimizer.java:
##########
@@ -250,8 +255,12 @@ private static class LimitPushdownContext implements NodeProcessorCtx {
 
     private final float threshold;
 
+    private final boolean disallowRSCopy;
+
     public LimitPushdownContext(HiveConf conf) throws SemanticException {
       threshold = conf.getFloatVar(HiveConf.ConfVars.HIVE_LIMIT_PUSHDOWN_MEMORY_USAGE);
+      disallowRSCopy = conf.getBoolVar(HiveConf.ConfVars.HIVE_OPTIMIZE_TOPNKEY) &&
+              !conf.getBoolVar(HiveConf.ConfVars.HIVE_MAPSIDE_AGGREGATE);

Review Comment:
   For query: `select value, sum(key) as sum from src group by value order by value limit 20;`
   
   when hive.map.aggr is true, tree stack has GBY[2] - RS[3] - GBY[4] - RS[6]
   
   when hive.map.aggr is false, tree stack has RS[2] - GBY[2] - RS[5]
   RS[2] here is Reduce output operator
   Without patch: TopNkey will be applied for both operators.
   With patch: TopNkey will be applied only to RS[5] operator. 
   
   There is no impact without this changes as well. RS[2] will have some of configurations set, which comes in explain 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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2669025866


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/LimitPushdownOptimizer.java:
##########
@@ -250,8 +255,12 @@ private static class LimitPushdownContext implements NodeProcessorCtx {
 
     private final float threshold;
 
+    private final boolean disallowRSCopy;
+
     public LimitPushdownContext(HiveConf conf) throws SemanticException {
       threshold = conf.getFloatVar(HiveConf.ConfVars.HIVE_LIMIT_PUSHDOWN_MEMORY_USAGE);
+      disallowRSCopy = conf.getBoolVar(HiveConf.ConfVars.HIVE_OPTIMIZE_TOPNKEY) &&
+              !conf.getBoolVar(HiveConf.ConfVars.HIVE_MAPSIDE_AGGREGATE);

Review Comment:
   For query: `select value, sum(key) as sum from src group by value order by value limit 20;`
   
   when hive.map.aggr is true, tree stack has GBY[2] - RS[3] - GBY[4] - RS[6]
   
   when hive.map.aggr is false, tree stack has RS[2] - GBY[2] - RS[5]
   
   Without patch: TopNkey will be applied for both operators.
   With patch: TopNkey will be applied only to RS[5] operator. 
   
   There is no impact without this changes as well. RS[2] will have some of configurations set, which comes in explain 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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2660711052


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -111,6 +123,50 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
     return null;
   }
 
+  /**
+   * Returns true if the ReduceSink is only under an ORDER BY + LIMIT plan
+   * and has no GroupBy or Join operators in its upstream ancestry.
+   * This is used to disable TopNKey for pure ORDER BY LIMIT queries where
+   * LIMIT pushdown must take precedence.
+   */
+  public static boolean isOrderByLimitPath(ReduceSinkOperator rs) {

Review Comment:
   I have a feeling that the traversal logic here could be skipped by properly setting up the `RuleRegExp` in `org.apache.hadoop.hive.ql.parse.TezCompiler#runTopNKeyOptimization`.
   
   Something like:
   ```java
   new RuleRegExp("Top n key optimization", "(GBY%|JOIN%).*RS%")
   ```
   The expression above is not tested but I have the impression that with some tuning we can get the desired matching scope.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3712390913

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [1 New issue](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2668539128


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1330,15 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  private static boolean hasPTFReduceSink(OptimizeTezProcContext ctx) {
+    for (ReduceSinkOperator rs : ctx.visitedReduceSinks) {
+      if (rs.getConf().isPTFReduceSink()) {
+        return true;
+      }
+    }
+    return false;
+  }
+

Review Comment:
   For windowing queries, since there is not much performance issues with TopNKey enabled, currently making the queries to use TopNkey Path. But to match the plan, there is no sequence of PTF%RS% patterns for some queries. only RS% will work for this case. 
   I chosed this approach, to avoid traversing the tree to check query has PTF operator.
   can you suggest a solution for the windowing queries



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2704788943


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();

Review Comment:
   Based on the screenshots of the dataset with 51M rows we have:
   ### TopNKey enabled
   #### Map 1:
   * INPUT_RECORDS: 51,193,885
   * OUTPUT_RECORDS: 72,272,499
   #### Reducer 2:
   * INPUT_RECORDS: 72,272,499
   
   ### TopNKey disabled
   #### Map 1:
   * INPUT_RECORDS: 51,193,885
   * OUTPUT_RECORDS: 6,144,000
   #### Reducer 2:
   * INPUT_RECORDS: 6,144,000
   
   There is a significant difference in the number of OUTPUT_RECORDS from Map 1 when the TopNKey is enabled/disabled. The same goes for the INPUT_RECORDS to Reducer 2. Is this difference negligible in terms of performance?
   
   > TopNKey operates per partition and, even when it forwards most or all rows, it does not introduce additional global shuffle or change the reducer fan-in.
   
   I don't understand to what we what exactly we refer to by saying **global** shuffle. I would also like some more clarifications about the "reducer fan-in". Since the number of input records to Reducer 2 differs when TopNKey is enabled and disabled what exactly do you mean that the fan-in is not affected?
   
   PS. The content of the [ptf_testcase.txt](https://github.com/user-attachments/files/24545845/ptf_testcase.txt) file is identical wih the previous run. The screenshots show inputs with 51M rows but the content of the attachment is not aligned.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2705187020


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();

Review Comment:
   i have used schema and generated more data for testing. I have performed insert overwrite select from same table.
   Since there is a partitioning key exist in case of PTF queries, each reducer only receives rows for the partitions it owns. In case of simple order by limit queries, all data will go to single reducer.
   
   > Since the number of input records to Reducer 2 differs when TopNKey is enabled and disabled what exactly do you mean that the fan-in is not affected?
   
   The comparison is for PTF queries Vs Simple Order by Limit queries, not PTF TopNkey enabled vs disabled.
   
   



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2705203218


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();

Review Comment:
   Even though less records are pushed down to Reducer for PTF queries TopNkey enabled vs disabled, both are finishing in more or less same time



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3707095881

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [1 New issue](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-4240536984

   This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.
   Feel free to reach out on the dev@hive.apache.org list if the patch is in need of reviews.


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2660249810


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -71,6 +71,13 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
       return null;
     }
 
+    // Skip the current optimization when a simple global ORDER BY...LIMIT is present
+    // (topN > -1 and hasOnlyOrderByLimit()).
+    // This plan structure is handled more efficiently by the specialized 'TopN In Reducer' optimization.
+    if (reduceSinkDesc.getTopN() > -1 && reduceSinkDesc.hasOnlyOrderByLimit()) {

Review Comment:
   @zabetak I have handled in TopNKeyProcessor to disable TopNkey for cases without JOIN/GROUP BY. can you look at the changes



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2678912718


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();

Review Comment:
   I have debugged Windowing queries case and below is the observation.
   
   Testcase (unsorted data):
   `CREATE TABLE topnkey_windowing (tw_code string, tw_value double);
   
   INSERT INTO topnkey_windowing VALUES (NULL, NULL),(NULL, 109),('A', 109),('A', 104),('A', 110),('A', 120),('A', 103),('A', 109),('B', 105),('B', 106),('B', 106),('B', NULL),('B', 106),('A', 109);
   
   SELECT tw_code, ranking
   FROM (
     SELECT tw_code AS tw_code,
       rank() OVER (PARTITION BY tw_code ORDER BY tw_value) AS ranking
     FROM topnkey_windowing) tmp1
     WHERE ranking < 2;
   `
   With TopNkey enabled, 
   Map phase: Input records: 14 Output Records: 9
   With TopNkey disabled, 
   Map phase: Input records: 14 Output Records: 8
   Time Taken : both almost same.
   
   1. In PTF queries, TopNKey creates a separate TopNKeyFilter for every distinct PARTITION BY key and maintains an in-memory Top-N heap per partition.
   2. Each incoming row performs partition-key hashing, map lookup, and heap comparison to decide whether it belongs to that partition’s Top-N.
   3. Rows are eliminated when their sort key compares worse than the current Top-N boundary, so they are not inserted into the partition’s ordered Top-N set.
   4. For ORDER BY … LIMIT queries, TopNKey maintains only a single global Top-N heap per reducer.
   
   I have tested with low-cardinality, monotonic-ordered windowing dataset and high-cardinality, multi-row-per-partition PTF test dataset. In this case, behaviour is similar to ORDER by.. Limit queries, where all the rows are forwarded. But query performance degradation is not observed for PTF operator case, comparing with disabling topnKeyoperator. 
   One such example: 
   [ptf_testcase.txt](https://github.com/user-attachments/files/24545845/ptf_testcase.txt)
   
   
   



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2683135646


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1300,9 +1302,10 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
       return;
     }
 
+    String topNKeyRegexPattern = buildTopNKeyRegexPattern(procCtx);
     Map<SemanticRule, SemanticNodeProcessor> opRules = new LinkedHashMap<SemanticRule, SemanticNodeProcessor>();
     opRules.put(
-        new RuleRegExp("Top n key optimization", ReduceSinkOperator.getOperatorName() + "%"),
+        new RuleRegExp("Top n key optimization", topNKeyRegexPattern),

Review Comment:
   i agree on this. @zabetak please provide your view on this. Thanks



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3626419979

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2760082186


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();

Review Comment:
   Many thanks for the additional results @Indhumathi27 they offer valuable insights that can definitely help us to push this work forward. 
   
   Looking into the results there is one particular case (i.e., "Sorted DESC") where TopNKey ON leads to rather bad pruning & performance but I am not sure if we should base our decision to disable the optimization on this sole scenario. Another interesting case is "Duplicate + Random" where despite the fact that we are sending 2.4M records from the mapper to reducer when TopNKey is ON the "Map Time" is lower than when TopNKey is OFF and the overall response time of the query is identical. Worth mentioning that the "ineffective" pruning on the mapper (2.4M vs 700) didn't affect significantly the Map/Reduce time that makes me skeptical of shifting the focus to data pruning. 
   
   Overall, I feel that we should run more experiments to cover some additional distributions in order to take a more informed decision regarding this optimization. Below I outline a few suggestions on the experimental setup for making the analysis more systematic and potentially help in extracting better conclusions.
   
   First of all, I would suggest to create a dedicated GitHub repository (e.g., https://github.com/Indhumathi27/HIVE-29322) for holding all the details around these set of experiments including setup scripts, raw results, runtime counters, and analysis results. Apart from the code changes, you have put a tremendous effort on these benchmarks so it would be nice to conclude the work with a nice blog post/article that summarizes our findings in this area. If you are interested, I would be more than happy in helping out writing it. 
   
   Staring out with the dataset, there are two important factors that we should consider: i) distribution and ii) layout. 
   
   For the distribution, we should test the following: Zipfian, and a few uniform ordinal distributions. For the uniform distributions, we can pick 3 variants for varying the pruning efficiency (best, worst, borderline). In order to pick the domain size (D) for the uniform distributions we can use the following formula: 
   ```
   D = N / (ρK)
   ```
   where N is the total number of rows, K the limit, and ρ the pruning difficulty. I think for this set of experiments we can keep N and K stable and vary `ρ ∈ {0.01, 1, 10}`. So with N=10M and K=100 the domain size for the three uniform distributions is 10M, 100K, 10K. In the latest run, you also covered a few more degenerate cases like `ρ=100` and `ρ=100K` where D is essentially 1 (constant) that we can still keep but are less important in terms of realistic use-cases.
   Having a Zipfian distribution, is a must since real data are usually skewed and many real use-cases fall into this category.
   
   For the layout, we basically have two options: random, and sorted. For the sorted layout we don't really need both ASC and DESC since we can take the direction into account in the query itself. 
   ```sql
   Q1: select * from seg1_orc order by h asc limit 100;
   Q2: select * from seg1_orc order by h desc limit 100;
   ```
   Having multiple queries with different sort direction is easier to follow than having multiple datasets.
   
   For the simple ORDER BY experiments it is rather safe to focus exclusively on the distributions of the scoring column (i.e., `h`). However, for the window queries (PTF) the partitioning column (`a`) is important as well:
   
   ```sql
   SELECT a,ranking
   FROM (
     SELECT
       a,
       h,
       RANK() OVER (PARTITION BY a ORDER BY h) AS ranking
     FROM seg1_orc
   ) tmp
   WHERE ranking <= 3;
   ``` 
   The width of the table (number of columns) and how many of those are returned to the user does not affect the pruning behavior but definitely has an impact on processing/response time for each operator. Since in the ORDER BY experiments we return all columns for keeping things consistent we should do the same for the window query. 
   
   Finally, there are various caching layers that can have an impact on the operator execution time so I would suggest to run each query multiple times (min 3) for reporting the results. Apart from the aggregated results please keep somewhere the raw results so that we can inspect them later on if needed.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3716807138

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [1 New issue](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2664585126


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -111,6 +123,50 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
     return null;
   }
 
+  /**
+   * Returns true if the ReduceSink is only under an ORDER BY + LIMIT plan
+   * and has no GroupBy or Join operators in its upstream ancestry.
+   * This is used to disable TopNKey for pure ORDER BY LIMIT queries where
+   * LIMIT pushdown must take precedence.
+   */
+  public static boolean isOrderByLimitPath(ReduceSinkOperator rs) {

Review Comment:
   @zabetak i am trying to use Regexp pattern to enable / disable topnKey. For cases like PTF, it won't follow a pattern along with RS. we can't use Regexp for this case. we have to iterate over the tree to check for PTF operators and use **RS%** as a regexp for this.
   
   something like, **hasPTFOperators** ? **RS%** : .*(GBY|JOIN|MAPJOIN|MERGEJOIN)%.*RS%
   what's your take on this?
   



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2675850724


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -111,6 +123,50 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
     return null;
   }
 
+  /**
+   * Returns true if the ReduceSink is only under an ORDER BY + LIMIT plan
+   * and has no GroupBy or Join operators in its upstream ancestry.
+   * This is used to disable TopNKey for pure ORDER BY LIMIT queries where
+   * LIMIT pushdown must take precedence.
+   */
+  public static boolean isOrderByLimitPath(ReduceSinkOperator rs) {

Review Comment:
   I understand that performance issue was observed on rather simple queries but the problem seems more general than that and goes beyond the SQL syntax. Since the PR changes how TopN optimizations are performed its important to understand the performance impact for interleaved operators in order to come up with a complete solution.
   
   The PR essentially redefines when the TopNKeyOptimization should be performed so we cannot really say that PTF operators are out-of-scope since there are code changes that explicitly target those.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2675901598


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();

Review Comment:
   ```sql
   select * 
   from ( select p_mfgr, rank() over(partition by p_mfgr order by p_name) r from part) a 
   where r < 4;
   ```
   Should such queries use the `Top N Key Operator`? 
   
   #### Plan A: With Top N Key Operator
   ```
           Map 1 
               Map Operator Tree:
                   TableScan
                     alias: part
                     Statistics: Num rows: 26 Data size: 5694 Basic stats: COMPLETE Column stats: COMPLETE
                     Top N Key Operator
                       sort order: ++
                       keys: p_mfgr (type: string), p_name (type: string)
                       null sort order: az
                       Map-reduce partition columns: p_mfgr (type: string)
                       Statistics: Num rows: 26 Data size: 5694 Basic stats: COMPLETE Column stats: COMPLETE
                       top n: 4
                       Reduce Output Operator
                         key expressions: p_mfgr (type: string), p_name (type: string)
                         null sort order: az
                         sort order: ++
                         Map-reduce partition columns: p_mfgr (type: string)
                         Statistics: Num rows: 26 Data size: 5694 Basic stats: COMPLETE Column stats: COMPLETE
   ```
   #### Plan B: Without Top N Key Operator
   ```
           Map 1 
               Map Operator Tree:
                   TableScan
                     alias: part
                     Statistics: Num rows: 26 Data size: 5694 Basic stats: COMPLETE Column stats: COMPLETE
                     Reduce Output Operator
                       key expressions: p_mfgr (type: string), p_name (type: string)
                       null sort order: az
                       sort order: ++
                       Map-reduce partition columns: p_mfgr (type: string)
                       Statistics: Num rows: 26 Data size: 5694 Basic stats: COMPLETE Column stats: COMPLETE
                       TopN Hash Memory Usage: 0.8
   ```
   The plan structure is almost identical to the case of ORDER BY + LIMIT queries so from the discussion so far, I was under the impression that "Plan B" is better and more efficient in most 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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "okumin (via GitHub)" <gi...@apache.org>.
okumin commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2681084252


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1300,9 +1302,10 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
       return;
     }
 
+    String topNKeyRegexPattern = buildTopNKeyRegexPattern(procCtx);
     Map<SemanticRule, SemanticNodeProcessor> opRules = new LinkedHashMap<SemanticRule, SemanticNodeProcessor>();
     opRules.put(
-        new RuleRegExp("Top n key optimization", ReduceSinkOperator.getOperatorName() + "%"),
+        new RuleRegExp("Top n key optimization", topNKeyRegexPattern),

Review Comment:
   I slightly suppose this level of complicated bailout should happen in [TopNKeyProcessor](https://github.com/apache/hive/blob/25e58308970f2855e8c017150096cae28c4a7f17/ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java#L70-L102). Most likely, can we skip adding a TopNKeyOperator when the RSO is not a PTFReduceSink and RSO's ancestors don't include RSO?



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2665553047


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -111,6 +123,50 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
     return null;
   }
 
+  /**
+   * Returns true if the ReduceSink is only under an ORDER BY + LIMIT plan
+   * and has no GroupBy or Join operators in its upstream ancestry.
+   * This is used to disable TopNKey for pure ORDER BY LIMIT queries where
+   * LIMIT pushdown must take precedence.
+   */
+  public static boolean isOrderByLimitPath(ReduceSinkOperator rs) {

Review Comment:
   HIVE-22666 is in general useful but here the question is for the specific case where we don't have GBY/JOIN below the RS (PTF).



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2665854600


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/LimitPushdownOptimizer.java:
##########
@@ -198,6 +198,11 @@ public Object process(Node nd, Stack<Node> stack,
           }
           currentOp = currentOp.getChildOperators().get(0);
         }
+        // Skip RS copy for plans that are already TopNKey-optimized to avoid re-propagating
+        // TopNKey configuration into the same ReduceSink.
+        if (((LimitPushdownContext)procCtx).disallowRSCopy && foundGroupByOperator) {

Review Comment:
   This check is added to avoid propagating RS in case of RS-GB-RS, where RS1 is already TopNkey optimized. 



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3627210971

   I left some questions under the JIRA ticket to better understand the issue that we are trying to solve 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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3597292151

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2668882660


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();

Review Comment:
   this is added for windowing queries to use topNkey Path - without group by / join in the query.
   example: windowing_streaming.q
   `select * 
   from ( select p_mfgr, rank() over(partition by p_mfgr order by p_name) r from part) a 
   where r < 4`
   



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2669204164


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1330,15 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  private static boolean hasPTFReduceSink(OptimizeTezProcContext ctx) {
+    for (ReduceSinkOperator rs : ctx.visitedReduceSinks) {
+      if (rs.getConf().isPTFReduceSink()) {
+        return true;
+      }
+    }
+    return false;
+  }
+

Review Comment:
   is it a better solution to traverse the tree to find PTF ?



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2689853193


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1300,9 +1302,10 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
       return;
     }
 
+    String topNKeyRegexPattern = buildTopNKeyRegexPattern(procCtx);
     Map<SemanticRule, SemanticNodeProcessor> opRules = new LinkedHashMap<SemanticRule, SemanticNodeProcessor>();
     opRules.put(
-        new RuleRegExp("Top n key optimization", ReduceSinkOperator.getOperatorName() + "%"),
+        new RuleRegExp("Top n key optimization", topNKeyRegexPattern),

Review Comment:
   As mentioned in https://github.com/apache/hive/pull/6202/changes#r2675925598 before talking about how to implement a change we need to understand what change we need to perform and if the change is needed.
   
   The question if we should add or not a TopNKeyOperator below a windowing (PTF) ReduceSink remains open. Let's finalize the discussion in https://github.com/apache/hive/pull/6202/changes#r2668127719 and then we can can come back to this.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2729107754


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();

Review Comment:
   Thanks for the feedback — it helped clarify the gaps in the earlier comparison.
   
   My previous runs used different datasets for ORDER BY and PTF, so I re-ran all tests on the same 16M-row dataset and attached the reports here. With this setup, PTF also shows a clear regression with TopNKey enabled for DESC-sorted data:
   
   PTF Sorted-DESC
   TopNKey ON → Map output = 16M, Time = 26.6s
   TopNKey OFF → Map output = 4, Time = 13.6s
   
   In this case, TopNKey cannot prune at the map side, which blocks ReduceSink pruning and forces all rows to be shuffled by partition. This aligns with the observation that performance depends on how much the mapper can reduce before the shuffle: for ORDER BY the reduction is very large, and for PTF it is smaller in many cases, but for DESC-sorted input it drops to ~1× (no pruning), which explains the visible slowdown.
   
   I’ve attached the full 16M-row reports for both ORDER BY and PTF. 
   [TopNkeyTest.txt](https://github.com/user-attachments/files/24867674/TopNkeyTest.txt)
   [TopNkeyTest_ptf.txt](https://github.com/user-attachments/files/24867678/TopNkeyTest_ptf.txt)
   
   I’d appreciate your thoughts on how you’d like to proceed based on these results. Happy to run more experiments or adjust the patch based on your recommendation.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2675925598


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1330,15 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  private static boolean hasPTFReduceSink(OptimizeTezProcContext ctx) {
+    for (ReduceSinkOperator rs : ctx.visitedReduceSinks) {
+      if (rs.getConf().isPTFReduceSink()) {
+        return true;
+      }
+    }
+    return false;
+  }
+

Review Comment:
   I am not sure to what extend the claim that "there is not much performance issues with TopNKey enabled" holds. As mentioned in other comments first we have to confirm when/if TopNKey is efficient for PTF reducers and then decide to skip or not.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3596979559

   @kasakrisz @deniskuzZ Can you help to review this PR. Thanks


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "deniskuzZ (via GitHub)" <gi...@apache.org>.
deniskuzZ commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2595404436


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -71,6 +71,13 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
       return null;
     }
 
+    // Skip the current optimization when a simple global ORDER BY...LIMIT is present
+    // (topN > -1 and hasOnlyOrderByLimit()).
+    // This plan structure is handled more efficiently by the specialized 'TopN In Reducer' optimization.
+    if (reduceSinkDesc.getTopN() > -1 && reduceSinkDesc.hasOnlyOrderByLimit()) {

Review Comment:
   WDYT @zabetak, @kasakrisz , @okumin, @ngsg   



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2800027509


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();

Review Comment:
   @zabetak Many thanks for the detailed feedback and helpful suggestions — they provide a very clear direction for improving the evaluation. At the moment I am a bit limited in bandwidth, but I plan to take this up and extend the experimental setup along the proposed lines when I have more time. Thanks again for the valuable input and the offer to collaborate on the write-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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2660249810


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -71,6 +71,13 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
       return null;
     }
 
+    // Skip the current optimization when a simple global ORDER BY...LIMIT is present
+    // (topN > -1 and hasOnlyOrderByLimit()).
+    // This plan structure is handled more efficiently by the specialized 'TopN In Reducer' optimization.
+    if (reduceSinkDesc.getTopN() > -1 && reduceSinkDesc.hasOnlyOrderByLimit()) {

Review Comment:
   @zabetak I have handled in TopNKeyProcessor to disable TopNkey for cases without JOIN/GROUP BY. can you look at the changes. Thanks



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2696786118


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();

Review Comment:
   > It would be great if you can run some experiments where the numbers are closer.
   
   Below are the number's with more data.
   Total rows: 51200000
   Dataset: Mixed Partition data
   Table schema and query: [ptf_testcase.txt](https://github.com/user-attachments/files/24545845/ptf_testcase.txt)
   
   With TopNkey enabled:
   <img width="967" height="491" alt="Screenshot 2026-01-16 at 9 14 54 AM" src="https://github.com/user-attachments/assets/77ca5a34-a604-4dc4-8a49-4c540d07a391" />
   
   
   With TopNkey disabled:
   <img width="967" height="491" alt="Screenshot 2026-01-16 at 9 13 50 AM" src="https://github.com/user-attachments/assets/bd1a9ecc-0b28-47f0-9de3-4b2a121f5113" />
   
   
   > I don't fully understand the statement about the shuffle and reducer stages. Can you elaborate a bit more?
   
   For PTF (windowing) queries, the shuffle and reducer stages are required to group rows by the PARTITION BY key before window functions can be evaluated. TopNKey operates per partition and, even when it forwards most or all rows, it does not introduce additional global shuffle or change the reducer fan-in.
   
   In contrast, for ORDER BY … LIMIT queries, TopNKey maintains a single global Top-N heap and can disable ReduceSink-level Top-N pruning; when input data is unsorted, this causes all rows to be shuffled globally, leading to severe performance degradation.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2711328802


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();

Review Comment:
   The description and analysis under HIVE-29322 imply that the performance difference with/without `TopNKeyOperator` is directly related to the number of records pruned by the mapper and processed by the reducer. It's not clear why the number of records matters for simple ORDER BY queries and does not matter for simple windowing queries.
   
   In the runs with ORDER BY the 16M INPUT_RECORDS  were pruned down to 100 OUTPUT_RECORDS. The decrease is ~**100,000** smaller.
   In the runs with window functions the 51M INPUT_RECORDS were pruned down 6M OUTPUT_RECORDS. The decrease is only ~**10** smaller. 
   
   I suspect that there is no visible different in performance because the reduction factor is still very different between the experiments.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3625168472

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3615358808

   @ayushtkn @zabetak @kasakrisz @deniskuzZ Can you help to review the PR. thanks


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "deniskuzZ (via GitHub)" <gi...@apache.org>.
deniskuzZ commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2595404436


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -71,6 +71,13 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
       return null;
     }
 
+    // Skip the current optimization when a simple global ORDER BY...LIMIT is present
+    // (topN > -1 and hasOnlyOrderByLimit()).
+    // This plan structure is handled more efficiently by the specialized 'TopN In Reducer' optimization.
+    if (reduceSinkDesc.getTopN() > -1 && reduceSinkDesc.hasOnlyOrderByLimit()) {

Review Comment:
   WDYT @zabetak, @kasakrisz , @thomasrebele,  @okumin, @ngsg   



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "deniskuzZ (via GitHub)" <gi...@apache.org>.
deniskuzZ commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2595404436


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -71,6 +71,13 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
       return null;
     }
 
+    // Skip the current optimization when a simple global ORDER BY...LIMIT is present
+    // (topN > -1 and hasOnlyOrderByLimit()).
+    // This plan structure is handled more efficiently by the specialized 'TopN In Reducer' optimization.
+    if (reduceSinkDesc.getTopN() > -1 && reduceSinkDesc.hasOnlyOrderByLimit()) {

Review Comment:
   cc @zabetak, @kasakrisz  



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3707331011

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [1 New issue](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2665500915


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -111,6 +123,50 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
     return null;
   }
 
+  /**
+   * Returns true if the ReduceSink is only under an ORDER BY + LIMIT plan
+   * and has no GroupBy or Join operators in its upstream ancestry.
+   * This is used to disable TopNKey for pure ORDER BY LIMIT queries where
+   * LIMIT pushdown must take precedence.
+   */
+  public static boolean isOrderByLimitPath(ReduceSinkOperator rs) {

Review Comment:
   it might perform better because of [HIVE-22666](https://issues.apache.org/jira/browse/HIVE-22666).



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] closed pull request #6202: HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries
URL: https://github.com/apache/hive/pull/6202


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When Map-Side LIMIT Pushdown Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6202:
URL: https://github.com/apache/hive/pull/6202#issuecomment-3598657906

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [5 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6202&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6202&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6202&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6202)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2668171523


##########
ql/src/java/org/apache/hadoop/hive/ql/optimizer/topnkey/TopNKeyProcessor.java:
##########
@@ -111,6 +123,50 @@ public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
     return null;
   }
 
+  /**
+   * Returns true if the ReduceSink is only under an ORDER BY + LIMIT plan
+   * and has no GroupBy or Join operators in its upstream ancestry.
+   * This is used to disable TopNKey for pure ORDER BY LIMIT queries where
+   * LIMIT pushdown must take precedence.
+   */
+  public static boolean isOrderByLimitPath(ReduceSinkOperator rs) {

Review Comment:
   Thanks for running the experiments. Ideally, it would be nice if we could have a theoretical claim that shows that TopNKeyOptimization is useful or not when we have simple (no GBY/JOIN etc) plan branches similarly to the analysis that we did in the JIRA ticket for the ORDER BY LIMIT use-case.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29322: Avoid TopNKeyOperator When ReduceSink TopNkey Filtering Provides Better Pruning for ORDER BY LIMIT Queries [hive]

Posted by "Indhumathi27 (via GitHub)" <gi...@apache.org>.
Indhumathi27 commented on code in PR #6202:
URL: https://github.com/apache/hive/pull/6202#discussion_r2669193385


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/TezCompiler.java:
##########
@@ -1322,6 +1325,54 @@ private static void runTopNKeyOptimization(OptimizeTezProcContext procCtx)
     ogw.startWalking(topNodes, null);
   }
 
+  /*
+   * Build the ReduceSink matching pattern used by TopNKey optimization.
+   *
+   * For ORDER BY / LIMIT queries that do not involve GROUP BY or JOIN,
+   * applying TopNKey results in a performance regression. ReduceSink
+   * operators created only for ordering must therefore be excluded from
+   * TopNKey.
+   *
+   * When ORDER BY or LIMIT is present, restrict TopNKey to ReduceSink
+   * operators that originate from GROUP BY, JOIN, MAPJOIN, LATERAL VIEW
+   * JOIN or PTF query shapes. SELECT and FILTER operators may appear in
+   * between.
+   */
+  private static String buildTopNKeyRegexPattern(OptimizeTezProcContext procCtx) {
+    String reduceSinkOp = ReduceSinkOperator.getOperatorName() + "%";
+
+    boolean hasOrderOrLimit =
+            procCtx.parseContext.getQueryProperties().hasLimit() ||
+                    procCtx.parseContext.getQueryProperties().hasOrderBy();
+
+    if (hasPTFReduceSink(procCtx) || !hasOrderOrLimit) {
+      return reduceSinkOp;
+    }
+
+    return "("
+            + GroupByOperator.getOperatorName() + "|"
+            + PTFOperator.getOperatorName() + "|"
+            + JoinOperator.getOperatorName() + "|"
+            + MapJoinOperator.getOperatorName() + "|"
+            + LateralViewJoinOperator.getOperatorName() + "|"
+            + CommonMergeJoinOperator.getOperatorName()
+            + ")"
+            + "(%("
+            + SelectOperator.getOperatorName() + "|"
+            + FilterOperator.getOperatorName()

Review Comment:
   modified the pattern to any 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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org