You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@drill.apache.org by ja...@apache.org on 2014/01/30 19:47:16 UTC

[11/15] DRILL-334: Subdivide Drillbit control and data messages. Add support for socket backpressure. Add TopLevel and Child memory allocator with debug mode to capture memory leaks. Various memory leak fixes to get build to complete.

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/partitionsender/PartitionSenderRootExec.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/partitionsender/PartitionSenderRootExec.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/partitionsender/PartitionSenderRootExec.java
index 409a9c3..d88e5b5 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/partitionsender/PartitionSenderRootExec.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/partitionsender/PartitionSenderRootExec.java
@@ -18,6 +18,7 @@
 package org.apache.drill.exec.physical.impl.partitionsender;
 
 import java.io.IOException;
+import java.util.concurrent.atomic.AtomicLong;
 
 import org.apache.drill.common.expression.ErrorCollector;
 import org.apache.drill.common.expression.ErrorCollectorImpl;
@@ -30,8 +31,10 @@ import org.apache.drill.exec.expr.TypeHelper;
 import org.apache.drill.exec.ops.FragmentContext;
 import org.apache.drill.exec.physical.config.HashPartitionSender;
 import org.apache.drill.exec.physical.impl.RootExec;
+import org.apache.drill.exec.physical.impl.SendingAccountor;
 import org.apache.drill.exec.physical.impl.filter.ReturnValueExpression;
 import org.apache.drill.exec.proto.CoordinationProtos;
+import org.apache.drill.exec.proto.ExecProtos.FragmentHandle;
 import org.apache.drill.exec.record.RecordBatch;
 import org.apache.drill.exec.record.TypedFieldId;
 import org.apache.drill.exec.record.VectorWrapper;
