You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@impala.apache.org by sa...@apache.org on 2017/11/19 22:55:56 UTC

[3/5] incubator-impala git commit: IMPALA-5976: Remove equivalence class computation in FE

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/5e9b4e2f/fe/src/main/java/org/apache/impala/planner/DistributedPlanner.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/planner/DistributedPlanner.java b/fe/src/main/java/org/apache/impala/planner/DistributedPlanner.java
index e1d83d7..0704445 100644
--- a/fe/src/main/java/org/apache/impala/planner/DistributedPlanner.java
+++ b/fe/src/main/java/org/apache/impala/planner/DistributedPlanner.java
@@ -26,6 +26,7 @@ import org.apache.impala.analysis.Analyzer;
 import org.apache.impala.analysis.Expr;
 import org.apache.impala.analysis.InsertStmt;
 import org.apache.impala.analysis.JoinOperator;
+import static org.apache.impala.analysis.JoinOperator.*;
 import org.apache.impala.analysis.QueryStmt;
 import org.apache.impala.catalog.KuduTable;
 import org.apache.impala.common.ImpalaException;
@@ -197,7 +198,8 @@ public class DistributedPlanner {
     // Kudu tables here (IMPALA-5254).
     DataPartition inputPartition = inputFragment.getDataPartition();
     if (!partitionExprs.isEmpty()
-        && analyzer.equivSets(inputPartition.getPartitionExprs(), partitionExprs)
+        && analyzer.setsHaveValueTransfer(inputPartition.getPartitionExprs(),
+        partitionExprs, true)
         && !(insertStmt.getTargetTable() instanceof KuduTable)) {
       return inputFragment;
     }
@@ -394,8 +396,26 @@ public class DistributedPlanner {
 
     // Connect the child fragments in a new fragment, and set the data partition
     // of the new fragment and its child fragments.
+    DataPartition outputPartition;
+    switch(node.getJoinOp()) {
+      // For full outer joins the null values of the lhs/rhs join exprs are not
+      // partitioned so random partition is the best we have now.
+      case FULL_OUTER_JOIN:
+        outputPartition = DataPartition.RANDOM;
+        break;
+      // For right anti and semi joins the lhs join slots does not appear in the output.
+      case RIGHT_ANTI_JOIN:
+      case RIGHT_SEMI_JOIN:
+      // For right outer joins the null values of the lhs join expr are not partitioned.
+      case RIGHT_OUTER_JOIN:
+        outputPartition = rhsJoinPartition;
+        break;
+      // Otherwise we're good to use the lhs partition.
+      default:
+        outputPartition = lhsJoinPartition;
+    }
     PlanFragment joinFragment =
-        new PlanFragment(ctx_.getNextFragmentId(), node, lhsJoinPartition);
+        new PlanFragment(ctx_.getNextFragmentId(), node, outputPartition);
     leftChildFragment.setDestination(lhsExchange);
     leftChildFragment.setOutputPartition(lhsJoinPartition);
     rightChildFragment.setDestination(rhsExchange);
@@ -449,10 +469,10 @@ public class DistributedPlanner {
     boolean rhsHasCompatPartition = false;
     long partitionCost = -1;
     if (lhsTree.getCardinality() != -1 && rhsTree.getCardinality() != -1) {
-      lhsHasCompatPartition = analyzer.equivSets(lhsJoinExprs,
-          leftChildFragment.getDataPartition().getPartitionExprs());
-      rhsHasCompatPartition = analyzer.equivSets(rhsJoinExprs,
-          rightChildFragment.getDataPartition().getPartitionExprs());
+      lhsHasCompatPartition = analyzer.setsHaveValueTransfer(
+          leftChildFragment.getDataPartition().getPartitionExprs(), lhsJoinExprs,false);
+      rhsHasCompatPartition = analyzer.setsHaveValueTransfer(
+          rightChildFragment.getDataPartition().getPartitionExprs(), rhsJoinExprs, false);
 
       Preconditions.checkState(rhsDataSize != -1);
       double lhsNetworkCost = (lhsHasCompatPartition) ? 0.0 :
@@ -567,7 +587,10 @@ public class DistributedPlanner {
     // 3. Each lhs part expr must have an equivalent expr at the same position
     // in the rhs part exprs.
     for (int i = 0; i < lhsPartExprs.size(); ++i) {
-      if (!analyzer.equivExprs(lhsPartExprs.get(i), rhsPartExprs.get(i))) return false;
+      if (!analyzer.exprsHaveValueTransfer(lhsPartExprs.get(i), rhsPartExprs.get(i),
+          true)) {
+        return false;
+      }
     }
     return true;
   }
@@ -594,9 +617,9 @@ public class DistributedPlanner {
     Preconditions.checkState(srcPartition.isHashPartitioned());
     List<Expr> srcPartExprs = srcPartition.getPartitionExprs();
     List<Expr> resultPartExprs = Lists.newArrayList();
-    for (int i = 0; i < srcPartExprs.size(); ++i) {
+    for (Expr srcPartExpr : srcPartExprs) {
       for (int j = 0; j < srcJoinExprs.size(); ++j) {
-        if (analyzer.equivExprs(srcPartExprs.get(i), srcJoinExprs.get(j))) {
+        if (analyzer.exprsHaveValueTransfer(srcPartExpr, srcJoinExprs.get(j), false)) {
           resultPartExprs.add(joinExprs.get(j).clone());
           break;
         }
@@ -785,9 +808,9 @@ public class DistributedPlanner {
     if (hasGrouping) {
       List<Expr> partitionExprs = node.getAggInfo().getPartitionExprs();
       if (partitionExprs == null) partitionExprs = groupingExprs;
-      boolean childHasCompatPartition = ctx_.getRootAnalyzer().equivSets(partitionExprs,
-            childFragment.getDataPartition().getPartitionExprs());
-      if (childHasCompatPartition && !childFragment.refsNullableTupleId(partitionExprs)) {
+      boolean childHasCompatPartition = ctx_.getRootAnalyzer().setsHaveValueTransfer(
+          partitionExprs, childFragment.getDataPartition().getPartitionExprs(), true);
+      if (childHasCompatPartition) {
         // The data is already partitioned on the required expressions. We can do the
         // aggregation in the child fragment without an extra merge step.
         // An exchange+merge step is required if the grouping exprs reference a tuple
@@ -874,8 +897,8 @@ public class DistributedPlanner {
         ctx_.getRootAnalyzer(), false);
 
     PlanFragment firstMergeFragment;
-    boolean childHasCompatPartition = ctx_.getRootAnalyzer().equivSets(partitionExprs,
-        childFragment.getDataPartition().getPartitionExprs());
+    boolean childHasCompatPartition = ctx_.getRootAnalyzer().setsHaveValueTransfer(
+        partitionExprs, childFragment.getDataPartition().getPartitionExprs(), true);
     if (childHasCompatPartition) {
       // The data is already partitioned on the required expressions, we can skip the
       // phase-1 merge step.
@@ -966,12 +989,8 @@ public class DistributedPlanner {
       sortNode.getInputPartition().substitute(
           childFragment.getPlanRoot().getOutputSmap(), ctx_.getRootAnalyzer());
       // Make sure the childFragment's output is partitioned as required by the sortNode.
-      // Even if the fragment and the sort partition exprs are equal, an exchange is
-      // required if the sort partition exprs reference a tuple that is made nullable in
-      // 'childFragment' to bring NULLs from outer-join non-matches together.
       DataPartition sortPartition = sortNode.getInputPartition();
-      if (!childFragment.getDataPartition().equals(sortPartition)
-          || childFragment.refsNullableTupleId(sortPartition.getPartitionExprs())) {
+      if (!childFragment.getDataPartition().equals(sortPartition)) {
         analyticFragment = createParentFragment(childFragment, sortPartition);
       }
     }

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/5e9b4e2f/fe/src/main/java/org/apache/impala/planner/PlanFragment.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/planner/PlanFragment.java b/fe/src/main/java/org/apache/impala/planner/PlanFragment.java
index 5ac9b2e..3b3ace7 100644
--- a/fe/src/main/java/org/apache/impala/planner/PlanFragment.java
+++ b/fe/src/main/java/org/apache/impala/planner/PlanFragment.java
@@ -496,23 +496,4 @@ public class PlanFragment extends TreeNode<PlanFragment> {
 
     for (PlanFragment child: getChildren()) child.verifyTree();
   }
-
-  /**
-   * Returns true if 'exprs' reference a tuple that is made nullable in this fragment,
-   * but not in any of its input fragments.
-   */
-  public boolean refsNullableTupleId(List<Expr> exprs) {
-    Preconditions.checkNotNull(planRoot_);
-    List<TupleId> tids = Lists.newArrayList();
-    for (Expr e: exprs) e.getIds(tids, null);
-    Set<TupleId> nullableTids = Sets.newHashSet(planRoot_.getNullableTupleIds());
-    // Remove all tuple ids that were made nullable in an input fragment.
-    List<ExchangeNode> exchNodes = Lists.newArrayList();
-    planRoot_.collect(ExchangeNode.class, exchNodes);
-    for (ExchangeNode exchNode: exchNodes) {
-      nullableTids.removeAll(exchNode.getNullableTupleIds());
-    }
-    for (TupleId tid: tids) if (nullableTids.contains(tid)) return true;
-    return false;
-  }
 }

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/5e9b4e2f/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java b/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java
index d72e818..5d933a3 100644
--- a/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java
+++ b/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java
@@ -128,8 +128,8 @@ public class SingleNodePlanner {
     // Use the stmt's analyzer which is not necessarily the root analyzer
     // to detect empty result sets.
     Analyzer analyzer = queryStmt.getAnalyzer();
-    analyzer.computeEquivClasses();
-    ctx_.getAnalysisResult().getTimeline().markEvent("Equivalence classes computed");
+    analyzer.computeValueTransferGraph();
+    ctx_.getAnalysisResult().getTimeline().markEvent("Value transfer graph computed");
 
     // Mark slots referenced by output exprs as materialized, prior to generating the
     // plan tree.
@@ -1372,25 +1372,15 @@ public class SingleNodePlanner {
     if (!result.isEmpty()) return result;
 
     // Construct join conjuncts derived from equivalence class membership.
+    HashSet<TupleId> lhsTblRefIdsHs = new HashSet<>(lhsTblRefIds);
     for (TupleId rhsId: rhsTblRefIds) {
       TableRef rhsTblRef = analyzer.getTableRef(rhsId);
       Preconditions.checkNotNull(rhsTblRef);
       for (SlotDescriptor slotDesc: rhsTblRef.getDesc().getSlots()) {
         SlotId rhsSid = slotDesc.getId();
-        // List of slots that participate in a value transfer with rhsSid and are belong
-        // to a tuple in lhsTblRefIds. The value transfer is not necessarily mutual.
-        List<SlotId> lhsSlotIds = analyzer.getEquivSlots(rhsSid, lhsTblRefIds);
-        for (SlotId lhsSid: lhsSlotIds) {
-          // A mutual value transfer between lhsSid and rhsSid is required for correctly
-          // generating an inferred predicate. Otherwise, the predicate might incorrectly
-          // eliminate rows that would have been non-matches of an outer or anti join.
-          if (analyzer.hasMutualValueTransfer(lhsSid, rhsSid)) {
-            // construct a BinaryPredicates in order to get correct casting;
-            // we only do this for one of the equivalent slots, all the other implied
-            // equalities are redundant
-            BinaryPredicate pred =
-                analyzer.createInferredEqPred(lhsSid, rhsSid);
-            result.add(pred);
+        for (SlotId lhsSid : analyzer.getEquivClass(rhsSid)) {
+          if (lhsTblRefIdsHs.contains(analyzer.getTupleId(lhsSid))) {
+            result.add(analyzer.createInferredEqPred(lhsSid, rhsSid));
             break;
           }
         }

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/5e9b4e2f/fe/src/main/java/org/apache/impala/util/Graph.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/util/Graph.java b/fe/src/main/java/org/apache/impala/util/Graph.java
new file mode 100644
index 0000000..762ed52
--- /dev/null
+++ b/fe/src/main/java/org/apache/impala/util/Graph.java
@@ -0,0 +1,387 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.impala.util;
+
+import com.google.common.base.Preconditions;
+import org.apache.impala.common.Pair;
+
+import java.util.*;
+
+import static java.lang.Math.min;
+
+/** Data structures for graphs represented with an adjacency list. */
+public abstract class Graph {
+  public abstract int numVertices();
+
+  /** Return an iterator of vertex IDs with an edge from srcVid. */
+  public abstract IntIterator dstIter(int srcVid);
+
+  public String print() {
+    StringBuilder sb = new StringBuilder();
+    for (int i = 0; i < numVertices(); ++i) {
+      IntIterator dstIter = dstIter(i);
+      if (!dstIter.hasNext()) continue;
+      sb.append(i).append(" => ");
+      while (dstIter.hasNext()) {
+        sb.append(dstIter.next()).append(", ");
+      }
+      sb.append('\n');
+    }
+    return sb.toString();
+  }
+
+  /**
+   * Helper function collecting all the indexes set in a bitset into an sorted array.
+   * Time complexity: O(n), where n is the number of bits in the bitset.
+   */
+  static private int[] collectIdxsFromBitSet(BitSet bs) {
+    int[] result = new int[bs.cardinality()];
+    for (int i = 0, j = bs.nextSetBit(0); j != -1; j = bs.nextSetBit(j + 1)) {
+      result[i++] = j;
+    }
+    return result;
+  }
+
+  /** Graph supporting adding edges. Duplicate edges are allowed. */
+  public static class WritableGraph extends Graph {
+    // Unsorted adjacency list.
+    private final IntArrayList[] adjList_;
+
+    public WritableGraph(int numVertices) {
+      adjList_ = new IntArrayList[numVertices];
+      for (int i = 0; i < numVertices; ++i) adjList_[i] = new IntArrayList();
+    }
+
+    @Override
+    public int numVertices() { return adjList_.length; }
+
+    @Override
+    public IntIterator dstIter(int srcVid) { return adjList_[srcVid].iterator(); }
+
+    public void addEdge(int srcVid, int dstVid) {
+      if (dstVid < 0 || dstVid >= numVertices()) throw new IndexOutOfBoundsException();
+      adjList_[srcVid].add(dstVid);
+    }
+
+    public RandomAccessibleGraph toRandomAccessible() {
+      int[][] sortedAdjList = new int[numVertices()][];
+      for (int srcVid = 0; srcVid < numVertices(); ++srcVid) {
+        int[] dsts = Arrays.copyOfRange(adjList_[srcVid].data(), 0,
+            adjList_[srcVid].size());
+        Arrays.sort(dsts);
+        int uniqueSize = 0;
+        for (int i = 0; i < dsts.length; ++i) {
+          if (i == 0 || dsts[i] != dsts[i - 1]) dsts[uniqueSize++] = dsts[i];
+        }
+        sortedAdjList[srcVid] = Arrays.copyOfRange(dsts, 0, uniqueSize);
+      }
+      return new RandomAccessibleGraph(sortedAdjList);
+    }
+  }
+
+  /** Graph supporting random access using binary search. */
+  public static class RandomAccessibleGraph extends Graph {
+    // Sorted adjacency list.
+    private final int[][] adjList_;
+
+    /**
+     * Construct from an adjacency list.
+     * Each list in the adjacency list must have been sorted.
+     */
+    RandomAccessibleGraph(int[][] adjList) { adjList_ = adjList; }
+
+    @Override
+    public int numVertices() { return adjList_.length; }
+
+    @Override
+    public IntIterator dstIter(int srcVid) {
+      return IntIterator.fromArray(adjList_[srcVid]);
+    }
+
+    /**
+     * Check whether there is an edge from 'srcVid' to 'dstVid'. Binary search is used
+     * instead of a standalone hash table because the typical use case has less than
+     * 10,000 vertices.
+     * Time complexity: O(log(V))
+     */
+    boolean hasEdge(int srcVid, int dstVid) {
+      int idx = Arrays.binarySearch(adjList_[srcVid], dstVid);
+      return idx >= 0 && idx < adjList_[srcVid].length && adjList_[srcVid][idx] == dstVid;
+    }
+
+    /**
+     * Compute the reflexive transitive closure of the graph by BFS from every vertex.
+     * Time complexity: O(V(V+E)).
+     */
+    public RandomAccessibleGraph reflexiveTransitiveClosure() {
+      int[][] tcAdjList = new int[numVertices()][];
+      BitSet visited = new BitSet(numVertices());
+      IntArrayList queue = new IntArrayList(numVertices());
+      for (int srcVid = 0; srcVid < numVertices(); ++srcVid) {
+        visited.clear();
+        visited.set(srcVid);
+        queue.clear();
+        queue.add(srcVid);
+        for (int queueFront = 0; queueFront < queue.size(); ++queueFront) {
+          for (IntIterator dstIt = dstIter(queue.get(queueFront));
+               dstIt.hasNext(); dstIt.next()) {
+            if (!visited.get(dstIt.peek())) {
+              visited.set(dstIt.peek());
+              queue.add(dstIt.peek());
+            }
+          }
+        }
+        tcAdjList[srcVid] = collectIdxsFromBitSet(visited);
+      }
+      return new RandomAccessibleGraph(tcAdjList);
+    }
+  }
+
+  /**
+   * A graph condensed by its strongly-connected components (SCC). Vertices are mapped to
+   * their SCCs and an inner graph on the SCCs is stored.
+   */
+  public static class SccCondensedGraph extends Graph {
+    // Map an original vid to its SCC ID.
+    private final int[] sccIds_;
+    // Map an SCC ID to its member vids.
+    private final int[][] sccMembers_;
+    // The SCC-condensed inner graph.
+    private final RandomAccessibleGraph condensed_;
+
+    private SccCondensedGraph(int[] sccIds, int[][] sccMembers,
+        RandomAccessibleGraph condensed) {
+      sccIds_ = sccIds;
+      sccMembers_ = sccMembers;
+      condensed_ = condensed;
+    }
+
+    @Override
+    public int numVertices() { return sccIds_.length; }
+
+    @Override
+    public IntIterator dstIter(final int srcVid) {
+      return new IntIterator() {
+        private final int[] condensedAdjList = condensed_.adjList_[sccIds_[srcVid]];
+        private int adjListPos = 0;
+        private int memberPos = 0;
+
+        @Override
+        public boolean hasNext() {
+          // After this loop the iterator either points to a valid dst or reaches the end.
+          while (adjListPos < condensedAdjList.length &&
+              memberPos == sccMembers_[condensedAdjList[adjListPos]].length) {
+            ++adjListPos;
+            memberPos = 0;
+          }
+          return adjListPos < condensedAdjList.length;
+        }
+
+        @Override
+        public int next() {
+          int result = peek();
+          ++memberPos;
+          return result;
+        }
+
+        @Override
+        public int peek() {
+          if (!hasNext()) throw new IndexOutOfBoundsException();
+          return sccMembers_[condensedAdjList[adjListPos]][memberPos];
+        }
+      };
+    }
+
+    /**
+     * Check whether there is an edge from 'srcVid' to 'dstVid'.
+     * Time complexity: O(log(V))
+     */
+    public boolean hasEdge(int srcVid, int dstVid) {
+      return condensed_.hasEdge(sccIds_[srcVid], sccIds_[dstVid]);
+    }
+
+    /**
+     * Create a condensed reflexive transitive closure of a graph.
+     * Time complexity: O(V(V+E)).
+     */
+    public static SccCondensedGraph condensedReflexiveTransitiveClosure(WritableGraph g) {
+      // Step 0: Compute the strongly connected components. O(V+E)
+      Pair<int[], int[][]> scc = tarjanScc(g);
+      // Step 1: Compute the condensed inner graph. O(V^2+E)
+      RandomAccessibleGraph condensed = condenseGraphOnScc(g, scc.first, scc.second);
+      // Step 2: Compute the reflexive transitive closure. O(V(V+E))
+      RandomAccessibleGraph condensedTc = condensed.reflexiveTransitiveClosure();
+      return new SccCondensedGraph(scc.first, scc.second, condensedTc);
+    }
+
+    /**
+     * Get the ID of the strongly connected component containing 'vid'.
+     * Time complexity: O(1)
+     */
+    public int sccId(int vid) { return sccIds_[vid]; }
+
+    /**
+     * Get an array of vertex IDs in the scc. The caller shouldn't modify the returned
+     * array.
+     * Time complexity: O(1)
+     */
+    public int[] sccMembersBySccId(int sccId) { return sccMembers_[sccId]; }
+
+    /**
+     * Get an array of vertices IDs in the scc. The caller shouldn't modify the returned
+     * array.
+     * Time complexity: O(1)
+     */
+    public int[] sccMembersByVid(int vid) { return sccMembers_[sccIds_[vid]]; }
+
+    /**
+     * Compute the strongly connected components using Tarjan's strongly connected
+     * component algorithm.
+     * https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
+     * To avoid unbounded system stack usage, the algorithm is implemented iteratively.
+     * Time complexity: O(V+E).
+     * Returns A pair of {@link #sccIds_} and {@link #sccMembers_}.
+     */
+    static private Pair<int[], int[][]> tarjanScc(final WritableGraph g) {
+      // A mapping from original vid to its SCC ID.
+      int[] sccIds = new int[g.numVertices()];
+      // Lists of vertex IDs in each SCC.
+      ArrayList<int[]> sccMembers = new ArrayList<>();
+      // A mapping from a vertex ID to its DFS preordering index. -1 means not visited.
+      int[] dfsIdxs = new int[g.numVertices()];
+      Arrays.fill(dfsIdxs, -1);
+      int[] lowLinks = new int[g.numVertices()];
+      // The stack of visited vertices that haven't been assigned to an SCC.
+      IntArrayList unAssignedStack = new IntArrayList(g.numVertices());
+      // The context of the iteratively implemented DFS.
+      class DfsContext {
+        // The vid being searched.
+        final int vid;
+        // The current position in the vertex's dst list. In each iteration, the dst
+        // vid in this position should be considered for DFS.
+        IntIterator dstIt;
+        // The position of vid in unAssignedStack. When the DFS of the successors
+        // finishes, vertices in unAssignedStack above this position belong to the same
+        // SCC as vid.
+        int unAssignedStackPos;
+        DfsContext(int vid) {
+          this.vid = vid;
+          dstIt = g.dstIter(vid);
+          // unAssignedStackPos will be initialized in DFS index assignment step.
+        }
+      }
+      // The DFS stack. java.util.Stack is synchronized, so ArrayDeque is used here.
+      ArrayDeque<DfsContext> dfsStack = new ArrayDeque<>();
+      BitSet onUnassignedStack = new BitSet(g.numVertices());
+      int nextDfsIndex = 0;
+      for (int dfsRootVid = 0; dfsRootVid < g.numVertices(); ++dfsRootVid) {
+        if (dfsIdxs[dfsRootVid] != -1) continue;
+        dfsStack.push(new DfsContext(dfsRootVid));
+        while (!dfsStack.isEmpty()) {
+          DfsContext ctx = dfsStack.peek();
+          if (dfsIdxs[ctx.vid] == -1) {
+            dfsIdxs[ctx.vid] = lowLinks[ctx.vid] = nextDfsIndex;
+            nextDfsIndex += 1;
+            ctx.unAssignedStackPos = unAssignedStack.size();
+            unAssignedStack.add(ctx.vid);
+            onUnassignedStack.set(ctx.vid);
+          }
+          if (!ctx.dstIt.hasNext()) {
+            // All successors have been searched. Check if this is the root of an SCC.
+            if (lowLinks[ctx.vid] == dfsIdxs[ctx.vid]) {
+              // Create an SCC from all elements on the unAssignedStack above (inclusive)
+              // the vertex being searched.
+              int[] members = Arrays.copyOfRange(unAssignedStack.data(),
+                  ctx.unAssignedStackPos, unAssignedStack.size());
+              unAssignedStack.removeLast(members.length);
+              for (int member : members) {
+                sccIds[member] = sccMembers.size();
+                onUnassignedStack.clear(member);
+              }
+              sccMembers.add(members);
+            }
+            dfsStack.pop();
+          } else {
+            int nextDstVid = ctx.dstIt.peek();
+            if (dfsIdxs[nextDstVid] == -1) {
+              // Tree edge. DFS this successor. ctx.dstIt is not advanced until the DFS
+              // of the successor finishes.
+              dfsStack.push(new DfsContext(nextDstVid));
+            } else {
+              if (onUnassignedStack.get(nextDstVid)) {
+                if (dfsIdxs[nextDstVid] >= dfsIdxs[ctx.vid]) {
+                  // Tree edge. The DFS of a successor just finished.
+                  // Take its lowlink value.
+                  lowLinks[ctx.vid] = min(lowLinks[ctx.vid], lowLinks[nextDstVid]);
+                } else {
+                  // Back or cross edge. Take its DFS index value.
+                  lowLinks[ctx.vid] = min(lowLinks[ctx.vid], dfsIdxs[nextDstVid]);
+                }
+              }
+              ctx.dstIt.next();
+            }
+          }
+        }
+        Preconditions.checkState(unAssignedStack.size() == 0);
+      }
+      return Pair.create(sccIds, sccMembers.toArray(new int[0][]));
+    }
+
+    /**
+     * Condense the original graph 'g' to a new graph in SCC space.
+     * Time complexity: O(V^2+E)
+     */
+    static private RandomAccessibleGraph condenseGraphOnScc(WritableGraph g, int[] sccIds,
+        int[][] sccMembers) {
+      int[][] condensedAdjList = new int[sccMembers.length][];
+      BitSet bs = new BitSet(sccMembers.length);
+      for (int srcSccId = 0; srcSccId < sccMembers.length; ++srcSccId) {
+        bs.clear();
+        for (int srcVid : sccMembers[srcSccId]) {
+          for (IntIterator dstIt = g.dstIter(srcVid); dstIt.hasNext(); dstIt.next()) {
+            bs.set(sccIds[dstIt.peek()]);
+          }
+        }
+        condensedAdjList[srcSccId] = collectIdxsFromBitSet(bs);
+      }
+      return new RandomAccessibleGraph(condensedAdjList);
+    }
+
+    /** Returns whether this graph is equal to 'reference'. */
+    public boolean validate(RandomAccessibleGraph reference) {
+      if (reference.numVertices() != numVertices()) return false;
+      IntArrayList sortedDsts = new IntArrayList(reference.numVertices());
+      for (int i = 0; i < reference.numVertices(); ++i) {
+        sortedDsts.clear();
+        for (IntIterator dstIt = dstIter(i); dstIt.hasNext(); dstIt.next()) {
+          sortedDsts.add(dstIt.peek());
+        }
+        Arrays.sort(sortedDsts.data(), 0, sortedDsts.size());
+        IntIterator refIt = reference.dstIter(i);
+        IntIterator condensedIt = sortedDsts.iterator();
+        while (refIt.hasNext() || condensedIt.hasNext()) {
+          if (!refIt.hasNext() || !condensedIt.hasNext() ||
+              refIt.next() != condensedIt.next()) {
+            return false;
+          }
+        }
+      }
+      return true;
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/5e9b4e2f/fe/src/main/java/org/apache/impala/util/IntArrayList.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/util/IntArrayList.java b/fe/src/main/java/org/apache/impala/util/IntArrayList.java
new file mode 100644
index 0000000..c263d5d
--- /dev/null
+++ b/fe/src/main/java/org/apache/impala/util/IntArrayList.java
@@ -0,0 +1,97 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.impala.util;
+
+/**
+ * An int arraylist used to reduce GC pressure and to remove unnecessary boxing.
+ */
+public class IntArrayList {
+  private int[] data_;
+  private int size_;
+
+  public IntArrayList() { this(0); }
+
+  public IntArrayList(int capacity) {
+    data_ = new int[capacity];
+    size_ = 0;
+  }
+
+  public int[] data() { return data_; }
+
+  /**
+   * Grow the internal array as needed to accommodate the specified number of elements.
+   */
+  private void ensureCapacity(int capacity) {
+    if (capacity > data_.length) {
+      int[] newData = new int[Math.max(data_.length * 2, capacity)];
+      System.arraycopy(data_, 0, newData, 0, data_.length);
+      data_ = newData;
+    }
+  }
+
+  /**
+   * Add an int at the end of the list.
+   */
+  public void add(int value) {
+    ensureCapacity(size_ + 1);
+    data_[size_++] = value;
+  }
+
+  /**
+   * Remove elements from the end the of list.
+   */
+  public void removeLast(int numRemove) {
+    if (numRemove < 0 || numRemove > size_) {
+      throw new ArrayIndexOutOfBoundsException();
+    }
+    size_ -= numRemove;
+  }
+
+  public void clear() { size_ = 0; }
+
+  public int size() { return size_; }
+
+  public void set(int index, int value) {
+    if (index >= size_) {
+      throw new ArrayIndexOutOfBoundsException(index);
+    }
+    data_[index] = value;
+  }
+
+  public int get(int index) {
+    if (index >= size_) {
+      throw new ArrayIndexOutOfBoundsException(index);
+    }
+    return data_[index];
+  }
+
+  public IntIterator iterator() {
+    return new IntIterator() {
+      private int pos_ = 0;
+
+      @Override
+      public boolean hasNext() { return pos_ < size(); }
+
+      @Override
+      public int next() { return get(pos_++); }
+
+      @Override
+      public int peek() { return get(pos_); }
+    };
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/5e9b4e2f/fe/src/main/java/org/apache/impala/util/IntIterator.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/util/IntIterator.java b/fe/src/main/java/org/apache/impala/util/IntIterator.java
new file mode 100644
index 0000000..c92c61f
--- /dev/null
+++ b/fe/src/main/java/org/apache/impala/util/IntIterator.java
@@ -0,0 +1,40 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.impala.util;
+
+/** Primitive int iterator */
+public abstract class IntIterator {
+  public abstract boolean hasNext();
+  public abstract int next();
+  public abstract int peek();
+
+  static IntIterator fromArray(final int[] array) {
+    return new IntIterator() {
+      private int pos_ = 0;
+
+      @Override
+      public boolean hasNext() { return pos_ < array.length; }
+
+      @Override
+      public int next() { return array[pos_++]; }
+
+      @Override
+      public int peek() { return array[pos_]; }
+    };
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/5e9b4e2f/fe/src/test/java/org/apache/impala/util/IntArrayListTest.java
----------------------------------------------------------------------
diff --git a/fe/src/test/java/org/apache/impala/util/IntArrayListTest.java b/fe/src/test/java/org/apache/impala/util/IntArrayListTest.java
new file mode 100644
index 0000000..acb2c69
--- /dev/null
+++ b/fe/src/test/java/org/apache/impala/util/IntArrayListTest.java
@@ -0,0 +1,102 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.impala.util;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class IntArrayListTest {
+  private void assertNaturalNumberSequence(IntArrayList arr, int size) {
+    // Test data()
+    assert arr.data().length >= size;
+    // Test size()
+    assertEquals(arr.size(), size);
+    // Test get()
+    for (int i = 0; i < size; ++i) assertEquals(arr.get(i), i);
+    try {
+      arr.get(-1);
+      fail();
+    } catch (ArrayIndexOutOfBoundsException e) {}
+    try {
+      arr.get(arr.size());
+      fail();
+    } catch (ArrayIndexOutOfBoundsException e) {}
+    // Test iterator()
+    IntIterator it = arr.iterator();
+    for (int i = 0; i < size; ++i) {
+      assert it.hasNext();
+      assert it.peek() == i;
+      assert it.next() == i;
+    }
+    assert !it.hasNext();
+    try {
+      it.peek();
+      fail();
+    } catch (ArrayIndexOutOfBoundsException e) {}
+    try {
+      it.next();
+      fail();
+    } catch (ArrayIndexOutOfBoundsException e) {}
+  }
+
+  private void fillNaturalNumberSequence(IntArrayList arr, int end) {
+    for (int i = arr.size(); i < end; ++i) arr.add(i);
+  }
+
+  @Test
+  public void testIntArrayList() {
+    // Test add()
+    IntArrayList arr = new IntArrayList();
+    fillNaturalNumberSequence(arr, 10);
+    assertNaturalNumberSequence(arr, 10);
+    // Test removeLast()
+    arr.removeLast(5);
+    assertNaturalNumberSequence(arr, 5);
+    fillNaturalNumberSequence(arr, 32);
+    assertNaturalNumberSequence(arr, 32);
+    try {
+      arr.removeLast(33);
+      fail();
+    } catch (ArrayIndexOutOfBoundsException e) {}
+    try {
+      arr.removeLast(Integer.MAX_VALUE);
+      fail();
+    } catch (ArrayIndexOutOfBoundsException e) {}
+    try {
+      arr.removeLast(-1);
+      fail();
+    } catch (ArrayIndexOutOfBoundsException e) {}
+    arr.removeLast(0);
+    assertNaturalNumberSequence(arr, 32);
+    // Test set()
+    arr.set(0, -1);
+    assert arr.get(0) == -1;
+    arr.set(31, -1);
+    assert arr.get(31) == -1;
+    try {
+      arr.set(-1, -1);
+      fail();
+    } catch (ArrayIndexOutOfBoundsException e) {}
+    try {
+      arr.set(32, -1);
+      fail();
+    } catch (ArrayIndexOutOfBoundsException e) {}
+    // Test clear()
+    arr.clear();
+    assertNaturalNumberSequence(arr, 0);
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/5e9b4e2f/testdata/workloads/functional-planner/queries/PlannerTest/outer-joins.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-planner/queries/PlannerTest/outer-joins.test b/testdata/workloads/functional-planner/queries/PlannerTest/outer-joins.test
index 4f7b809..d593dd0 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/outer-joins.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/outer-joins.test
@@ -1049,3 +1049,108 @@ PLAN-ROOT SINK
 00:SCAN HDFS [functional.alltypes t1]
    partitions=24/24 files=24 size=478.45KB
 ====
+# IMPALA-6123: Test the partition compatibility check with consecutive outer joins.
+# In this query the output partition of the right outer join should be the rhs partition
+# t3.id, which is not compatible with the aggregation partition t2.id. There should be
+# an exchange node in the aggregation.
+# The first left outer join is used to ensure 't2' is made nullable before the fragment
+# executing the right outer join.
+select /* +straight_join */ t2.id, count(*)
+from functional.alltypes t1
+left outer join /* +shuffle */ functional.alltypessmall t2
+  on t1.int_col = t2.int_col
+right outer join /* +shuffle */ functional.alltypestiny t3
+  on t2.id = t3.id
+group by t2.id
+---- DISTRIBUTEDPLAN
+PLAN-ROOT SINK
+|
+12:EXCHANGE [UNPARTITIONED]
+|
+11:AGGREGATE [FINALIZE]
+|  output: count:merge(*)
+|  group by: t2.id
+|
+10:EXCHANGE [HASH(t2.id)]
+|
+05:AGGREGATE [STREAMING]
+|  output: count(*)
+|  group by: t2.id
+|
+04:HASH JOIN [RIGHT OUTER JOIN, PARTITIONED]
+|  hash predicates: t2.id = t3.id
+|  runtime filters: RF000 <- t3.id
+|
+|--09:EXCHANGE [HASH(t3.id)]
+|  |
+|  02:SCAN HDFS [functional.alltypestiny t3]
+|     partitions=4/4 files=4 size=460B
+|
+08:EXCHANGE [HASH(t2.id)]
+|
+03:HASH JOIN [LEFT OUTER JOIN, PARTITIONED]
+|  hash predicates: t1.int_col = t2.int_col
+|
+|--07:EXCHANGE [HASH(t2.int_col)]
+|  |
+|  01:SCAN HDFS [functional.alltypessmall t2]
+|     partitions=4/4 files=4 size=6.32KB
+|     runtime filters: RF000 -> t2.id
+|
+06:EXCHANGE [HASH(t1.int_col)]
+|
+00:SCAN HDFS [functional.alltypes t1]
+   partitions=24/24 files=24 size=478.45KB
+====
+# IMPALA-6123: Test the partition compatibility check with consecutive outer joins.
+# In this query the output partition of the full outer join should be random. There should
+# be an exchange node in the aggregation.
+# The first right outer join is used to ensure 't1' is made nullable before the fragment
+# executing the full outer join.
+select /* +straight_join */ t1.int_col, count(*)
+from functional.alltypes t1
+right outer join /* +shuffle */ functional.alltypes t2
+  on t1.smallint_col = t2.smallint_col
+full outer join /* +shuffle */ functional.alltypes t3
+  on t1.int_col = t3.int_col
+group by t1.int_col
+---- DISTRIBUTEDPLAN
+PLAN-ROOT SINK
+|
+12:EXCHANGE [UNPARTITIONED]
+|
+11:AGGREGATE [FINALIZE]
+|  output: count:merge(*)
+|  group by: t1.int_col
+|
+10:EXCHANGE [HASH(t1.int_col)]
+|
+05:AGGREGATE [STREAMING]
+|  output: count(*)
+|  group by: t1.int_col
+|
+04:HASH JOIN [FULL OUTER JOIN, PARTITIONED]
+|  hash predicates: t1.int_col = t3.int_col
+|
+|--09:EXCHANGE [HASH(t3.int_col)]
+|  |
+|  02:SCAN HDFS [functional.alltypes t3]
+|     partitions=24/24 files=24 size=478.45KB
+|
+08:EXCHANGE [HASH(t1.int_col)]
+|
+03:HASH JOIN [RIGHT OUTER JOIN, PARTITIONED]
+|  hash predicates: t1.smallint_col = t2.smallint_col
+|  runtime filters: RF000 <- t2.smallint_col
+|
+|--07:EXCHANGE [HASH(t2.smallint_col)]
+|  |
+|  01:SCAN HDFS [functional.alltypes t2]
+|     partitions=24/24 files=24 size=478.45KB
+|
+06:EXCHANGE [HASH(t1.smallint_col)]
+|
+00:SCAN HDFS [functional.alltypes t1]
+   partitions=24/24 files=24 size=478.45KB
+   runtime filters: RF000 -> t1.smallint_col
+====