You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@impala.apache.org by mi...@apache.org on 2026/10/02 16:22:29 UTC

(impala) branch master updated: IMPALA-7996: Optimize constant-false outer joins

This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/impala.git


The following commit(s) were added to refs/heads/master by this push:
     new 59ef46a6c IMPALA-7996: Optimize constant-false outer joins
59ef46a6c is described below

commit 59ef46a6ca0dc6867924005436e79352992e7159
Author: Aleksandr Efimov <dz...@gmail.com>
AuthorDate: Fri Jul 17 18:59:51 2026 +0300

    IMPALA-7996: Optimize constant-false outer joins
    
    Constant FALSE or NULL ON conjuncts eliminate usable equi-join
    predicates during expression rewriting. The classic planner then
    chooses a nested-loop join although the join cannot produce a match.
    
    Add a synthetic non-matching hash predicate for outer joins and drop
    redundant remaining ON conjuncts. The predicate is what keeps this a
    hash join: left where the analyzer put it, among the other conjuncts,
    the FALSE leaves the planner choosing a nested loop join, and the
    constant buys nothing. Replace the non-preserved input of
    left and right outer joins with EmptySetNode.
    
    Broadcast the empty build for constant-false left outer joins, even
    with a SHUFFLE hint. Invert right outer joins so their empty input also
    becomes the broadcast build. Keep full outer joins partitioned and use
    random distribution on both inputs to avoid constant-key skew.
    
    Add planner coverage for single-node and distributed plans with
    literal, folded, and typed NULL predicates. Add query tests with
    constant inline views to verify preserved-side row counts.
    
    Change-Id: I6505825fc958720eec12e13d546661834f221b80
    Assisted-by: gpt-5.6-sol (OpenAI Codex)
    Reviewed-on: http://gerrit.cloudera.org:8080/24597
    Reviewed-by: Impala Public Jenkins <im...@cloudera.com>
    Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
 .../apache/impala/planner/DistributedPlanner.java  | 33 ++++++--
 .../org/apache/impala/planner/HashJoinNode.java    | 17 ++++
 .../java/org/apache/impala/planner/Planner.java    | 18 +++--
 .../apache/impala/planner/SingleNodePlanner.java   | 54 ++++++++++++-
 .../queries/PlannerTest/empty.test                 | 90 ++++++++++++++++------
 .../queries/QueryTest/outer-joins.test             | 34 +++++++-
 6 files changed, 210 insertions(+), 36 deletions(-)

