private RelNode choosePlan(RelNode node, RelNode optimized) {
    JaninoRelMetadataProvider original = RelMetadataQuery.THREAD_PROVIDERS.get();
    try {
      RelMetadataQuery.THREAD_PROVIDERS.set(
          HiveTezModelRelMetadataProvider.DEFAULT);
      node.getCluster().invalidateMetadataQuery();
      RelMetadataQuery metadataQuery = RelMetadataQuery.instance();

      RelOptCost optimizedCost = metadataQuery.getCumulativeCost(optimized);
      RelOptCost originalCost = metadataQuery.getCumulativeCost(node);
      originalCost = originalCost.multiplyBy(factor);
      LOG.debug("Original plan cost {} vs Optimized plan cost {}", originalCost, optimizedCost);
      if (optimizedCost.isLt(originalCost)) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("Plan after:\n" + RelOptUtil.toString(optimized));
        }
        return optimized;
      }

      return node;
    }
    finally {
      node.getCluster().invalidateMetadataQuery();
      RelMetadataQuery.THREAD_PROVIDERS.set(original);
    }
  }
Rule to trigger {@link HiveCardinalityPreservingJoinOptimization} on top of the plan.
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveCardinalityPreservingJoinRule.java