You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@impala.apache.org by cs...@apache.org on 2026/09/20 14:55:28 UTC

(impala) 02/02: IMPALA-14601: Support HBO for JoinNode cardinality

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

commit a64de029b8d20b25497f8fbe093c4ed6e536cae0
Author: stiga-huang <hu...@gmail.com>
AuthorDate: Mon Jun 1 12:39:26 2026 +0800

    IMPALA-14601: Support HBO for JoinNode cardinality
    
    This extends HBO to support tracking and using cardinality of JoinNodes.
    Only frontend changes are needed.
    
    HBO Key String
    --------------
    The HBO key string for a JoinNode consists of the following info:
     - JoinOp, e.g. LEFT_OUTER_JOIN, LEFT_SEMI_JOIN, LEFT_ANTI_JOIN, etc.
     - LIMIT
     - Join conjuncts.
     - Optional WHERE conjuncts.
     - HBO key strings of the left and right children.
    
    Right-handed joins like RIGHT_OUTER_JOIN are inverted in the HBO key
    string so a plan and its inverted counterpart hash identically. For
    instance, these two JoinNodes have the same HBO key string:
    
               LeftOuterJoin       RightOuterJoin
                  /     \             /     \
                 A       B           B       A
    
    For INNER/CROSS joins that the join order doesn't impact the final
    cardinality, the HBO key string is optimized to be independent with the
    join order. For each of such JoinNode, a maximal contiguous group of
    such joins are collected and flatten into sorted operand strings in the
    HBO key string. Then added all the conjuncts. For instance, the
    following two plans would have the same HBO key string in the top level
    JoinNode:
    
                 InnerJoin              InnerJoin
                  /     \                /     \
             InnerJoin   C          InnerJoin   B
              /     \                /     \
             A       B              A       C
    
    This patch also renames the HBO key string fields to use Camel names,
    and adds a util method in PlanNode to start generating HBO key string
    with the optional LIMIT.
    
    Canonicalization
    ----------------
    Conjuncts are canonicalized in the same way as in HdfsScanNode and
    AggregationNode, except that column names are qualified using a
    canonicalized alias "op<idx>" where idx is the index of the operand in
    the sorted operand list. E.g. the following two queries have the same
    conjunct string:
    
    select count(*) from alltypes a join alltypestiny b on a.id = b.int_col;
    select count(*) from alltypestiny a join alltypes b on a.id = b.int_col;
    
    But their canonicalized conjunct strings are different:
      1) op0.id = op1.int_col
      2) op1.id = op0.int_col
    Note that alltypes is operand 0 and alltypestiny is operand 1.
    
    When an AggregationNode is on top of a JoinNode, these operand strings
    are also used in canonicalizing aggregation expressions to distinguish
    which tuple the column comes from. E.g. for the following query:
    
      select t1.int_col, t2.int_col, t3.int_col, count(*)
      from functional.alltypes t1
        join functional.alltypestiny t2 on t1.id = t2.id
        left join functional.alltypessmall t3 on t1.id = t3.id
      group by t1.int_col, t2.int_col, t3.int_col
    
    The query plan with the operand strings ("op0.0", "op0.1", "op1"):
                           Agg
                            |
                         LeftJoin
                         /      \
               InnerJoin(op0)  t3(op1)
                 /       \
           t1(op0.0)   t2(op0.1)
    
    The GroupBy columns will be canonicalized as "op0.0.int_col",
    "op0.1.int_col", "op1.int_col".
    
    Testing
     - Added FE tests on the HBO key strings.
     - Added e2e tests.
    
    Assisted-by: Opus 4.8 (Claude Code)
    Change-Id: I70b655ae7027d0d9eb8e9fae9ba2e1b7ad9876b4
    Reviewed-on: http://gerrit.cloudera.org:8080/24426
    Reviewed-by: Impala Public Jenkins <im...@cloudera.com>
    Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
 .../org/apache/impala/analysis/JoinOperator.java   |   5 +
 .../java/org/apache/impala/analysis/SlotRef.java   |  20 +-
 .../org/apache/impala/planner/AggregationNode.java |  37 +-
 .../org/apache/impala/planner/ExchangeNode.java    |   3 +
 .../apache/impala/planner/ExprCanonicalizer.java   | 161 ++++-
 .../org/apache/impala/planner/HashJoinNode.java    |   1 +
 .../org/apache/impala/planner/HdfsScanNode.java    |  13 +-
 .../impala/planner/IcebergDeleteJoinNode.java      |   2 +
 .../java/org/apache/impala/planner/JoinNode.java   | 204 ++++++
 .../apache/impala/planner/NestedLoopJoinNode.java  |   1 +
 .../java/org/apache/impala/planner/PlanNode.java   |  88 ++-
 .../org/apache/impala/planner/TupleCacheNode.java  |   3 +
 .../java/org/apache/impala/planner/UnionNode.java  |   9 +-
 .../apache/impala/planner/HboKeyStringTest.java    | 705 +++++++++++++++++++--
 .../queries/QueryTest/hbo-except.test              | 166 +++++
 .../queries/QueryTest/hbo-inner-join.test          | 178 ++++++
 .../queries/QueryTest/hbo-intersect.test           | 187 ++++++
 .../queries/QueryTest/hbo-multiple-scans.test      |  18 +-
 .../queries/QueryTest/hbo-outer-join.test          |  77 +++
 tests/query_test/test_hbo.py                       |  51 +-
 20 files changed, 1806 insertions(+), 123 deletions(-)

diff --git a/fe/src/main/java/org/apache/impala/analysis/JoinOperator.java b/fe/src/main/java/org/apache/impala/analysis/JoinOperator.java
index 0ea9525f1..a14ec0183 100644
--- a/fe/src/main/java/org/apache/impala/analysis/JoinOperator.java
+++ b/fe/src/main/java/org/apache/impala/analysis/JoinOperator.java
@@ -75,6 +75,11 @@ public enum JoinOperator {
     return this == JoinOperator.RIGHT_SEMI_JOIN || this == JoinOperator.RIGHT_ANTI_JOIN;
   }
 
+  public boolean isRightHandedJoin() {
+    return this == RIGHT_OUTER_JOIN || this == JoinOperator.RIGHT_SEMI_JOIN
+        || this == JoinOperator.RIGHT_ANTI_JOIN;
+  }
+
   public boolean isCrossJoin() {
     return this == JoinOperator.CROSS_JOIN;
   }