diff --git a/fe/src/main/java/org/apache/impala/planner/DistributedPlanner.java b/fe/src/main/java/org/apache/impala/planner/DistributedPlanner.java
index 037a1e920..ff9163664 100644
--- a/fe/src/main/java/org/apache/impala/planner/DistributedPlanner.java
+++ b/fe/src/main/java/org/apache/impala/planner/DistributedPlanner.java
@@ -497,6 +497,7 @@ public class DistributedPlanner {
       List<Expr> lhsJoinExprs, List<Expr> rhsJoinExprs,
       List<PlanFragment> fragments) throws ImpalaException {
     Preconditions.checkState(node.getDistributionMode() == DistributionMode.PARTITIONED);
+    boolean useRandomPartitioning = node.isConstantFalseOuterJoin();
     // The lhs and rhs input fragments are already partitioned on the join exprs.
     // Combine the lhs/rhs input fragments into leftChildFragment by placing the join
     // node into leftChildFragment and setting its lhs/rhs children to the plan root of
@@ -506,7 +507,7 @@ public class DistributedPlanner {
     // may reject partitions that could be made physically compatible. Fix this by
     // removing equivalent duplicates from partition exprs and impose a canonical order
     // on partition exprs (both using the canonical equivalence class representatives).
-    if (lhsHasCompatPartition
+    if (!useRandomPartitioning && lhsHasCompatPartition
         && rhsHasCompatPartition
         && isCompatPartition(
             leftChildFragment.getDataPartition(),
@@ -532,7 +533,7 @@ public class DistributedPlanner {
     // ExchangeNode that is fed by the rhsInputFragment whose sink repartitions
     // its data by the rhs join exprs.
     DataPartition rhsJoinPartition = null;
-    if (lhsHasCompatPartition) {
+    if (!useRandomPartitioning && lhsHasCompatPartition) {
       rhsJoinPartition = getCompatPartition(lhsJoinExprs,
           leftChildFragment.getDataPartition(), rhsJoinExprs, analyzer);
       if (rhsJoinPartition != null) {
@@ -546,7 +547,7 @@ public class DistributedPlanner {
 
     // Same as above but with rhs and lhs reversed.
     DataPartition lhsJoinPartition = null;
-    if (rhsHasCompatPartition) {
+    if (!useRandomPartitioning && rhsHasCompatPartition) {
       lhsJoinPartition = getCompatPartition(rhsJoinExprs,
           rightChildFragment.getDataPartition(), lhsJoinExprs, analyzer);
       if (lhsJoinPartition != null) {
@@ -560,15 +561,23 @@ public class DistributedPlanner {
 
     Preconditions.checkState(lhsJoinPartition == null);
     Preconditions.checkState(rhsJoinPartition == null);
-    lhsJoinPartition = DataPartition.hashPartitioned(Expr.cloneList(lhsJoinExprs));
-    rhsJoinPartition = DataPartition.hashPartitioned(Expr.cloneList(rhsJoinExprs));
+    if (useRandomPartitioning) {
+      // No rows can match, so the inputs need not be co-located by their synthetic
+      // constant hash keys. Random partitioning preserves parallelism without skew.
+      lhsJoinPartition = DataPartition.RANDOM;
+      rhsJoinPartition = DataPartition.RANDOM;
+    } else {
+      lhsJoinPartition = DataPartition.hashPartitioned(Expr.cloneList(lhsJoinExprs));
+      rhsJoinPartition = DataPartition.hashPartitioned(Expr.cloneList(rhsJoinExprs));
+    }
 
     // Neither lhs nor rhs are already partitioned on the join exprs.
     // Create a new parent fragment containing a HashJoin node with two
     // ExchangeNodes as inputs; the latter are the destinations of the
     // left- and rightChildFragments, which now partition their output
     // on their respective join exprs.
-    // The new fragment is hash-partitioned on the lhs input join exprs.
+    // The new fragment uses the lhs input partition unless the join type requires a
+    // different output partition below.
     ExchangeNode lhsExchange =
         new ExchangeNode(ctx_.getNextNodeId(), leftChildFragment.getPlanRoot());
     lhsExchange.computeStats(ctx_.getRootAnalyzer());
@@ -763,7 +772,7 @@ public class DistributedPlanner {
   * For 'broadcastCost', 'partitionCost', and 'rhsDataSize' a value of -1 indicates
   * unknown, e.g., due to missing stats.
   */
- private DistributionMode computeJoinDistributionMode(JoinNode node,
+ private DistributionMode computeJoinDistributionMode(HashJoinNode node,
      long broadcastCost, long partitionCost, long rhsDataSize) {
    // Check join types that require a specific distribution strategy to run correctly.
    JoinOperator op = node.getJoinOp();
@@ -773,6 +782,16 @@ public class DistributedPlanner {
    }
    if (op == JoinOperator.NULL_AWARE_LEFT_ANTI_JOIN) return DistributionMode.BROADCAST;
 
+   // A constant-false left outer join has an empty build side. Broadcast that empty
+   // input instead of repartitioning the preserved probe side, even with a SHUFFLE hint.
+   if (node.isConstantFalseOuterJoin()) {
+     // Left outer is all that reaches here: full and right outer took the early return
+     // above, and a constant-false right outer was inverted into a left one while the
+     // plan was built.
+     Preconditions.checkState(op == JoinOperator.LEFT_OUTER_JOIN);
+     return DistributionMode.BROADCAST;
+   }
+
    // Check join hints.
    if (node.getDistributionModeHint() != DistributionMode.NONE) {
      return node.getDistributionModeHint();
diff --git a/fe/src/main/java/org/apache/impala/planner/HashJoinNode.java b/fe/src/main/java/org/apache/impala/planner/HashJoinNode.java
index f4c8a3b69..8a9988acd 100644
--- a/fe/src/main/java/org/apache/impala/planner/HashJoinNode.java
+++ b/fe/src/main/java/org/apache/impala/planner/HashJoinNode.java
@@ -53,6 +53,16 @@ import com.google.common.base.Preconditions;
 public class HashJoinNode extends JoinNode implements SpillableOperator {
   private final static Logger LOG = LoggerFactory.getLogger(HashJoinNode.class);
 
+  // True when the join uses synthetic non-matching constant hash keys for an outer
+  // join whose On-clause contains FALSE or NULL. Partitioned execution must distribute
+  // these inputs randomly because hashing either constant would create data skew.
+  //
+  // What the distributed planner reads off this is that the join produces no match at
+  // all; a constant-false On-clause is today the only thing that proves it. Another
+  // proof - say two conjuncts that cannot hold at once - would want the same handling
+  // and this name would then be the narrow one.
+  private boolean isConstantFalseOuterJoin_ = false;
+
   // Coefficients for estimating hash join CPU processing cost.  Derived from
   // benchmarking. Probe side cost per input row consumed
   private static final double COST_COEFFICIENT_PROBE_INPUT = 0.2565;
@@ -77,6 +87,13 @@ public class HashJoinNode extends JoinNode implements SpillableOperator {
   @Override
   public List<BinaryPredicate> getEqJoinConjuncts() { return eqJoinConjuncts_; }
 
+  void markAsConstantFalseOuterJoin() {
+    Preconditions.checkState(joinOp_.isOuterJoin());
+    isConstantFalseOuterJoin_ = true;
+  }
+
+  boolean isConstantFalseOuterJoin() { return isConstantFalseOuterJoin_; }
+
   @Override
   public void init(Analyzer analyzer) throws ImpalaException {
     super.init(analyzer);
diff --git a/fe/src/main/java/org/apache/impala/planner/Planner.java b/fe/src/main/java/org/apache/impala/planner/Planner.java
index 67bb1ed1a..f99af157d 100644
--- a/fe/src/main/java/org/apache/impala/planner/Planner.java
+++ b/fe/src/main/java/org/apache/impala/planner/Planner.java
@@ -1019,13 +1019,15 @@ public class Planner {
   /**
    * Traverses the plan tree rooted at 'root' and inverts joins in the following
    * situations:
-   * 1. If the left-hand side is a SingularRowSrcNode then we invert the join because
+   * 1. If a constant-false right outer join has an empty left-hand side then we invert
+   *    the join so that the empty input becomes the build side.
+   * 2. If the left-hand side is a SingularRowSrcNode then we invert the join because
    *    then the build side is guaranteed to have only a single row.
-   * 2. There is no backend support for distributed non-equi right outer/semi joins,
+   * 3. There is no backend support for distributed non-equi right outer/semi joins,
    *    so we invert them (any distributed left semi/outer join is ok).
-   * 3. If we estimate that the inverted join is cheaper (see isInvertedJoinCheaper()).
+   * 4. If we estimate that the inverted join is cheaper (see isInvertedJoinCheaper()).
    *    Do not invert if relevant stats are missing.
-   * The first two inversion rules are independent of the presence/absence of stats.
+   * The first three inversion rules are independent of the presence/absence of stats.
    * Left Null Aware Anti Joins are never inverted due to lack of backend support.
    * Joins that originate from query blocks with a straight join hint are not inverted.
    * The 'isLocalPlan' parameter indicates whether the plan tree rooted at 'root'
@@ -1057,7 +1059,13 @@ public class Planner {
         return;
       }
 
-      if (joinNode.getChild(0) instanceof SingularRowSrcNode) {
+      if (joinNode instanceof HashJoinNode
+          && ((HashJoinNode) joinNode).isConstantFalseOuterJoin()
+          && joinOp.isRightOuterJoin()) {
+        // Put the empty input on the build side so the distributed planner can
+        // broadcast it without duplicating unmatched rows from the preserved side.
+        joinNode.invertJoin();
+      } else if (joinNode.getChild(0) instanceof SingularRowSrcNode) {
         // Always place a singular row src on the build side because it
         // only produces a single row.
         joinNode.invertJoin();
diff --git a/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java b/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java
index b922bc3a4..aada81b44 100644
--- a/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java
+++ b/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java
@@ -34,6 +34,7 @@ import org.apache.impala.analysis.Analyzer;
 import org.apache.impala.analysis.BaseTableRef;
 import org.apache.impala.analysis.BinaryPredicate;
 import org.apache.impala.analysis.BinaryPredicate.Operator;
+import org.apache.impala.analysis.BoolLiteral;
 import org.apache.impala.analysis.CollectionTableRef;
 import org.apache.impala.analysis.Expr;
 import org.apache.impala.analysis.ExprId;
@@ -2109,6 +2110,27 @@ public class SingleNodePlanner implements SingleNodePlannerIntf {
     PlanNode.removeZippingUnnestConjuncts(otherJoinConjuncts, analyzer);
     analyzer.markConjunctsAssigned(otherJoinConjuncts);
 
+    // A FALSE or NULL conjunct makes the complete On-clause impossible to satisfy.
+    // Use constant non-matching keys to make a hash join available. The distributed
+    // planner randomly partitions these joins instead of hashing the constant keys.
+    // Prune an input if the outer-join semantics do not require its unmatched rows.
+    boolean optimizeConstantFalseOuterJoin = innerRef.getJoinOp().isOuterJoin()
+        && Iterables.any(otherJoinConjuncts,
+            e -> Expr.IS_FALSE_LITERAL.apply(e) || Expr.IS_NULL_VALUE.apply(e));
+    if (optimizeConstantFalseOuterJoin) {
+      eqJoinConjuncts.clear();
+      eqJoinConjuncts.add(createNonMatchingEqJoinConjunct(analyzer));
+      // The synthetic predicate already guarantees that no rows can match.
+      otherJoinConjuncts.clear();
+      if (innerRef.getJoinOp().isLeftOuterJoin()) {
+        inner = createEmptyJoinInput(inner, analyzer);
+      } else if (innerRef.getJoinOp().isRightOuterJoin()) {
+        outer = createEmptyJoinInput(outer, analyzer);
+      } else {
+        Preconditions.checkState(innerRef.getJoinOp().isFullOuterJoin());
+      }
+    }
+
     if (analyzer.getQueryOptions().isEnable_distinct_semi_join_optimization() &&
             innerRef.getJoinOp().isLeftSemiJoin()) {
       inner =
@@ -2126,14 +2148,44 @@ public class SingleNodePlanner implements SingleNodePlannerIntf {
       result = new NestedLoopJoinNode(outer, inner, analyzer.isStraightJoin(),
           innerRef.getDistributionMode(), innerRef.getJoinOp(), otherJoinConjuncts);
     } else {
-      result = new HashJoinNode(outer, inner, analyzer.isStraightJoin(),
+      HashJoinNode hashJoin = new HashJoinNode(outer, inner, analyzer.isStraightJoin(),
           innerRef.getDistributionMode(), innerRef.getJoinOp(), eqJoinConjuncts,
           otherJoinConjuncts);
+      if (optimizeConstantFalseOuterJoin) hashJoin.markAsConstantFalseOuterJoin();
+      result = hashJoin;
     }
     result.init(analyzer);
     return result;
   }
 
+  /**
+   * Creates an empty replacement for a join input while preserving its tuple and
+   * substitution metadata.
+   */
+  private EmptySetNode createEmptyJoinInput(PlanNode input, Analyzer analyzer) {
+    EmptySetNode empty = new EmptySetNode(ctx_.getNextNodeId(), input.getTupleIds());
+    empty.setTblRefIds(Lists.newArrayList(input.getTblRefIds()));
+    empty.setOutputSmap(input.getOutputSmap());
+    empty.init(analyzer);
+    return empty;
+  }
+
+  /**
+   * Creates a hash predicate whose probe and build keys can never match.
+   *
+   * <p>The join needs an equi conjunct to be a hash join at all: with the FALSE left
+   * where the analyzer put it, among the other conjuncts, the planner picks a nested
+   * loop join instead and the constant buys nothing. So the usable keys are replaced
+   * by one that cannot match rather than removed.
+   */
+  private BinaryPredicate createNonMatchingEqJoinConjunct(Analyzer analyzer)
+      throws AnalysisException {
+    BinaryPredicate result = new BinaryPredicate(
+        Operator.EQ, new BoolLiteral(true), new BoolLiteral(false));
+    result.analyze(analyzer);
+    return result;
+  }
+
   /**
    * Optionally add a aggregation node on top of 'joinInput' if it is cheaper to project
    * and aggregate the slots needed to evaluate the provided join conjuncts. This
diff --git a/testdata/workloads/functional-planner/queries/PlannerTest/empty.test b/testdata/workloads/functional-planner/queries/PlannerTest/empty.test
index 4d54804cc..b9e0388d6 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/empty.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/empty.test
@@ -152,39 +152,32 @@ PLAN-ROOT SINK
 # assigned to the join.
 select *
 from functional.alltypessmall a
-left outer join functional.alltypestiny b
+left outer join [shuffle] functional.alltypestiny b
 on (a.id = b.id and 1 + 1 > 10)
 ---- PLAN
 PLAN-ROOT SINK
 |
-02:NESTED LOOP JOIN [LEFT OUTER JOIN]
-|  join predicates: FALSE
+03:HASH JOIN [LEFT OUTER JOIN]
+|  hash predicates: TRUE = FALSE
 |  row-size=178B cardinality=100
 |
-|--01:SCAN HDFS [functional.alltypestiny b]
-|     HDFS partitions=4/4 files=4 size=460B
-|     row-size=89B cardinality=8
+|--02:EMPTYSET
 |
 00:SCAN HDFS [functional.alltypessmall a]
    HDFS partitions=4/4 files=4 size=6.32KB
    row-size=89B cardinality=100
-====
-# Constant conjunct in the ON-clause of an outer join is
-# assigned to the join.
-select *
-from functional.alltypessmall a
-right outer join functional.alltypestiny b
-on (a.id = b.id and !true)
----- PLAN
+---- DISTRIBUTEDPLAN
 PLAN-ROOT SINK
 |
-02:NESTED LOOP JOIN [RIGHT OUTER JOIN]
-|  join predicates: FALSE
+05:EXCHANGE [UNPARTITIONED]
+|
+03:HASH JOIN [LEFT OUTER JOIN, BROADCAST]
+|  hash predicates: TRUE = FALSE
 |  row-size=178B cardinality=100
 |
-|--01:SCAN HDFS [functional.alltypestiny b]
-|     HDFS partitions=4/4 files=4 size=460B
-|     row-size=89B cardinality=8
+|--04:EXCHANGE [BROADCAST]
+|  |
+|  02:EMPTYSET
 |
 00:SCAN HDFS [functional.alltypessmall a]
    HDFS partitions=4/4 files=4 size=6.32KB
@@ -194,20 +187,73 @@ PLAN-ROOT SINK
 # assigned to the join.
 select *
 from functional.alltypessmall a
+right outer join [shuffle] functional.alltypestiny b
+on (a.id = b.id and false)
+---- PLAN
+PLAN-ROOT SINK
+|
+03:HASH JOIN [LEFT OUTER JOIN]
+|  hash predicates: FALSE = TRUE
+|  row-size=178B cardinality=8
+|
+|--02:EMPTYSET
+|
+01:SCAN HDFS [functional.alltypestiny b]
+   HDFS partitions=4/4 files=4 size=460B
+   row-size=89B cardinality=8
+---- DISTRIBUTEDPLAN
+PLAN-ROOT SINK
+|
+05:EXCHANGE [UNPARTITIONED]
+|
+03:HASH JOIN [LEFT OUTER JOIN, BROADCAST]
+|  hash predicates: FALSE = TRUE
+|  row-size=178B cardinality=8
+|
+|--04:EXCHANGE [BROADCAST]
+|  |
+|  02:EMPTYSET
+|
+01:SCAN HDFS [functional.alltypestiny b]
+   HDFS partitions=4/4 files=4 size=460B
+   row-size=89B cardinality=8
+====
+# A typed NULL conjunct in the ON-clause of an outer join is assigned to the join.
+select *
+from functional.alltypessmall a
 full outer join functional.alltypestiny b
-on (a.id = b.id and null = "abc")
+on (a.id = b.id and cast(null as boolean))
 ---- PLAN
 PLAN-ROOT SINK
 |
 02:HASH JOIN [FULL OUTER JOIN]
-|  hash predicates: a.id = b.id
-|  other join predicates: NULL
+|  hash predicates: TRUE = FALSE
 |  row-size=178B cardinality=108
 |
 |--01:SCAN HDFS [functional.alltypestiny b]
 |     HDFS partitions=4/4 files=4 size=460B
 |     row-size=89B cardinality=8
 |
+00:SCAN HDFS [functional.alltypessmall a]
+   HDFS partitions=4/4 files=4 size=6.32KB
+   row-size=89B cardinality=100
+---- DISTRIBUTEDPLAN
+PLAN-ROOT SINK
+|
+05:EXCHANGE [UNPARTITIONED]
+|
+02:HASH JOIN [FULL OUTER JOIN, PARTITIONED]
+|  hash predicates: TRUE = FALSE
+|  row-size=178B cardinality=108
+|
+|--04:EXCHANGE [RANDOM]
+|  |
+|  01:SCAN HDFS [functional.alltypestiny b]
+|     HDFS partitions=4/4 files=4 size=460B
+|     row-size=89B cardinality=8
+|
+03:EXCHANGE [RANDOM]
+|
 00:SCAN HDFS [functional.alltypessmall a]
    HDFS partitions=4/4 files=4 size=6.32KB
    row-size=89B cardinality=100
diff --git a/testdata/workloads/functional-query/queries/QueryTest/outer-joins.test b/testdata/workloads/functional-query/queries/QueryTest/outer-joins.test
index 6761e88c1..6bde86f66 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/outer-joins.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/outer-joins.test
@@ -1,5 +1,37 @@
 ====
 ---- QUERY
+# IMPALA-7996: Constant-false outer joins preserve the left input.
+select count(*), count(a.id), count(b.id)
+from (select 1 id union all select 2) a
+left outer join (select 3 id union all select 4) b on false
+---- RESULTS
+2,2,0
+---- TYPES
+bigint,bigint,bigint
+====
+---- QUERY
+# IMPALA-7996: Constant-false outer joins preserve the right input.
+select count(*), count(a.id), count(b.id)
+from (select 1 id union all select 2) a
+right outer join (select 3 id union all select 4) b on false
+---- RESULTS
+2,0,2
+---- TYPES
+bigint,bigint,bigint
+====
+---- QUERY
+# IMPALA-7996: A typed NULL conjunct makes the equi predicate non-matching, even
+# for overlapping keys, so a full outer join returns both inputs as unmatched rows.
+select count(*), count(a.id), count(b.id)
+from (select 1 id union all select 2) a
+full outer join (select 1 id union all select 3) b
+on a.id = b.id and cast(null as boolean)
+---- RESULTS
+4,2,2
+---- TYPES
+bigint,bigint,bigint
+====
+---- QUERY
 # join cols are not part of select list (and still get materialized)
 select j.test_name, d.name
 from JoinTbl j inner join DimTbl d on (j.test_id = d.id)
@@ -787,4 +819,4 @@ WHERE a = 1
 6
 ---- TYPES
 bigint
-====
\ No newline at end of file
+====