@@ -54,6 +57,9 @@ public class PartitionSenderRootExec implements RootExec {
   private Partitioner partitioner;
   private FragmentContext context;
   private boolean ok = true;
+  private AtomicLong batchesSent = new AtomicLong(0);
+  private final SendingAccountor sendCount = new SendingAccountor();
+
 
   public PartitionSenderRootExec(FragmentContext context,
                                  RecordBatch incoming,
@@ -65,8 +71,9 @@ public class PartitionSenderRootExec implements RootExec {
     this.outgoing = new OutgoingRecordBatch[operator.getDestinations().size()];
     int fieldId = 0;
     for (CoordinationProtos.DrillbitEndpoint endpoint : operator.getDestinations()) {
-      outgoing[fieldId] = new OutgoingRecordBatch(operator,
-                                                    context.getCommunicator().getTunnel(endpoint),
+      FragmentHandle opposite = context.getHandle().toBuilder().setMajorFragmentId(operator.getOppositeMajorFragmentId()).setMinorFragmentId(fieldId).build();
+      outgoing[fieldId] = new OutgoingRecordBatch(sendCount, operator,
+                                                    context.getDataTunnel(endpoint, opposite),
                                                     incoming,
                                                     context,
                                                     fieldId);
@@ -79,6 +86,7 @@ public class PartitionSenderRootExec implements RootExec {
 
     if (!ok) {
       stop();
+      
       return false;
     }
 
@@ -119,8 +127,8 @@ public class PartitionSenderRootExec implements RootExec {
         }
       case OK:
         partitioner.partitionBatch(incoming);
-        context.batchesCompleted.inc(1);
-        context.recordsCompleted.inc(incoming.getRecordCount());
+        context.getStats().batchesCompleted.inc(1);
+        context.getStats().recordsCompleted.inc(incoming.getRecordCount());
         return true;
       case NOT_YET:
       default:
@@ -128,10 +136,7 @@ public class PartitionSenderRootExec implements RootExec {
     }
   }
 
-  public void stop() {
-    ok = false;
-    incoming.kill();
-  }
+
   
   private void generatePartitionFunction() throws SchemaChangeException {
 
@@ -285,4 +290,14 @@ public class PartitionSenderRootExec implements RootExec {
       }
     }
   }
+  
+  public void stop() {
+    logger.debug("Partition sender stopping.");
+    ok = false;
+    for(OutgoingRecordBatch b : outgoing){
+      b.clear();
+    }
+    incoming.cleanup();
+    sendCount.waitForSendComplete();
+  }
 }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortBatch.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortBatch.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortBatch.java
index e01fb74..f862510 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortBatch.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortBatch.java
@@ -36,9 +36,12 @@ import org.apache.drill.exec.expr.ExpressionTreeMaterializer;
 import org.apache.drill.exec.expr.HoldingContainerExpression;
 import org.apache.drill.exec.expr.fn.impl.ComparatorFunctions;
 import org.apache.drill.exec.ops.FragmentContext;
-import org.apache.drill.exec.physical.base.PhysicalOperator;
 import org.apache.drill.exec.physical.config.Sort;
-import org.apache.drill.exec.record.*;
+import org.apache.drill.exec.record.AbstractRecordBatch;
+import org.apache.drill.exec.record.BatchSchema;
+import org.apache.drill.exec.record.RecordBatch;
+import org.apache.drill.exec.record.VectorAccessible;
+import org.apache.drill.exec.record.WritableBatch;
 import org.apache.drill.exec.record.selection.SelectionVector2;
 import org.apache.drill.exec.record.selection.SelectionVector4;
 
@@ -56,24 +59,25 @@ public class SortBatch extends AbstractRecordBatch<Sort> {
   private static long MAX_SORT_BYTES = 8l * 1024 * 1024 * 1024;
 
   private final RecordBatch incoming;
-  private SortRecordBatchBuilder builder;
-  private SelectionVector4 sv4;
+  private final SortRecordBatchBuilder builder;
   private Sorter sorter;
   private BatchSchema schema;
   
   public SortBatch(Sort popConfig, FragmentContext context, RecordBatch incoming) {
     super(popConfig, context);
     this.incoming = incoming;
+    this.builder = new SortRecordBatchBuilder(context.getAllocator(), MAX_SORT_BYTES);
   }
 
   @Override
   public int getRecordCount() {
-    return sv4.getCount();
+    return builder.getSv4().getCount();
   }
 
   @Override
   public void kill() {
     incoming.kill();
+    cleanup();
   }
 
   @Override
@@ -83,22 +87,22 @@ public class SortBatch extends AbstractRecordBatch<Sort> {
 
   @Override
   public SelectionVector4 getSelectionVector4() {
-    return sv4;
+    return builder.getSv4();
   }
 
   
   
   @Override
-  protected void cleanup() {
+  public void cleanup() {
     super.cleanup();
-    container.zeroVectors();;
-    sv4.clear();
+    incoming.cleanup();
+    builder.clear();
   }
 
   @Override
   public IterOutcome next() {
-    if(builder != null){
-      if(sv4.next()){
+    if(schema != null){
+      if(getSelectionVector4().next()){
         return IterOutcome.OK;
       }else{
         return IterOutcome.NONE;
@@ -113,14 +117,14 @@ public class SortBatch extends AbstractRecordBatch<Sort> {
         case NONE:
           break outer;
         case NOT_YET:
+          throw new UnsupportedOperationException();
         case STOP:
-          container.zeroVectors();
+          cleanup();
           return upstream;
         case OK_NEW_SCHEMA:
           // only change in the case that the schema truly changes.  Artificial schema changes are ignored.
           if(!incoming.getSchema().equals(schema)){
-            if (builder != null) throw new UnsupportedOperationException("Sort doesn't currently support sorts with changing schemas.");
-            builder = new SortRecordBatchBuilder(context.getAllocator(), MAX_SORT_BYTES, container);
+            if (schema != null) throw new UnsupportedOperationException("Sort doesn't currently support sorts with changing schemas.");
             this.schema = incoming.getSchema();
           }
           // fall through.
@@ -134,19 +138,16 @@ public class SortBatch extends AbstractRecordBatch<Sort> {
         }
       }
       
-      if (builder == null){
+      if (schema == null){
         // builder may be null at this point if the first incoming batch is empty
         return IterOutcome.NONE;
       }
         
-      builder.build(context);
-      sv4 = builder.getSv4();
+      builder.build(context, container);
 
       sorter = createNewSorter();
-      sorter.setup(context, this.getSelectionVector4(), this.container);
-      long t1 = System.nanoTime();
-      sorter.sort(sv4, container);
-      logger.debug("Sorted {} records in {} micros.", sv4.getTotalCount(), (System.nanoTime() - t1)/1000);
+      sorter.setup(context, getSelectionVector4(), this.container);
+      sorter.sort(getSelectionVector4(), this.container);
       
       return IterOutcome.OK_NEW_SCHEMA;
       

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortRecordBatchBuilder.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortRecordBatchBuilder.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortRecordBatchBuilder.java
index cb55a01..d8bbc6a 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortRecordBatchBuilder.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/sort/SortRecordBatchBuilder.java
@@ -17,9 +17,6 @@
  */
 package org.apache.drill.exec.physical.impl.sort;
 
-import com.google.common.collect.Lists;
-import io.netty.buffer.ByteBuf;
-
 import java.util.ArrayList;
 import java.util.List;
 
@@ -27,18 +24,22 @@ import org.apache.drill.exec.exception.SchemaChangeException;
 import org.apache.drill.exec.memory.BufferAllocator;
 import org.apache.drill.exec.memory.BufferAllocator.PreAllocator;
 import org.apache.drill.exec.ops.FragmentContext;
-import org.apache.drill.exec.record.*;
+import org.apache.drill.exec.record.BatchSchema;
 import org.apache.drill.exec.record.BatchSchema.SelectionVectorMode;
+import org.apache.drill.exec.record.MaterializedField;
+import org.apache.drill.exec.record.VectorAccessible;
+import org.apache.drill.exec.record.VectorContainer;
+import org.apache.drill.exec.record.VectorWrapper;
 import org.apache.drill.exec.record.selection.SelectionVector4;
 import org.apache.drill.exec.vector.ValueVector;
 
 import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.Lists;
 
 public class SortRecordBatchBuilder {
   static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SortRecordBatchBuilder.class);
   
   private final ArrayListMultimap<BatchSchema, RecordBatchData> batches = ArrayListMultimap.create();
-  private final VectorContainer container;
 
   private int recordCount;
   private long runningBytes;
@@ -47,10 +48,9 @@ public class SortRecordBatchBuilder {
   private SelectionVector4 sv4;
   final PreAllocator svAllocator;
   
-  public SortRecordBatchBuilder(BufferAllocator a, long maxBytes, VectorContainer container){
+  public SortRecordBatchBuilder(BufferAllocator a, long maxBytes){
     this.maxBytes = maxBytes;
-    this.svAllocator = a.getPreAllocator();
-    this.container = container;
+    this.svAllocator = a.getNewPreAllocator();
   }
   
   private long getSize(VectorAccessible batch){
@@ -89,8 +89,8 @@ public class SortRecordBatchBuilder {
     return true;
   }
 
-  public void build(FragmentContext context) throws SchemaChangeException{
-    container.clear();
+  public void build(FragmentContext context, VectorContainer outputContainer) throws SchemaChangeException{
+    outputContainer.clear();
     if(batches.keySet().size() > 1) throw new SchemaChangeException("Sort currently only supports a single schema.");
     if(batches.size() > Character.MAX_VALUE) throw new SchemaChangeException("Sort cannot work on more than %d batches at a time.", (int) Character.MAX_VALUE);
     assert batches.keySet().size() > 0;
@@ -138,18 +138,25 @@ public class SortRecordBatchBuilder {
     
     for(MaterializedField f : vectors.keySet()){
       List<ValueVector> v = vectors.get(f);
-      container.addHyperList(v);
+      outputContainer.addHyperList(v, false);
     }
     
-    container.buildSchema(SelectionVectorMode.FOUR_BYTE);
+    outputContainer.buildSchema(SelectionVectorMode.FOUR_BYTE);
   }
 
   public SelectionVector4 getSv4() {
     return sv4;
   }
 
-  public List<VectorContainer> getContainers() {
-    ArrayList containerList = Lists.newArrayList();
+  public void clear(){
+    for(RecordBatchData d : batches.values()){
+      d.container.clear();
+    }
+    if(sv4 != null) sv4.clear();
+  }
+  
+  public List<VectorContainer> getHeldRecordBatches() {
+    ArrayList<VectorContainer> containerList = Lists.newArrayList();
     for (BatchSchema bs : batches.keySet()) {
       for (RecordBatchData bd : batches.get(bs)) {
         VectorContainer c = bd.getContainer();
@@ -157,6 +164,7 @@ public class SortRecordBatchBuilder {
         containerList.add(c);
       }
     }
+    batches.clear();
     return containerList;
   }
   

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/CopierTemplate2.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/CopierTemplate2.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/CopierTemplate2.java
index a8b1eec..6d12731 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/CopierTemplate2.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/CopierTemplate2.java
@@ -22,6 +22,7 @@ import javax.inject.Named;
 import org.apache.drill.exec.exception.SchemaChangeException;
 import org.apache.drill.exec.ops.FragmentContext;
 import org.apache.drill.exec.record.RecordBatch;
+import org.apache.drill.exec.record.VectorWrapper;
 import org.apache.drill.exec.record.selection.SelectionVector2;
 import org.apache.drill.exec.vector.allocator.VectorAllocator;
 
@@ -30,11 +31,13 @@ public abstract class CopierTemplate2 implements Copier{
   
   private SelectionVector2 sv2;
   private VectorAllocator[] allocators;
+  private RecordBatch incoming;
   
   @Override
   public void setupRemover(FragmentContext context, RecordBatch incoming, RecordBatch outgoing, VectorAllocator[] allocators) throws SchemaChangeException{
     this.allocators = allocators;
     this.sv2 = incoming.getSelectionVector2();
+    this.incoming = incoming;
     doSetup(context, incoming, outgoing);
   }
   
@@ -53,6 +56,10 @@ public abstract class CopierTemplate2 implements Copier{
     for(int svIndex = 0; svIndex < recordCount; svIndex++, outgoingPosition++){
       doEval(sv2.getIndex(svIndex), outgoingPosition);
     }
+//    logger.debug("This: {}, Incoming: {}", System.identityHashCode(this), incoming);
+    for(VectorWrapper<?> v : incoming){
+      v.clear();
+    }
   }
   
   public abstract void doSetup(@Named("context") FragmentContext context, @Named("incoming") RecordBatch incoming, @Named("outgoing") RecordBatch outgoing);

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/CopierTemplate4.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/CopierTemplate4.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/CopierTemplate4.java
index ea35272..2a3a2e2 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/CopierTemplate4.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/CopierTemplate4.java
@@ -22,6 +22,7 @@ import javax.inject.Named;
 import org.apache.drill.exec.exception.SchemaChangeException;
 import org.apache.drill.exec.ops.FragmentContext;
 import org.apache.drill.exec.record.RecordBatch;
+import org.apache.drill.exec.record.VectorWrapper;
 import org.apache.drill.exec.record.selection.SelectionVector2;
 import org.apache.drill.exec.record.selection.SelectionVector4;
 import org.apache.drill.exec.vector.allocator.VectorAllocator;
@@ -31,7 +32,7 @@ public abstract class CopierTemplate4 implements Copier{
   
   private SelectionVector4 sv4;
   private VectorAllocator[] allocators;
-
+  private RecordBatch incoming;
   
   private void allocateVectors(int recordCount){
     for(VectorAllocator a : allocators){
@@ -42,6 +43,7 @@ public abstract class CopierTemplate4 implements Copier{
   @Override
   public void setupRemover(FragmentContext context, RecordBatch incoming, RecordBatch outgoing, VectorAllocator[] allocators) throws SchemaChangeException{
     this.allocators = allocators;
+    this.incoming = incoming;
     this.sv4 = incoming.getSelectionVector4();
     doSetup(context, incoming, outgoing);
   }
@@ -49,6 +51,7 @@ public abstract class CopierTemplate4 implements Copier{
 
   @Override
   public void copyRecords(){
+//    logger.debug("Copying records.");
     final int recordCount = sv4.getCount();
     allocateVectors(recordCount);
     int outgoingPosition = 0;
@@ -56,6 +59,11 @@ public abstract class CopierTemplate4 implements Copier{
       int deRefIndex = sv4.get(svIndex);
       doEval(deRefIndex, outgoingPosition);
     }
+    
+    for(VectorWrapper<?> v : incoming){
+      v.clear();
+    }
+
   }
   
   public abstract void doSetup(@Named("context") FragmentContext context, @Named("incoming") RecordBatch incoming, @Named("outgoing") RecordBatch outgoing);

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/RemovingRecordBatch.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/RemovingRecordBatch.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/RemovingRecordBatch.java
index 663f4c3..123f022 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/RemovingRecordBatch.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/RemovingRecordBatch.java
@@ -54,6 +54,7 @@ public class RemovingRecordBatch extends AbstractSingleRecordBatch<SelectionVect
   
   public RemovingRecordBatch(SelectionVectorRemover popConfig, FragmentContext context, RecordBatch incoming) {
     super(popConfig, context, incoming);
+    logger.debug("Created.");
   }
 
   @Override
@@ -64,7 +65,7 @@ public class RemovingRecordBatch extends AbstractSingleRecordBatch<SelectionVect
   @Override
   protected void setupNewSchema() throws SchemaChangeException {
     container.clear();
-    
+
     switch(incoming.getSchema().getSelectionVectorMode()){
     case NONE:
       this.copier = getStraightCopier();
@@ -93,6 +94,9 @@ public class RemovingRecordBatch extends AbstractSingleRecordBatch<SelectionVect
     }
   }
 
+  public void cleanup(){
+    super.cleanup();
+  }
   
   private class StraightCopier implements Copier{
 

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/trace/TraceRecordBatch.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/trace/TraceRecordBatch.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/trace/TraceRecordBatch.java
index c138aba..c9a73f9 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/trace/TraceRecordBatch.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/trace/TraceRecordBatch.java
@@ -1,5 +1,5 @@
 /**
- * Licensed to the Apache Software Foundation (ASF) under one
+ * Licensed to th7e 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
@@ -18,38 +18,25 @@
 
 package org.apache.drill.exec.physical.impl.trace;
 
-import java.io.File;
-import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
-import java.nio.channels.FileChannel;
-import java.nio.ByteBuffer;
-import java.util.List;
-import java.util.Formatter;
 
-import com.google.common.collect.Iterators;
-import io.netty.buffer.CompositeByteBuf;
+import org.apache.drill.common.exceptions.ExecutionSetupException;
 import org.apache.drill.exec.ExecConstants;
 import org.apache.drill.exec.cache.VectorAccessibleSerializable;
 import org.apache.drill.exec.exception.SchemaChangeException;
-import org.apache.drill.common.exceptions.ExecutionSetupException;
-import org.apache.drill.exec.expr.TypeHelper;
-import org.apache.drill.exec.memory.BufferAllocator;
 import org.apache.drill.exec.ops.FragmentContext;
 import org.apache.drill.exec.physical.config.Trace;
-import org.apache.drill.exec.record.*;
-import org.apache.drill.exec.record.BatchSchema.SelectionVectorMode;
-import org.apache.drill.exec.record.selection.SelectionVector2;
-import org.apache.drill.exec.vector.ValueVector;
 import org.apache.drill.exec.proto.ExecProtos.FragmentHandle;
 import org.apache.drill.exec.proto.helper.QueryIdHelper;
-import org.apache.drill.exec.proto.UserBitShared.RecordBatchDef;
-import org.apache.drill.exec.proto.UserBitShared.FieldMetadata;
-import org.apache.drill.exec.proto.SchemaDefProtos.FieldDef;
-
-import io.netty.buffer.ByteBuf;
+import org.apache.drill.exec.record.AbstractSingleRecordBatch;
+import org.apache.drill.exec.record.BatchSchema.SelectionVectorMode;
+import org.apache.drill.exec.record.RecordBatch;
+import org.apache.drill.exec.record.TransferPair;
+import org.apache.drill.exec.record.VectorWrapper;
+import org.apache.drill.exec.record.WritableBatch;
+import org.apache.drill.exec.record.selection.SelectionVector2;
 import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FSDataOutputStream;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
 
@@ -174,7 +161,7 @@ public class TraceRecordBatch extends AbstractSingleRecordBatch<Trace> {
   }
 
   @Override
-  protected void cleanup() {
+  public void cleanup() {
     /* Release the selection vector */
     if (sv != null)
       sv.clear();
@@ -185,6 +172,7 @@ public class TraceRecordBatch extends AbstractSingleRecordBatch<Trace> {
     } catch (IOException e) {
       logger.error("Unable to close file descriptors for file: " + getFileName());
     }
+    super.cleanup();
   }
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/validate/IteratorValidatorBatchIterator.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/validate/IteratorValidatorBatchIterator.java b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/validate/IteratorValidatorBatchIterator.java
index d6f08f1..8552465 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/validate/IteratorValidatorBatchIterator.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/validate/IteratorValidatorBatchIterator.java
@@ -113,4 +113,9 @@ public class IteratorValidatorBatchIterator implements RecordBatch{
     validateReadState();
     return incoming.getWritableBatch();
   }
+
+  @Override
+  public void cleanup() {
+    incoming.cleanup();
+  }
 }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/planner/fragment/SimpleParallelizer.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/planner/fragment/SimpleParallelizer.java b/exec/java-exec/src/main/java/org/apache/drill/exec/planner/fragment/SimpleParallelizer.java
index 8262691..ffb4c5b 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/planner/fragment/SimpleParallelizer.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/planner/fragment/SimpleParallelizer.java
@@ -27,9 +27,9 @@ import org.apache.drill.exec.physical.base.FragmentRoot;
 import org.apache.drill.exec.physical.base.PhysicalOperator;
 import org.apache.drill.exec.planner.PhysicalPlanReader;
 import org.apache.drill.exec.planner.fragment.Materializer.IndexedFragmentNode;
+import org.apache.drill.exec.proto.BitControl.PlanFragment;
 import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
 import org.apache.drill.exec.proto.ExecProtos.FragmentHandle;
-import org.apache.drill.exec.proto.ExecProtos.PlanFragment;
 import org.apache.drill.exec.proto.UserBitShared.QueryId;
 import org.apache.drill.exec.work.QueryWorkUnit;
 
@@ -128,11 +128,11 @@ public class SimpleParallelizer {
             .build();
 
         if (isRootNode) {
-          logger.debug("Root fragment {}", fragment);
+          logger.debug("Root fragment:\n {}", fragment);
           rootFragment = fragment;
           rootOperator = root;
         } else {
-          logger.debug("Remote fragment {}", fragment);
+          logger.debug("Remote fragment:\n {}", fragment);
           fragments.add(fragment);
         }
       }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/proto/helper/QueryIdHelper.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/proto/helper/QueryIdHelper.java b/exec/java-exec/src/main/java/org/apache/drill/exec/proto/helper/QueryIdHelper.java
new file mode 100644
index 0000000..749b3d5
--- /dev/null
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/proto/helper/QueryIdHelper.java
@@ -0,0 +1,32 @@
+/**
+ * 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.drill.exec.proto.helper;
+
+import java.util.UUID;
+import org.apache.drill.exec.proto.UserBitShared.QueryId;
+
+/* Helper class around the QueryId protobuf */
+public class QueryIdHelper {
+
+    /* Generate a UUID from the two parts of the queryid */
+    public static String getQueryId(QueryId queryId)
+    {
+        return (new UUID(queryId.getPart1(), queryId.getPart2())).toString();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/record/AbstractRecordBatch.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/record/AbstractRecordBatch.java b/exec/java-exec/src/main/java/org/apache/drill/exec/record/AbstractRecordBatch.java
index ec2d246..d4f458f 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/record/AbstractRecordBatch.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/record/AbstractRecordBatch.java
@@ -59,16 +59,16 @@ public abstract class AbstractRecordBatch<T extends PhysicalOperator> implements
 
   @Override
   public void kill() {
-    container.zeroVectors();
     killIncoming();
     cleanup();
   }
   
   protected abstract void killIncoming();
   
-  protected void cleanup(){
+  public void cleanup(){
+    container.clear();
   }
-  
+ 
   @Override
   public SelectionVector2 getSelectionVector2() {
     throw new UnsupportedOperationException();
@@ -92,7 +92,10 @@ public abstract class AbstractRecordBatch<T extends PhysicalOperator> implements
   
   @Override
   public WritableBatch getWritableBatch() {
-    return WritableBatch.get(this);
+//    logger.debug("Getting writable batch.");
+    WritableBatch batch = WritableBatch.get(this);
+    return batch;
+    
   }
   
   

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/record/AbstractSingleRecordBatch.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/record/AbstractSingleRecordBatch.java b/exec/java-exec/src/main/java/org/apache/drill/exec/record/AbstractSingleRecordBatch.java
index 1639940..7b832e4 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/record/AbstractSingleRecordBatch.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/record/AbstractSingleRecordBatch.java
@@ -22,7 +22,7 @@ import org.apache.drill.exec.ops.FragmentContext;
 import org.apache.drill.exec.physical.base.PhysicalOperator;
 
 public abstract class AbstractSingleRecordBatch<T extends PhysicalOperator> extends AbstractRecordBatch<T> {
-  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AbstractSingleRecordBatch.class);
+  final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(this.getClass());
   
   protected final RecordBatch incoming;
   private boolean first = true;
@@ -46,7 +46,6 @@ public abstract class AbstractSingleRecordBatch<T extends PhysicalOperator> exte
     case NONE:
     case NOT_YET:
     case STOP:
-      container.zeroVectors();
       cleanup();
       return upstream;
     case OK_NEW_SCHEMA:
@@ -67,6 +66,13 @@ public abstract class AbstractSingleRecordBatch<T extends PhysicalOperator> exte
     }
   }
 
+  @Override
+  public void cleanup() {
+//    logger.debug("Cleaning up.");
+    incoming.cleanup();
+    super.cleanup();
+  }
+
   protected abstract void setupNewSchema() throws SchemaChangeException;
   protected abstract void doWork();
 }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/record/FragmentWritableBatch.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/record/FragmentWritableBatch.java b/exec/java-exec/src/main/java/org/apache/drill/exec/record/FragmentWritableBatch.java
index 41ad8b7..33fd5a2 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/record/FragmentWritableBatch.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/record/FragmentWritableBatch.java
@@ -19,8 +19,8 @@ package org.apache.drill.exec.record;
 
 import io.netty.buffer.ByteBuf;
 
+import org.apache.drill.exec.proto.BitData.FragmentRecordBatch;
 import org.apache.drill.exec.proto.ExecProtos.FragmentHandle;
-import org.apache.drill.exec.proto.ExecProtos.FragmentRecordBatch;
 import org.apache.drill.exec.proto.UserBitShared.QueryId;
 import org.apache.drill.exec.proto.UserBitShared.RecordBatchDef;
 

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/record/HyperVectorWrapper.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/record/HyperVectorWrapper.java b/exec/java-exec/src/main/java/org/apache/drill/exec/record/HyperVectorWrapper.java
index d6d49c9..44b935b 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/record/HyperVectorWrapper.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/record/HyperVectorWrapper.java
@@ -88,7 +88,7 @@ public class HyperVectorWrapper<T extends ValueVector> implements VectorWrapper<
 //    return new HyperVectorWrapper<T>(f, newVectors);
   }
 
-  public static <T extends ValueVector> HyperVectorWrapper<T> create(MaterializedField f, T[] v){
-    return new HyperVectorWrapper<T>(f, v);
+  public static <T extends ValueVector> HyperVectorWrapper<T> create(MaterializedField f, T[] v, boolean releasable){
+    return new HyperVectorWrapper<T>(f, v, releasable);
   }
 }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/record/RawFragmentBatch.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/record/RawFragmentBatch.java b/exec/java-exec/src/main/java/org/apache/drill/exec/record/RawFragmentBatch.java
index 7497475..a7d3f4b 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/record/RawFragmentBatch.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/record/RawFragmentBatch.java
@@ -19,18 +19,21 @@ package org.apache.drill.exec.record;
 
 import io.netty.buffer.ByteBuf;
 
-import org.apache.drill.exec.proto.ExecProtos.FragmentRecordBatch;
+import org.apache.drill.exec.proto.BitData.FragmentRecordBatch;
+import org.apache.drill.exec.rpc.RemoteConnection;
 
 public class RawFragmentBatch {
   static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(RawFragmentBatch.class);
 
+  final RemoteConnection connection;
   final FragmentRecordBatch header;
   final ByteBuf body;
 
-  public RawFragmentBatch(FragmentRecordBatch header, ByteBuf body) {
+  public RawFragmentBatch(RemoteConnection connection, FragmentRecordBatch header, ByteBuf body) {
     super();
     this.header = header;
     this.body = body;
+    this.connection = connection;
     if(body != null) body.retain();
   }
 
@@ -51,4 +54,9 @@ public class RawFragmentBatch {
     if(body != null) body.release();
   }
 
+  public RemoteConnection getConnection() {
+    return connection;
+  }
+
+  
 }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/record/RecordBatch.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/record/RecordBatch.java b/exec/java-exec/src/main/java/org/apache/drill/exec/record/RecordBatch.java
index c13838c..b41b733 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/record/RecordBatch.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/record/RecordBatch.java
@@ -110,5 +110,7 @@ public interface RecordBatch extends VectorAccessible {
    * @return
    */
   public WritableBatch getWritableBatch();
+  
+  public void cleanup();
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/record/RecordBatchLoader.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/record/RecordBatchLoader.java b/exec/java-exec/src/main/java/org/apache/drill/exec/record/RecordBatchLoader.java
index f19184f..bbeae4f 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/record/RecordBatchLoader.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/record/RecordBatchLoader.java
@@ -153,6 +153,8 @@ public class RecordBatchLoader implements VectorAccessible, Iterable<VectorWrapp
     return schema;
   }
 
-
+  public void clear(){
+    container.clear();
+  }
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/record/VectorContainer.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/record/VectorContainer.java b/exec/java-exec/src/main/java/org/apache/drill/exec/record/VectorContainer.java
index 462c00a..8d952e3 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/record/VectorContainer.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/record/VectorContainer.java
@@ -32,7 +32,6 @@ public class VectorContainer implements Iterable<VectorWrapper<?>>, VectorAccess
   static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(VectorContainer.class);
 
   private final List<VectorWrapper<?>> wrappers = Lists.newArrayList();
-  private final List<VectorWrapper<?>> oldWrappers = Lists.newArrayList();
   private BatchSchema schema;
   private int recordCount = -1;
 
@@ -50,12 +49,16 @@ public class VectorContainer implements Iterable<VectorWrapper<?>>, VectorAccess
   // }
 
   public void addHyperList(List<ValueVector> vectors) {
+    addHyperList(vectors, true);
+  }
+  
+  public void addHyperList(List<ValueVector> vectors, boolean releasable) {
     schema = null;
     ValueVector[] vv = new ValueVector[vectors.size()];
     for (int i = 0; i < vv.length; i++) {
       vv[i] = vectors.get(i);
     }
-    add(vv);
+    add(vv, releasable);
   }
 
   /**
@@ -95,6 +98,9 @@ public class VectorContainer implements Iterable<VectorWrapper<?>>, VectorAccess
   }
 
   public void add(ValueVector[] hyperVector) {
+    
+  }
+  public void add(ValueVector[] hyperVector, boolean releasable) {
     assert hyperVector.length != 0;
     schema = null;
     Class<?> clazz = hyperVector[0].getClass();
@@ -103,7 +109,7 @@ public class VectorContainer implements Iterable<VectorWrapper<?>>, VectorAccess
       c[i] = hyperVector[i];
     }
     // todo: work with a merged schema.
-    wrappers.add(HyperVectorWrapper.create(hyperVector[0].getField(), c));
+    wrappers.add(HyperVectorWrapper.create(hyperVector[0].getField(), c, releasable));
   }
 
   public void remove(ValueVector v) {
@@ -166,10 +172,7 @@ public class VectorContainer implements Iterable<VectorWrapper<?>>, VectorAccess
   }
 
   public void clear() {
-    // TODO: figure out a better approach for this.
-    // we don't clear schema because we want empty batches to carry previous schema to avoid extra schema update for no
-    // data.  
-    // schema = null;
+    schema = null;
     zeroVectors();
     wrappers.clear();
   }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/record/WritableBatch.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/record/WritableBatch.java b/exec/java-exec/src/main/java/org/apache/drill/exec/record/WritableBatch.java
index 945df41..288aa7f 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/record/WritableBatch.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/record/WritableBatch.java
@@ -41,7 +41,6 @@ public class WritableBatch {
   private boolean cleared = false;
 
   private WritableBatch(RecordBatchDef def, List<ByteBuf> buffers) {
-    logger.debug("Created new writable batch with def {} and buffers {}", def, buffers);
     this.def = def;
     this.buffers = buffers.toArray(new ByteBuf[buffers.size()]);
   }
@@ -106,6 +105,7 @@ public class WritableBatch {
   }
 
   public void clear() {
+    if(cleared) return;
     for (ByteBuf buf : buffers) {
       buf.release();
     }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/record/selection/SelectionVector2.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/record/selection/SelectionVector2.java b/exec/java-exec/src/main/java/org/apache/drill/exec/record/selection/SelectionVector2.java
index 6ff6cf2..f7b5155 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/record/selection/SelectionVector2.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/record/selection/SelectionVector2.java
@@ -106,7 +106,7 @@ public class SelectionVector2 implements Closeable{
   }
   
   public void setRecordCount(int recordCount){
-    logger.debug("Seting record count to {}", recordCount);
+//    logger.debug("Seting record count to {}", recordCount);
     this.recordCount = recordCount;
   }
 

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/record/selection/SelectionVector4.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/record/selection/SelectionVector4.java b/exec/java-exec/src/main/java/org/apache/drill/exec/record/selection/SelectionVector4.java
index 4533cc2..ac9dcda 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/record/selection/SelectionVector4.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/record/selection/SelectionVector4.java
@@ -20,11 +20,12 @@ package org.apache.drill.exec.record.selection;
 import io.netty.buffer.ByteBuf;
 
 import org.apache.drill.exec.exception.SchemaChangeException;
+import org.apache.drill.exec.record.DeadBuf;
 
 public class SelectionVector4 {
   static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SelectionVector4.class);
 
-  private final ByteBuf vector;
+  private ByteBuf data;
   private int recordCount;
   private int start;
   private int length;
@@ -34,7 +35,7 @@ public class SelectionVector4 {
     this.recordCount = recordCount;
     this.start = 0;
     this.length = Math.min(batchRecordCount, recordCount);
-    this.vector = vector;
+    this.data = vector;
   }
   
   public int getTotalCount(){
@@ -51,14 +52,14 @@ public class SelectionVector4 {
   }
 
   public void set(int index, int compound){
-    vector.setInt(index*4, compound);
+    data.setInt(index*4, compound);
   }
   public void set(int index, int recordBatch, int recordIndex){
-    vector.setInt(index*4, (recordBatch << 16) | (recordIndex & 65535));
+    data.setInt(index*4, (recordBatch << 16) | (recordIndex & 65535));
   }
   
   public int get(int index){
-    return vector.getInt( (start+index)*4);
+    return data.getInt( (start+index)*4);
   }
 
   /**
@@ -68,8 +69,8 @@ public class SelectionVector4 {
    */
   public SelectionVector4 createNewWrapperCurrent(){
     try {
-      vector.retain();
-      SelectionVector4 sv4 = new SelectionVector4(vector, length, length);
+      data.retain();
+      SelectionVector4 sv4 = new SelectionVector4(data, length, length);
       sv4.start = this.start;
       return sv4;
     } catch (SchemaChangeException e) {
@@ -98,7 +99,10 @@ public class SelectionVector4 {
   public void clear(){
     start = 0;
     length = 0;
-    this.vector.clear();
+    if (data != DeadBuf.DEAD_BUFFER) {
+      data.release();
+      data = DeadBuf.DEAD_BUFFER;
+    }
   }
   
   

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BasicClient.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BasicClient.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BasicClient.java
index 066af06..4a43a99 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BasicClient.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BasicClient.java
@@ -30,6 +30,7 @@ import io.netty.channel.socket.SocketChannel;
 import io.netty.channel.socket.nio.NioSocketChannel;
 import io.netty.util.concurrent.GenericFutureListener;
 
+import org.apache.drill.exec.memory.BufferAllocator;
 import org.apache.drill.exec.rpc.RpcConnectionHandler.FailureType;
 
 import com.google.protobuf.Internal.EnumLite;
@@ -60,16 +61,17 @@ public abstract class BasicClient<T extends EnumLite, R extends RemoteConnection
         .option(ChannelOption.ALLOCATOR, alloc) //
         .option(ChannelOption.SO_RCVBUF, 1 << 17) //
         .option(ChannelOption.SO_SNDBUF, 1 << 17) //
+        .option(ChannelOption.TCP_NODELAY, true)
         .handler(new ChannelInitializer<SocketChannel>() {
 
           @Override
           protected void initChannel(SocketChannel ch) throws Exception {
-            logger.debug("initializing client connection.");
+//            logger.debug("initializing client connection.");
             connection = initRemoteConnection(ch);
             ch.closeFuture().addListener(getCloseHandler(connection));
             
             ch.pipeline().addLast( //
-                new ZeroCopyProtobufLengthDecoder(), //
+                getDecoder(connection.getAllocator()), //
                 new RpcDecoder("c-" + rpcConfig.getName()), //
                 new RpcEncoder("c-" + rpcConfig.getName()), //
                 new ClientHandshakeHandler(), //
@@ -82,6 +84,8 @@ public abstract class BasicClient<T extends EnumLite, R extends RemoteConnection
 
     ;
   }
+  
+  public abstract ProtobufLengthDecoder getDecoder(BufferAllocator allocator);
 
   public boolean isActive(){
     return connection.getChannel().isActive() ;
@@ -94,18 +98,12 @@ public abstract class BasicClient<T extends EnumLite, R extends RemoteConnection
     return new ChannelClosedHandler();
   }
 
-  protected final <SEND extends MessageLite, RECEIVE extends MessageLite> DrillRpcFutureImpl<RECEIVE> send(
-      T connection, T rpcType, SEND protobufBody, Class<RECEIVE> clazz, ByteBuf... dataBodies) throws RpcException {
-    throw new UnsupportedOperationException(
-        "This shouldn't be used in client mode as a client only has a single connection.");
-  }
-
-  protected <SEND extends MessageLite, RECEIVE extends MessageLite> void send(RpcOutcomeListener<RECEIVE> listener,
-      T rpcType, SEND protobufBody, Class<RECEIVE> clazz, ByteBuf... dataBodies) throws RpcException {
+  public <SEND extends MessageLite, RECEIVE extends MessageLite> void send(RpcOutcomeListener<RECEIVE> listener,
+      T rpcType, SEND protobufBody, Class<RECEIVE> clazz, ByteBuf... dataBodies) {
     super.send(listener, connection, rpcType, protobufBody, clazz, dataBodies);
   }
 
-  protected <SEND extends MessageLite, RECEIVE extends MessageLite> DrillRpcFuture<RECEIVE> send(T rpcType,
+  public <SEND extends MessageLite, RECEIVE extends MessageLite> DrillRpcFuture<RECEIVE> send(T rpcType,
       SEND protobufBody, Class<RECEIVE> clazz, ByteBuf... dataBodies) throws RpcException {
     return super.send(connection, rpcType, protobufBody, clazz, dataBodies);
   }
@@ -146,7 +144,8 @@ public abstract class BasicClient<T extends EnumLite, R extends RemoteConnection
         try {
           future.get();
           if (future.isSuccess()) {
-            send(handshakeSendHandler, handshakeType, handshakeValue, responseClass);
+            // send a handshake on the current thread.  This is the only time we will send from within the event thread.  We can do this because the connection will not be backed up.
+            send(handshakeSendHandler, connection, handshakeType, handshakeValue, responseClass, true);
           } else {
             l.connectionFailed(FailureType.CONNECTION, new RpcException("General connection failure."));
           }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BasicClientWithConnection.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BasicClientWithConnection.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BasicClientWithConnection.java
index df8638b..a0b5cfd 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BasicClientWithConnection.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BasicClientWithConnection.java
@@ -18,24 +18,27 @@
 package org.apache.drill.exec.rpc;
 
 import io.netty.buffer.ByteBuf;
-import io.netty.buffer.ByteBufAllocator;
 import io.netty.channel.Channel;
 import io.netty.channel.ChannelFuture;
 import io.netty.channel.EventLoopGroup;
 import io.netty.util.concurrent.GenericFutureListener;
 
+import org.apache.drill.exec.memory.BufferAllocator;
 import org.apache.drill.exec.rpc.BasicClientWithConnection.ServerConnection;
 
+import com.google.protobuf.Internal.EnumLite;
 import com.google.protobuf.MessageLite;
 import com.google.protobuf.Parser;
-import com.google.protobuf.Internal.EnumLite;
 
 public abstract class BasicClientWithConnection<T extends EnumLite, HANDSHAKE_SEND extends MessageLite, HANDSHAKE_RESPONSE extends MessageLite> extends BasicClient<T, ServerConnection, HANDSHAKE_SEND, HANDSHAKE_RESPONSE>{
   static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(BasicClientWithConnection.class);
 
-  public BasicClientWithConnection(RpcConfig rpcMapping, ByteBufAllocator alloc, EventLoopGroup eventLoopGroup, T handshakeType,
+  private BufferAllocator alloc;
+  
+  public BasicClientWithConnection(RpcConfig rpcMapping, BufferAllocator alloc, EventLoopGroup eventLoopGroup, T handshakeType,
       Class<HANDSHAKE_RESPONSE> responseClass, Parser<HANDSHAKE_RESPONSE> handshakeParser) {
-    super(rpcMapping, alloc, eventLoopGroup, handshakeType, responseClass, handshakeParser);
+    super(rpcMapping, alloc.getUnderlyingAllocator(), eventLoopGroup, handshakeType, responseClass, handshakeParser);
+    this.alloc = alloc;
   }
   
   @Override
@@ -52,15 +55,25 @@ public abstract class BasicClientWithConnection<T extends EnumLite, HANDSHAKE_SE
     
   @Override
   public ServerConnection initRemoteConnection(Channel channel) {
-    return new ServerConnection(channel);
+    return new ServerConnection(channel, alloc);
   }
 
   public static class ServerConnection extends RemoteConnection{
 
-    public ServerConnection(Channel channel) {
+    private final BufferAllocator alloc;
+    
+    public ServerConnection(Channel channel, BufferAllocator alloc) {
       super(channel);
+      this.alloc = alloc;
     }
 
+    @Override
+    public BufferAllocator getAllocator() {
+      return alloc;
+    }
+    
+    
+
   }
 
   

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BasicServer.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BasicServer.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BasicServer.java
index a947f0a..f5e77f1 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BasicServer.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/BasicServer.java
@@ -18,7 +18,9 @@
 package org.apache.drill.exec.rpc;
 
 import io.netty.bootstrap.ServerBootstrap;
+import io.netty.buffer.ByteBuf;
 import io.netty.buffer.ByteBufAllocator;
+import io.netty.channel.Channel;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.ChannelInitializer;
 import io.netty.channel.ChannelOption;
@@ -32,6 +34,7 @@ import java.io.IOException;
 import java.net.BindException;
 
 import org.apache.drill.exec.exception.DrillbitStartupException;
+import org.apache.drill.exec.memory.BufferAllocator;
 import org.apache.drill.exec.proto.GeneralRPCProtos.RpcMode;
 
 import com.google.protobuf.Internal.EnumLite;
@@ -42,7 +45,7 @@ import com.google.protobuf.Parser;
  * A server is bound to a port and is responsible for responding to various type of requests. In some cases, the inbound
  * requests will generate more than one outbound request.
  */
-public abstract class BasicServer<T extends EnumLite, C extends RemoteConnection> extends RpcBus<T, C>{
+public abstract class BasicServer<T extends EnumLite, C extends RemoteConnection> extends RpcBus<T, C> {
   static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(BasicServer.class);
 
   private ServerBootstrap b;
@@ -52,10 +55,11 @@ public abstract class BasicServer<T extends EnumLite, C extends RemoteConnection
   public BasicServer(RpcConfig rpcMapping, ByteBufAllocator alloc, EventLoopGroup eventLoopGroup) {
     super(rpcMapping);
     this.eventLoopGroup = eventLoopGroup;
-    
+
     b = new ServerBootstrap() //
         .channel(NioServerSocketChannel.class) //
         .option(ChannelOption.SO_BACKLOG, 100) //
+        .option(ChannelOption.TCP_NODELAY, true)
         .option(ChannelOption.SO_RCVBUF, 1 << 17) //
         .option(ChannelOption.SO_SNDBUF, 1 << 17) //
         .group(eventLoopGroup) //
@@ -64,30 +68,30 @@ public abstract class BasicServer<T extends EnumLite, C extends RemoteConnection
         .childHandler(new ChannelInitializer<SocketChannel>() {
           @Override
           protected void initChannel(SocketChannel ch) throws Exception {
-            
+//            logger.debug("Starting initialization of server connection.");
             C connection = initRemoteConnection(ch);
             ch.closeFuture().addListener(getCloseHandler(connection));
-            
+
             ch.pipeline().addLast( //
-                new ZeroCopyProtobufLengthDecoder(), //
+                getDecoder(connection.getAllocator()), //
                 new RpcDecoder("s-" + rpcConfig.getName()), //
                 new RpcEncoder("s-" + rpcConfig.getName()), //
-                getHandshakeHandler(connection),
-                new InboundHandler(connection), //
+                getHandshakeHandler(connection), new InboundHandler(connection), //
                 new RpcExceptionHandler() //
-                );            
+                );
             connect = true;
-            
+//            logger.debug("Server connection initialization completed.");
           }
         });
   }
- 
+
+  public abstract ProtobufLengthDecoder getDecoder(BufferAllocator allocator);
+  
   @Override
   public boolean isClient() {
     return false;
   }
 
-  
   protected abstract ServerHandshakeHandler<?> getHandshakeHandler(C connection);
 
   protected static abstract class ServerHandshakeHandler<T extends MessageLite> extends AbstractHandshakeHandler<T> {
@@ -98,17 +102,44 @@ public abstract class BasicServer<T extends EnumLite, C extends RemoteConnection
 
     @Override
     protected final void consumeHandshake(ChannelHandlerContext ctx, T inbound) throws Exception {
-      OutboundRpcMessage msg = new OutboundRpcMessage(RpcMode.RESPONSE, this.handshakeType, coordinationId, getHandshakeResponse(inbound));
+      OutboundRpcMessage msg = new OutboundRpcMessage(RpcMode.RESPONSE, this.handshakeType, coordinationId,
+          getHandshakeResponse(inbound));
       ctx.writeAndFlush(msg);
     }
-    
+
     public abstract MessageLite getHandshakeResponse(T inbound) throws Exception;
-    
+
   }
-  
-  
-  public int bind(final int initialPort) throws InterruptedException, DrillbitStartupException{
-    int port = initialPort-1;
+
+  @Override
+  protected MessageLite getResponseDefaultInstance(int rpcType) throws RpcException {
+    return null;
+  }
+
+  @Override
+  protected Response handle(C connection, int rpcType, ByteBuf pBody, ByteBuf dBody) throws RpcException {
+    return null;
+  }
+
+  @Override
+  public <SEND extends MessageLite, RECEIVE extends MessageLite> DrillRpcFuture<RECEIVE> send(C connection, T rpcType,
+      SEND protobufBody, Class<RECEIVE> clazz, ByteBuf... dataBodies) {
+    return super.send(connection, rpcType, protobufBody, clazz, dataBodies);
+  }
+
+  @Override
+  public <SEND extends MessageLite, RECEIVE extends MessageLite> void send(RpcOutcomeListener<RECEIVE> listener,
+      C connection, T rpcType, SEND protobufBody, Class<RECEIVE> clazz, ByteBuf... dataBodies) {
+    super.send(listener, connection, rpcType, protobufBody, clazz, dataBodies);
+  }
+
+  @Override
+  public C initRemoteConnection(Channel channel) {
+    return null;
+  }
+
+  public int bind(final int initialPort) throws InterruptedException, DrillbitStartupException {
+    int port = initialPort - 1;
     while (true) {
       try {
         b.bind(++port).sync();
@@ -119,17 +150,15 @@ public abstract class BasicServer<T extends EnumLite, C extends RemoteConnection
         throw new DrillbitStartupException("Could not bind Drillbit", e);
       }
     }
-    
+
     connect = !connect;
     logger.debug("Server started on port {} of type {} ", port, this.getClass().getSimpleName());
-    return port;    
+    return port;
   }
 
   @Override
   public void close() throws IOException {
     eventLoopGroup.shutdownGracefully();
   }
-  
-  
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/CoordinationQueue.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/CoordinationQueue.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/CoordinationQueue.java
index 6e1cf79..2bce738 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/CoordinationQueue.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/CoordinationQueue.java
@@ -78,7 +78,7 @@ public class CoordinationQueue {
 
     @Override
     public void operationComplete(ChannelFuture future) throws Exception {
-      connection.releasePermit();
+
       if(!future.isSuccess()){
         removeFromMap(coordinationId);
         if(future.channel().isActive()) {

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/FutureBitCommand.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/FutureBitCommand.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/FutureBitCommand.java
new file mode 100644
index 0000000..fe5d12d
--- /dev/null
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/FutureBitCommand.java
@@ -0,0 +1,73 @@
+/**
+ * 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.drill.exec.rpc;
+
+import io.netty.buffer.ByteBuf;
+
+import com.google.common.util.concurrent.SettableFuture;
+import com.google.protobuf.MessageLite;
+
+public abstract class FutureBitCommand<T extends MessageLite, C extends RemoteConnection> implements RpcCommand<T,C> {
+  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FutureBitCommand.class);
+
+  protected final SettableFuture<T> settableFuture;
+  private final RpcCheckedFuture<T> parentFuture;
+
+  public FutureBitCommand() {
+    this.settableFuture = SettableFuture.create();
+    this.parentFuture = new RpcCheckedFuture<T>(settableFuture);
+  }
+
+  public abstract void doRpcCall(RpcOutcomeListener<T> outcomeListener, C connection);
+
+  @Override
+  public void connectionAvailable(C connection) {
+    
+    doRpcCall(new DeferredRpcOutcome(), connection);
+  }
+
+  @Override
+  public void connectionSucceeded(C connection) {
+    connectionAvailable(connection);
+  }
+
+  private class DeferredRpcOutcome implements RpcOutcomeListener<T> {
+
+    @Override
+    public void failed(RpcException ex) {
+      settableFuture.setException(ex);
+    }
+
+    @Override
+    public void success(T value, ByteBuf buf) {
+      settableFuture.set(value);
+    }
+
+  }
+
+  public DrillRpcFuture<T> getFuture() {
+    return parentFuture;
+  }
+
+  @Override
+  public void connectionFailed(FailureType type, Throwable t) {
+    settableFuture.setException(RpcException.mapException(
+        String.format("Command failed while establishing connection.  Failure type %s.", type), t));
+  }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ListeningCommand.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ListeningCommand.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ListeningCommand.java
new file mode 100644
index 0000000..acb696c
--- /dev/null
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ListeningCommand.java
@@ -0,0 +1,66 @@
+/**
+ * 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.drill.exec.rpc;
+
+import io.netty.buffer.ByteBuf;
+
+import com.google.protobuf.MessageLite;
+
+public abstract class ListeningCommand<T extends MessageLite, C extends RemoteConnection> implements RpcCommand<T, C> {
+  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ListeningCommand.class);
+
+  private final RpcOutcomeListener<T> listener;
+
+  public ListeningCommand(RpcOutcomeListener<T> listener) {
+    this.listener = listener;
+  }
+
+  public abstract void doRpcCall(RpcOutcomeListener<T> outcomeListener, C connection);
+
+  @Override
+  public void connectionAvailable(C connection) {
+    
+    doRpcCall(new DeferredRpcOutcome(), connection);
+  }
+
+  @Override
+  public void connectionSucceeded(C connection) {
+    connectionAvailable(connection);
+  }
+
+  private class DeferredRpcOutcome implements RpcOutcomeListener<T> {
+
+    @Override
+    public void failed(RpcException ex) {
+      listener.failed(ex);
+    }
+
+    @Override
+    public void success(T value, ByteBuf buf) {
+      listener.success(value, buf);
+    }
+
+  }
+
+  @Override
+  public void connectionFailed(FailureType type, Throwable t) {
+    listener.failed(RpcException.mapException(
+        String.format("Command failed while establishing connection.  Failure type %s.", type), t));
+  }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ProtobufLengthDecoder.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ProtobufLengthDecoder.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ProtobufLengthDecoder.java
new file mode 100644
index 0000000..6fef7e5
--- /dev/null
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ProtobufLengthDecoder.java
@@ -0,0 +1,107 @@
+/**
+ * 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.drill.exec.rpc;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.ByteToMessageDecoder;
+import io.netty.handler.codec.CorruptedFrameException;
+
+import java.util.List;
+
+import org.apache.drill.exec.memory.BufferAllocator;
+
+import com.google.protobuf.CodedInputStream;
+
+/**
+ * Modified version of ProtobufVarint32FrameDecoder that avoids bytebuf copy.
+ */
+public class ProtobufLengthDecoder extends ByteToMessageDecoder {
+  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ProtobufLengthDecoder.class);
+
+  
+  private BufferAllocator allocator;
+  
+  public ProtobufLengthDecoder(BufferAllocator allocator) {
+    super();
+    this.allocator = allocator;
+  }
+
+
+  @Override
+  protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
+    if (!ctx.channel().isOpen()) {
+      if (in.readableBytes() > 0)
+        logger.info("Channel is closed, discarding remaining {} byte(s) in buffer.", in.readableBytes());
+      in.skipBytes(in.readableBytes());
+      return;
+    }
+
+    in.markReaderIndex();
+    final byte[] buf = new byte[5];
+    for (int i = 0; i < buf.length; i++) {
+      if (!in.isReadable()) {
+        in.resetReaderIndex();
+        return;
+      }
+
+      buf[i] = in.readByte();
+      if (buf[i] >= 0) {
+
+        int length = CodedInputStream.newInstance(buf, 0, i + 1).readRawVarint32();
+
+        if (length < 0) {
+          throw new CorruptedFrameException("negative length: " + length);
+        }
+        if (length == 0) {
+          throw new CorruptedFrameException("Received a message of length 0.");
+        }
+
+        if (in.readableBytes() < length) {
+          in.resetReaderIndex();
+          return;
+        } else {
+          // need to make buffer copy, otherwise netty will try to refill this buffer if we move the readerIndex forward...
+          // TODO: Can we avoid this copy?
+          ByteBuf outBuf = allocator.buffer(length);
+          if(outBuf == null){
+            logger.debug("Failure allocating buffer on incoming stream due to memory limits.");
+            in.resetReaderIndex();
+            return;
+          }
+          outBuf.writeBytes(in, in.readerIndex(), length);
+          
+          in.skipBytes(length);
+          
+          if (RpcConstants.EXTRA_DEBUGGING)
+            logger.debug(String.format(
+                "ReaderIndex is %d after length header of %d bytes and frame body of length %d bytes.",
+                in.readerIndex(), i + 1, length));
+          
+          out.add(outBuf);
+          return;
+        }
+      }
+    }
+
+    // Couldn't find the byte whose MSB is off.
+    throw new CorruptedFrameException("length wider than 32-bit");
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java
new file mode 100644
index 0000000..4cd4155
--- /dev/null
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ReconnectingConnection.java
@@ -0,0 +1,242 @@
+/**
+ * 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.drill.exec.rpc;
+
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.GenericFutureListener;
+
+import java.io.Closeable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.AbstractFuture;
+import com.google.protobuf.MessageLite;
+
+/**
+ * Manager all connections between two particular bits.
+ */
+public abstract class ReconnectingConnection<CONNECTION_TYPE extends RemoteConnection, OUTBOUND_HANDSHAKE extends MessageLite>
+    implements Closeable {
+  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ReconnectingConnection.class);
+
+  private final AtomicReference<CONNECTION_TYPE> connectionHolder = new AtomicReference<CONNECTION_TYPE>();
+  private final String host;
+  private final int port;
+  private final OUTBOUND_HANDSHAKE handshake;
+
+  public ReconnectingConnection(OUTBOUND_HANDSHAKE handshake, String host, int port) {
+    Preconditions.checkNotNull(host);
+    Preconditions.checkArgument(port > 0);
+    this.host = host;
+    this.port = port;
+    this.handshake = handshake;
+  }
+
+  protected abstract BasicClient<?, CONNECTION_TYPE, OUTBOUND_HANDSHAKE, ?> getNewClient();
+
+  public <R extends MessageLite, C extends RpcCommand<R, CONNECTION_TYPE>> void runCommand(C cmd) {
+//    if(logger.isDebugEnabled()) logger.debug(String.format("Running command %s sending to host %s:%d", cmd, host, port));
+    CONNECTION_TYPE connection = connectionHolder.get();
+    if (connection != null) {
+      if (connection.isActive()) {
+        cmd.connectionAvailable(connection);
+//        logger.debug("Connection available and active, command run inline.");
+        return;
+      } else {
+        // remove the old connection. (don't worry if we fail since someone else should have done it.
+        connectionHolder.compareAndSet(connection, null);
+      }
+    }
+
+    /**
+     * We've arrived here without a connection, let's make sure only one of us makes a connection. (fyi, another
+     * endpoint could create a reverse connection
+     **/
+    synchronized (this) {
+      connection = connectionHolder.get();
+      if (connection != null) {
+        cmd.connectionAvailable(connection);
+        
+      } else {
+//        logger.debug("No connection active, opening client connection.");
+        BasicClient<?, CONNECTION_TYPE, OUTBOUND_HANDSHAKE, ?> client = getNewClient();
+        ConnectionListeningFuture<R, C> future = new ConnectionListeningFuture<R, C>(cmd);
+        client.connectAsClient(future, handshake, host, port);
+        future.waitAndRun();
+//        logger.debug("Connection available and active, command now being run inline.");
+      }
+      return;
+
+    }
+  }
+
+  public class ConnectionListeningFuture<R extends MessageLite, C extends RpcCommand<R, CONNECTION_TYPE>> extends
+      AbstractFuture<CONNECTION_TYPE> implements RpcConnectionHandler<CONNECTION_TYPE> {
+
+    private C cmd;
+
+    public ConnectionListeningFuture(C cmd) {
+      super();
+      this.cmd = cmd;
+    }
+
+    /**
+     * Called by
+     */
+    public void waitAndRun() {
+      try {
+//        logger.debug("Waiting for connection.");
+        CONNECTION_TYPE connection = this.get();
+
+        if (connection == null) {
+//          logger.debug("Connection failed.");
+          return;
+        } else {
+//          logger.debug("Connection received. {}", connection);
+          cmd.connectionSucceeded(connection);
+//          logger.debug("Finished connection succeeded activity.");
+        }
+      } catch (InterruptedException e) {
+        cmd.connectionFailed(FailureType.CONNECTION, e);
+      } catch (ExecutionException e) {
+        throw new IllegalStateException();
+      }
+
+    }
+
+    @Override
+    public void connectionFailed(org.apache.drill.exec.rpc.RpcConnectionHandler.FailureType type, Throwable t) {
+      set(null);
+      cmd.connectionFailed(type, t);
+    }
+
+    @Override
+    public void connectionSucceeded(CONNECTION_TYPE incoming) {
+      CONNECTION_TYPE connection = connectionHolder.get();
+      while (true) {
+        boolean setted = connectionHolder.compareAndSet(null, incoming);
+        if (setted) {
+          connection = incoming;
+          break;
+        }
+        connection = connectionHolder.get();
+        if (connection != null) break;
+      }
+
+      if (connection != incoming) {
+        // close the incoming because another channel was created in the mean time (unless this is a self connection).
+        logger.debug("Closing incoming connection because a connection was already set.");
+        incoming.getChannel().close();
+      }
+      set(connection);
+      
+    }
+
+  }
+
+  /** Factory for close handlers **/
+  public class CloseHandlerCreator {
+    public GenericFutureListener<ChannelFuture> getHandler(CONNECTION_TYPE connection,
+        GenericFutureListener<ChannelFuture> parent) {
+      return new CloseHandler(connection, parent);
+    }
+  }
+
+  /**
+   * Listens for connection closes and clears connection holder.
+   */
+  protected class CloseHandler implements GenericFutureListener<ChannelFuture> {
+    private CONNECTION_TYPE connection;
+    private GenericFutureListener<ChannelFuture> parent;
+
+    public CloseHandler(CONNECTION_TYPE connection, GenericFutureListener<ChannelFuture> parent) {
+      super();
+      this.connection = connection;
+      this.parent = parent;
+    }
+
+    @Override
+    public void operationComplete(ChannelFuture future) throws Exception {
+      connectionHolder.compareAndSet(connection, null);
+      parent.operationComplete(future);
+    }
+
+  }
+
+  public CloseHandlerCreator getCloseHandlerCreator() {
+    return new CloseHandlerCreator();
+  }
+
+  public void addExternalConnection(CONNECTION_TYPE connection) {
+    // if the connection holder is not set, set it to this incoming connection. We'll simply ignore if already set.
+    this.connectionHolder.compareAndSet(null, connection);
+  }
+
+  @Override
+  public void close() {
+    CONNECTION_TYPE c = connectionHolder.getAndSet(null);
+    if (c != null) {
+      c.getChannel().close();
+    }
+  }
+
+  /**
+   * Decorate a connection creation so that we capture a success and keep it available for future requests. If we have
+   * raced and another is already available... we return that one and close things down on this one.
+   */
+  private class ConnectionListeningDecorator implements RpcConnectionHandler<CONNECTION_TYPE> {
+
+    private final RpcConnectionHandler<CONNECTION_TYPE> delegate;
+
+    public ConnectionListeningDecorator(RpcConnectionHandler<CONNECTION_TYPE> delegate) {
+      this.delegate = delegate;
+    }
+
+    @Override
+    public void connectionSucceeded(CONNECTION_TYPE incoming) {
+      CONNECTION_TYPE connection = connectionHolder.get();
+      while (true) {
+        boolean setted = connectionHolder.compareAndSet(null, incoming);
+        if (setted) {
+          connection = incoming;
+          break;
+        }
+        connection = connectionHolder.get();
+        if (connection != null)
+          break;
+      }
+
+      if (connection == incoming) {
+        delegate.connectionSucceeded(connection);
+      } else {
+        // close the incoming because another channel was created in the mean time (unless this is a self connection).
+        logger.debug("Closing incoming connection because a connection was already set.");
+        incoming.getChannel().close();
+        delegate.connectionSucceeded(connection);
+      }
+    }
+
+    @Override
+    public void connectionFailed(org.apache.drill.exec.rpc.RpcConnectionHandler.FailureType type, Throwable t) {
+      delegate.connectionFailed(type, t);
+    }
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/RemoteConnection.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/RemoteConnection.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/RemoteConnection.java
index 657b350..0eaade8 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/RemoteConnection.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/RemoteConnection.java
@@ -18,48 +18,88 @@
 package org.apache.drill.exec.rpc;
 
 import io.netty.channel.Channel;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
 
-import java.util.concurrent.Semaphore;
+import org.apache.drill.exec.memory.BufferAllocator;
 
-public class RemoteConnection{
+public abstract class RemoteConnection{
   static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(RemoteConnection.class);
   private final Channel channel;
+  private final WriteManager writeManager;
   
-  final Semaphore throttle;
-  
-  public void acquirePermit() throws InterruptedException{
-    if(RpcConstants.EXTRA_DEBUGGING) logger.debug("Acquiring send permit.");
-    this.throttle.acquire();
-    if(RpcConstants.EXTRA_DEBUGGING) logger.debug("Send permit acquired.");
-  }
-  
-  public void releasePermit() {
-    throttle.release();
+  public boolean inEventLoop(){
+    return channel.eventLoop().inEventLoop();
   }
   
-  public RemoteConnection(Channel channel, int maxOutstanding) {
+  public RemoteConnection(Channel channel) {
     super();
     this.channel = channel;
-    this.throttle  = new Semaphore(maxOutstanding);
+    this.writeManager = new WriteManager();
+    channel.pipeline().addLast(new BackPressureHandler());
   }
   
-  public RemoteConnection(Channel channel) {
-    this(channel, 100);
-  }
-
+  public abstract BufferAllocator getAllocator();
 
   public final Channel getChannel() {
     return channel;
   }
 
+  public boolean blockOnNotWritable(RpcOutcomeListener<?> listener){
+    try{
+      writeManager.waitForWritable();
+      return true;
+    }catch(InterruptedException e){
+      listener.failed(new RpcException(e));
+      return false;
+    }
+  }
 
-  public ConnectionThrottle getConnectionThrottle(){
-    // can't be implemented until we switch to per query sockets.
-    return null;
+  public void setAutoRead(boolean enableAutoRead){
+    channel.config().setAutoRead(enableAutoRead); 
   }
   
-  public interface ConnectionThrottle{
-    public void disableReceiving();
-    public void enableReceiving();
+  public boolean isActive(){
+    return channel.isActive();
+  }
+  
+  /**
+   * The write manager is responsible for controlling whether or not a write can be sent.  It controls whether or not to block a sender if we have tcp backpressure on the receive side.
+   */
+  private static class WriteManager{
+    private final ResettableBarrier barrier = new ResettableBarrier();
+    
+    public WriteManager(){
+      barrier.openBarrier();
+    }
+    
+    public void waitForWritable() throws InterruptedException{
+      barrier.await();
+    }
+    
+    public void setWritable(boolean isWritable){
+//      logger.debug("Set writable: {}", isWritable);
+      if(isWritable){
+        barrier.openBarrier();  
+      }else{
+        barrier.closeBarrier();
+      }
+      
+    }
+    
+  }
+
+  
+  
+  private class BackPressureHandler extends ChannelInboundHandlerAdapter{
+
+    @Override
+    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
+//      logger.debug("Channel writability changed.", ctx.channel().isWritable());
+      writeManager.setWritable(ctx.channel().isWritable());
+      ctx.fireChannelWritabilityChanged();
+    }
+    
+    
   }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ResettableBarrier.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ResettableBarrier.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ResettableBarrier.java
new file mode 100644
index 0000000..a19b753
--- /dev/null
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/ResettableBarrier.java
@@ -0,0 +1,85 @@
+/**
+ * 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.drill.exec.rpc;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.AbstractQueuedSynchronizer;
+
+/**
+ * Modified implementation of countdown latch that allows a barrier to be unilaterally opened and closed.  All others simply wait when it is closed.  Is initialized in a closed state.
+ */
+public class ResettableBarrier {
+  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ResettableBarrier.class);
+
+  private final InternalSynchronizer sync = new InternalSynchronizer();
+
+  public ResettableBarrier() {
+  }
+
+  private static final class InternalSynchronizer extends AbstractQueuedSynchronizer {
+
+    private InternalSynchronizer() {
+      setState(1);
+    }
+
+    protected int tryAcquireShared(int acquires) {
+      assert acquires == 1;
+      return (getState() == 0) ? 1 : -1;
+    }
+
+    protected boolean tryReleaseShared(int releases) {
+      assert releases == 1;
+
+      while(true) {
+        int c = getState();
+        if (c == 0)
+          return false;
+        int nextc = c - 1;
+        if (compareAndSetState(c, nextc)){
+          return nextc == 0;
+        }
+      }
+    }
+
+    protected void reset() {
+      setState(1);
+    }
+
+  }
+
+  public void await() throws InterruptedException {
+//    logger.debug("awaiting barrier interruptibly.");
+    sync.acquireSharedInterruptibly(1);
+  }
+
+  public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
+//    logger.debug("awaiting barrier with timeout {}.", timeout);
+    return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
+  }
+
+  public void openBarrier() {
+//    logger.debug("opening barrier.");
+    sync.releaseShared(1);
+  }
+  
+  public void closeBarrier(){
+//    logger.debug("closing barrier.");
+    sync.reset();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/Response.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/Response.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/Response.java
index b65e756..12b73a8 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/Response.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/Response.java
@@ -17,8 +17,6 @@
  */
 package org.apache.drill.exec.rpc;
 
-import org.apache.drill.exec.proto.ExecProtos.RpcType;
-
 import io.netty.buffer.ByteBuf;
 
 import com.google.protobuf.Internal.EnumLite;

http://git-wip-us.apache.org/repos/asf/incubator-drill/blob/a0eabf63/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/RpcBus.java
----------------------------------------------------------------------
diff --git a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/RpcBus.java b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/RpcBus.java
index 3f31431..1be5392 100644
--- a/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/RpcBus.java
+++ b/exec/java-exec/src/main/java/org/apache/drill/exec/rpc/RpcBus.java
@@ -21,6 +21,7 @@ import io.netty.buffer.ByteBuf;
 import io.netty.buffer.ByteBufInputStream;
 import io.netty.channel.Channel;
 import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelFutureListener;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.handler.codec.MessageToMessageDecoder;
 import io.netty.util.concurrent.GenericFutureListener;
@@ -61,7 +62,7 @@ public abstract class RpcBus<T extends EnumLite, C extends RemoteConnection> imp
     this.rpcConfig = rpcConfig;
   }
 
-  public <SEND extends MessageLite, RECEIVE extends MessageLite> DrillRpcFuture<RECEIVE> send(C connection, T rpcType,
+  <SEND extends MessageLite, RECEIVE extends MessageLite> DrillRpcFuture<RECEIVE> send(C connection, T rpcType,
       SEND protobufBody, Class<RECEIVE> clazz, ByteBuf... dataBodies) {
     DrillRpcFutureImpl<RECEIVE> rpcFuture = new DrillRpcFutureImpl<RECEIVE>();
     this.send(rpcFuture, connection, rpcType, protobufBody, clazz, dataBodies);
@@ -70,27 +71,35 @@ public abstract class RpcBus<T extends EnumLite, C extends RemoteConnection> imp
   
   public <SEND extends MessageLite, RECEIVE extends MessageLite> void send(RpcOutcomeListener<RECEIVE> listener, C connection, T rpcType,
       SEND protobufBody, Class<RECEIVE> clazz, ByteBuf... dataBodies) {
+    send(listener, connection, rpcType, protobufBody, clazz, false, dataBodies);
+  }
   
-    
-
-
-    assert !Arrays.asList(dataBodies).contains(null);
-    assert rpcConfig.checkSend(rpcType, protobufBody.getClass(), clazz);
+  public <SEND extends MessageLite, RECEIVE extends MessageLite> void send(RpcOutcomeListener<RECEIVE> listener, C connection, T rpcType,
+      SEND protobufBody, Class<RECEIVE> clazz, boolean allowInEventLoop, ByteBuf... dataBodies) {
+  
+    if(!allowInEventLoop){
+      if(connection.inEventLoop()) throw new IllegalStateException("You attempted to send while inside the rpc event thread.  This isn't allowed because sending will block if the channel is backed up.");
+      
+      if(!connection.blockOnNotWritable(listener)) return;
+    }
 
     ByteBuf pBuffer = null;
     boolean completed = false;
 
     try {
+
+      assert !Arrays.asList(dataBodies).contains(null);
+      assert rpcConfig.checkSend(rpcType, protobufBody.getClass(), clazz);
+
       Preconditions.checkNotNull(protobufBody);
       ChannelListenerWithCoordinationId futureListener = queue.get(listener, clazz, connection);
       OutboundRpcMessage m = new OutboundRpcMessage(RpcMode.REQUEST, rpcType, futureListener.getCoordinationId(), protobufBody, dataBodies);
-      connection.acquirePermit();
       ChannelFuture channelFuture = connection.getChannel().writeAndFlush(m);
       channelFuture.addListener(futureListener);
+      channelFuture.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
       completed = true;
-    } catch (InterruptedException e) {
-      completed = true;
-      listener.failed(new RpcException("Interrupted while attempting to acquire outbound queue.", e));
+    } catch(Exception | AssertionError e){
+      listener.failed(new RpcException("Failure sending message.", e));
     } finally {
       if (!completed) {
         if (pBuffer != null) pBuffer.release();
@@ -167,6 +176,7 @@ public abstract class RpcBus<T extends EnumLite, C extends RemoteConnection> imp
       case RESPONSE_FAILURE:
         RpcFailure failure = RpcFailure.parseFrom(new ByteBufInputStream(msg.pBody, msg.pBody.readableBytes()));
         queue.updateFailedFuture(msg.coordinationId, failure);
+        msg.release();
         if (RpcConstants.EXTRA_DEBUGGING)
           logger.debug("Updated rpc future with coordinationId {} with failure ", msg.coordinationId, failure);
         break;