diff --git a/fe/src/main/java/org/apache/impala/analysis/SlotRef.java b/fe/src/main/java/org/apache/impala/analysis/SlotRef.java
index 849e9609a..43dc85cf0 100644
--- a/fe/src/main/java/org/apache/impala/analysis/SlotRef.java
+++ b/fe/src/main/java/org/apache/impala/analysis/SlotRef.java
@@ -57,6 +57,13 @@ public class SlotRef extends Expr {
   // would be used instead of a SlotRef.
   protected boolean isZippingUnnest_ = false;
 
+  // Transient rendering hint used only when producing HBO key strings
+  // (ToSqlOptions.FOR_HBO). When set, it is prepended (as "<qualifier>.") to the
+  // unqualified column name so that join predicates can record which operand a column
+  // belongs to (see ExprCanonicalizer.qualifyForHbo). It is NOT propagated by the copy
+  // constructor, analyzed, serialized to thrift, or considered in equals/hashCode.
+  private String hboQualifier_ = null;
+
   public SlotRef(List<String> rawPath) {
     super();
     rawPath_ = rawPath;
@@ -343,6 +350,13 @@ public class SlotRef extends Expr {
 
   public void setIsZippingUnnest(boolean b) { isZippingUnnest_ = b; }
 
+  /**
+   * Sets a transient HBO qualifier (e.g. "op0") that is prepended to the unqualified
+   * column name when rendering with ToSqlOptions.FOR_HBO. Used by ExprCanonicalizer to
+   * tag join-predicate columns with their canonical operand index.
+   */
+  public void setHboQualifier(String qualifier) { hboQualifier_ = qualifier; }
+
   @Override
   public String toSqlImpl(ToSqlOptions options) {
     if (options.showForHbo()) {
@@ -362,7 +376,11 @@ public class SlotRef extends Expr {
       } else {
         col = label_;
       }
-      return col;
+      // For join predicates the bare column name is ambiguous (e.g. "a.id = b.int_col"
+      // and "b.id = a.int_col" would both render as "id = int_col"). The qualifier, when
+      // set, records which operand the column belongs to using a canonical, alias-
+      // independent index.
+      return hboQualifier_ == null ? col : hboQualifier_ + "." + col;
     }
     if (label_ != null) return label_;
     if (rawPath_ != null) return ToSqlUtils.getPathSql(rawPath_);
diff --git a/fe/src/main/java/org/apache/impala/planner/AggregationNode.java b/fe/src/main/java/org/apache/impala/planner/AggregationNode.java
index 15ff2c609..6becade1c 100644
--- a/fe/src/main/java/org/apache/impala/planner/AggregationNode.java
+++ b/fe/src/main/java/org/apache/impala/planner/AggregationNode.java
@@ -255,6 +255,7 @@ public class AggregationNode extends PlanNode implements SpillableOperator {
       aggInfo.getIntermediateTupleDesc().computeMemLayout();
     }
 
+    computeHboOperandQualifierMap(analyzer);
     // Do at the end so it can take all conjuncts into account
     computeStats(analyzer);
 
@@ -832,36 +833,42 @@ public class AggregationNode extends PlanNode implements SpillableOperator {
       return null;
     }
 
-    StringBuilder sb = new StringBuilder(statsType.name())
-        .append(":AggregationNode:");
-
     String logicalPhase = aggPhase_.isFirstPhase() ? "FIRST"
         : aggPhase_.isTranspose() ? "TRANSPOSE" : "MERGE";
-    sb.append(logicalPhase)
-        .append("|preagg:").append(isPreagg_)
-        .append("|groupingSet:")
-        .append(multiAggInfo_.getIsGroupingSet())
-        .append("|");
-    if (limit_ > 0) sb.append("limit:").append(limit_).append("|");
+    StringBuilder sb = startHboKeyString(statsType, ":AggregationNode:" + logicalPhase);
+    sb.append("|Preagg:").append(isPreagg_)
+        .append("|GroupingSet:")
+        .append(multiAggInfo_.getIsGroupingSet());
+
+    // When the aggregation sits on top of a join (directly or through
+    // operand-transparent nodes), qualify grouping/HAVING columns with the join's
+    // canonical operand index so that columns from different operands are
+    // distinguishable, e.g. "GROUP BY a.int_col, b.bigint_col" vs
+    // "GROUP BY b.int_col, a.bigint_col". A subtree with no join (e.g. a scan or union
+    // node) exposes a single tuple set with no such ambiguity, so its columns are left
+    // unqualified (getHboOperandQualifierMap returns null).
+    Map<TupleId, String> operandIdx = baseChild.getHboOperandQualifierMap();
 
     List<String> aggClassStrings = new ArrayList<>(aggInfos_.size());
     for (AggregateInfo aggInfo : aggInfos_) {
       List<Expr> groupingExprs = aggInfo.getGroupingExprs();
-      List<String> groupingStrs = ExprCanonicalizer.canonicalizeExprs(groupingExprs);
-      aggClassStrings.add("GROUP:" + String.join(",", groupingStrs));
+      List<String> groupingStrs = ExprCanonicalizer.canonicalizeExprs(
+          groupingExprs, CanonicalizationStrategy.EXPR_REWRITE, operandIdx);
+      aggClassStrings.add("Group:" + String.join(",", groupingStrs));
     }
     Collections.sort(aggClassStrings);
     for (int i = 0; i < aggClassStrings.size(); ++i) {
       aggClassStrings.set(i, i + ":" + aggClassStrings.get(i));
     }
-    sb.append("AggClasses:[").append(String.join(",", aggClassStrings)).append("]|");
+    sb.append("|AggClasses:[").append(String.join(",", aggClassStrings)).append("]");
 
     if (!conjuncts_.isEmpty()) {
-      List<String> conjunctStrs = ExprCanonicalizer.canonicalizeExprs(conjuncts_);
-      sb.append("HAVING:").append(String.join(",", conjunctStrs)).append("|");
+      List<String> conjunctStrs = ExprCanonicalizer.canonicalizeExprs(
+          conjuncts_, CanonicalizationStrategy.EXPR_REWRITE, operandIdx);
+      sb.append("|Having:").append(String.join(",", conjunctStrs));
     }
 
-    sb.append("CHILD:[").append(childKey).append("]");
+    sb.append("|Child:[").append(childKey).append("]");
     return sb.toString();
   }
 
diff --git a/fe/src/main/java/org/apache/impala/planner/ExchangeNode.java b/fe/src/main/java/org/apache/impala/planner/ExchangeNode.java
index 0db0e54eb..fec546cb1 100644
--- a/fe/src/main/java/org/apache/impala/planner/ExchangeNode.java
+++ b/fe/src/main/java/org/apache/impala/planner/ExchangeNode.java
@@ -413,4 +413,7 @@ public class ExchangeNode extends PlanNode {
 
   @Override
   public boolean isCardinalityPreserving() { return true; }
+
+  @Override
+  public boolean isOperandTransparent() { return true; }
 }
diff --git a/fe/src/main/java/org/apache/impala/planner/ExprCanonicalizer.java b/fe/src/main/java/org/apache/impala/planner/ExprCanonicalizer.java
index 281542e41..e8a834a33 100644
--- a/fe/src/main/java/org/apache/impala/planner/ExprCanonicalizer.java
+++ b/fe/src/main/java/org/apache/impala/planner/ExprCanonicalizer.java
@@ -20,14 +20,20 @@ package org.apache.impala.planner;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
+import java.util.Map;
 
 import org.apache.impala.analysis.BinaryPredicate;
 import org.apache.impala.analysis.Expr;
 import org.apache.impala.analysis.InPredicate;
 import org.apache.impala.analysis.LiteralExpr;
+import org.apache.impala.analysis.SlotDescriptor;
 import org.apache.impala.analysis.SlotRef;
 import org.apache.impala.analysis.ToSqlOptions;
+import org.apache.impala.analysis.TupleDescriptor;
+import org.apache.impala.analysis.TupleId;
 import org.apache.impala.catalog.FeTable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Utility class for canonicalizing expressions for History-Based Optimization (HBO).
@@ -42,6 +48,7 @@ import org.apache.impala.catalog.FeTable;
  * so we don't need to redo it here.
  */
 public class ExprCanonicalizer {
+  private final static Logger LOG = LoggerFactory.getLogger(ExprCanonicalizer.class);
 
   // Placeholder string used when removing constants from predicates
   private static final String CONST = "<CONST>";
@@ -79,14 +86,151 @@ public class ExprCanonicalizer {
   }
 
   /**
-   * Canonicalizes a list of expressions for HBO keys on non-scan plan nodes,
-   * e.g. aggregation nodes.
+   * Canonicalizes a list of expressions for HBO keys on non-scan plan nodes, qualifying
+   * each column with its canonical operand index (see {@link #qualifyForHbo}) when
+   * 'operandIdx' is provided. Used for the single-operand WHERE conjuncts of a join
+   * node so that columns of different operands are distinguishable.
    */
-  public static List<String> canonicalizeExprs(List<Expr> exprs) {
-    // TODO: AggregationNode won't have partition predicates that need canonicalization
-    // since they are all applied on the scan node. Revisit this when we support more
-    // non-scan plan nodes.
-    return canonicalizeScanConjuncts(exprs, null, CanonicalizationStrategy.EXPR_REWRITE);
+  public static List<String> canonicalizeExprs(List<Expr> exprs,
+      CanonicalizationStrategy strategy, Map<TupleId, String> operandIdx) {
+    return canonicalizeScanConjuncts(qualifyForHbo(exprs, operandIdx), null, strategy);
+  }
+
+  /**
+   * Canonicalizes join predicates for HBO keys, qualifying each column with its
+   * canonical operand index (see {@link #qualifyForHbo}) when 'operandIdx' is provided.
+   * Qualification disambiguates predicates that would otherwise collapse to the same
+   * string, e.g. "a.id = b.int_col" vs "b.id = a.int_col" both rendering as
+   * "id = int_col".
+   */
+  public static List<String> canonicalizeJoinConjuncts(List<Expr> exprs,
+      CanonicalizationStrategy strategy, Map<TupleId, String> operandIdx) {
+    if (exprs == null || exprs.isEmpty()) return Collections.emptyList();
+    List<String> result = new ArrayList<>();
+    for (Expr expr : qualifyForHbo(exprs, operandIdx)) {
+      result.add(canonicalizeJoinConjunct(expr, strategy));
+    }
+    Collections.sort(result);
+    return result;
+  }
+
+  /**
+   * Returns a list of deep clones of 'exprs' whose SlotRefs are tagged with their
+   * canonical operand qualifier. The originals are never mutated.
+   */
+  private static List<Expr> qualifyForHbo(List<Expr> exprs,
+      Map<TupleId, String> operandIdx) {
+    if (operandIdx == null || operandIdx.isEmpty()) return exprs;
+    List<Expr> result = new ArrayList<>(exprs.size());
+    for (Expr expr : exprs) {
+      Expr newExpr = qualifyForHbo(expr.clone(), operandIdx);
+      result.add(newExpr);
+    }
+    return result;
+  }
+
+  /**
+   * Returns a deep clone of 'expr' whose SlotRefs are tagged with a canonical operand
+   * qualifier ("op<path>") so that FOR_HBO rendering records which operand each column
+   * belongs to. Returns the original Expr if nothing needs qualification.
+   */
+  private static Expr qualifyForHbo(Expr node, Map<TupleId, String> operandIdx) {
+    if (node instanceof SlotRef slot) {
+      String path = resolveOperandIndex(slot, operandIdx);
+      // For a SlotRef that resolves to a single operand, sets its qualifier.
+      if (path != null) {
+        slot.setHboQualifier("op" + path);
+        return slot;
+      }
+      // If the slot doesn't resolve to a single operand, recurse into its source expr.
+      // E.g. for a materialized slot whose single source is a compound expr, descend into
+      // a clone of that source and qualify its nested SlotRefs individually.
+      if (slot.hasDesc()) {
+        SlotDescriptor desc = slot.getDesc();
+        List<Expr> srcExprs = desc.getSourceExprs();
+        if (!desc.isScanSlot() && srcExprs.size() == 1) {
+          return qualifyForHbo(srcExprs.get(0).clone(), operandIdx);
+        }
+      }
+      // Don't need qualifier.
+      return slot;
+    }
+    // Recursively tags 'node' (a mutable clone) so FOR_HBO rendering records each
+    // column's operand.
+    for (int i = 0; i < node.getChildCount(); ++i) {
+      node.setChild(i, qualifyForHbo(node.getChild(i), operandIdx));
+    }
+    return node;
+  }
+
+  /**
+   * Returns the canonical operand path of 'slot', i.e. the path mapped to the first of
+   * its enclosing tuples present in 'operandIdx'. For a substituted slot whose enclosing
+   * tuple is not an operand tuple (e.g. a merge aggregation's output slot), the search
+   * follows the slot's single source expr down to the base operand tuple.
+   * Returns null if none is found, which means the slot doesn't need to be qualified.
+   */
+  private static String resolveOperandIndex(SlotRef slot,
+      Map<TupleId, String> operandIdx) {
+    SlotDescriptor desc = slot.getDesc();
+    if (desc == null) return null;
+    for (TupleDescriptor tupleDesc : desc.getEnclosingTupleDescs()) {
+      String path = operandIdx.get(tupleDesc.getId());
+      if (path != null) return path;
+    }
+    // Substituted slot: trace through the single source column reference to its operand.
+    List<Expr> sourceExprs = desc.getSourceExprs();
+    // Slots with more than one source expr, or a non-SlotRef source, are left
+    // unqualified. In particular a UNION output slot has one source expr per branch and
+    // cannot be attributed to a single operand.
+    if (sourceExprs.size() != 1 || !(sourceExprs.get(0) instanceof SlotRef)) return null;
+    return resolveOperandIndex(((SlotRef) sourceExprs.get(0)), operandIdx);
+  }
+
+  private static String canonicalizeJoinConjunct(Expr expr,
+      CanonicalizationStrategy strategy) {
+    // For symmetric equality predicates (EQ, NOT_DISTINCT), the two operands are sorted
+    // so that join key order is independent of left/right child ordering.
+    if (expr instanceof BinaryPredicate) {
+      BinaryPredicate binPred = (BinaryPredicate) expr;
+      if (binPred.getOp() == BinaryPredicate.Operator.EQ
+          || binPred.getOp() == BinaryPredicate.Operator.NOT_DISTINCT) {
+        String lhs = binPred.getChild(0).toSql(ToSqlOptions.FOR_HBO);
+        String rhs = binPred.getChild(1).toSql(ToSqlOptions.FOR_HBO);
+        if (lhs.compareTo(rhs) > 0) {
+          String tmp = lhs;
+          lhs = rhs;
+          rhs = tmp;
+        }
+        return lhs + binPred.getOp().toString() + rhs;
+      }
+    }
+    return canonicalizeExpr(expr, null, strategy);
+  }
+
+  /**
+   * Resolves the table an expression's columns belong to by inspecting its SlotRefs.
+   * Returns null if the expression references columns from multiple or no tables.
+   */
+  private static FeTable resolveSingleTable(Expr expr) {
+    List<SlotRef> slotRefs = new ArrayList<>();
+    expr.collect(SlotRef.class, slotRefs);
+    FeTable table = null;
+    for (SlotRef ref : slotRefs) {
+      SlotDescriptor desc = ref.getDesc();
+      if (desc == null || desc.getParent() == null) continue;
+      FeTable t = desc.getParent().getTable();
+      if (table == null) {
+        table = t;
+      } else if (table != t) {
+        if (LOG.isTraceEnabled()) {
+          LOG.trace("Expr {} references columns from different tables: {} and {}",
+              expr.toSql(), table.getFullName(), t.getFullName());
+        }
+        return null;
+      }
+    }
+    return table;
   }
 
   /**
@@ -94,6 +238,9 @@ public class ExprCanonicalizer {
    */
   private static String canonicalizeExpr(Expr expr, FeTable table,
       CanonicalizationStrategy strategy) {
+    // Non-scan callers (e.g. a join node's retained WHERE conjuncts) pass no table.
+    // Resolve it from the expression's own slots.
+    if (table == null) table = resolveSingleTable(expr);
     // Remove constants only from partition column equality predicates when the strategy
     // is not EXPR_REWRITE (i.e. more aggressive than EXPR_REWRITE).
     boolean shouldRemoveConstants = false;
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 9bf082308..f4c8a3b69 100644
--- a/fe/src/main/java/org/apache/impala/planner/HashJoinNode.java
+++ b/fe/src/main/java/org/apache/impala/planner/HashJoinNode.java
@@ -161,6 +161,7 @@ public class HashJoinNode extends JoinNode implements SpillableOperator {
     if (!serialCtx.isTupleCache()) {
       msg.join_node.hash_join_node.setHash_seed(getFragment().getHashSeed());
     }
+    populateHboThriftFields(msg, serialCtx);
   }
 
   @Override
diff --git a/fe/src/main/java/org/apache/impala/planner/HdfsScanNode.java b/fe/src/main/java/org/apache/impala/planner/HdfsScanNode.java
index bf65b84d0..eea7f024c 100644
--- a/fe/src/main/java/org/apache/impala/planner/HdfsScanNode.java
+++ b/fe/src/main/java/org/apache/impala/planner/HdfsScanNode.java
@@ -1929,15 +1929,14 @@ public class HdfsScanNode extends ScanNode {
   @Override
   public String generateHboKeyString(THboStatsType statsType,
       CanonicalizationStrategy strategy) {
-    // Start with stats type prefix
-    StringBuilder sb = new StringBuilder(statsType.name()).append(":ScanNode:");
+    StringBuilder sb = startHboKeyString(statsType, ":ScanNode:");
+    if (limit_ > 0) sb.append("|");
     // Use the full path including collection columns if available
     if (desc_.getPath() != null) {
       sb.append(desc_.getPath().toString());
     } else {
       sb.append(tbl_.getFullName());
     }
-    sb.append("|");
 
     // Canonicalize partition conjuncts and regular conjuncts.
     List<String> partConjStrings =
@@ -1946,17 +1945,13 @@ public class HdfsScanNode extends ScanNode {
         ExprCanonicalizer.canonicalizeScanConjuncts(conjuncts_, tbl_, strategy);
 
     for (String s: partConjStrings) {
-      sb.append(s).append("|");
+      sb.append("|").append(s);
       LOG.trace("HBO PARTITION CONJUNCT STR ({}, {}): {}", statsType, strategy, s);
     }
     for (String s: conjStrings) {
-      sb.append(s).append("|");
+      sb.append("|").append(s);
       LOG.trace("HBO CONJUNCT STR ({}, {}): {}", statsType, strategy, s);
     }
-
-    if (limit_ != -1) {
-      sb.append("LIMIT:").append(limit_);
-    }
     return sb.toString();
   }
 
diff --git a/fe/src/main/java/org/apache/impala/planner/IcebergDeleteJoinNode.java b/fe/src/main/java/org/apache/impala/planner/IcebergDeleteJoinNode.java
index 86d7660dd..905986ec2 100644
--- a/fe/src/main/java/org/apache/impala/planner/IcebergDeleteJoinNode.java
+++ b/fe/src/main/java/org/apache/impala/planner/IcebergDeleteJoinNode.java
@@ -128,6 +128,7 @@ public class IcebergDeleteJoinNode extends JoinNode {
     Preconditions.checkState(leftSampling <= 1.0);
     effectiveRightCardinality = (long)(effectiveRightCardinality * leftSampling);
     cardinality_ = Math.max(1, leftCardWithSelectivity - effectiveRightCardinality);
+    tryUpdateCardinalityFromHbo(analyzer);
   }
 
   @Override
@@ -154,6 +155,7 @@ public class IcebergDeleteJoinNode extends JoinNode {
     msg.join_node.iceberg_delete_node.setEq_join_conjuncts(
         getThriftEquiJoinConjuncts(serialCtx));
     msg.join_node.iceberg_delete_node.setClear_file_path_slot(clearFilePathSlot_);
+    populateHboThriftFields(msg, serialCtx);
   }
 
   @Override
diff --git a/fe/src/main/java/org/apache/impala/planner/JoinNode.java b/fe/src/main/java/org/apache/impala/planner/JoinNode.java
index fd4b89da4..795ddd7ff 100644
--- a/fe/src/main/java/org/apache/impala/planner/JoinNode.java
+++ b/fe/src/main/java/org/apache/impala/planner/JoinNode.java
@@ -18,7 +18,9 @@
 package org.apache.impala.planner;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
@@ -42,9 +44,11 @@ import org.apache.impala.common.ThriftSerializationCtx;
 import org.apache.impala.planner.TupleCacheInfo.IneligibilityReason;
 import org.apache.impala.thrift.TEqJoinCondition;
 import org.apache.impala.thrift.TExecNodePhase;
+import org.apache.impala.thrift.THboStatsType;
 import org.apache.impala.thrift.TJoinDistributionMode;
 import org.apache.impala.thrift.TJoinNode;
 import org.apache.impala.thrift.TPlanNode;
+import org.apache.impala.thrift.TPlanNodeRun;
 import org.apache.impala.thrift.TQueryOptions;
 import org.apache.impala.util.MathUtil;
 import org.slf4j.Logger;
@@ -275,6 +279,7 @@ public abstract class JoinNode extends PlanNode {
     // Do not call super.init() to defer computeStats() until all conjuncts
     // have been collected.
     assignConjuncts(analyzer);
+    computeHboOperandQualifierMap(analyzer);
     createDefaultSmap(analyzer);
     // Mark slots used by 'conjuncts_' as materialized after substitution. Recompute
     // memory layout for affected tuples. Note: only tuples of the masked tables could
@@ -896,12 +901,211 @@ public abstract class JoinNode extends PlanNode {
       }
     }
     cardinality_ = capCardinalityAtLimit(cardinality_);
+    tryUpdateCardinalityFromHbo(analyzer);
     Preconditions.checkState(hasValidStats());
     if (LOG.isTraceEnabled()) {
       LOG.trace("stats Join: cardinality=" + Long.toString(cardinality_));
     }
   }
 
+  /**
+   * Skips cardinality-preserving nodes until a non-preserving node is reached.
+   */
+  private static PlanNode skipCardinalityPreservingNodes(PlanNode node) {
+    while (node.isCardinalityPreserving()) {
+      Preconditions.checkState(node.getChildCount() == 1);
+      node = node.getChild(0);
+    }
+    return node;
+  }
+
+  /**
+   * Collects join group info for inner/cross joins by flattening the join tree.
+   * Contiguous group of inner/cross JoinNodes are collected in 'groupNodes'.
+   * Flatten operands are collected in 'operands'.
+   */
+  private static void collectInnerCrossJoinGroup(JoinNode node, List<JoinNode> groupNodes,
+      List<PlanNode> operands) {
+    groupNodes.add(node);
+    for (PlanNode child : node.getChildren()) {
+      PlanNode baseChild = skipCardinalityPreservingNodes(child);
+      if (baseChild instanceof JoinNode joinChild
+          && (joinChild.joinOp_.isInnerJoin() || joinChild.joinOp_.isCrossJoin())
+          && !joinChild.hasLimit()) {
+        collectInnerCrossJoinGroup(joinChild, groupNodes, operands);
+      } else {
+        operands.add(baseChild);
+      }
+    }
+  }
+
+  /**
+   * Returns the logical operands of this join for HBO ordering. For an inner/cross join
+   * this is the flattened maximal contiguous group of inner/cross joins. Every other join
+   * type keeps its two children (the default).
+   */
+  @Override
+  protected List<PlanNode> getFlattenOperands() {
+    if (joinOp_.isInnerJoin() || joinOp_.isCrossJoin()) {
+      List<JoinNode> groupNodes = new ArrayList<>();
+      List<PlanNode> operands = new ArrayList<>();
+      collectInnerCrossJoinGroup(this, groupNodes, operands);
+      return operands;
+    }
+    return children_;
+  }
+
+  /**
+   * Orders this join's operands into their canonical HBO positions, i.e. the order
+   * recorded in the HBO key. Inner/cross joins flatten their contiguous group and full
+   * outer joins keep their two children; both sort operands by scan table names because
+   * operand order is insignificant. Right-handed joins invert to [right, left] so a right
+   * join hashes like its left-handed counterpart. Every other (left-directional) join
+   * keeps [left, right], where operand order is significant.
+   */
+  @Override
+  protected List<PlanNode> getHboOrderedOperands() {
+    if (joinOp_.isInnerJoin() || joinOp_.isCrossJoin() || joinOp_.isFullOuterJoin()) {
+      return super.getHboOrderedOperands();
+    }
+    if (joinOp_.isRightHandedJoin()) {
+      return Arrays.asList(getChild(1), getChild(0));
+    }
+    return children_;
+  }
+
+  private String generateFlattenJoinGroupKeyString(THboStatsType statsType,
+      CanonicalizationStrategy strategy) {
+    List<PlanNode> sortedOperands = getHboOrderedOperands();
+
+    StringBuilder sb = startHboKeyString(statsType, ":JoinNode:INNER");
+
+    sb.append("|Operands:[");
+    for (int i = 0; i < sortedOperands.size(); ++i) {
+      String childKey = sortedOperands.get(i).generateHboKeyString(statsType, strategy);
+      if (childKey == null) return null;
+      if (i > 0) sb.append(",");
+      sb.append(childKey);
+    }
+    sb.append("]");
+
+    Map<TupleId, String> operandIdx = getHboOperandQualifierMap();
+    if (operandIdx == null) return null;
+    List<String> predStrs = ExprCanonicalizer.canonicalizeJoinConjuncts(
+        collectFlattenGroupPredicates(), strategy, operandIdx);
+    sb.append("|Predicates:[").append(String.join(",", predStrs)).append("]");
+    return sb.toString();
+  }
+
+  /**
+   * Collects all predicates of this join's flattened inner/cross group: the eq-join,
+   * other-join, and WHERE conjuncts of every JoinNode in the group.
+   * TODO: Here we simply collect all the predicates. We should canonicalize equality
+   * predicate sets, e.g. (a.id=b.id AND b.id=c.id) is equivalent to
+   * (a.id=c.id AND b.id=c.id).
+   */
+  private List<Expr> collectFlattenGroupPredicates() {
+    List<JoinNode> groupNodes = new ArrayList<>();
+    collectInnerCrossJoinGroup(this, groupNodes, new ArrayList<>());
+    List<Expr> allPredicates = new ArrayList<>();
+    for (JoinNode groupNode : groupNodes) {
+      allPredicates.addAll(groupNode.eqJoinConjuncts_);
+      allPredicates.addAll(groupNode.otherJoinConjuncts_);
+      allPredicates.addAll(groupNode.conjuncts_);
+    }
+    return allPredicates;
+  }
+
+  private static String extendPath(String prefix, int idx) {
+    return prefix.isEmpty() ? String.valueOf(idx) : prefix + "." + idx;
+  }
+
+  /**
+   * Recursively assigns each base tuple under this join a canonical operand path,
+   * descending through the same operand structure the HBO key uses. Operand-transparent
+   * nodes are skipped so a join nested under e.g. an ExchangeNode is still descended
+   * into.
+   * The path is a dotted sequence of operand indices, one segment per join level (e.g.
+   * "0", "0.1"). A single index suffices for a tuple that is its join's direct operand;
+   * deeper paths distinguish tuples nested within a multi-tuple operand (a non-flattened
+   * OUTER/SEMI/ANTI/FULL side, or an inner-group operand that is itself such a join).
+   * E.g. for ((A left join B) left join C) left join D, assuming A, B, C, D are scans so
+   * just have one tuple each, the operand qualifier map of the top join node would be:
+   * { A: "0.0.0", B: "0.0.1", C: "0.1", D: "1" }. Column A.id would be canonicalized to
+   * "op0.0.0.id".
+   */
+  @Override
+  protected Map<TupleId, String> buildHboOperandQualifierMap(String prefix) {
+    Map<TupleId, String> map = new HashMap<>();
+    List<PlanNode> operands = getHboOrderedOperands();
+    for (int i = 0; i < operands.size(); ++i) {
+      map.putAll(operands.get(i).buildHboOperandQualifierMap(extendPath(prefix, i)));
+    }
+    return map;
+  }
+
+  private String generateSingleJoinKeyString(THboStatsType statsType,
+      CanonicalizationStrategy strategy) {
+    List<PlanNode> operands = getHboOrderedOperands();
+    Preconditions.checkState(operands.size() == 2);
+    String[] childKeys = new String[2];
+    for (int i = 0; i < 2; i++) {
+      childKeys[i] = operands.get(i).generateHboKeyString(statsType, strategy);
+      if (childKeys[i] == null) {
+        LOG.debug("Child of {} doesn't support HBO.", getDisplayLabel());
+        return null;
+      }
+    }
+
+    JoinOperator keyJoinOp = joinOp_.isRightHandedJoin() ? joinOp_.invert() : joinOp_;
+    Map<TupleId, String> operandIdx = getHboOperandQualifierMap();
+    if (operandIdx == null) return null;
+
+    StringBuilder sb = startHboKeyString(statsType, ":JoinNode:" + keyJoinOp.name());
+
+    List<Expr> eqConjsAsExprs = new ArrayList<>(eqJoinConjuncts_);
+    List<String> eqConjStrs = ExprCanonicalizer.canonicalizeJoinConjuncts(
+        eqConjsAsExprs, strategy, operandIdx);
+    sb.append("|Eq:").append(String.join(",", eqConjStrs));
+
+    if (!otherJoinConjuncts_.isEmpty()) {
+      List<String> otherConjStrs = ExprCanonicalizer.canonicalizeJoinConjuncts(
+          otherJoinConjuncts_, strategy, operandIdx);
+      sb.append("|Other:").append(String.join(",", otherConjStrs));
+    }
+    if (!conjuncts_.isEmpty()) {
+      List<String> conjStrs = ExprCanonicalizer.canonicalizeExprs(
+          conjuncts_, strategy, operandIdx);
+      sb.append("|Where:").append(String.join(",", conjStrs));
+    }
+
+    sb.append("|Left:").append(childKeys[0]);
+    sb.append("|Right:").append(childKeys[1]);
+    return sb.toString();
+  }
+
+  @Override
+  public String generateHboKeyString(THboStatsType statsType,
+      CanonicalizationStrategy strategy) {
+    Preconditions.checkState(children_.size() == 2);
+    // Inner join is associative and commutative so we can flatten the continuous inner
+    // joins into a join group and sort the operands, which maps queries differ only in
+    // inner join order into the same HBO key. Cross join is a special case of inner join
+    // that the join condition is always true.
+    if (joinOp_.isInnerJoin() || joinOp_.isCrossJoin()) {
+      return generateFlattenJoinGroupKeyString(statsType, strategy);
+    }
+    return generateSingleJoinKeyString(statsType, strategy);
+  }
+
+  @Override
+  public void appendScanInputStats(TPlanNodeRun execStats) {
+    // Iterate in the same order as generateHboKeyString()
+    for (PlanNode operand : getHboOrderedOperands()) {
+      operand.appendScanInputStats(execStats);
+    }
+  }
+
   /**
    * Inverts the join op, swaps our children, and swaps the children
    * of all eqJoinConjuncts_. All modifications are in place.
diff --git a/fe/src/main/java/org/apache/impala/planner/NestedLoopJoinNode.java b/fe/src/main/java/org/apache/impala/planner/NestedLoopJoinNode.java
index d1dbe6d25..51fdf702c 100644
--- a/fe/src/main/java/org/apache/impala/planner/NestedLoopJoinNode.java
+++ b/fe/src/main/java/org/apache/impala/planner/NestedLoopJoinNode.java
@@ -172,6 +172,7 @@ public class NestedLoopJoinNode extends JoinNode {
     for (Expr e : otherJoinConjuncts_) {
       msg.join_node.nested_loop_join_node.addToJoin_conjuncts(e.treeToThrift(serialCtx));
     }
+    populateHboThriftFields(msg, serialCtx);
   }
 
   @Override
diff --git a/fe/src/main/java/org/apache/impala/planner/PlanNode.java b/fe/src/main/java/org/apache/impala/planner/PlanNode.java
index b7e1a0789..401c5a2dc 100644
--- a/fe/src/main/java/org/apache/impala/planner/PlanNode.java
+++ b/fe/src/main/java/org/apache/impala/planner/PlanNode.java
@@ -216,6 +216,14 @@ abstract public class PlanNode extends TreeNode<PlanNode> {
   // Cardinality before an HBO match replaced it. Only meaningful when hboMatch_ is set.
   protected long cardinalityBeforeHbo_ = -1;
 
+  // Cached result for getHboOrderedOperands(). See more in method comments.
+  private List<PlanNode> hboOrderedOperands_;
+
+  // Cached operand-qualifier map, computed eagerly in init() when HBO is enabled.
+  // See buildHboOperandQualifierMap() for how the map is built. Null when HBO is off.
+  // Empty when this node's subtree exposes no join (a single unqualified operand).
+  private Map<TupleId, String> hboOperandQualifierMap_;
+
   protected PlanNode(PlanNodeId id, List<TupleId> tupleIds, String displayName) {
     this(id, displayName);
     tupleIds_.addAll(tupleIds);
@@ -368,6 +376,7 @@ abstract public class PlanNode extends TreeNode<PlanNode> {
   protected void setDisplayName(String s) { displayName_ = s; }
 
   final protected String getDisplayLabel() {
+    if (id_ == null) return displayName_;
     return String.format("%s:%s", id_.toString(), displayName_);
   }
 
@@ -710,6 +719,7 @@ abstract public class PlanNode extends TreeNode<PlanNode> {
    */
   public void init(Analyzer analyzer) throws ImpalaException {
     assignConjuncts(analyzer);
+    computeHboOperandQualifierMap(analyzer);
     computeStats(analyzer);
     validateCardinality();
     createDefaultSmap(analyzer);
@@ -1060,21 +1070,38 @@ abstract public class PlanNode extends TreeNode<PlanNode> {
    */
   public boolean isCardinalityPreserving() { return false; }
 
+  /**
+   * Returns true if parent node can reference operand alias in/under this node.
+   */
+  public boolean isOperandTransparent() { return false; }
+
   record HboKeyedNode(String key, int originalIndex, PlanNode node) {}
 
   /**
-   * Returns children_ sorted by their concatenated and sorted scan table names.
-   * The sort is stable so two children with the same names preserve their original order
-   * in the query. Another query that flips their order will have a different HBO key
-   * string, which misses the HBO stats. Such cases are rare in practice, so we don't
-   * optimize them for simplicity. The returned list is cached and reused since the order
-   * depends only on table names, which are fixed after tree construction.
+   * Returns the logical operands of this node that should be HBO-ordered by
+   * {@link #getHboOrderedOperands}. Defaults to children_ (e.g. UnionNode's operands are
+   * its children). Nodes whose operand list isn't simply children_ (e.g. JoinNode, which
+   * flattens a contiguous inner/cross join group) override this.
+   */
+  protected List<PlanNode> getFlattenOperands() { return children_; }
+
+  /**
+   * Returns getFlattenOperands() sorted by each operand's concatenated and sorted scan
+   * table names. The sort is stable that two operands with the same names keep their
+   * order in the query. Another query that flips their order will have a different HBO
+   * key string, which misses the HBO stats. Such cases are rare in practice, so we don't
+   * optimize them for simplicity.
+   * The returned list is cached and reused to ensure all the callers get a consistent
+   * view regardless of tree structure changes. E.g. join inversion swaps children in
+   * place. Recomputing the list would flip operands on the same table, which changes the
+   * HBO key and is what we want to avoid.
    */
   protected List<PlanNode> getHboOrderedOperands() {
     if (hboOrderedOperands_ == null) {
-      hboOrderedOperands_ = IntStream.range(0, children_.size())
+      List<PlanNode> operands = getFlattenOperands();
+      hboOrderedOperands_ = IntStream.range(0, operands.size())
           .mapToObj(i -> {
-            PlanNode node = children_.get(i);
+            PlanNode node = operands.get(i);
             List<ScanNode> scans = new ArrayList<>();
             node.collect(ScanNode.class, scans);
             String key = scans.stream()
@@ -1090,7 +1117,39 @@ abstract public class PlanNode extends TreeNode<PlanNode> {
     }
     return hboOrderedOperands_;
   }
-  private List<PlanNode> hboOrderedOperands_;
+
+  Map<TupleId, String> getHboOperandQualifierMap() { return hboOperandQualifierMap_; }
+
+  /**
+   * Builds the canonical operand-qualifier map (TupleId -> operand path) that this node's
+   * subtree exposes. Empty when the subtree exposes no join, e.g. a scan/aggregation
+   * (possibly wrapped by operand-transparent nodes) whose columns need no qualification.
+   */
+  protected Map<TupleId, String> buildHboOperandQualifierMap(String prefix) {
+    if (isOperandTransparent()) {
+      Preconditions.checkState(getChildCount() == 1);
+      return getChild(0).buildHboOperandQualifierMap(prefix);
+    }
+    // Empty prefix at a leaf means "no join above"
+    if (prefix.isEmpty()) return Collections.emptyMap();
+    // Keeps the prefix by default. Nodes that add nested operand index into the prefix,
+    // e.g. JoinNode, should override this.
+    Map<TupleId, String> map = new HashMap<>(tupleIds_.size());
+    tupleIds_.forEach(id -> map.put(id, prefix));
+    return map;
+  }
+
+  /**
+   * Computes and caches hboOperandQualifierMap_ when HBO is enabled. This only depends on
+   * the tree structure so should be invoked in init() where all the children have been
+   * added.
+   */
+  protected void computeHboOperandQualifierMap(Analyzer analyzer) {
+    TQueryOptions opts = analyzer.getQueryOptions();
+    if (opts.use_hbo_stats || opts.store_hbo_stats) {
+      hboOperandQualifierMap_ = buildHboOperandQualifierMap("");
+    }
+  }
 
   /**
    * Generates an HBO key string for this node, or null if HBO is not supported.
@@ -1124,6 +1183,17 @@ abstract public class PlanNode extends TreeNode<PlanNode> {
     }
   }
 
+  /**
+   * Helper to start generating an HBO key string for a stats type and a given header.
+   * PlanNode fields like limit_ can be added here.
+   */
+  public StringBuilder startHboKeyString(THboStatsType statsType, String header) {
+    StringBuilder sb = new StringBuilder(statsType.name())
+        .append(header);
+    if (limit_ > 0) sb.append("|limit:").append(limit_);
+    return sb;
+  }
+
   /** The caveat of the strategy that matched, ready to follow "from HBO" in EXPLAIN. */
   private String hboCaveat() {
     String caveat = hboMatch_.strategy().getMatchCaveat();
diff --git a/fe/src/main/java/org/apache/impala/planner/TupleCacheNode.java b/fe/src/main/java/org/apache/impala/planner/TupleCacheNode.java
index 8dd7a71e5..890083a3f 100644
--- a/fe/src/main/java/org/apache/impala/planner/TupleCacheNode.java
+++ b/fe/src/main/java/org/apache/impala/planner/TupleCacheNode.java
@@ -148,4 +148,7 @@ public class TupleCacheNode extends PlanNode {
   @Override
   public boolean isCardinalityPreserving() { return true; }
 
+  @Override
+  public boolean isOperandTransparent() { return true; }
+
 }
diff --git a/fe/src/main/java/org/apache/impala/planner/UnionNode.java b/fe/src/main/java/org/apache/impala/planner/UnionNode.java
index 7e96a7587..69d34af9b 100644
--- a/fe/src/main/java/org/apache/impala/planner/UnionNode.java
+++ b/fe/src/main/java/org/apache/impala/planner/UnionNode.java
@@ -369,10 +369,9 @@ public class UnionNode extends PlanNode {
   @Override
   public String generateHboKeyString(THboStatsType statsType,
       CanonicalizationStrategy strategy) {
-    StringBuilder sb = new StringBuilder(statsType.name()).append(":UnionNode:");
-    if (limit_ > 0) sb.append("limit:").append(limit_).append("|");
+    StringBuilder sb = startHboKeyString(statsType, ":UnionNode:");
     if (!constExprLists_.isEmpty() && !addConstOpsToHboKeyString(sb)) return null;
-    sb.append("operands:[");
+    sb.append("|Operands:[");
     boolean first = true;
     for (PlanNode operand : getHboOrderedOperands()) {
       String childKey = operand.generateHboKeyString(statsType, strategy);
@@ -386,7 +385,7 @@ public class UnionNode extends PlanNode {
   }
 
   private boolean addConstOpsToHboKeyString(StringBuilder sb) {
-    sb.append("constRows:[");
+    sb.append("|ConstRows:[");
     for (int i = 0; i < constExprLists_.size(); i++) {
       List<Expr> row = constExprLists_.get(i);
       if (i > 0) sb.append(",");
@@ -405,7 +404,7 @@ public class UnionNode extends PlanNode {
       }
       sb.append(")");
     }
-    sb.append("]|");
+    sb.append("]");
     return true;
   }
 
diff --git a/fe/src/test/java/org/apache/impala/planner/HboKeyStringTest.java b/fe/src/test/java/org/apache/impala/planner/HboKeyStringTest.java
index 7eadcc4d6..f9cc78c87 100644
--- a/fe/src/test/java/org/apache/impala/planner/HboKeyStringTest.java
+++ b/fe/src/test/java/org/apache/impala/planner/HboKeyStringTest.java
@@ -63,10 +63,10 @@ public class HboKeyStringTest extends FrontendTestBase {
   static {
     ALLTYPES_SCAN_CHILD_KEYS.put(CanonicalizationStrategy.EXPR_REWRITE,
         "CARDINALITY:ScanNode:functional.alltypes|" +
-        "`month` > 1|`year` = 2009|bigint_col IN (0, 1)|int_col = 0|");
+        "`month` > 1|`year` = 2009|bigint_col IN (0, 1)|int_col = 0");
     ALLTYPES_SCAN_CHILD_KEYS.put(CanonicalizationStrategy.IGNORE_PARTITION_CONSTANTS,
         "CARDINALITY:ScanNode:functional.alltypes|" +
-        "`month` > 1|`year`=<CONST>|bigint_col IN (0, 1)|int_col = 0|");
+        "`month` > 1|`year`=<CONST>|bigint_col IN (0, 1)|int_col = 0");
   }
 
   private List<PlanFragment> planFragments(String query) throws ImpalaException {
@@ -126,13 +126,13 @@ public class HboKeyStringTest extends FrontendTestBase {
     String exprRewriteKey = scanNode.generateHboKeyString(
         THboStatsType.CARDINALITY, CanonicalizationStrategy.EXPR_REWRITE);
     String expectedExprRewriteKey = "CARDINALITY:ScanNode:functional.alltypes|" +
-        "`month` > 1|`year` = 2009|bigint_col IN (0, 1)|int_col = 0|";
+        "`month` > 1|`year` = 2009|bigint_col IN (0, 1)|int_col = 0";
     assertEquals(expectedExprRewriteKey, exprRewriteKey);
 
     String ignorePartConstkey = scanNode.generateHboKeyString(
         THboStatsType.CARDINALITY, CanonicalizationStrategy.IGNORE_PARTITION_CONSTANTS);
     String expectedIgnorePartConstKey = "CARDINALITY:ScanNode:functional.alltypes|" +
-        "`month` > 1|`year`=<CONST>|bigint_col IN (0, 1)|int_col = 0|";
+        "`month` > 1|`year`=<CONST>|bigint_col IN (0, 1)|int_col = 0";
     assertEquals(expectedIgnorePartConstKey, ignorePartConstkey);
   }
 
@@ -149,7 +149,7 @@ public class HboKeyStringTest extends FrontendTestBase {
     String childKey = ALLTYPES_SCAN_CHILD_KEYS.get(
         CanonicalizationStrategy.EXPR_REWRITE);
     String expectedKeyFmt = "CARDINALITY:AggregationNode:FIRST|" +
-        "preagg:true|groupingSet:false|AggClasses:[0:GROUP:`month`]|CHILD:[%s]";
+        "Preagg:true|GroupingSet:false|AggClasses:[0:Group:`month`]|Child:[%s]";
     assertEquals(String.format(expectedKeyFmt, childKey), exprRewriteKey);
     String ignorePartConstKey = aggregationNode.generateHboKeyString(
         THboStatsType.CARDINALITY, CanonicalizationStrategy.IGNORE_PARTITION_CONSTANTS);
@@ -162,8 +162,8 @@ public class HboKeyStringTest extends FrontendTestBase {
     exprRewriteKey = aggregationNode.generateHboKeyString(
         THboStatsType.CARDINALITY, CanonicalizationStrategy.EXPR_REWRITE);
     expectedKeyFmt = "CARDINALITY:AggregationNode:FIRST|" +
-        "preagg:false|groupingSet:false|AggClasses:[0:GROUP:`month`]|" +
-        "HAVING:count(id) > 10|CHILD:[%s]";
+        "Preagg:false|GroupingSet:false|AggClasses:[0:Group:`month`]|" +
+        "Having:count(id) > 10|Child:[%s]";
     assertEquals(String.format(expectedKeyFmt, childKey), exprRewriteKey);
     ignorePartConstKey = aggregationNode.generateHboKeyString(
         THboStatsType.CARDINALITY, CanonicalizationStrategy.IGNORE_PARTITION_CONSTANTS);
@@ -172,10 +172,14 @@ public class HboKeyStringTest extends FrontendTestBase {
   }
 
   private static final String ALIAS_TEST_AGG_KEY_FMT =
-      "CARDINALITY:AggregationNode:FIRST|preagg:false|groupingSet:false|" +
-      "AggClasses:[0:GROUP:%s]|CHILD:[%s]";
-  private static final String ALIAS_TEST_SCAN_CHILD_KEY =
-      "CARDINALITY:ScanNode:functional.alltypes|";
+      "CARDINALITY:AggregationNode:FIRST|Preagg:false|GroupingSet:false|" +
+      "AggClasses:[0:Group:%s]|Child:[%s]";
+  private static final String ALLTYPES_SCAN_KEY =
+      "CARDINALITY:ScanNode:functional.alltypes";
+  private static final String ALLTYPESTINY_SCAN_KEY =
+      "CARDINALITY:ScanNode:functional.alltypestiny";
+  private static final String ALLTYPESSMALL_SCAN_KEY =
+      "CARDINALITY:ScanNode:functional.alltypessmall";
 
   @Test
   public void testAggKeyResolvesColumnAlias() throws ImpalaException {
@@ -190,9 +194,9 @@ public class HboKeyStringTest extends FrontendTestBase {
       String k2 = finalAggNode(q2).generateHboKeyString(
           THboStatsType.CARDINALITY, strategy);
       assertEquals(String.format(ALIAS_TEST_AGG_KEY_FMT, "id",
-          ALIAS_TEST_SCAN_CHILD_KEY), k1);
+          ALLTYPES_SCAN_KEY), k1);
       assertEquals(String.format(ALIAS_TEST_AGG_KEY_FMT, "int_col",
-          ALIAS_TEST_SCAN_CHILD_KEY), k2);
+          ALLTYPES_SCAN_KEY), k2);
       assertNotEquals(k1, k2);
     }
   }
@@ -210,9 +214,9 @@ public class HboKeyStringTest extends FrontendTestBase {
       String k2 = finalAggNode(q2).generateHboKeyString(
           THboStatsType.CARDINALITY, strategy);
       assertEquals(String.format(ALIAS_TEST_AGG_KEY_FMT, "id + int_col",
-          ALIAS_TEST_SCAN_CHILD_KEY), k1);
+          ALLTYPES_SCAN_KEY), k1);
       assertEquals(String.format(ALIAS_TEST_AGG_KEY_FMT, "id + bigint_col",
-          ALIAS_TEST_SCAN_CHILD_KEY), k2);
+          ALLTYPES_SCAN_KEY), k2);
       assertNotEquals(k1, k2);
     }
   }
@@ -226,7 +230,7 @@ public class HboKeyStringTest extends FrontendTestBase {
         "(select id bi, int_col from functional.alltypes) t group by bi";
     for (CanonicalizationStrategy strategy : CanonicalizationStrategy.values()) {
       String expected = String.format(ALIAS_TEST_AGG_KEY_FMT, "id",
-          ALIAS_TEST_SCAN_CHILD_KEY);
+          ALLTYPES_SCAN_KEY);
       assertEquals(expected, finalAggNode(q1).generateHboKeyString(
           THboStatsType.CARDINALITY, strategy));
       assertEquals(expected, finalAggNode(q2).generateHboKeyString(
@@ -251,46 +255,46 @@ public class HboKeyStringTest extends FrontendTestBase {
       String exprRewriteKey = aggregationNode.generateHboKeyString(
           THboStatsType.CARDINALITY, strategy);
       String expectedKeyFmt = "CARDINALITY:AggregationNode:FIRST|" +
-          "preagg:true|groupingSet:false|" +
-          "AggClasses:[0:GROUP:`month`,bigint_col,1:GROUP:`month`,int_col]|" +
-          "CHILD:[%s]";
+          "Preagg:true|GroupingSet:false|" +
+          "AggClasses:[0:Group:`month`,bigint_col,1:Group:`month`,int_col]|" +
+          "Child:[%s]";
       assertEquals(String.format(expectedKeyFmt, childKey), exprRewriteKey);
       // FinalAgg for FIRST phase
       aggregationNode = (AggregationNode) planNodes.get(5);
       exprRewriteKey = aggregationNode.generateHboKeyString(
           THboStatsType.CARDINALITY, strategy);
       expectedKeyFmt = "CARDINALITY:AggregationNode:FIRST|" +
-          "preagg:false|groupingSet:false|" +
-          "AggClasses:[0:GROUP:`month`,bigint_col,1:GROUP:`month`,int_col]|" +
-          "CHILD:[%s]";
+          "Preagg:false|GroupingSet:false|" +
+          "AggClasses:[0:Group:`month`,bigint_col,1:Group:`month`,int_col]|" +
+          "Child:[%s]";
       assertEquals(String.format(expectedKeyFmt, childKey), exprRewriteKey);
       // PreAgg for MERGE phase
       aggregationNode = (AggregationNode) planNodes.get(2);
       exprRewriteKey = aggregationNode.generateHboKeyString(
           THboStatsType.CARDINALITY, strategy);
       expectedKeyFmt = "CARDINALITY:AggregationNode:MERGE|" +
-          "preagg:true|groupingSet:false|" +
-          "AggClasses:[0:GROUP:`month`,1:GROUP:`month`]|" +
-          "CHILD:[%s]";
+          "Preagg:true|GroupingSet:false|" +
+          "AggClasses:[0:Group:`month`,1:Group:`month`]|" +
+          "Child:[%s]";
       assertEquals(String.format(expectedKeyFmt, childKey), exprRewriteKey);
       // FinalAgg for MERGE phase
       aggregationNode = (AggregationNode) planNodes.get(7);
       exprRewriteKey = aggregationNode.generateHboKeyString(
           THboStatsType.CARDINALITY, strategy);
       expectedKeyFmt = "CARDINALITY:AggregationNode:MERGE|" +
-          "preagg:false|groupingSet:false|" +
-          "AggClasses:[0:GROUP:`month`,1:GROUP:`month`]|" +
-          "CHILD:[%s]";
+          "Preagg:false|GroupingSet:false|" +
+          "AggClasses:[0:Group:`month`,1:Group:`month`]|" +
+          "Child:[%s]";
       assertEquals(String.format(expectedKeyFmt, childKey), exprRewriteKey);
       // Agg for TRANSPOSE phase
       aggregationNode = (AggregationNode) planNodes.get(3);
       exprRewriteKey = aggregationNode.generateHboKeyString(
           THboStatsType.CARDINALITY, strategy);
       expectedKeyFmt = "CARDINALITY:AggregationNode:TRANSPOSE|" +
-          "preagg:false|groupingSet:false|AggClasses:[" +
-          "0:GROUP:CASE valid_tid(2,4) WHEN 2 THEN `month` WHEN 4 THEN `month` END]|" +
-          "HAVING:aggif(valid_tid(2,4) = 2, count(int_col)) > 10|" +
-          "CHILD:[%s]";
+          "Preagg:false|GroupingSet:false|AggClasses:[" +
+          "0:Group:CASE valid_tid(2,4) WHEN 2 THEN `month` WHEN 4 THEN `month` END]|" +
+          "Having:aggif(valid_tid(2,4) = 2, count(int_col)) > 10|" +
+          "Child:[%s]";
       assertEquals(String.format(expectedKeyFmt, childKey), exprRewriteKey);
     }
   }
@@ -312,31 +316,31 @@ public class HboKeyStringTest extends FrontendTestBase {
       String exprRewriteKey = aggregationNode.generateHboKeyString(
           THboStatsType.CARDINALITY, strategy);
       String expectedKeyFmt = "CARDINALITY:AggregationNode:FIRST|" +
-          "preagg:true|groupingSet:true|" +
-          "AggClasses:[0:GROUP:NULL,NULL,1:GROUP:`month`,`year`]|" +
-          "CHILD:[%s]";
+          "Preagg:true|GroupingSet:true|" +
+          "AggClasses:[0:Group:NULL,NULL,1:Group:`month`,`year`]|" +
+          "Child:[%s]";
       assertEquals(String.format(expectedKeyFmt, childKey), exprRewriteKey);
       // FinalAgg
       aggregationNode = (AggregationNode) planNodes.get(4);
       exprRewriteKey = aggregationNode.generateHboKeyString(
           THboStatsType.CARDINALITY, strategy);
       expectedKeyFmt = "CARDINALITY:AggregationNode:FIRST|" +
-          "preagg:false|groupingSet:true|" +
-          "AggClasses:[0:GROUP:NULL,NULL,1:GROUP:`month`,`year`]|" +
-          "CHILD:[%s]";
+          "Preagg:false|GroupingSet:true|" +
+          "AggClasses:[0:Group:NULL,NULL,1:Group:`month`,`year`]|" +
+          "Child:[%s]";
       assertEquals(String.format(expectedKeyFmt, childKey), exprRewriteKey);
       // TRANSPOSE Agg
       aggregationNode = (AggregationNode) planNodes.get(2);
       exprRewriteKey = aggregationNode.generateHboKeyString(
           THboStatsType.CARDINALITY, strategy);
       expectedKeyFmt = "CARDINALITY:AggregationNode:TRANSPOSE|" +
-          "preagg:false|groupingSet:true|AggClasses:[" +
-          "0:GROUP:CASE valid_tid(1,2) WHEN 1 THEN 1 WHEN 2 THEN 2 END," +
+          "Preagg:false|GroupingSet:true|AggClasses:[" +
+          "0:Group:CASE valid_tid(1,2) WHEN 1 THEN 1 WHEN 2 THEN 2 END," +
           "CASE valid_tid(1,2) WHEN 1 THEN `month` WHEN 2 THEN NULL END," +
           "CASE valid_tid(1,2) WHEN 1 THEN `year` WHEN 2 THEN NULL END]|" +
-          "HAVING:aggif(valid_tid(1,2) IN (1, 2), " +
+          "Having:aggif(valid_tid(1,2) IN (1, 2), " +
           "CASE valid_tid(1,2) WHEN 1 THEN count(id) WHEN 2 THEN count(id) END) > 10|" +
-          "CHILD:[%s]";
+          "Child:[%s]";
       assertEquals(String.format(expectedKeyFmt, childKey), exprRewriteKey);
     }
   }
@@ -370,9 +374,9 @@ public class HboKeyStringTest extends FrontendTestBase {
     String query = "select distinct id from functional.alltypestiny limit 2";
     Map<Integer, PlanNode> nodes = collectPlanNodesInDistributedPlan(query);
     PlanNode aggNode = nodes.get(1);
-    assertEquals("CARDINALITY:AggregationNode:FIRST|preagg:false|groupingSet:false|"
-        + "limit:2|AggClasses:[0:GROUP:id]|CHILD:["
-        + "CARDINALITY:ScanNode:functional.alltypestiny|]",
+    assertEquals("CARDINALITY:AggregationNode:FIRST|limit:2|Preagg:false|"
+        + "GroupingSet:false|AggClasses:[0:Group:id]|Child:["
+        + "CARDINALITY:ScanNode:functional.alltypestiny]",
         aggNode.generateHboKeyString(
             THboStatsType.CARDINALITY, CanonicalizationStrategy.EXPR_REWRITE));
   }
@@ -415,9 +419,9 @@ public class HboKeyStringTest extends FrontendTestBase {
 
     // Operands are sorted by base scan table name, so alltypes comes first.
     String scanAllER =
-        "CARDINALITY:ScanNode:functional.alltypes|`year` = 2009|int_col = 0|";
-    String scanTinyER = "CARDINALITY:ScanNode:functional.alltypestiny|int_col = 0|";
-    String expectedER = "CARDINALITY:UnionNode:operands:["
+        "CARDINALITY:ScanNode:functional.alltypes|`year` = 2009|int_col = 0";
+    String scanTinyER = "CARDINALITY:ScanNode:functional.alltypestiny|int_col = 0";
+    String expectedER = "CARDINALITY:UnionNode:|Operands:["
         + scanAllER + "," + scanTinyER + "]";
     assertEquals(expectedER, union1.generateHboKeyString(
         THboStatsType.CARDINALITY, CanonicalizationStrategy.EXPR_REWRITE));
@@ -425,8 +429,8 @@ public class HboKeyStringTest extends FrontendTestBase {
         THboStatsType.CARDINALITY, CanonicalizationStrategy.EXPR_REWRITE));
 
     String scanAllIPC =
-        "CARDINALITY:ScanNode:functional.alltypes|`year`=<CONST>|int_col = 0|";
-    String expectedIPC = "CARDINALITY:UnionNode:operands:["
+        "CARDINALITY:ScanNode:functional.alltypes|`year`=<CONST>|int_col = 0";
+    String expectedIPC = "CARDINALITY:UnionNode:|Operands:["
         + scanAllIPC + "," + scanTinyER + "]";
     assertEquals(expectedIPC, union1.generateHboKeyString(
         THboStatsType.CARDINALITY,
@@ -450,9 +454,9 @@ public class HboKeyStringTest extends FrontendTestBase {
         + "union all select 2, '2'";
     PlanNode union = singleUnion(query);
     String scanAllER =
-        "CARDINALITY:ScanNode:functional.alltypes|`year` = 2009|int_col = 0|";
+        "CARDINALITY:ScanNode:functional.alltypes|`year` = 2009|int_col = 0";
     String expectedER = "CARDINALITY:UnionNode:"
-        + "constRows:[(INT:1,STRING:'1'),(INT:2,STRING:'2')]|operands:["
+        + "|ConstRows:[(INT:1,STRING:'1'),(INT:2,STRING:'2')]|Operands:["
         + scanAllER + "]";
     assertEquals(expectedER, union.generateHboKeyString(
         THboStatsType.CARDINALITY, CanonicalizationStrategy.EXPR_REWRITE));
@@ -476,9 +480,9 @@ public class HboKeyStringTest extends FrontendTestBase {
     assertTrue(msg.isSetHbo_hash_keys());
     assertTrue(msg.isSetExec_stats());
     assertEquals(0, msg.getExec_stats().getScan_input_statsSize());
-    assertEquals("CARDINALITY:AggregationNode:FIRST|preagg:false|groupingSet:false|"
-        + "AggClasses:[0:GROUP:1]|CHILD:[CARDINALITY:UnionNode:constRows:"
-        + "[(INT:1),(INT:2)]|operands:[]]",
+    assertEquals("CARDINALITY:AggregationNode:FIRST|Preagg:false|GroupingSet:false|"
+        + "AggClasses:[0:Group:1]|Child:[CARDINALITY:UnionNode:|ConstRows:"
+        + "[(INT:1),(INT:2)]|Operands:[]]",
         agg.generateHboKeyString(
             THboStatsType.CARDINALITY, CanonicalizationStrategy.EXPR_REWRITE));
   }
@@ -510,8 +514,8 @@ public class HboKeyStringTest extends FrontendTestBase {
     options.setEnable_expr_rewrites(false);
     String query = "select 1 + 1 union all select id from functional.alltypes";
     UnionNode union = singleUnion(query, options);
-    String expectedER = "CARDINALITY:UnionNode:constRows:[(1 + 1)]|operands:["
-        + "CARDINALITY:ScanNode:functional.alltypes|]";
+    String expectedER = "CARDINALITY:UnionNode:|ConstRows:[(1 + 1)]|Operands:["
+        + "CARDINALITY:ScanNode:functional.alltypes]";
     assertEquals(expectedER, union.generateHboKeyString(
         THboStatsType.CARDINALITY, CanonicalizationStrategy.EXPR_REWRITE));
   }
@@ -520,10 +524,10 @@ public class HboKeyStringTest extends FrontendTestBase {
   public void testUnionNodeLimit() throws ImpalaException {
     String q = "select id from functional.alltypestiny union all values(9),(10) limit 1";
     Map<Integer, PlanNode> nodes = collectPlanNodesInDistributedPlan(q);
-    String scanKey = "CARDINALITY:ScanNode:functional.alltypestiny|";
-    String innerUnionKey = "CARDINALITY:UnionNode:limit:1|"
-        + "constRows:[(INT:9),(INT:10)]|operands:[]";
-    String outerUnionKey = "CARDINALITY:UnionNode:operands:["
+    String scanKey = "CARDINALITY:ScanNode:functional.alltypestiny";
+    String innerUnionKey = "CARDINALITY:UnionNode:|limit:1|"
+        + "ConstRows:[(INT:9),(INT:10)]|Operands:[]";
+    String outerUnionKey = "CARDINALITY:UnionNode:|Operands:["
         + innerUnionKey + "," + scanKey + "]";
     UnionNode innerUnion = (UnionNode) nodes.get(2);
     UnionNode outerUnion = (UnionNode) nodes.get(0);
@@ -536,9 +540,584 @@ public class HboKeyStringTest extends FrontendTestBase {
         + "select id from functional.alltypestiny union all values(9),(10)"
         + ") t limit 1";
     UnionNode union = singleUnion(q);
-    String unionKey = "CARDINALITY:UnionNode:limit:1|"
-        + "constRows:[(INT:9),(INT:10)]|operands:[" + scanKey + "]";
+    String unionKey = "CARDINALITY:UnionNode:|limit:1|"
+        + "ConstRows:[(INT:9),(INT:10)]|Operands:[" + scanKey + "]";
     assertEquals(unionKey, union.generateHboKeyString(
         THboStatsType.CARDINALITY, CanonicalizationStrategy.EXPR_REWRITE));
   }
+
+  /** Counts the number of JoinNodes in the plan node map. */
+  private int countJoinNodes(Map<Integer, PlanNode> planNodes) {
+    int count = 0;
+    for (PlanNode n : planNodes.values()) {
+      if (n instanceof JoinNode) count++;
+    }
+    return count;
+  }
+
+  private JoinNode singleJoin(String query) throws ImpalaException {
+    Map<Integer, PlanNode> nodes = collectPlanNodesInDistributedPlan(query);
+    assertEquals("Expected exactly one JoinNode for query: " + query, 1,
+        countJoinNodes(nodes));
+    for (PlanNode n : nodes.values()) {
+      if (n instanceof JoinNode) return (JoinNode) n;
+    }
+    return null;
+  }
+
+  /**
+   * Plans {@code query}, asserts it has exactly one JoinNode, and checks the
+   * JoinNode's HBO key string against the expected values for both
+   * canonicalization strategies.
+   */
+  private void verifySingleJoinKey(String query, String expectedExprRewrite,
+      String expectedIgnorePartConsts) throws ImpalaException {
+    JoinNode join = singleJoin(query);
+    assertEquals("Wrong key for query: " + query, expectedExprRewrite,
+        join.generateHboKeyString(THboStatsType.CARDINALITY,
+            CanonicalizationStrategy.EXPR_REWRITE));
+    assertEquals("Wrong key for query: " + query, expectedIgnorePartConsts,
+        join.generateHboKeyString(THboStatsType.CARDINALITY,
+            CanonicalizationStrategy.IGNORE_PARTITION_CONSTANTS));
+  }
+
+  @Test
+  public void testInnerJoinGroupKeyIsOrderIndependent() throws ImpalaException {
+    // STRAIGHT_JOIN preserves FROM-clause order so the planner builds two different join
+    // trees. The HBO key for the top join must be identical between the two queries
+    // because the inner-join group flattens both trees into the same set of operands and
+    // predicates.
+    String filters = "where a.year=2009 and b.year=2009 and c.year=2009 "
+        + "and a.int_col=0 and b.int_col=0 and c.int_col=0";
+    String q1 = "select STRAIGHT_JOIN count(*) from functional.alltypes c "
+        + "join functional.alltypessmall b on c.id = b.id "
+        + "join functional.alltypestiny a on b.id = a.id " + filters;
+    String q2 = "select STRAIGHT_JOIN count(*) from functional.alltypestiny a "
+        + "join functional.alltypessmall b on a.id = b.id "
+        + "join functional.alltypes c on b.id = c.id " + filters;
+
+    // Plan IDs: scans 0/1/2, bottom join 3, top join 4.
+    final int BOTTOM_JOIN_ID = 3;
+    final int TOP_JOIN_ID = 4;
+
+    Map<Integer, PlanNode> q1Nodes = collectPlanNodesInDistributedPlan(q1);
+    Map<Integer, PlanNode> q2Nodes = collectPlanNodesInDistributedPlan(q2);
+
+    // Scan keys in ExprRewrite (ER) and IgnorePartitionConstants (IPC) strategies.
+    String scanAllER =
+        "CARDINALITY:ScanNode:functional.alltypes|`year` = 2009|int_col = 0";
+    String scanSmallER =
+        "CARDINALITY:ScanNode:functional.alltypessmall|`year` = 2009|int_col = 0";
+    String scanTinyER =
+        "CARDINALITY:ScanNode:functional.alltypestiny|`year` = 2009|int_col = 0";
+    String scanAllIPC =
+        "CARDINALITY:ScanNode:functional.alltypes|`year`=<CONST>|int_col = 0";
+    String scanSmallIPC =
+        "CARDINALITY:ScanNode:functional.alltypessmall|`year`=<CONST>|int_col = 0";
+    String scanTinyIPC =
+        "CARDINALITY:ScanNode:functional.alltypestiny|`year`=<CONST>|int_col = 0";
+
+    // OPERANDS are sorted by scan table name (functional.alltypes <
+    // functional.alltypessmall < functional.alltypestiny), and join-predicate columns are
+    // qualified with their operand's index in that sorted list ("op<idx>").
+    // q1 bottom join (op0:alltypes, op1:alltypessmall)
+    // q2 bottom join (op0:alltypestiny, op1:alltypessmall)
+    String expectedQ1BottomER = "CARDINALITY:JoinNode:INNER|Operands:["
+        + scanAllER + "," + scanSmallER + "]|Predicates:[op0.id=op1.id]";
+    String expectedQ2BottomER = "CARDINALITY:JoinNode:INNER|Operands:["
+        + scanSmallER + "," + scanTinyER + "]|Predicates:[op0.id=op1.id]";
+    // Top join operands sorted: 0 = all, 1 = small, 2 = tiny. Edges all-small and
+    // small-tiny render as op0.id=op1.id and op1.id=op2.id (then sorted).
+    String expectedTopER = "CARDINALITY:JoinNode:INNER|Operands:["
+        + scanAllER + "," + scanSmallER + "," + scanTinyER
+        + "]|Predicates:[op0.id=op1.id,op1.id=op2.id]";
+
+    String expectedQ1BottomIPC = "CARDINALITY:JoinNode:INNER|Operands:["
+        + scanAllIPC + "," + scanSmallIPC + "]|Predicates:[op0.id=op1.id]";
+    String expectedQ2BottomIPC = "CARDINALITY:JoinNode:INNER|Operands:["
+        + scanSmallIPC + "," + scanTinyIPC + "]|Predicates:[op0.id=op1.id]";
+    String expectedTopIPC = "CARDINALITY:JoinNode:INNER|Operands:["
+        + scanAllIPC + "," + scanSmallIPC + "," + scanTinyIPC
+        + "]|Predicates:[op0.id=op1.id,op1.id=op2.id]";
+
+    // q1 bottom join is (alltypes, alltypessmall).
+    JoinNode q1Bottom = (JoinNode) q1Nodes.get(BOTTOM_JOIN_ID);
+    JoinNode q1Top = (JoinNode) q1Nodes.get(TOP_JOIN_ID);
+    assertEquals(expectedQ1BottomER, q1Bottom.generateHboKeyString(
+        THboStatsType.CARDINALITY, CanonicalizationStrategy.EXPR_REWRITE));
+    assertEquals(expectedQ1BottomIPC, q1Bottom.generateHboKeyString(
+        THboStatsType.CARDINALITY,
+        CanonicalizationStrategy.IGNORE_PARTITION_CONSTANTS));
+    assertEquals(expectedTopER, q1Top.generateHboKeyString(
+        THboStatsType.CARDINALITY, CanonicalizationStrategy.EXPR_REWRITE));
+    assertEquals(expectedTopIPC, q1Top.generateHboKeyString(
+        THboStatsType.CARDINALITY,
+        CanonicalizationStrategy.IGNORE_PARTITION_CONSTANTS));
+
+    // q2 bottom join is (alltypestiny, alltypessmall).
+    JoinNode q2Bottom = (JoinNode) q2Nodes.get(BOTTOM_JOIN_ID);
+    JoinNode q2Top = (JoinNode) q2Nodes.get(TOP_JOIN_ID);
+    assertEquals(expectedQ2BottomER, q2Bottom.generateHboKeyString(
+        THboStatsType.CARDINALITY, CanonicalizationStrategy.EXPR_REWRITE));
+    assertEquals(expectedQ2BottomIPC, q2Bottom.generateHboKeyString(
+        THboStatsType.CARDINALITY,
+        CanonicalizationStrategy.IGNORE_PARTITION_CONSTANTS));
+    assertEquals(expectedTopER, q2Top.generateHboKeyString(
+        THboStatsType.CARDINALITY, CanonicalizationStrategy.EXPR_REWRITE));
+    assertEquals(expectedTopIPC, q2Top.generateHboKeyString(
+        THboStatsType.CARDINALITY,
+        CanonicalizationStrategy.IGNORE_PARTITION_CONSTANTS));
+
+    // Compare keys of two queries.
+    for (CanonicalizationStrategy strategy : CanonicalizationStrategy.values()) {
+      assertNotEquals(
+          "Bottom join keys must differ between FROM-clause orderings for "
+              + strategy,
+          q1Bottom.generateHboKeyString(THboStatsType.CARDINALITY, strategy),
+          q2Bottom.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+      assertEquals(
+          "Top join keys must match between FROM-clause orderings for " + strategy,
+          q1Top.generateHboKeyString(THboStatsType.CARDINALITY, strategy),
+          q2Top.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+    }
+  }
+
+  @Test
+  public void testJoinOperandAlias() throws ImpalaException {
+    // Two joins of the same two tables on the same columns but with the column-to-table
+    // assignment (alias) swapped must NOT produce the same key.
+    String q1 = "select count(*) from functional.alltypes a "
+        + "join functional.alltypestiny b on a.id = b.int_col";
+    String q2 = "select count(*) from functional.alltypestiny a "
+        + "join functional.alltypes b on a.id = b.int_col";
+
+    JoinNode join1 = singleJoin(q1);
+    JoinNode join2 = singleJoin(q2);
+
+    // OPERANDS sorted by table name: alltypes is operand 0 and alltypestiny is operand 1.
+    String operands = "CARDINALITY:JoinNode:INNER|Operands:["
+        + ALLTYPES_SCAN_KEY + "," + ALLTYPESTINY_SCAN_KEY + "]|";
+    // q1: a.id (alltypes.id) = b.int_col (alltypestiny.int_col) -> op0.id=op1.int_col
+    String expectedQ1 = operands + "Predicates:[op0.id=op1.int_col]";
+    // q2: a.id (alltypestiny.id) = b.int_col (alltypes.int_col) -> op0.int_col=op1.id
+    String expectedQ2 = operands + "Predicates:[op0.int_col=op1.id]";
+
+    for (CanonicalizationStrategy strategy : CanonicalizationStrategy.values()) {
+      assertEquals(expectedQ1,
+          join1.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+      assertEquals(expectedQ2,
+          join2.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+    }
+  }
+
+  @Test
+  public void testJoinClauses() throws ImpalaException {
+    String[] fromClauses = {
+        "functional.alltypes join functional.alltypestiny using (id)",
+        "functional.alltypes a join functional.alltypestiny b on a.id = b.id",
+        "functional.alltypes a, functional.alltypestiny b where a.id = b.id"
+    };
+    String expectedKey = "CARDINALITY:JoinNode:INNER|Operands:["
+        + "CARDINALITY:ScanNode:functional.alltypes,"
+        + "CARDINALITY:ScanNode:functional.alltypestiny]|"
+        + "Predicates:[op0.id=op1.id]";
+    for (String fromClause : fromClauses) {
+      verifySingleJoinKey("select count(*) from " + fromClause, expectedKey, expectedKey);
+    }
+  }
+
+  @Test
+  public void testRightHandedJoins() throws ImpalaException {
+    // Right-handed joins (RIGHT_ANTI / RIGHT_SEMI / RIGHT_OUTER) must produce
+    // the same HBO key as their LEFT-handed counterparts.
+    String semiAntiFilters = "where a.year=2009 and a.int_col=0";
+    String outerFilters =
+        "where a.year=2009 and b.year=2009 and a.int_col=0 and b.int_col=0";
+    String leftAntiQuery = "select count(*) from functional_parquet.alltypes a "
+        + "left anti join functional.alltypes b on a.id = b.id " + semiAntiFilters;
+    String rightAntiQuery = "select count(*) from functional.alltypes b "
+        + "right anti join functional_parquet.alltypes a on b.id = a.id "
+        + semiAntiFilters;
+    String leftSemiQuery = "select count(*) from functional_parquet.alltypes a "
+        + "left semi join functional.alltypes b on a.id = b.id " + semiAntiFilters;
+    String rightSemiQuery = "select count(*) from functional.alltypes b "
+        + "right semi join functional_parquet.alltypes a on b.id = a.id "
+        + semiAntiFilters;
+    String leftOuterQuery = "select count(*) from functional_parquet.alltypes a "
+        + "left outer join functional.alltypes b on a.id = b.id " + outerFilters;
+    String rightOuterQuery = "select count(*) from functional.alltypes b "
+        + "right outer join functional_parquet.alltypes a on b.id = a.id "
+        + outerFilters;
+
+    String parquetScanER = "CARDINALITY:ScanNode:functional_parquet.alltypes|"
+        + "`year` = 2009|int_col = 0";
+    String parquetScanIPC = "CARDINALITY:ScanNode:functional_parquet.alltypes|"
+        + "`year`=<CONST>|int_col = 0";
+    String plainScanWithPredsER =
+        "CARDINALITY:ScanNode:functional.alltypes|`year` = 2009|int_col = 0";
+    String plainScanWithPredsIPC =
+        "CARDINALITY:ScanNode:functional.alltypes|`year`=<CONST>|int_col = 0";
+
+    // Anti
+    String exprRewriteKey = "CARDINALITY:JoinNode:LEFT_ANTI_JOIN|Eq:op0.id=op1.id|"
+        + "Left:" + parquetScanER + "|Right:" + ALLTYPES_SCAN_KEY;
+    String ignorePartConstsKey = "CARDINALITY:JoinNode:LEFT_ANTI_JOIN|Eq:op0.id=op1.id|"
+        + "Left:" + parquetScanIPC + "|Right:" + ALLTYPES_SCAN_KEY;
+    verifySingleJoinKey(leftAntiQuery, exprRewriteKey, ignorePartConstsKey);
+    verifySingleJoinKey(rightAntiQuery, exprRewriteKey, ignorePartConstsKey);
+
+    // Semi
+    exprRewriteKey = "CARDINALITY:JoinNode:LEFT_SEMI_JOIN|Eq:op0.id=op1.id|"
+        + "Left:" + parquetScanER + "|Right:" + ALLTYPES_SCAN_KEY;
+    ignorePartConstsKey = "CARDINALITY:JoinNode:LEFT_SEMI_JOIN|Eq:op0.id=op1.id|"
+        + "Left:" + parquetScanIPC + "|Right:" + ALLTYPES_SCAN_KEY;
+    verifySingleJoinKey(leftSemiQuery, exprRewriteKey, ignorePartConstsKey);
+    verifySingleJoinKey(rightSemiQuery, exprRewriteKey, ignorePartConstsKey);
+
+    // Outer: outer joins keep their preserved side's WHERE predicates as conjuncts_ on
+    // the join. The two scans here both have their predicates pushed down, but b's
+    // predicates stay on the join in leftOuter (and equivalently on rightOuter after
+    // inversion) and are canonicalized with op1.
+    String outerWhereER = "Where:op1.`year` = 2009,op1.int_col = 0|";
+    String outerWhereIPC = "Where:op1.`year`=<CONST>,op1.int_col = 0|";
+    exprRewriteKey = "CARDINALITY:JoinNode:LEFT_OUTER_JOIN|Eq:op0.id=op1.id|"
+        + outerWhereER + "Left:" + parquetScanER + "|Right:" + plainScanWithPredsER;
+    ignorePartConstsKey = "CARDINALITY:JoinNode:LEFT_OUTER_JOIN|Eq:op0.id=op1.id|"
+        + outerWhereIPC + "Left:" + parquetScanIPC + "|Right:" + plainScanWithPredsIPC;
+    verifySingleJoinKey(leftOuterQuery, exprRewriteKey, ignorePartConstsKey);
+    verifySingleJoinKey(rightOuterQuery, exprRewriteKey, ignorePartConstsKey);
+  }
+
+  @Test
+  public void testCrossJoin() throws ImpalaException {
+    // CROSS JOIN is a special case of INNER JOIN that the join condition is always true.
+    // So the key prefix is "JoinNode:INNER" and the Predicates list is empty.
+    String query = "select count(*) from functional.alltypes a "
+        + "cross join functional.alltypestiny b where a.year=2009";
+    JoinNode join = singleJoin(query);
+    // Keys for ExprRewrite strategy.
+    String alltypesScanER =
+        "CARDINALITY:ScanNode:functional.alltypes|`year` = 2009";
+    String alltypesTinyScanER = "CARDINALITY:ScanNode:functional.alltypestiny";
+    // OPERANDS sorted by scan table name: alltypes < alltypestiny.
+    String expectedER = "CARDINALITY:JoinNode:INNER|Operands:["
+        + alltypesScanER + "," + alltypesTinyScanER + "]|Predicates:[]";
+    assertEquals(expectedER, join.generateHboKeyString(
+        THboStatsType.CARDINALITY, CanonicalizationStrategy.EXPR_REWRITE));
+    // Keys for IgnorePartitionConstants strategy.
+    String alltypesScanIPC =
+        "CARDINALITY:ScanNode:functional.alltypes|`year`=<CONST>";
+    String expectedIPC = "CARDINALITY:JoinNode:INNER|Operands:["
+        + alltypesScanIPC + "," + alltypesTinyScanER + "]|Predicates:[]";
+    assertEquals(expectedIPC, join.generateHboKeyString(
+        THboStatsType.CARDINALITY,
+        CanonicalizationStrategy.IGNORE_PARTITION_CONSTANTS));
+  }
+
+  @Test
+  public void testFullOuterJoin() throws ImpalaException {
+    // Full outer joins sort child keys so that "FROM a FULL OUTER JOIN b" and
+    // "FROM b FULL OUTER JOIN a" produce the same HBO key.
+    String q1 = "select count(*) from functional.alltypestiny a "
+        + "full outer join functional.alltypes b on a.id = b.id";
+    String q2 = "select count(*) from functional.alltypes b "
+        + "full outer join functional.alltypestiny a on a.id = b.id";
+    JoinNode join1 = singleJoin(q1);
+    JoinNode join2 = singleJoin(q2);
+
+    String expectedER = "CARDINALITY:JoinNode:FULL_OUTER_JOIN|Eq:op0.id=op1.id|"
+        + "Left:" + ALLTYPES_SCAN_KEY + "|Right:" + ALLTYPESTINY_SCAN_KEY;
+    for (CanonicalizationStrategy strategy : CanonicalizationStrategy.values()) {
+      assertEquals(expectedER, join1.generateHboKeyString(
+          THboStatsType.CARDINALITY, strategy));
+      assertEquals(expectedER, join2.generateHboKeyString(
+          THboStatsType.CARDINALITY, strategy));
+    }
+  }
+
+  @Test
+  public void testOtherJoinConjuncts() throws ImpalaException {
+    // Non-equi ON-clause predicates become otherJoinConjuncts_ and appear in
+    // the key as a separate Other: section between Eq: and Where:.
+    String query = "select count(*) from functional.alltypes a "
+        + "left outer join functional.alltypes b "
+        + "on a.id = b.id and a.int_col != b.int_col "
+        + "where a.year=2009 and b.year=2010";
+    JoinNode join = singleJoin(query);
+
+    String leftScanER = "CARDINALITY:ScanNode:functional.alltypes|`year` = 2009";
+    String leftScanIPC = "CARDINALITY:ScanNode:functional.alltypes|`year`=<CONST>";
+    String rightScanER = "CARDINALITY:ScanNode:functional.alltypes|`year` = 2010";
+    String rightScanIPC = "CARDINALITY:ScanNode:functional.alltypes|`year`=<CONST>";
+    String keyFmt = "CARDINALITY:JoinNode:LEFT_OUTER_JOIN|Eq:op0.id=op1.id|"
+        + "Other:op0.int_col != op1.int_col|Where:%s|"
+        + "Left:%s|Right:%s";
+
+    String expectedER =
+        String.format(keyFmt, "op1.`year` = 2010", leftScanER, rightScanER);
+    String expectedIPC =
+        String.format(keyFmt, "op1.`year`=<CONST>", leftScanIPC, rightScanIPC);
+    assertEquals(expectedER, join.generateHboKeyString(
+        THboStatsType.CARDINALITY, CanonicalizationStrategy.EXPR_REWRITE));
+    assertEquals(expectedIPC, join.generateHboKeyString(
+        THboStatsType.CARDINALITY,
+        CanonicalizationStrategy.IGNORE_PARTITION_CONSTANTS));
+  }
+
+  @Test
+  public void testAggOverInnerJoin() throws ImpalaException {
+    // An aggregation on top of a join whose grouping columns come from different join
+    // operands must qualify each column with its canonical operand index.
+    String q1 = "select a.int_col, b.bigint_col, count(*) "
+        + "from functional.alltypes a join functional.alltypestiny b on a.id = b.id "
+        + "group by a.int_col, b.bigint_col";
+    String q2 = "select b.int_col, a.bigint_col, count(*) "
+        + "from functional.alltypes a join functional.alltypestiny b on a.id = b.id "
+        + "group by b.int_col, a.bigint_col";
+
+    // Plan IDs
+    final int PREAGG_ID = 3;
+    final int FINAL_AGG_ID = 6;
+
+    // Operands sort by table name: alltypes is operand 0, alltypestiny operand 1.
+    // Neither table has partition predicates so both strategies match.
+    String childKey = "CARDINALITY:JoinNode:INNER|Operands:["
+        + "CARDINALITY:ScanNode:functional.alltypes,"
+        + "CARDINALITY:ScanNode:functional.alltypestiny]|Predicates:[op0.id=op1.id]";
+    String q1Group = "0:Group:op0.int_col,op1.bigint_col";
+    String q2Group = "0:Group:op0.bigint_col,op1.int_col";
+    String preaggFmt = "CARDINALITY:AggregationNode:FIRST|Preagg:true|GroupingSet:false|"
+        + "AggClasses:[%s]|Child:[" + childKey + "]";
+    String finalFmt = "CARDINALITY:AggregationNode:FIRST|Preagg:false|GroupingSet:false|"
+        + "AggClasses:[%s]|Child:[" + childKey + "]";
+
+    Map<Integer, PlanNode> q1Nodes = collectPlanNodesInDistributedPlan(q1);
+    Map<Integer, PlanNode> q2Nodes = collectPlanNodesInDistributedPlan(q2);
+    AggregationNode q1Preagg = (AggregationNode) q1Nodes.get(PREAGG_ID);
+    AggregationNode q1Final = (AggregationNode) q1Nodes.get(FINAL_AGG_ID);
+    AggregationNode q2Preagg = (AggregationNode) q2Nodes.get(PREAGG_ID);
+    AggregationNode q2Final = (AggregationNode) q2Nodes.get(FINAL_AGG_ID);
+
+    for (CanonicalizationStrategy strategy : CanonicalizationStrategy.values()) {
+      assertEquals(String.format(preaggFmt, q1Group),
+          q1Preagg.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+      assertEquals(String.format(finalFmt, q1Group),
+          q1Final.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+      assertEquals(String.format(preaggFmt, q2Group),
+          q2Preagg.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+      assertEquals(String.format(finalFmt, q2Group),
+          q2Final.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+
+      // Swapped column-to-table assignment must hash differently, at every agg phase.
+      assertNotEquals("Pre-agg keys must differ for " + strategy,
+          q1Preagg.generateHboKeyString(THboStatsType.CARDINALITY, strategy),
+          q2Preagg.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+      assertNotEquals("Final agg keys must differ for " + strategy,
+          q1Final.generateHboKeyString(THboStatsType.CARDINALITY, strategy),
+          q2Final.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+    }
+  }
+
+  @Test
+  public void testAggOnMultiLevelJoinOperands() throws ImpalaException {
+    // An aggregation above an OUTER join whose preserved side is itself a multi-table
+    // join must distinguish columns from the different tables on that side. Both t1
+    // (alltypes) and t2 (alltypestiny) sit on the LEFT (preserved) side of the
+    // LEFT OUTER JOIN.
+    String q1 = "select t1.int_col, t2.bigint_col, count(*) "
+        + "from functional.alltypes t1 "
+        + "join functional.alltypestiny t2 on t1.id = t2.id "
+        + "left join functional.alltypessmall t3 on t1.id = t3.id "
+        + "group by t1.int_col, t2.bigint_col";
+    String q2 = "select t1.bigint_col, t2.int_col, count(*) "
+        + "from functional.alltypes t1 "
+        + "join functional.alltypestiny t2 on t1.id = t2.id "
+        + "left join functional.alltypessmall t3 on t1.id = t3.id "
+        + "group by t1.bigint_col, t2.int_col";
+
+    // Plan IDs
+    final int PREAGG_ID = 5;
+    final int FINAL_AGG_ID = 10;
+
+    // The LEFT side (op0) is an inner group with operands sorted, so within it
+    // alltypes=op0.0 and alltypestiny=op0.1. alltypessmall is the outer join's right
+    // operand (op1).
+    String innerGroup = "CARDINALITY:JoinNode:INNER|Operands:["
+        + "CARDINALITY:ScanNode:functional.alltypes,"
+        + "CARDINALITY:ScanNode:functional.alltypestiny]|Predicates:[op0.id=op1.id]";
+    String childKey = "CARDINALITY:JoinNode:LEFT_OUTER_JOIN|Eq:op0.0.id=op1.id|"
+        + "Left:" + innerGroup + "|Right:CARDINALITY:ScanNode:functional.alltypessmall";
+    String q1Group = "0:Group:op0.0.int_col,op0.1.bigint_col";
+    String q2Group = "0:Group:op0.0.bigint_col,op0.1.int_col";
+    String preaggFmt = "CARDINALITY:AggregationNode:FIRST|Preagg:true|GroupingSet:false|"
+        + "AggClasses:[%s]|Child:[" + childKey + "]";
+    String finalFmt = "CARDINALITY:AggregationNode:FIRST|Preagg:false|GroupingSet:false|"
+        + "AggClasses:[%s]|Child:[" + childKey + "]";
+
+    Map<Integer, PlanNode> q1Nodes = collectPlanNodesInDistributedPlan(q1);
+    Map<Integer, PlanNode> q2Nodes = collectPlanNodesInDistributedPlan(q2);
+    AggregationNode q1Preagg = (AggregationNode) q1Nodes.get(PREAGG_ID);
+    AggregationNode q1Final = (AggregationNode) q1Nodes.get(FINAL_AGG_ID);
+    AggregationNode q2Preagg = (AggregationNode) q2Nodes.get(PREAGG_ID);
+    AggregationNode q2Final = (AggregationNode) q2Nodes.get(FINAL_AGG_ID);
+
+    for (CanonicalizationStrategy strategy : CanonicalizationStrategy.values()) {
+      assertEquals(String.format(preaggFmt, q1Group),
+          q1Preagg.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+      assertEquals(String.format(finalFmt, q1Group),
+          q1Final.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+      assertEquals(String.format(preaggFmt, q2Group),
+          q2Preagg.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+      assertEquals(String.format(finalFmt, q2Group),
+          q2Final.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+
+      assertNotEquals("Nested-operand column swap must hash differently for " + strategy,
+          q1Preagg.generateHboKeyString(THboStatsType.CARDINALITY, strategy),
+          q2Preagg.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+      assertNotEquals("Nested-operand column swap must hash differently for " + strategy,
+          q1Final.generateHboKeyString(THboStatsType.CARDINALITY, strategy),
+          q2Final.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+    }
+  }
+
+  @Test
+  public void testMultiLevelOpIndexUnderLeftJoin() throws ImpalaException {
+    // The conjunct "t1.id + t2.id = t3.id" mixes columns from different operands.
+    // Each column must be qualified with a unique prefix.
+    String query = "select t1.int_col, t2.int_col, t3.int_col "
+        + "from functional.alltypes t1 "
+        + "join functional.alltypestiny t2 on t1.id = t2.id "
+        + "left join functional.alltypessmall t3 on t1.id + t2.id = t3.id";
+
+    // The LEFT side (op0) is an inner group with operands sorted, so within it
+    // alltypes=op0.0 and alltypestiny=op0.1. alltypessmall is the outer join's right
+    // operand (op1).
+    String innerJoinKey = "CARDINALITY:JoinNode:INNER|Operands:["
+        + "CARDINALITY:ScanNode:functional.alltypes,"
+        + "CARDINALITY:ScanNode:functional.alltypestiny]|Predicates:[op0.id=op1.id]";
+    String leftJoinKey = "CARDINALITY:JoinNode:LEFT_OUTER_JOIN|"
+        + "Eq:op0.0.id + op0.1.id=op1.id|"
+        + "Left:" + innerJoinKey + "|"
+        + "Right:CARDINALITY:ScanNode:functional.alltypessmall";
+
+    Map<Integer, PlanNode> nodes = collectPlanNodesInDistributedPlan(query);
+    JoinNode leftJoin = (JoinNode) nodes.get(4);
+    for (CanonicalizationStrategy strategy : CanonicalizationStrategy.values()) {
+      assertEquals(leftJoinKey,
+          leftJoin.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+    }
+  }
+
+  @Test
+  public void testMultiLevelOpIndexUnderInnerJoin() throws ImpalaException {
+    // The conjunct "t1.id + t2.id = t3.id" mixes columns from different operands.
+    // Each column must be qualified with a unique prefix.
+    String query = "select t1.int_col, t2.int_col, t3.int_col "
+        + "from functional.alltypestiny t1 "
+        + "left join functional.alltypes t2 on t1.id = t2.id "
+        + "join functional.alltypessmall t3 on t1.id + t2.id = t3.id";
+    Map<Integer, PlanNode> nodes = collectPlanNodesInDistributedPlan(query);
+    String leftJoinKey = "CARDINALITY:JoinNode:LEFT_OUTER_JOIN|Eq:op0.id=op1.id|"
+        + "Left:CARDINALITY:ScanNode:functional.alltypestiny|"
+        + "Right:CARDINALITY:ScanNode:functional.alltypes";
+    String innerJoinKey = "CARDINALITY:JoinNode:INNER|Operands:[" + leftJoinKey
+        + ",CARDINALITY:ScanNode:functional.alltypessmall]|"
+        + "Predicates:[op0.0.id + op0.1.id=op1.id]";
+    JoinNode innerJoin = (JoinNode) nodes.get(5);
+    for (CanonicalizationStrategy strategy : CanonicalizationStrategy.values()) {
+      assertEquals(innerJoinKey,
+          innerJoin.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+    }
+  }
+
+  @Test
+  public void testMultiTableInPredicate() throws ImpalaException {
+    // Test IN predicate referencing a partitioned table and a non-partitioned table
+    // is not canonicalized as a partition equality predicate.
+    String query = "select t1.id "
+        + "from functional.alltypestiny t1, functional.alltypesnopart t2 "
+        + "where t1.id IN (1, 2, t2.id)";
+    JoinNode join = singleJoin(query);
+    String expectedKey = "CARDINALITY:JoinNode:INNER|Operands:["
+        + "CARDINALITY:ScanNode:functional.alltypesnopart,"
+        + "CARDINALITY:ScanNode:functional.alltypestiny]|"
+        + "Predicates:[op1.id IN (1, 2, op0.id)]";
+    for (CanonicalizationStrategy strategy : CanonicalizationStrategy.values()) {
+      assertEquals(expectedKey,
+          join.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+    }
+  }
+
+  @Test
+  public void testGroupByMultiTableFuncExpr() throws ImpalaException {
+    // Test agg that has a materialized slot whose single source is a FunctionCallExpr
+    // over two join operands. The columns should be qualified individually, i.e.
+    // coalesce(a.id, b.int_col) -> coalesce(op0.id, op1.int_col).
+    String[] queries = {
+        "select coalesce(a.id, b.int_col), count(*) "
+            + "from functional.alltypes a join functional.alltypestiny b on a.id = b.id "
+            + "group by coalesce(a.id, b.int_col)",
+        // Test an equivalent query using inline view
+        "select col, count(*) from ( "
+            + "select coalesce(a.id, b.int_col) as col "
+            + "from functional.alltypes a join functional.alltypestiny b on a.id = b.id "
+            + ") t group by col"
+    };
+    String expectedFinalAggKey = "CARDINALITY:AggregationNode:FIRST|Preagg:false|"
+        + "GroupingSet:false|AggClasses:[0:Group:coalesce(op0.id, op1.int_col)]|"
+        + "Child:[CARDINALITY:JoinNode:INNER|Operands:["
+        + "CARDINALITY:ScanNode:functional.alltypes,"
+        + "CARDINALITY:ScanNode:functional.alltypestiny]|"
+        + "Predicates:[op0.id=op1.id]]";
+    for (String query : queries) {
+      Map<Integer, PlanNode> nodes = collectPlanNodesInDistributedPlan(query);
+      PlanNode finalAgg = nodes.get(6);
+      for (CanonicalizationStrategy strategy : CanonicalizationStrategy.values()) {
+        assertEquals(expectedFinalAggKey,
+            finalAgg.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+      }
+    }
+  }
+
+  @Test
+  public void testInnerJoinWithLimit() throws ImpalaException {
+    String query = "select a.id from functional.alltypes a "
+        + "join functional.alltypestiny b on a.id = b.id limit 5";
+    String expectedKey = "CARDINALITY:JoinNode:INNER|limit:5|Operands:["
+        + ALLTYPES_SCAN_KEY + "," + ALLTYPESTINY_SCAN_KEY
+        + "]|Predicates:[op0.id=op1.id]";
+    verifySingleJoinKey(query, expectedKey, expectedKey);
+  }
+
+  @Test
+  public void testLeftJoinWithLimit() throws ImpalaException {
+    String query = "select a.id from functional.alltypes a "
+        + "left outer join functional.alltypestiny b on a.id = b.id limit 5";
+    String expectedKey = "CARDINALITY:JoinNode:LEFT_OUTER_JOIN|limit:5|Eq:op0.id=op1.id|"
+        + "Left:" + ALLTYPES_SCAN_KEY + "|Right:" + ALLTYPESTINY_SCAN_KEY;
+    verifySingleJoinKey(query, expectedKey, expectedKey);
+  }
+
+  @Test
+  public void testInnerJoinLimitBreaksGroup() throws ImpalaException {
+    String query = "select y.id from functional.alltypessmall x join ("
+        + "select a.id from functional.alltypes a "
+        + "join functional.alltypestiny b on a.id = b.id limit 5) y on x.id = y.id";
+
+    // Operands are sorted by scan table name. The sub-join's operands (alltypes,
+    // alltypestiny) sort before the alltypessmall scan, so the sub-join is op0 and
+    // alltypessmall is op1.
+    String subJoinKey = "CARDINALITY:JoinNode:INNER|limit:5|Operands:["
+        + ALLTYPES_SCAN_KEY + "," + ALLTYPESTINY_SCAN_KEY
+        + "]|Predicates:[op0.id=op1.id]";
+    String expectedWithLimit = "CARDINALITY:JoinNode:INNER|Operands:["
+        + subJoinKey + "," + ALLTYPESSMALL_SCAN_KEY + "]|Predicates:[op0.0.id=op1.id]";
+
+    PlanNode topWithLimit = collectPlanNodesInDistributedPlan(query).get(4);
+    for (CanonicalizationStrategy strategy : CanonicalizationStrategy.values()) {
+      assertEquals("LIMIT sub-join must stay an opaque operand for " + strategy,
+          expectedWithLimit,
+          topWithLimit.generateHboKeyString(THboStatsType.CARDINALITY, strategy));
+    }
+  }
 }
diff --git a/testdata/workloads/functional-query/queries/QueryTest/hbo-except.test b/testdata/workloads/functional-query/queries/QueryTest/hbo-except.test
new file mode 100644
index 000000000..86ae161f5
--- /dev/null
+++ b/testdata/workloads/functional-query/queries/QueryTest/hbo-except.test
@@ -0,0 +1,166 @@
+====
+---- QUERY
+# EXPLAIN the same query that has been executed
+EXPLAIN select id from functional.alltypes where string_col != 'test_except'
+  except
+  select id from functional.alltypestiny where string_col != 'test_except'
+---- PLAN
+PLAN-ROOT SINK
+|
+07:EXCHANGE [UNPARTITIONED]
+|
+03:HASH JOIN [LEFT ANTI JOIN, PARTITIONED]
+|  hash predicates: id IS NOT DISTINCT FROM id
+|  row-size=4B cardinality=7.29K (from HBO)
+|
+|--06:EXCHANGE [HASH(id)]
+|  |
+|  02:SCAN HDFS [functional.alltypestiny]
+|     HDFS partitions=4/4 files=4 size=460B
+|     predicates: string_col != 'test_except'
+|     row-size=17B cardinality=8 (from HBO)
+|
+05:AGGREGATE [FINALIZE]
+|  group by: id
+|  row-size=4B cardinality=7.30K (from HBO)
+|
+04:EXCHANGE [HASH(id)]
+|
+01:AGGREGATE [STREAMING]
+|  group by: id
+|  row-size=4B cardinality=7.30K (from HBO)
+|
+00:SCAN HDFS [functional.alltypes]
+   HDFS partitions=24/24 files=24 size=478.45KB
+   predicates: string_col != 'test_except'
+   row-size=17B cardinality=7.30K (from HBO)
+---- CALCITE_PLANNER_PLAN
+# Calcite uses UNION+AGG instead of ANTI JOIN for EXCEPT
+PLAN-ROOT SINK
+|
+06:EXCHANGE [UNPARTITIONED]
+|
+05:AGGREGATE [FINALIZE]
+|  output: count:merge(if($f1 = 0, 1, NULL)), count:merge(if($f1 = 1, 1, NULL))
+|  group by: ID
+|  having: count(if($f1 = 0, 1, NULL)) > 0, count(if($f1 = 1, 1, NULL)) = 0
+|  row-size=20B cardinality=7.29K (from HBO)
+|
+04:EXCHANGE [HASH(ID)]
+|
+03:AGGREGATE [STREAMING]
+|  output: count(if($f1 = 0, 1, NULL)), count(if($f1 = 1, 1, NULL))
+|  group by: ID
+|  row-size=20B cardinality=7.30K (from HBO)
+|
+00:UNION
+|  row-size=5B cardinality=7.31K (from HBO)
+|
+|--02:SCAN HDFS [functional.alltypestiny]
+|     HDFS partitions=4/4 files=4 size=460B
+|     predicates: functional.alltypestiny.string_col != 'test_except'
+|     row-size=17B cardinality=8 (from HBO)
+|
+01:SCAN HDFS [functional.alltypes]
+   HDFS partitions=24/24 files=24 size=478.45KB
+   predicates: functional.alltypes.string_col != 'test_except'
+   row-size=17B cardinality=7.30K (from HBO)
+====
+---- QUERY
+# EXPLAIN the rewritten query which is equivalent to the EXCEPT query
+EXPLAIN select * from (
+  select distinct id from functional.alltypes
+  where string_col != 'test_except'
+) t1
+where not exists (
+  select 1 from functional.alltypestiny t2
+  where string_col != 'test_except' and t1.id <=> t2.id)
+---- PLAN
+PLAN-ROOT SINK
+|
+07:EXCHANGE [UNPARTITIONED]
+|
+03:HASH JOIN [LEFT ANTI JOIN, PARTITIONED]
+|  hash predicates: id IS NOT DISTINCT FROM id
+|  row-size=4B cardinality=7.29K (from HBO)
+|
+|--06:EXCHANGE [HASH(id)]
+|  |
+|  02:SCAN HDFS [functional.alltypestiny]
+|     HDFS partitions=4/4 files=4 size=460B
+|     predicates: string_col != 'test_except'
+|     row-size=17B cardinality=8 (from HBO)
+|
+05:AGGREGATE [FINALIZE]
+|  group by: id
+|  row-size=4B cardinality=7.30K (from HBO)
+|
+04:EXCHANGE [HASH(id)]
+|
+01:AGGREGATE [STREAMING]
+|  group by: id
+|  row-size=4B cardinality=7.30K (from HBO)
+|
+00:SCAN HDFS [functional.alltypes]
+   HDFS partitions=24/24 files=24 size=478.45KB
+   predicates: string_col != 'test_except'
+   row-size=17B cardinality=7.30K (from HBO)
+---- CALCITE_PLANNER_PLAN
+PLAN-ROOT SINK
+|
+14:EXCHANGE [UNPARTITIONED]
+|
+07:NESTED LOOP JOIN [LEFT OUTER JOIN, BROADCAST]
+|  join predicates: functional.alltypes.id IS NULL OR functional.alltypes_0.id = functional.alltypes.id, functional.alltypes_0.id IS NULL OR functional.alltypes_0.id = functional.alltypes.id
+|  predicates: if(TupleIsNull(3), NULL, TRUE) IS NULL
+|  row-size=8B cardinality=7.30K
+|
+|--13:EXCHANGE [BROADCAST]
+|  |
+|  04:AGGREGATE [FINALIZE]
+|  |  group by: functional.alltypes.id
+|  |  row-size=4B cardinality=7.30K
+|  |
+|  03:HASH JOIN [INNER JOIN, PARTITIONED]
+|  |  hash predicates: functional.alltypes.id IS NOT DISTINCT FROM functional.alltypestiny.id
+|  |  runtime filters: RF000 <- functional.alltypestiny.id
+|  |  row-size=21B cardinality=7.30K
+|  |
+|  |--12:EXCHANGE [HASH(functional.alltypestiny.id)]
+|  |  |
+|  |  02:SCAN HDFS [functional.alltypestiny]
+|  |     HDFS partitions=4/4 files=4 size=460B
+|  |     predicates: functional.alltypestiny.string_col != 'test_except'
+|  |     row-size=17B cardinality=8 (from HBO)
+|  |
+|  11:AGGREGATE [FINALIZE]
+|  |  group by: functional.alltypes.id
+|  |  row-size=4B cardinality=7.30K
+|  |
+|  10:EXCHANGE [HASH(functional.alltypes.id)]
+|  |
+|  01:AGGREGATE [STREAMING]
+|  |  group by: functional.alltypes.id
+|  |  row-size=4B cardinality=7.30K
+|  |
+|  00:SCAN HDFS [functional.alltypes]
+|     HDFS partitions=24/24 files=24 size=478.45KB
+|     predicates: functional.alltypes.string_col != 'test_except'
+|     runtime filters: RF000 -> functional.alltypes.id
+|     row-size=17B cardinality=7.30K (from HBO)
+|
+09:AGGREGATE [FINALIZE]
+|  group by: functional.alltypes_0.id
+|  row-size=4B cardinality=7.30K
+|
+08:EXCHANGE [HASH(functional.alltypes_0.id)]
+|
+06:AGGREGATE [STREAMING]
+|  group by: functional.alltypes_0.id
+|  row-size=4B cardinality=7.30K
+|
+05:SCAN HDFS [functional.alltypes]
+   HDFS partitions=24/24 files=24 size=478.45KB
+   predicates: functional.alltypes_0.string_col != 'test_except'
+   row-size=17B cardinality=7.30K (from HBO)
+====
diff --git a/testdata/workloads/functional-query/queries/QueryTest/hbo-inner-join.test b/testdata/workloads/functional-query/queries/QueryTest/hbo-inner-join.test
new file mode 100644
index 000000000..ac8de0a23
--- /dev/null
+++ b/testdata/workloads/functional-query/queries/QueryTest/hbo-inner-join.test
@@ -0,0 +1,178 @@
+====
+---- QUERY
+# EXPLAIN the same 3-way inner join that has been executed
+EXPLAIN select STRAIGHT_JOIN count(*) from functional.alltypes a
+join functional.alltypessmall b on a.id = b.id
+join functional.alltypestiny c on b.id = c.id
+where a.year = 2009 and b.year = 2009 and c.year = 2009
+  and a.int_col = 0 and b.int_col = 0 and c.int_col = 0
+  and a.string_col != 'test_inner_join'
+  and b.string_col != 'test_inner_join'
+  and c.string_col != 'test_inner_join'
+---- PLAN
+PLAN-ROOT SINK
+|
+10:AGGREGATE [FINALIZE]
+|  output: count:merge(*)
+|  row-size=8B cardinality=1 (from HBO)
+|
+09:EXCHANGE [UNPARTITIONED]
+|
+05:AGGREGATE
+|  output: count(*)
+|  row-size=8B cardinality=3 (from HBO)
+|
+04:HASH JOIN [INNER JOIN, PARTITIONED]
+|  hash predicates: b.id = c.id
+|  runtime filters: RF000 <- c.id
+|  row-size=63B cardinality=1 (from HBO)
+|
+|--08:EXCHANGE [HASH(c.id)]
+|  |
+|  02:SCAN HDFS [functional.alltypestiny c]
+|     partition predicates: c.`year` = 2009
+|     HDFS partitions=4/4 files=4 size=460B
+|     predicates: c.int_col = 0, c.string_col != 'test_inner_join'
+|     row-size=21B cardinality=4 (from HBO)
+|
+07:EXCHANGE [HASH(b.id)]
+|
+03:HASH JOIN [INNER JOIN, BROADCAST]
+|  hash predicates: a.id = b.id
+|  runtime filters: RF002 <- b.id
+|  row-size=42B cardinality=6 (from HBO)
+|
+|--06:EXCHANGE [BROADCAST]
+|  |
+|  01:SCAN HDFS [functional.alltypessmall b]
+|     partition predicates: b.`year` = 2009
+|     HDFS partitions=4/4 files=4 size=6.32KB
+|     predicates: b.int_col = 0, b.string_col != 'test_inner_join'
+|     runtime filters: RF000 -> b.id
+|     row-size=21B cardinality=12 (from HBO)
+|
+00:SCAN HDFS [functional.alltypes a]
+   partition predicates: a.`year` = 2009
+   HDFS partitions=12/24 files=12 size=238.68KB
+   predicates: a.int_col = 0, a.string_col != 'test_inner_join'
+   runtime filters: RF000 -> a.id, RF002 -> a.id
+   row-size=21B cardinality=365 (from HBO)
+====
+---- QUERY
+# Same join predicates but different join order. The top join node should hit HBO stats.
+EXPLAIN select STRAIGHT_JOIN count(*) from functional.alltypestiny a
+join functional.alltypessmall b on a.id = b.id
+join functional.alltypes c on b.id = c.id
+where a.year = 2009 and b.year = 2009 and c.year = 2009
+  and a.int_col = 0 and b.int_col = 0 and c.int_col = 0
+  and a.string_col != 'test_inner_join'
+  and b.string_col != 'test_inner_join'
+  and c.string_col != 'test_inner_join'
+---- PLAN
+PLAN-ROOT SINK
+|
+10:AGGREGATE [FINALIZE]
+|  output: count:merge(*)
+|  row-size=8B cardinality=1 (from HBO)
+|
+09:EXCHANGE [UNPARTITIONED]
+|
+05:AGGREGATE
+|  output: count(*)
+|  row-size=8B cardinality=3 (from HBO)
+|
+04:HASH JOIN [INNER JOIN, PARTITIONED]
+|  hash predicates: b.id = c.id
+|  runtime filters: RF000 <- c.id
+|  row-size=63B cardinality=1 (from HBO)
+|
+|--08:EXCHANGE [HASH(c.id)]
+|  |
+|  02:SCAN HDFS [functional.alltypes c]
+|     partition predicates: c.`year` = 2009
+|     HDFS partitions=12/24 files=12 size=238.68KB
+|     predicates: c.int_col = 0, c.string_col != 'test_inner_join'
+|     row-size=21B cardinality=365 (from HBO)
+|
+03:HASH JOIN [INNER JOIN, PARTITIONED]
+|  hash predicates: a.id = b.id
+|  runtime filters: RF002 <- b.id
+|  row-size=42B cardinality=4
+|
+|--07:EXCHANGE [HASH(b.id)]
+|  |
+|  01:SCAN HDFS [functional.alltypessmall b]
+|     partition predicates: b.`year` = 2009
+|     HDFS partitions=4/4 files=4 size=6.32KB
+|     predicates: b.int_col = 0, b.string_col != 'test_inner_join'
+|     runtime filters: RF000 -> b.id
+|     row-size=21B cardinality=12 (from HBO)
+|
+06:EXCHANGE [HASH(a.id)]
+|
+00:SCAN HDFS [functional.alltypestiny a]
+   partition predicates: a.`year` = 2009
+   HDFS partitions=4/4 files=4 size=460B
+   predicates: a.int_col = 0, a.string_col != 'test_inner_join'
+   runtime filters: RF000 -> a.id, RF002 -> a.id
+   row-size=21B cardinality=4 (from HBO)
+====
+---- QUERY
+# Use a new table that hasn't been joined. a join b should hit HBO stats.
+EXPLAIN select STRAIGHT_JOIN count(*) from functional.alltypes a
+join functional.alltypessmall b on a.id = b.id
+join functional.alltypesagg c on b.id = c.id
+where a.year = 2009 and b.year = 2009 and c.year = 2010
+  and a.int_col = 0 and b.int_col = 0 and c.int_col = 0
+  and a.string_col != 'test_inner_join'
+  and b.string_col != 'test_inner_join'
+  and c.string_col != 'test_inner_join'
+---- PLAN
+PLAN-ROOT SINK
+|
+10:AGGREGATE [FINALIZE]
+|  output: count:merge(*)
+|  row-size=8B cardinality=1
+|
+09:EXCHANGE [UNPARTITIONED]
+|
+05:AGGREGATE
+|  output: count(*)
+|  row-size=8B cardinality=3
+|
+04:HASH JOIN [INNER JOIN, PARTITIONED]
+|  hash predicates: b.id = c.id
+|  runtime filters: RF000 <- c.id
+|  row-size=65B cardinality=6
+|
+|--08:EXCHANGE [HASH(c.id)]
+|  |
+|  02:SCAN HDFS [functional.alltypesagg c]
+|     partition predicates: c.`year` = 2010
+|     HDFS partitions=11/11 files=11 size=814.73KB
+|     predicates: c.int_col = 0, c.string_col != 'test_inner_join'
+|     row-size=23B cardinality=11
+|
+07:EXCHANGE [HASH(b.id)]
+|
+03:HASH JOIN [INNER JOIN, BROADCAST]
+|  hash predicates: a.id = b.id
+|  runtime filters: RF002 <- b.id
+|  row-size=42B cardinality=6 (from HBO)
+|
+|--06:EXCHANGE [BROADCAST]
+|  |
+|  01:SCAN HDFS [functional.alltypessmall b]
+|     partition predicates: b.`year` = 2009
+|     HDFS partitions=4/4 files=4 size=6.32KB
+|     predicates: b.int_col = 0, b.string_col != 'test_inner_join'
+|     runtime filters: RF000 -> b.id
+|     row-size=21B cardinality=12 (from HBO)
+|
+00:SCAN HDFS [functional.alltypes a]
+   partition predicates: a.`year` = 2009
+   HDFS partitions=12/24 files=12 size=238.68KB
+   predicates: a.int_col = 0, a.string_col != 'test_inner_join'
+   runtime filters: RF000 -> a.id, RF002 -> a.id
+   row-size=21B cardinality=365 (from HBO)
+====
diff --git a/testdata/workloads/functional-query/queries/QueryTest/hbo-intersect.test b/testdata/workloads/functional-query/queries/QueryTest/hbo-intersect.test
new file mode 100644
index 000000000..cc9f80b1b
--- /dev/null
+++ b/testdata/workloads/functional-query/queries/QueryTest/hbo-intersect.test
@@ -0,0 +1,187 @@
+====
+---- QUERY
+# EXPLAIN the same query that has been executed
+EXPLAIN select id from functional.alltypes where string_col != 'test_intersect'
+  intersect
+  select id from functional.alltypestiny where string_col != 'test_intersect'
+---- PLAN
+PLAN-ROOT SINK
+|
+07:EXCHANGE [UNPARTITIONED]
+|
+03:HASH JOIN [LEFT SEMI JOIN, PARTITIONED]
+|  hash predicates: id IS NOT DISTINCT FROM id
+|  row-size=4B cardinality=8 (from HBO)
+|
+|--06:EXCHANGE [HASH(id)]
+|  |
+|  02:SCAN HDFS [functional.alltypestiny]
+|     HDFS partitions=4/4 files=4 size=460B
+|     predicates: string_col != 'test_intersect'
+|     row-size=17B cardinality=8 (from HBO)
+|
+05:AGGREGATE [FINALIZE]
+|  group by: id
+|  row-size=4B cardinality=7.30K (from HBO)
+|
+04:EXCHANGE [HASH(id)]
+|
+01:AGGREGATE [STREAMING]
+|  group by: id
+|  row-size=4B cardinality=7.30K (from HBO)
+|
+00:SCAN HDFS [functional.alltypes]
+   HDFS partitions=24/24 files=24 size=478.45KB
+   predicates: string_col != 'test_intersect'
+   row-size=17B cardinality=7.30K (from HBO)
+---- CALCITE_PLANNER_PLAN
+# Calcite uses UNION+AGG instead of JOIN for INTERSECT
+PLAN-ROOT SINK
+|
+12:EXCHANGE [UNPARTITIONED]
+|
+11:AGGREGATE [FINALIZE]
+|  output: count:merge()
+|  group by: ID
+|  having: count() = 2
+|  row-size=12B cardinality=8 (from HBO)
+|
+10:EXCHANGE [HASH(ID)]
+|
+05:AGGREGATE [STREAMING]
+|  output: count()
+|  group by: ID
+|  row-size=12B cardinality=7.30K (from HBO)
+|
+00:UNION
+|  pass-through-operands: all
+|  row-size=4B cardinality=7.31K (from HBO)
+|
+|--09:AGGREGATE [FINALIZE]
+|  |  group by: functional.alltypestiny.id
+|  |  row-size=4B cardinality=8 (from HBO)
+|  |
+|  08:EXCHANGE [HASH(functional.alltypestiny.id)]
+|  |
+|  04:AGGREGATE [STREAMING]
+|  |  group by: functional.alltypestiny.id
+|  |  row-size=4B cardinality=8 (from HBO)
+|  |
+|  03:SCAN HDFS [functional.alltypestiny]
+|     HDFS partitions=4/4 files=4 size=460B
+|     predicates: functional.alltypestiny.string_col != 'test_intersect'
+|     row-size=17B cardinality=8 (from HBO)
+|
+07:AGGREGATE [FINALIZE]
+|  group by: functional.alltypes.id
+|  row-size=4B cardinality=7.30K (from HBO)
+|
+06:EXCHANGE [HASH(functional.alltypes.id)]
+|
+02:AGGREGATE [STREAMING]
+|  group by: functional.alltypes.id
+|  row-size=4B cardinality=7.30K (from HBO)
+|
+01:SCAN HDFS [functional.alltypes]
+   HDFS partitions=24/24 files=24 size=478.45KB
+   predicates: functional.alltypes.string_col != 'test_intersect'
+   row-size=17B cardinality=7.30K (from HBO)
+====
+---- QUERY
+# EXPLAIN the rewritten query which is equivalent to the INTERSECT query
+EXPLAIN select * from (
+  select distinct id from functional.alltypes
+  where string_col != 'test_intersect'
+) t1
+where exists (
+  select 1 from functional.alltypestiny t2
+  where string_col != 'test_intersect' and t1.id <=> t2.id
+)
+---- PLAN
+PLAN-ROOT SINK
+|
+07:EXCHANGE [UNPARTITIONED]
+|
+03:HASH JOIN [LEFT SEMI JOIN, PARTITIONED]
+|  hash predicates: id IS NOT DISTINCT FROM id
+|  row-size=4B cardinality=8 (from HBO)
+|
+|--06:EXCHANGE [HASH(id)]
+|  |
+|  02:SCAN HDFS [functional.alltypestiny]
+|     HDFS partitions=4/4 files=4 size=460B
+|     predicates: string_col != 'test_intersect'
+|     row-size=17B cardinality=8 (from HBO)
+|
+05:AGGREGATE [FINALIZE]
+|  group by: id
+|  row-size=4B cardinality=7.30K (from HBO)
+|
+04:EXCHANGE [HASH(id)]
+|
+01:AGGREGATE [STREAMING]
+|  group by: id
+|  row-size=4B cardinality=7.30K (from HBO)
+|
+00:SCAN HDFS [functional.alltypes]
+   HDFS partitions=24/24 files=24 size=478.45KB
+   predicates: string_col != 'test_intersect'
+   row-size=17B cardinality=7.30K (from HBO)
+---- CALCITE_PLANNER_PLAN
+PLAN-ROOT SINK
+|
+14:EXCHANGE [UNPARTITIONED]
+|
+07:NESTED LOOP JOIN [INNER JOIN, BROADCAST]
+|  predicates: functional.alltypes.id IS NULL OR functional.alltypes.id = functional.alltypes_0.id, functional.alltypes_0.id IS NULL OR functional.alltypes.id = functional.alltypes_0.id
+|  row-size=8B cardinality=7.30K
+|
+|--13:EXCHANGE [BROADCAST]
+|  |
+|  06:AGGREGATE [FINALIZE]
+|  |  group by: functional.alltypes_0.id
+|  |  row-size=4B cardinality=7.30K
+|  |
+|  05:HASH JOIN [INNER JOIN, PARTITIONED]
+|  |  hash predicates: functional.alltypes_0.id IS NOT DISTINCT FROM functional.alltypestiny.id
+|  |  runtime filters: RF000 <- functional.alltypestiny.id
+|  |  row-size=21B cardinality=7.30K
+|  |
+|  |--12:EXCHANGE [HASH(functional.alltypestiny.id)]
+|  |  |
+|  |  04:SCAN HDFS [functional.alltypestiny]
+|  |     HDFS partitions=4/4 files=4 size=460B
+|  |     predicates: functional.alltypestiny.string_col != 'test_intersect'
+|  |     row-size=17B cardinality=8 (from HBO)
+|  |
+|  11:AGGREGATE [FINALIZE]
+|  |  group by: functional.alltypes_0.id
+|  |  row-size=4B cardinality=7.30K (from HBO)
+|  |
+|  10:EXCHANGE [HASH(functional.alltypes_0.id)]
+|  |
+|  03:AGGREGATE [STREAMING]
+|  |  group by: functional.alltypes_0.id
+|  |  row-size=4B cardinality=7.30K (from HBO)
+|  |
+|  02:SCAN HDFS [functional.alltypes]
+|     HDFS partitions=24/24 files=24 size=478.45KB
+|     predicates: functional.alltypes_0.string_col != 'test_intersect'
+|     runtime filters: RF000 -> functional.alltypes_0.id
+|     row-size=17B cardinality=7.30K (from HBO)
+|
+09:AGGREGATE [FINALIZE]
+|  group by: functional.alltypes.id
+|  row-size=4B cardinality=7.30K (from HBO)
+|
+08:EXCHANGE [HASH(functional.alltypes.id)]
+|
+01:AGGREGATE [STREAMING]
+|  group by: functional.alltypes.id
+|  row-size=4B cardinality=7.30K (from HBO)
+|
+00:SCAN HDFS [functional.alltypes]
+   HDFS partitions=24/24 files=24 size=478.45KB
+   predicates: functional.alltypes.string_col != 'test_intersect'
+   row-size=17B cardinality=7.30K (from HBO)
+====
diff --git a/testdata/workloads/functional-query/queries/QueryTest/hbo-multiple-scans.test b/testdata/workloads/functional-query/queries/QueryTest/hbo-multiple-scans.test
index 3af3e681c..47a695e6c 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/hbo-multiple-scans.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/hbo-multiple-scans.test
@@ -10,18 +10,18 @@ PLAN-ROOT SINK
 |
 06:AGGREGATE [FINALIZE]
 |  output: count:merge(*)
-|  row-size=8B cardinality=1
+|  row-size=8B cardinality=1 (from HBO)
 |
 05:EXCHANGE [UNPARTITIONED]
 |
 03:AGGREGATE
 |  output: count(*)
-|  row-size=8B cardinality=2
+|  row-size=8B cardinality=3 (from HBO)
 |
 02:HASH JOIN [INNER JOIN, BROADCAST]
 |  hash predicates: b.id = a.id
 |  runtime filters: RF000 <- a.id
-|  row-size=29B cardinality=2
+|  row-size=29B cardinality=31 (from HBO)
 |
 |--04:EXCHANGE [BROADCAST]
 |  |
@@ -50,18 +50,18 @@ PLAN-ROOT SINK
 |
 06:AGGREGATE [FINALIZE]
 |  output: count:merge(a.id), min:merge(b.int_col)
-|  row-size=12B cardinality=1
+|  row-size=12B cardinality=1 (from HBO)
 |
 05:EXCHANGE [UNPARTITIONED]
 |
 03:AGGREGATE
 |  output: count(a.id), min(b.int_col)
-|  row-size=12B cardinality=2
+|  row-size=12B cardinality=3 (from HBO)
 |
 02:HASH JOIN [INNER JOIN, BROADCAST]
 |  hash predicates: b.id = a.id
 |  runtime filters: RF000 <- a.id
-|  row-size=29B cardinality=2
+|  row-size=29B cardinality=31 (from HBO)
 |
 |--04:EXCHANGE [BROADCAST]
 |  |
@@ -89,18 +89,18 @@ PLAN-ROOT SINK
 |
 06:AGGREGATE [FINALIZE]
 |  output: count:merge(*)
-|  row-size=8B cardinality=1
+|  row-size=8B cardinality=1 (from HBO, key ignores partition constants)
 |
 05:EXCHANGE [UNPARTITIONED]
 |
 03:AGGREGATE
 |  output: count(*)
-|  row-size=8B cardinality=2
+|  row-size=8B cardinality=3 (from HBO, key ignores partition constants)
 |
 02:HASH JOIN [INNER JOIN, BROADCAST]
 |  hash predicates: b.id = a.id
 |  runtime filters: RF000 <- a.id
-|  row-size=29B cardinality=2
+|  row-size=29B cardinality=31 (from HBO, key ignores partition constants)
 |
 |--04:EXCHANGE [BROADCAST]
 |  |
diff --git a/testdata/workloads/functional-query/queries/QueryTest/hbo-outer-join.test b/testdata/workloads/functional-query/queries/QueryTest/hbo-outer-join.test
new file mode 100644
index 000000000..ab96be38a
--- /dev/null
+++ b/testdata/workloads/functional-query/queries/QueryTest/hbo-outer-join.test
@@ -0,0 +1,77 @@
+====
+---- QUERY
+# EXPLAIN the same query
+EXPLAIN select STRAIGHT_JOIN count(*) from functional.alltypes a
+left outer join functional.alltypestiny b on a.id = b.id
+where a.year = 2009
+  and a.string_col != 'test_outer_join'
+  and a.int_col = 0
+---- PLAN
+PLAN-ROOT SINK
+|
+06:AGGREGATE [FINALIZE]
+|  output: count:merge(*)
+|  row-size=8B cardinality=1 (from HBO)
+|
+05:EXCHANGE [UNPARTITIONED]
+|
+03:AGGREGATE
+|  output: count(*)
+|  row-size=8B cardinality=3 (from HBO)
+|
+02:HASH JOIN [LEFT OUTER JOIN, BROADCAST]
+|  hash predicates: a.id = b.id
+|  row-size=25B cardinality=365 (from HBO)
+|
+|--04:EXCHANGE [BROADCAST]
+|  |
+|  01:SCAN HDFS [functional.alltypestiny b]
+|     HDFS partitions=4/4 files=4 size=460B
+|     row-size=4B cardinality=8 (from HBO)
+|
+00:SCAN HDFS [functional.alltypes a]
+   partition predicates: a.`year` = 2009
+   HDFS partitions=12/24 files=12 size=238.68KB
+   predicates: a.int_col = 0, a.string_col != 'test_outer_join'
+   row-size=21B cardinality=365 (from HBO)
+====
+---- QUERY
+# EXPLAIN the reverted query using right outer join
+EXPLAIN select STRAIGHT_JOIN count(*) from functional.alltypestiny a
+right outer join functional.alltypes b on a.id = b.id
+where b.year = 2009
+  and b.string_col != 'test_outer_join'
+  and b.int_col = 0
+---- PLAN
+PLAN-ROOT SINK
+|
+07:AGGREGATE [FINALIZE]
+|  output: count:merge(*)
+|  row-size=8B cardinality=1 (from HBO)
+|
+06:EXCHANGE [UNPARTITIONED]
+|
+03:AGGREGATE
+|  output: count(*)
+|  row-size=8B cardinality=3 (from HBO)
+|
+02:HASH JOIN [RIGHT OUTER JOIN, PARTITIONED]
+|  hash predicates: a.id = b.id
+|  runtime filters: RF000 <- b.id
+|  row-size=25B cardinality=365 (from HBO)
+|
+|--05:EXCHANGE [HASH(b.id)]
+|  |
+|  01:SCAN HDFS [functional.alltypes b]
+|     partition predicates: b.`year` = 2009
+|     HDFS partitions=12/24 files=12 size=238.68KB
+|     predicates: b.int_col = 0, b.string_col != 'test_outer_join'
+|     row-size=21B cardinality=365 (from HBO)
+|
+04:EXCHANGE [HASH(a.id)]
+|
+00:SCAN HDFS [functional.alltypestiny a]
+   HDFS partitions=4/4 files=4 size=460B
+   runtime filters: RF000 -> a.id
+   row-size=4B cardinality=8 (from HBO)
+====
diff --git a/tests/query_test/test_hbo.py b/tests/query_test/test_hbo.py
index 3e2445ff3..790a876a2 100644
--- a/tests/query_test/test_hbo.py
+++ b/tests/query_test/test_hbo.py
@@ -251,18 +251,18 @@ class TestHBO(ImpalaTestSuite):
         select STRAIGHT_JOIN count(*)
         from functional.alltypes a join [SHUFFLE] functional.alltypestiny b
           on a.month = b.month + 10000
-        where a.string_col < 'hbo_test' and b.string_col < 'hbo_test'""")
+        where a.string_col < 'hbo_rf_test' and b.string_col < 'hbo_rf_test'""")
     # Wait for 1 second to ensure the stats are written to the cache.
     time.sleep(1)
-    # Scan node of the alltypes table with predicate string_col < 'hbo_test' has an
+    # Scan node of the alltypes table with predicate string_col < 'hbo_rf_test' has an
     # effective runtime filter. HBO stats on this shouldn't exist.
     res = self.execute_query(
-        "explain select * from functional.alltypes where string_col < 'hbo_test'")
+        "explain select * from functional.alltypes where string_col < 'hbo_rf_test'")
     assert "from HBO" not in '\n'.join(res.data), '\n'.join(res.data)
     # The other scan node doesn't have any runtime filters. HBO stats on this should
     # exist.
     res = self.execute_query(
-        "explain select * from functional.alltypestiny where string_col < 'hbo_test'")
+        "explain select * from functional.alltypestiny where string_col < 'hbo_rf_test'")
     assert "cardinality=8 (from HBO)" in '\n'.join(res.data), '\n'.join(res.data)
 
     # Test runtime filters applied on scan of aggregation node.
@@ -271,7 +271,7 @@ class TestHBO(ImpalaTestSuite):
     self.execute_query("""with l as ({0})
         select l.* from l join functional.alltypestiny t
         on l.year = t.year and l.month = t.month
-        where t.id < 5""".format(agg_stmt))
+        where t.id < 5 and t.string_col < 'hbo_rf_test'""".format(agg_stmt))
     # Wait for 1 second to ensure the stats are written to the cache.
     time.sleep(1)
     res = self.execute_query("explain " + agg_stmt)
@@ -361,3 +361,44 @@ class TestHBO(ImpalaTestSuite):
         select item from functional_parquet.complextypes_arrays.arr1 where item > 10
         """)
     self._run_hbo_explains('QueryTest/hbo-union-collection-scan')
+
+  def test_inner_join_cardinality(self):
+    self.client.set_configuration(QUERY_OPTIONS)
+    self.execute_query("""
+        select STRAIGHT_JOIN count(*) from functional.alltypes a
+          join functional.alltypessmall b on a.id = b.id
+          join functional.alltypestiny c on b.id = c.id
+        where a.year = 2009 and b.year = 2009 and c.year = 2009
+          and a.int_col = 0 and b.int_col = 0 and c.int_col = 0
+          and a.string_col != 'test_inner_join'
+          and b.string_col != 'test_inner_join'
+          and c.string_col != 'test_inner_join'""")
+    self._run_hbo_explains('QueryTest/hbo-inner-join')
+
+  def test_outer_join_cardinality(self):
+    self.client.set_configuration(QUERY_OPTIONS)
+    self.execute_query("""
+        select STRAIGHT_JOIN count(*) from functional.alltypes a
+          left outer join functional.alltypestiny b on a.id = b.id
+        where a.year = 2009 and a.string_col != 'test_outer_join'
+          and a.int_col = 0""")
+    self._run_hbo_explains('QueryTest/hbo-outer-join')
+
+  def test_except_cardinality(self):
+    self.client.set_configuration(QUERY_OPTIONS)
+    self.execute_query("""
+        select id from functional.alltypes where string_col != 'test_except'
+        except
+        select id from functional.alltypestiny where string_col != 'test_except'
+        """)
+    self._run_hbo_explains('QueryTest/hbo-except')
+
+  def test_intersect_cardinality(self):
+    self.client.set_configuration({
+        **QUERY_OPTIONS, 'runtime_filter_mode': 'off'})
+    self.execute_query("""
+        select id from functional.alltypes where string_col != 'test_intersect'
+        intersect
+        select id from functional.alltypestiny where string_col != 'test_intersect'
+        """)
+    self._run_hbo_explains('QueryTest/hbo-intersect')