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

dkuzmenko pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hive.git


The following commit(s) were added to refs/heads/master by this push:
     new e6e2f41e6f4 HIVE-22977: Merge delta files instead of running a query 
in major/minor compaction (Sourabh Badhya, reviewed by Denys Kuzmenko, Laszlo 
Vegh)
e6e2f41e6f4 is described below

commit e6e2f41e6f4c422281eb5803828ec7f544a01a9a
Author: Sourabh Badhya <[email protected]>
AuthorDate: Wed Jan 25 13:43:41 2023 +0530

    HIVE-22977: Merge delta files instead of running a query in major/minor 
compaction (Sourabh Badhya, reviewed by Denys Kuzmenko, Laszlo Vegh)
    
    Closes #3801
---
 .../java/org/apache/hadoop/hive/conf/HiveConf.java |   3 +
 .../ql/txn/compactor/CompactionPoolOnTezTest.java  |  14 +-
 .../hive/ql/txn/compactor/CompactorOnTezTest.java  |  29 +-
 .../ql/txn/compactor/TestCrudCompactorOnTez.java   | 512 ++++++++++++++++++++-
 .../ql/txn/compactor/TestMmCompactorOnTez.java     |  32 +-
 .../hadoop/hive/ql/txn/compactor/Compactor.java    |  18 +-
 .../hive/ql/txn/compactor/CompactorContext.java    |  78 ++++
 .../hive/ql/txn/compactor/CompactorFactory.java    |  22 +-
 .../hive/ql/txn/compactor/CompactorPipeline.java   |  69 +++
 .../hadoop/hive/ql/txn/compactor/MRCompactor.java  |  20 +-
 .../hive/ql/txn/compactor/MajorQueryCompactor.java |  14 +-
 .../hive/ql/txn/compactor/MergeCompactor.java      | 212 +++++++++
 .../hive/ql/txn/compactor/MinorQueryCompactor.java |  14 +-
 .../ql/txn/compactor/MmMajorQueryCompactor.java    |  16 +-
 .../ql/txn/compactor/MmMinorQueryCompactor.java    |  14 +-
 .../hive/ql/txn/compactor/OrcFileMerger.java       | 114 +++++
 .../hive/ql/txn/compactor/QueryCompactor.java      |   4 -
 .../ql/txn/compactor/RebalanceQueryCompactor.java  |  18 +-
 .../hadoop/hive/ql/txn/compactor/Worker.java       |   8 +-
 .../apache/hadoop/hive/ql/TestTxnCommands2.java    |   3 +-
 .../apache/hadoop/hive/ql/TestTxnCommands3.java    |   9 +-
 .../hadoop/hive/ql/txn/compactor/TestWorker.java   |   2 +-
 22 files changed, 1096 insertions(+), 129 deletions(-)

diff --git a/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java 
b/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java
index 463f2c8ad18..e2aa4cf845d 100644
--- a/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java
+++ b/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java
@@ -3277,6 +3277,9 @@ public class HiveConf extends Configuration {
         "If the number of small delta directories under a table/partition 
passes this threshold, a " +
             "warning message will be logged."),
 
+    HIVE_MERGE_COMPACTION_ENABLED("hive.compaction.merge.enabled", false,
+            "Enables merge-based compaction which is a compaction optimization 
when few ORC delta files are present"),
+
     /**
      * @deprecated use MetastoreConf.METASTORE_DELTAMETRICS_LOGGER_FREQUENCY
      */
diff --git 
a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/CompactionPoolOnTezTest.java
 
b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/CompactionPoolOnTezTest.java
index dd60c5eecca..f7e6985cbc7 100644
--- 
a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/CompactionPoolOnTezTest.java
+++ 
b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/CompactionPoolOnTezTest.java
@@ -70,7 +70,7 @@ public class CompactionPoolOnTezTest extends 
CompactorOnTezTest {
     Map<String, String> properties = new HashMap<>();
     properties.put("hive.compactor.worker.pool", "pool1");
     provider.createFullAcidTable(null, DEFAULT_TABLE_NAME, false, false, 
properties);
-    provider.insertTestData(DEFAULT_TABLE_NAME);
+    provider.insertTestData(DEFAULT_TABLE_NAME, false);
 
     executeStatementOnDriver("ALTER TABLE " + DEFAULT_TABLE_NAME + " COMPACT 
'major' POOL 'pool2'", driver);
 
@@ -93,7 +93,7 @@ public class CompactionPoolOnTezTest extends 
CompactorOnTezTest {
     Map<String, String> properties = new HashMap<>();
     properties.put("hive.compactor.worker.pool", "pool1");
     provider.createFullAcidTable(null, DEFAULT_TABLE_NAME, false, false, 
properties);
-    provider.insertTestData(DEFAULT_TABLE_NAME);
+    provider.insertTestData(DEFAULT_TABLE_NAME, false);
 
     TxnCommandsBaseForTests.runInitiator(conf);
 
@@ -103,7 +103,7 @@ public class CompactionPoolOnTezTest extends 
CompactorOnTezTest {
   @Test
   public void testInitiatorHandlesEmptyPoolName() throws Exception {
     provider.createFullAcidTable(null, DEFAULT_TABLE_NAME, false, false);
-    provider.insertTestData(DEFAULT_TABLE_NAME);
+    provider.insertTestData(DEFAULT_TABLE_NAME, false);
 
     TxnCommandsBaseForTests.runInitiator(conf);
 
@@ -128,9 +128,9 @@ public class CompactionPoolOnTezTest extends 
CompactorOnTezTest {
     Map<String, String> properties = new HashMap<>();
     properties.put("hive.compactor.worker.pool", "pool1");
     provider.createFullAcidTable(null, DEFAULT_TABLE_NAME, false, false, 
properties);
-    provider.insertTestData(DEFAULT_TABLE_NAME);
+    provider.insertTestData(DEFAULT_TABLE_NAME, false);
     provider.createFullAcidTable(null, "table2", false, false);
-    provider.insertTestData("table2");
+    provider.insertTestData("table2", false);
 
     TxnCommandsBaseForTests.runInitiator(conf);
 
@@ -152,10 +152,10 @@ public class CompactionPoolOnTezTest extends 
CompactorOnTezTest {
     Map<String, String> properties = new HashMap<>();
     properties.put("hive.compactor.worker.pool", "pool1");
     provider.createFullAcidTable(null, DEFAULT_TABLE_NAME, false, false, 
properties);
-    provider.insertTestData(DEFAULT_TABLE_NAME);
+    provider.insertTestData(DEFAULT_TABLE_NAME, false);
     properties.put("hive.compactor.worker.pool", "pool2");
     provider.createFullAcidTable(null, "table2", false, false, properties);
-    provider.insertTestData("table2");
+    provider.insertTestData("table2", false);
 
     TxnCommandsBaseForTests.runInitiator(conf);
 
diff --git 
a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorOnTezTest.java
 
b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorOnTezTest.java
index 796372571be..37f06371ba4 100644
--- 
a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorOnTezTest.java
+++ 
b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorOnTezTest.java
@@ -297,7 +297,7 @@ public abstract class CompactorOnTezTest {
     /**
      * 3 txns.
      */
-    protected void insertMmTestDataPartitioned(String tblName) throws 
Exception {
+    protected void insertOnlyTestDataPartitioned(String tblName) throws 
Exception {
       executeStatementOnDriver("insert into " + tblName
           + " values('1',2, 'today'),('1',3, 'today'),('1',4, 
'yesterday'),('2',2, 'tomorrow'),"
           + "('2',3, 'yesterday'),('2',4, 'today')", driver);
@@ -308,10 +308,27 @@ public abstract class CompactorOnTezTest {
           + "('5',4, 'today'),('6',2, 'today'),('6',3, 'today'),('6',4, 
'today')", driver);
     }
 
+    protected void insertTestData(String tblName, boolean isPartitioned) 
throws Exception {
+      if (isPartitioned) {
+        insertTestDataPartitioned(tblName);
+      } else {
+        insertTestData(tblName);
+      }
+    }
+
+
+    protected void insertOnlyTestData(String tblName, boolean isPartitioned) 
throws Exception {
+      if (isPartitioned) {
+        insertOnlyTestDataPartitioned(tblName);
+      } else {
+        insertOnlyTestData(tblName);
+      }
+    }
+
     /**
      * 5 txns.
      */
-    void insertTestData(String tblName) throws Exception {
+    private void insertTestData(String tblName) throws Exception {
       insertTestData(null, tblName);
     }
 
@@ -406,14 +423,14 @@ public abstract class CompactorOnTezTest {
     /**
      * 5 txns.
      */
-    void insertMmTestData(String tblName) throws Exception {
-      insertMmTestData(null, tblName);
+    void insertOnlyTestData(String tblName) throws Exception {
+      insertOnlyTestData(null, tblName);
     }
 
     /**
      * 3 txns.
      */
-    void insertMmTestData(String dbName, String tblName) throws Exception {
+    void insertOnlyTestData(String dbName, String tblName) throws Exception {
       if (dbName != null) {
         tblName = dbName + "." + tblName;
       }
@@ -440,7 +457,7 @@ public abstract class CompactorOnTezTest {
     /**
      * i txns.
      */
-    protected void insertMmTestData(String tblName, int iterations) throws 
Exception {
+    protected void insertOnlyTestData(String tblName, int iterations) throws 
Exception {
       for (int i = 0; i < iterations; i++) {
         executeStatementOnDriver("insert into " + tblName + " values('" + i + 
"'," + i + ")", driver);
       }
diff --git 
a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestCrudCompactorOnTez.java
 
b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestCrudCompactorOnTez.java
index 2ab2e28adab..c4d5fde2e12 100644
--- 
a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestCrudCompactorOnTez.java
+++ 
b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestCrudCompactorOnTez.java
@@ -18,6 +18,7 @@
 package org.apache.hadoop.hive.ql.txn.compactor;
 
 import java.io.IOException;
+import java.lang.reflect.Field;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -65,6 +66,11 @@ import org.apache.hadoop.hive.ql.io.AcidUtils;
 import org.apache.hadoop.hive.ql.io.BucketCodec;
 import org.apache.hadoop.hive.ql.metadata.Hive;
 import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.apache.hadoop.hive.ql.txn.compactor.Compactor;
+import org.apache.hadoop.hive.ql.txn.compactor.CompactorContext;
+import org.apache.hadoop.hive.ql.txn.compactor.CompactorFactory;
+import org.apache.hadoop.hive.ql.txn.compactor.CompactorPipeline;
+import org.apache.hadoop.hive.ql.txn.compactor.Worker;
 import org.apache.hive.streaming.HiveStreamingConnection;
 import org.apache.hive.streaming.StreamingConnection;
 import org.apache.hive.streaming.StrictDelimitedInputWriter;
@@ -107,7 +113,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
 
     TestDataProvider testDataProvider = new TestDataProvider();
     testDataProvider.createFullAcidTable(stageTableName, true, false);
-    testDataProvider.insertTestDataPartitioned(stageTableName);
+    testDataProvider.insertTestData(stageTableName, true);
 
     executeStatementOnDriver("drop table if exists " + tableName, driver);
     executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) 
" +
@@ -356,7 +362,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
 
     TestDataProvider testDataProvider = new TestDataProvider();
     testDataProvider.createFullAcidTable(stageTableName, true, false);
-    testDataProvider.insertTestDataPartitioned(stageTableName);
+    testDataProvider.insertTestData(stageTableName, true);
 
     executeStatementOnDriver("drop table if exists " + tableName, driver);
     executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) 
" +
@@ -520,12 +526,17 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 
'rebalance'", driver);
 
     CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
-    AtomicReference<QueryCompactor> reference = new AtomicReference<>();
+    AtomicReference<Compactor> reference = new AtomicReference<>();
     doAnswer(invocation -> {
-      QueryCompactor result = (QueryCompactor)invocation.callRealMethod();
-      reference.set(result);
+      CompactorPipeline result = 
(CompactorPipeline)invocation.callRealMethod();
+      // Use reflection to fetch inner compactors
+      CompactorPipeline compactorPipeline = (CompactorPipeline) result;
+      Field field = compactorPipeline.getClass().getDeclaredField("compactor");
+      field.setAccessible(true);
+      Compactor compactor = (Compactor) field.get(compactorPipeline);
+      reference.set(compactor);
       return result;
-    }).when(factory).getCompactor(any(), any(), any(), any());
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
 
 
     Worker worker = new Worker(factory);
@@ -847,7 +858,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     String dbTableName = dbName + "." + tblName;
     TestDataProvider testDataProvider = new TestDataProvider();
     testDataProvider.createFullAcidTable(tblName, false, false);
-    testDataProvider.insertTestData(tblName);
+    testDataProvider.insertTestData(tblName, false);
     // Find the location of the table
     IMetaStoreClient msClient = new HiveMetaStoreClient(conf);
     Table table = msClient.getTable(dbName, tblName);
@@ -925,7 +936,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     additionalTblProperties.put("orc.bloom.filter.columns", "b");
     additionalTblProperties.put("orc.bloom.filter.fpp", "0.02");
     testDataProvider.createFullAcidTable(dbName, tblName, false, false, 
additionalTblProperties);
-    testDataProvider.insertTestData(tblName);
+    testDataProvider.insertTestData(tblName, false);
     // Find the location of the table
     IMetaStoreClient msClient = new HiveMetaStoreClient(conf);
     Table table = msClient.getTable(dbName, tblName);
@@ -1049,7 +1060,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     String tblName = "testMajorCompaction";
     TestDataProvider testDataProvider = new TestDataProvider();
     testDataProvider.createFullAcidTable(tblName, true, false);
-    testDataProvider.insertTestDataPartitioned(tblName);
+    testDataProvider.insertTestData(tblName, true);
     // Find the location of the table
     IMetaStoreClient msClient = new HiveMetaStoreClient(conf);
     Table table = msClient.getTable(dbName, tblName);
@@ -1137,7 +1148,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    dataProvider.insertTestDataPartitioned(tableName);
+    dataProvider.insertTestData(tableName, true);
     // Get all data before compaction is run
     List<String> expectedData = dataProvider.getAllData(tableName);
     // Verify deltas
@@ -1242,7 +1253,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     Table table = msClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    dataProvider.insertTestData(tableName);
+    dataProvider.insertTestData(tableName, false);
     // Get all data before compaction is run
     List<String> expectedData = dataProvider.getAllData(tableName);
     // Verify deltas
@@ -1538,7 +1549,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    dataProvider.insertTestData(tableName);
+    dataProvider.insertTestData(tableName, false);
     // Get all data before compaction is run
     List<String> expectedData = dataProvider.getAllData(tableName);
     // Verify deltas
@@ -1615,7 +1626,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    dataProvider.insertTestDataPartitioned(tableName);
+    dataProvider.insertTestData(tableName, true);
     // Get all data before compaction is run
     List<String> expectedData = dataProvider.getAllData(tableName);
     // Verify deltas
@@ -1699,7 +1710,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    dataProvider.insertTestDataPartitioned(tableName);
+    dataProvider.insertTestData(tableName, true);
     // Get all data before compaction is run
     List<String> expectedData = dataProvider.getAllData(tableName);
     // Verify deltas
@@ -1841,7 +1852,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    dataProvider.insertTestData(tableName);
+    dataProvider.insertTestData(tableName, false);
     // Run a compaction
     CompactorTestUtil.runCompaction(conf, dbName, tableName, 
CompactionType.MINOR, true);
     // Clean up resources
@@ -1849,7 +1860,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     // Only 1 compaction should be in the response queue with succeeded state
     verifySuccessfulCompaction(1);
     // Insert test data into test table
-    dataProvider.insertTestData(tableName);
+    dataProvider.insertTestData(tableName, false);
     // Run a compaction
     CompactorTestUtil.runCompaction(conf, dbName, tableName, 
CompactionType.MINOR, true);
     // Clean up resources
@@ -1857,7 +1868,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     // 2 compactions should be in the response queue with succeeded state
     verifySuccessfulCompaction(2);
     // Insert test data into test table
-    dataProvider.insertTestData(tableName);
+    dataProvider.insertTestData(tableName, false);
     // Run a compaction
     CompactorTestUtil.runCompaction(conf, dbName, tableName, 
CompactionType.MINOR, true);
     // Clean up resources
@@ -2021,7 +2032,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    dataProvider.insertTestData(tableName);
+    dataProvider.insertTestData(tableName, false);
     // Get all data before compaction is run
     List<String> expectedData = dataProvider.getAllData(tableName);
     Collections.sort(expectedData);
@@ -2042,7 +2053,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     List<String> actualData = dataProvider.getAllData(tableName);
     Assert.assertEquals(expectedData, actualData);
     // Insert another round of test data
-    dataProvider.insertTestData(tableName);
+    dataProvider.insertTestData(tableName, false);
     expectedData = dataProvider.getAllData(tableName);
     Collections.sort(expectedData);
     // Run a compaction
@@ -2072,7 +2083,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    dataProvider.insertTestData(tableName);
+    dataProvider.insertTestData(tableName, false);
     // Get all data before compaction is run
     List<String> expectedData = dataProvider.getAllData(tableName);
     Collections.sort(expectedData);
@@ -2090,7 +2101,7 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     List<String> actualData = dataProvider.getAllData(tableName);
     Assert.assertEquals(expectedData, actualData);
     // Insert another round of test data
-    dataProvider.insertTestData(tableName);
+    dataProvider.insertTestData(tableName, false);
     expectedData = dataProvider.getAllData(tableName);
     Collections.sort(expectedData);
     // Run a compaction
@@ -2699,8 +2710,8 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     // Setup
     QueryCompactor qc = new QueryCompactor() {
       @Override
-      public void run(HiveConf hiveConf, Table table, Partition partition, 
StorageDescriptor storageDescriptor,
-               ValidWriteIdList writeIds, CompactionInfo compactionInfo, 
AcidDirectory dir) throws IOException {
+      public boolean run(CompactorContext context) throws IOException {
+        return true;
       }
     };
     StorageDescriptor sdMock = mock(StorageDescriptor.class);
@@ -3161,4 +3172,459 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     Assert.assertEquals("The number of rows is differing from the expected", 
"2", parameters.get("numRows"));
     executeStatementOnDriver("drop table if exists " + tblName, driver);
   }
+
+  @Test
+  public void testMajorCompactionWithMergeNotPartitionedWithoutBuckets() 
throws Exception {
+    testCompactionWithMerge(CompactionType.MAJOR, false, false, null, 
Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("base_0000003_v0000007"), true, true, 
false);
+  }
+
+  @Test
+  public void testMajorCompactionWithFallbackNotPartitionedWithoutBuckets() 
throws Exception {
+    testCompactionWithMerge(CompactionType.MAJOR, false, false, null, 
Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("base_0000003_v0000007"), true, true, 
true);
+  }
+
+  @Test
+  public void testMajorCompactionWithMergePartitionedWithoutBuckets() throws 
Exception {
+    testCompactionWithMerge(CompactionType.MAJOR, true, false, "ds=today", 
Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("base_0000003_v0000007"), true, true, 
false);
+  }
+
+  @Test
+  public void testMajorCompactionWithFallbackPartitionedWithoutBuckets() 
throws Exception {
+    testCompactionWithMerge(CompactionType.MAJOR, true, false, "ds=today", 
Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("base_0000003_v0000007"), true, true, 
true);
+  }
+
+  @Test
+  public void testMajorCompactionWithMergeNotPartitionedWithBuckets() throws 
Exception {
+    testCompactionWithMerge(CompactionType.MAJOR, false, true, null, 
Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("base_0000003_v0000007"), true, true, 
false);
+  }
+
+  @Test
+  public void testMajorCompactionWithFallbackNotPartitionedWithBuckets() 
throws Exception {
+    testCompactionWithMerge(CompactionType.MAJOR, false, true, null, 
Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("base_0000003_v0000007"), true, true, 
true);
+  }
+
+  @Test
+  public void testMajorCompactionWithMergePartitionedWithBuckets() throws 
Exception {
+    testCompactionWithMerge(CompactionType.MAJOR, true, true, "ds=today", 
Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("base_0000003_v0000007"), true, true, 
false);
+  }
+
+  @Test
+  public void testMajorCompactionWithFallbackPartitionedWithBuckets() throws 
Exception {
+    testCompactionWithMerge(CompactionType.MAJOR, true, true, "ds=today", 
Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("base_0000003_v0000007"), true, true, 
true);
+  }
+
+  @Test
+  public void testMinorCompactionWithMergeNotPartitionedWithoutBuckets() 
throws Exception {
+    testCompactionWithMerge(CompactionType.MINOR, false, false, null,
+            Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("delta_0000001_0000003_v0000007"), true, 
true, false);
+  }
+
+  @Test
+  public void testMinorCompactionWithFallbackNotPartitionedWithoutBuckets() 
throws Exception {
+    testCompactionWithMerge(CompactionType.MINOR, false, false, null,
+            Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("delta_0000001_0000003_v0000007"), true, 
true, true);
+  }
+
+  @Test
+  public void testMinorCompactionWithMergePartitionedWithoutBuckets() throws 
Exception {
+    testCompactionWithMerge(CompactionType.MINOR, true, false, "ds=today",
+            Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("delta_0000001_0000003_v0000007"), true, 
true, false);
+  }
+
+  @Test
+  public void testMinorCompactionWithFallbackPartitionedWithoutBuckets() 
throws Exception {
+    testCompactionWithMerge(CompactionType.MINOR, true, false, "ds=today",
+            Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("delta_0000001_0000003_v0000007"), true, 
true, true);
+  }
+
+  @Test
+  public void testMinorCompactionWithMergeNotPartitionedWithBuckets() throws 
Exception {
+    testCompactionWithMerge(CompactionType.MINOR, false, true, null,
+            Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("delta_0000001_0000003_v0000007"), true, 
true, false);
+  }
+
+  @Test
+  public void testMinorCompactionWithFallbackNotPartitionedWithBuckets() 
throws Exception {
+    testCompactionWithMerge(CompactionType.MINOR, false, true, null,
+            Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("delta_0000001_0000003_v0000007"), true, 
true, true);
+  }
+
+  @Test
+  public void testMinorCompactionWithMergePartitionedWithBuckets() throws 
Exception {
+    testCompactionWithMerge(CompactionType.MINOR, true, true, "ds=today",
+            Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("delta_0000001_0000003_v0000007"), true, 
true, false);
+  }
+
+  @Test
+  public void testMinorCompactionWithFallbackPartitionedWithBuckets() throws 
Exception {
+    testCompactionWithMerge(CompactionType.MINOR, true, true, "ds=today",
+            Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("delta_0000001_0000003_v0000007"), true, 
true, true);
+  }
+
+  @Test
+  public void testMajorCompactionAfterMinorWithMerge() throws Exception {
+    testCompactionWithMerge(CompactionType.MINOR, true, true, "ds=today",
+            Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("delta_0000001_0000003_v0000007"),true, 
false, false);
+    testCompactionWithMerge(CompactionType.MAJOR, true, true, "ds=today",
+            Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000001_0000003_v0000007", 
"delta_0000004_0000004_0000", "delta_0000005_0000005_0000",
+                    "delta_0000006_0000006_0000"), 
Collections.singletonList("base_0000006_v0000014"), false, true, false);
+  }
+
+  @Test
+  public void testMajorCompactionAfterMinorWithFallback() throws Exception {
+    testCompactionWithMerge(CompactionType.MINOR, true, true, "ds=today",
+            Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("delta_0000001_0000003_v0000007"),true, 
false, true);
+    testCompactionWithMerge(CompactionType.MAJOR, true, true, "ds=today",
+            Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000001_0000003_v0000007", 
"delta_0000004_0000004_0000", "delta_0000005_0000005_0000",
+                    "delta_0000006_0000006_0000"), 
Collections.singletonList("base_0000006_v0000025"), false, true, true);
+  }
+
+  @Test
+  public void testMinorCompactionAfterMajorWithMerge() throws Exception {
+    testCompactionWithMerge(CompactionType.MAJOR, false, false, null,
+            Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("base_0000003_v0000007"), true, false, 
false);
+    testCompactionWithMerge(CompactionType.MINOR, false, false, null,
+            Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000004_0000004_0000", 
"delta_0000005_0000005_0000", "delta_0000006_0000006_0000"),
+            Collections.singletonList("delta_0000001_0000006_v0000014"), 
false, true, false);
+  }
+
+  @Test
+  public void testMinorCompactionAfterMajorWithFallback() throws Exception {
+    testCompactionWithMerge(CompactionType.MAJOR, false, false, null,
+            Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("base_0000003_v0000007"), true, false, 
true);
+    testCompactionWithMerge(CompactionType.MINOR, false, false, null,
+            Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000004_0000004_0000", 
"delta_0000005_0000005_0000", "delta_0000006_0000006_0000"),
+            Collections.singletonList("delta_0000004_0000006_v0000017"), 
false, true, true);
+  }
+
+  @Test
+  public void testMultipleMajorCompactionWithMerge() throws Exception {
+    testCompactionWithMerge(CompactionType.MAJOR, true, true, "ds=today",
+            Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("base_0000003_v0000007"), true, false, 
false);
+    testCompactionWithMerge(CompactionType.MAJOR, true, true, "ds=today",
+            Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000004_0000004_0000", 
"delta_0000005_0000005_0000", "delta_0000006_0000006_0000"),
+            Collections.singletonList("base_0000006_v0000014"), false, true, 
false);
+  }
+
+  @Test
+  public void testMultipleMajorCompactionWithFallback() throws Exception {
+    testCompactionWithMerge(CompactionType.MAJOR, true, true, "ds=today",
+            Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("base_0000003_v0000007"), true, false, 
true);
+    testCompactionWithMerge(CompactionType.MAJOR, true, true, "ds=today",
+            Arrays.asList("bucket_00000", "bucket_00001"),
+            Arrays.asList("delta_0000004_0000004_0000", 
"delta_0000005_0000005_0000", "delta_0000006_0000006_0000"),
+            Collections.singletonList("base_0000006_v0000017"), false, true, 
true);
+  }
+
+  @Test
+  public void testMultipleMinorCompactionWithMerge() throws Exception {
+    testCompactionWithMerge(CompactionType.MINOR, false, false, null,
+            Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("delta_0000001_0000003_v0000007"), true, 
false, false);
+    testCompactionWithMerge(CompactionType.MINOR, false, false, null,
+            Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000001_0000003_v0000007", 
"delta_0000004_0000004_0000", "delta_0000005_0000005_0000",
+                    "delta_0000006_0000006_0000"),
+            Collections.singletonList("delta_0000001_0000006_v0000014"), 
false, true, false);
+  }
+
+  @Test
+  public void testMultipleMinorCompactionWithFallback() throws Exception {
+    testCompactionWithMerge(CompactionType.MINOR, false, false, null,
+            Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000001_0000001_0000", 
"delta_0000002_0000002_0000", "delta_0000003_0000003_0000"),
+            Collections.singletonList("delta_0000001_0000003_v0000007"), true, 
false, true);
+    testCompactionWithMerge(CompactionType.MINOR, false, false, null,
+            Collections.singletonList("bucket_00000"),
+            Arrays.asList("delta_0000001_0000003_v0000007", 
"delta_0000004_0000004_0000", "delta_0000005_0000005_0000",
+                    "delta_0000006_0000006_0000"),
+            Collections.singletonList("delta_0000001_0000006_v0000025"), 
false, true, true);
+  }
+
+  private void testCompactionWithMerge(CompactionType compactionType, boolean 
isPartitioned, boolean isBucketed,
+                                       String partitionName, List<String> 
bucketName, List<String> deltaDirNames, List<String> compactDirNames,
+                                       boolean createTable, boolean dropTable, 
boolean useFallback) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_MERGE_COMPACTION_ENABLED, 
!useFallback);
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    String dbName = "default";
+    String tableName = "testCompaction";
+    // Create test table
+    TestDataProvider dataProvider = new TestDataProvider();
+    if (createTable) {
+      dataProvider.createFullAcidTable(tableName, isPartitioned, isBucketed);
+    }
+    // Find the location of the table
+    IMetaStoreClient metaStoreClient = new HiveMetaStoreClient(conf);
+    Table table = metaStoreClient.getTable(dbName, tableName);
+    FileSystem fs = FileSystem.get(conf);
+    // Insert test data into test table with only insert queries
+    dataProvider.insertOnlyTestData(tableName, isPartitioned);
+    // Get all data before compaction is run
+    List<String> expectedData = dataProvider.getAllData(tableName);
+    // Verify deltas
+    Assert.assertEquals("Delta directories does not match",
+            deltaDirNames, CompactorTestUtil.getBaseOrDeltaNames(fs, 
AcidUtils.deltaFileFilter, table, partitionName));
+    // Verify delete delta
+    Assert.assertTrue(CompactorTestUtil.getBaseOrDeltaNames(fs, 
AcidUtils.deleteEventDeltaDirFilter, table,
+            partitionName).isEmpty());
+    // Run a compaction which uses only merge compactor / query-based 
compaction
+    CompactorFactory compactorFactory = spy(CompactorFactory.getInstance());
+    AtomicReference<Compactor> primary = new AtomicReference<>();
+    AtomicReference<Compactor> secondary = new AtomicReference<>();
+    doAnswer(invocationOnMock -> {
+      Object result = invocationOnMock.callRealMethod();
+      Assert.assertTrue(result instanceof CompactorPipeline);
+      // Use reflection to fetch inner compactors
+      CompactorPipeline compactorPipeline = (CompactorPipeline) result;
+      Field field = compactorPipeline.getClass().getDeclaredField("compactor");
+      field.setAccessible(true);
+      Compactor compactor = (Compactor) field.get(compactorPipeline);
+      Assert.assertTrue(compactor instanceof 
CompactorPipeline.FallbackCompactor);
+      CompactorPipeline.FallbackCompactor fallbackCompactor = 
spy((CompactorPipeline.FallbackCompactor) compactor);
+      field.set(compactorPipeline, fallbackCompactor);
+      field = 
fallbackCompactor.getClass().getDeclaredField("primaryCompactor");
+      field.setAccessible(true);
+      Compactor compactor1 = (Compactor) field.get(fallbackCompactor);
+      Assert.assertTrue(compactor1 instanceof MergeCompactor);
+      compactor1 = spy(compactor1);
+      field.set(fallbackCompactor, compactor1);
+      field = 
fallbackCompactor.getClass().getDeclaredField("secondaryCompactor");
+      field.setAccessible(true);
+      Compactor compactor2 = (Compactor) field.get(fallbackCompactor);
+      if (compactionType == CompactionType.MAJOR) {
+        Assert.assertTrue(compactor2 instanceof MajorQueryCompactor);
+      } else {
+        Assert.assertTrue(compactor2 instanceof MinorQueryCompactor);
+      }
+      compactor2 = spy(compactor2);
+      field.set(fallbackCompactor, compactor2);
+      primary.set(compactor1);
+      secondary.set(compactor2);
+      return result;
+    }).when(compactorFactory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(compactorFactory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    TxnStore txnHandler = TxnUtils.getTxnStore(conf);
+    CompactionRequest cr = new CompactionRequest(dbName, tableName, 
compactionType);
+    if (partitionName == null) {
+      txnHandler.compact(cr);
+      worker.run();
+    } else {
+      cr.setPartitionname(partitionName);
+      txnHandler.compact(cr);
+      worker.run();
+    }
+
+    if (useFallback) {
+      verify(primary.get(), times(1)).run(any());
+      verify(secondary.get(), times(1)).run(any());
+    } else {
+      verify(primary.get(), times(1)).run(any());
+      verify(secondary.get(), times(0)).run(any());
+    }
+
+    // Clean up resources
+    CompactorTestUtil.runCleaner(conf);
+    // Only 1 compaction should be in the response queue with succeeded state
+    List<ShowCompactResponseElement> compacts =
+            TxnUtils.getTxnStore(conf).showCompact(new 
ShowCompactRequest()).getCompacts();
+    compacts.forEach(c -> Assert.assertEquals("succeeded", c.getState()));
+    // Verify directories after compaction
+    List<String> actualDirAfterComp =
+            CompactorTestUtil.getBaseOrDeltaNames(fs, compactionType == 
CompactionType.MAJOR ? AcidUtils.baseFileFilter :
+                    AcidUtils.deltaFileFilter, table, partitionName);
+    Assert.assertEquals("Base directory does not match after compaction", 
compactDirNames, actualDirAfterComp);
+    Assert.assertTrue(CompactorTestUtil.getBaseOrDeltaNames(fs, 
AcidUtils.deleteEventDeltaDirFilter, table,
+            partitionName).isEmpty());
+    // Verify bucket files in delta dirs
+    Assert.assertEquals("Bucket names are not matching after compaction", 
bucketName,
+            CompactorTestUtil.getBucketFileNames(fs, table, partitionName, 
actualDirAfterComp.get(0)));
+    // Verify all contents
+    List<String> actualData = dataProvider.getAllData(tableName);
+    Assert.assertEquals(expectedData, actualData);
+    // Clean up
+    if (dropTable) {
+      dataProvider.dropTable(tableName);
+    }
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_MERGE_COMPACTION_ENABLED, false);
+  }
+
+  @Test
+  public void testFallbackForMergeCompactionOnParquetTables() throws Exception 
{
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_MERGE_COMPACTION_ENABLED, true);
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    String dbName = "default";
+    String tableName = "testParquetFallback";
+    String partitionName = "bkt=1";
+    executeStatementOnDriver("drop table if exists " + tableName, driver);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a INT, b STRING) 
" + " PARTITIONED BY(bkt INT)" +
+            " STORED AS PARQUET TBLPROPERTIES ('transactional'='true', 
'transactional_properties'='insert_only')", driver);
+
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " 
PARTITION(bkt=1)" +
+            " values(57, 'Budapest')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " 
PARTITION(bkt=1)" +
+            " values(58, 'Milano')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " 
PARTITION(bkt=1)" +
+            " values(59, 'Bangalore')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " 
PARTITION(bkt=1)" +
+            " values(60, 'New York')", driver);
+
+    CompactorFactory compactorFactory = spy(CompactorFactory.getInstance());
+    AtomicReference<Compactor> primary = new AtomicReference<>();
+    AtomicReference<Compactor> secondary = new AtomicReference<>();
+    doAnswer(invocationOnMock -> {
+      Object result = invocationOnMock.callRealMethod();
+      Assert.assertTrue(result instanceof CompactorPipeline);
+      // Use reflection to fetch inner compactors
+      CompactorPipeline compactorPipeline = (CompactorPipeline) result;
+      Field field = compactorPipeline.getClass().getDeclaredField("compactor");
+      field.setAccessible(true);
+      Compactor compactor = (Compactor) field.get(compactorPipeline);
+      Assert.assertTrue(compactor instanceof 
CompactorPipeline.FallbackCompactor);
+      CompactorPipeline.FallbackCompactor fallbackCompactor = 
spy((CompactorPipeline.FallbackCompactor) compactor);
+      field.set(compactorPipeline, fallbackCompactor);
+      field = 
fallbackCompactor.getClass().getDeclaredField("primaryCompactor");
+      field.setAccessible(true);
+      Compactor compactor1 = (Compactor) field.get(fallbackCompactor);
+      Assert.assertTrue(compactor1 instanceof MergeCompactor);
+      compactor1 = spy(compactor1);
+      field.set(fallbackCompactor, compactor1);
+      field = 
fallbackCompactor.getClass().getDeclaredField("secondaryCompactor");
+      field.setAccessible(true);
+      Compactor compactor2 = (Compactor) field.get(fallbackCompactor);
+      Assert.assertTrue(compactor2 instanceof MmMajorQueryCompactor);
+      compactor2 = spy(compactor2);
+      field.set(fallbackCompactor, compactor2);
+      primary.set(compactor1);
+      secondary.set(compactor2);
+      return result;
+    }).when(compactorFactory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(compactorFactory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    TxnStore txnHandler = TxnUtils.getTxnStore(conf);
+    CompactionRequest cr = new CompactionRequest(dbName, tableName, 
CompactionType.MAJOR);
+    cr.setPartitionname(partitionName);
+    txnHandler.compact(cr);
+    worker.run();
+
+    verify(primary.get(), times(1)).run(any());
+    verify(secondary.get(), times(1)).run(any());
+  }
+
+  @Test
+  public void testFallbackForMergeCompactionWhenDeleteDeltaPresent() throws 
Exception {
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_MERGE_COMPACTION_ENABLED, true);
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    String dbName = "default";
+    String tableName = "testOrcFallback";
+    String partitionName = "bkt=1";
+    executeStatementOnDriver("drop table if exists " + tableName, driver);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a INT, b STRING) 
" + " PARTITIONED BY(bkt INT)" +
+            " STORED AS ORC TBLPROPERTIES ('transactional'='true')", driver);
+
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " 
PARTITION(bkt=1)" +
+            " values(57, 'Budapest')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " 
PARTITION(bkt=1)" +
+            " values(58, 'Milano')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " 
PARTITION(bkt=1)" +
+            " values(59, 'Bangalore')", driver);
+    executeStatementOnDriver("DELETE FROM " + tableName + " WHERE a = 57", 
driver);
+
+    CompactorFactory compactorFactory = spy(CompactorFactory.getInstance());
+    AtomicReference<Compactor> primary = new AtomicReference<>();
+    AtomicReference<Compactor> secondary = new AtomicReference<>();
+    doAnswer(invocationOnMock -> {
+      Object result = invocationOnMock.callRealMethod();
+      Assert.assertTrue(result instanceof CompactorPipeline);
+      // Use reflection to fetch inner compactors
+      CompactorPipeline compactorPipeline = (CompactorPipeline) result;
+      Field field = compactorPipeline.getClass().getDeclaredField("compactor");
+      field.setAccessible(true);
+      Compactor compactor = (Compactor) field.get(compactorPipeline);
+      Assert.assertTrue(compactor instanceof 
CompactorPipeline.FallbackCompactor);
+      CompactorPipeline.FallbackCompactor fallbackCompactor = 
spy((CompactorPipeline.FallbackCompactor) compactor);
+      field.set(compactorPipeline, fallbackCompactor);
+      field = 
fallbackCompactor.getClass().getDeclaredField("primaryCompactor");
+      field.setAccessible(true);
+      Compactor compactor1 = (Compactor) field.get(fallbackCompactor);
+      Assert.assertTrue(compactor1 instanceof MergeCompactor);
+      compactor1 = spy(compactor1);
+      field.set(fallbackCompactor, compactor1);
+      field = 
fallbackCompactor.getClass().getDeclaredField("secondaryCompactor");
+      field.setAccessible(true);
+      Compactor compactor2 = (Compactor) field.get(fallbackCompactor);
+      Assert.assertTrue(compactor2 instanceof MajorQueryCompactor);
+      compactor2 = spy(compactor2);
+      field.set(fallbackCompactor, compactor2);
+      primary.set(compactor1);
+      secondary.set(compactor2);
+      return result;
+    }).when(compactorFactory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(compactorFactory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    TxnStore txnHandler = TxnUtils.getTxnStore(conf);
+    CompactionRequest cr = new CompactionRequest(dbName, tableName, 
CompactionType.MAJOR);
+    cr.setPartitionname(partitionName);
+    txnHandler.compact(cr);
+    worker.run();
+
+    verify(primary.get(), times(1)).run(any());
+    verify(secondary.get(), times(1)).run(any());
+  }
 }
diff --git 
a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestMmCompactorOnTez.java
 
b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestMmCompactorOnTez.java
index 40b49f2df36..0a57c458833 100644
--- 
a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestMmCompactorOnTez.java
+++ 
b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestMmCompactorOnTez.java
@@ -75,7 +75,7 @@ public class TestMmCompactorOnTez extends CompactorOnTezTest {
     Table table = msClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    testDataProvider.insertMmTestData(tableName);
+    testDataProvider.insertOnlyTestData(tableName);
     // Get all data before compaction is run
     List<String> expectedData = testDataProvider.getAllData(tableName);
     // Verify deltas
@@ -132,7 +132,7 @@ public class TestMmCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    testDataProvider.insertMmTestData(tableName);
+    testDataProvider.insertOnlyTestData(tableName);
     // Get all data before compaction is run
     List<String> expectedData = testDataProvider.getAllData(tableName);
     // Verify deltas
@@ -174,7 +174,7 @@ public class TestMmCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    dataProvider.insertMmTestDataPartitioned(tableName);
+    dataProvider.insertOnlyTestDataPartitioned(tableName);
     // Get all data before compaction is run
     List<String> expectedData = dataProvider.getAllData(tableName);
     // Verify deltas
@@ -246,7 +246,7 @@ public class TestMmCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    dataProvider.insertMmTestDataPartitioned(tableName);
+    dataProvider.insertOnlyTestDataPartitioned(tableName);
     // Get all data before compaction is run
     List<String> expectedData = dataProvider.getAllData(tableName);
     // Verify deltas
@@ -290,7 +290,7 @@ public class TestMmCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    dataProvider.insertMmTestData(tableName, 10);
+    dataProvider.insertOnlyTestData(tableName, 10);
     // Get all data before compaction is run
     List<String> expectedData = dataProvider.getAllData(tableName);
     Collections.sort(expectedData);
@@ -331,19 +331,19 @@ public class TestMmCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    dataProvider.insertMmTestData(tableName);
+    dataProvider.insertOnlyTestData(tableName);
     // Run a compaction
     CompactorTestUtil.runCompaction(conf, dbName, tableName, 
CompactionType.MINOR, true);
     CompactorTestUtil.runCleaner(conf);
     verifySuccessulTxn(1);
     // Insert test data into test table
-    dataProvider.insertMmTestData(tableName);
+    dataProvider.insertOnlyTestData(tableName);
     // Run a compaction
     CompactorTestUtil.runCompaction(conf, dbName, tableName, 
CompactionType.MINOR, true);
     CompactorTestUtil.runCleaner(conf);
     verifySuccessulTxn(2);
     // Insert test data into test table
-    dataProvider.insertMmTestData(tableName);
+    dataProvider.insertOnlyTestData(tableName);
     // Run a compaction
     CompactorTestUtil.runCompaction(conf, dbName, tableName, 
CompactionType.MINOR, true);
     CompactorTestUtil.runCleaner(conf);
@@ -367,7 +367,7 @@ public class TestMmCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    dataProvider.insertMmTestData(tableName);
+    dataProvider.insertOnlyTestData(tableName);
     // Get all data before compaction is run
     List<String> expectedData = dataProvider.getAllData(tableName);
     Collections.sort(expectedData);
@@ -382,7 +382,7 @@ public class TestMmCompactorOnTez extends 
CompactorOnTezTest {
     verifyAllContents(tableName, dataProvider, expectedData);
     List<String> actualData;
     // Insert a second round of test data into test table; update expectedData
-    dataProvider.insertMmTestData(tableName);
+    dataProvider.insertOnlyTestData(tableName);
     expectedData = dataProvider.getAllData(tableName);
     // Run a compaction
     CompactorTestUtil.runCompaction(conf, dbName, tableName, 
CompactionType.MAJOR, true);
@@ -407,7 +407,7 @@ public class TestMmCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    dataProvider.insertMmTestData(tableName);
+    dataProvider.insertOnlyTestData(tableName);
     // Get all data before compaction is run
     List<String> expectedData = dataProvider.getAllData(tableName);
     Collections.sort(expectedData);
@@ -421,7 +421,7 @@ public class TestMmCompactorOnTez extends 
CompactorOnTezTest {
         CompactorTestUtil.getBaseOrDeltaNames(fs, AcidUtils.baseFileFilter, 
table, null));
     verifyAllContents(tableName, dataProvider, expectedData);
     // Insert test data into test table
-    dataProvider.insertMmTestData(tableName);
+    dataProvider.insertOnlyTestData(tableName);
     expectedData = dataProvider.getAllData(tableName);
     Collections.sort(expectedData);
     // Run a compaction
@@ -530,7 +530,7 @@ public class TestMmCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    testDataProvider.insertMmTestData(tableName);
+    testDataProvider.insertOnlyTestData(tableName);
     // Get all data before compaction is run. Expected data is 2 x MmTestData 
insertion
     List<String> expectedData = new ArrayList<>();
     List<String> oneMmTestDataInsertion = 
testDataProvider.getAllData(tableName);
@@ -539,7 +539,7 @@ public class TestMmCompactorOnTez extends 
CompactorOnTezTest {
     Collections.sort(expectedData);
     // Insert an aborted directory (txns 4-6)
     rollbackAllTxns(true, driver);
-    testDataProvider.insertMmTestData(tableName);
+    testDataProvider.insertOnlyTestData(tableName);
     rollbackAllTxns(false, driver);
     // Check that delta dirs 4-6 exist
     List<String> actualDeltasAfterComp =
@@ -549,7 +549,7 @@ public class TestMmCompactorOnTez extends 
CompactorOnTezTest {
             "delta_0000003_0000003_0000", "delta_0000004_0000004_0000",
             "delta_0000005_0000005_0000", "delta_0000006_0000006_0000"), 
actualDeltasAfterComp);
     // Insert another round of test data (txns 7-9)
-    testDataProvider.insertMmTestData(tableName);
+    testDataProvider.insertOnlyTestData(tableName);
     verifyAllContents(tableName, testDataProvider, expectedData);
     // Run a minor compaction
     CompactorTestUtil.runCompaction(conf, dbName, tableName, 
CompactionType.MINOR, true);
@@ -585,7 +585,7 @@ public class TestMmCompactorOnTez extends 
CompactorOnTezTest {
     Table table = metaStoreClient.getTable(dbName, tableName);
     FileSystem fs = FileSystem.get(conf);
     // Insert test data into test table
-    dataProvider.insertMmTestData(dbName, tableName);
+    dataProvider.insertOnlyTestData(dbName, tableName);
     // Get all data before compaction is run
     List<String> expectedData = dataProvider.getAllData(dbName, tableName, 
false);
     Collections.sort(expectedData);
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Compactor.java 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Compactor.java
index 06cbe09fec8..73eb7372a5a 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Compactor.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Compactor.java
@@ -20,13 +20,6 @@ package org.apache.hadoop.hive.ql.txn.compactor;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.hive.common.ValidReadTxnList;
 import org.apache.hadoop.hive.common.ValidTxnList;
-import org.apache.hadoop.hive.common.ValidWriteIdList;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.metastore.api.Partition;
-import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
-import org.apache.hadoop.hive.metastore.api.Table;
-import org.apache.hadoop.hive.metastore.txn.CompactionInfo;
-import org.apache.hadoop.hive.ql.io.AcidDirectory;
 import org.apache.hadoop.hive.ql.metadata.HiveException;
 import org.apache.parquet.Strings;
 
@@ -50,17 +43,10 @@ public interface Compactor {
 
   /**
    * Start a compaction.
-   * @param hiveConf hive configuration
-   * @param table the table, where the compaction should run
-   * @param partition the partition, where the compaction should run
-   * @param storageDescriptor this is the resolved storage descriptor
-   * @param writeIds valid write IDs used to filter rows while they're being 
read for compaction
-   * @param compactionInfo provides info about the type of compaction
-   * @param dir provides ACID directory layout information
+   * @param context CompactionContext which contains information to perform 
compaction.
    * @throws IOException compaction cannot be finished.
    */
-  void run(HiveConf hiveConf, Table table, Partition partition, 
StorageDescriptor storageDescriptor,
-           ValidWriteIdList writeIds, CompactionInfo compactionInfo, 
AcidDirectory dir)
+  boolean run(CompactorContext context)
       throws IOException, HiveException, InterruptedException;
 
 }
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorContext.java 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorContext.java
new file mode 100644
index 00000000000..0d36402e56e
--- /dev/null
+++ b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorContext.java
@@ -0,0 +1,78 @@
+/*
+ * 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.hadoop.hive.ql.txn.compactor;
+
+import org.apache.hadoop.hive.common.ValidWriteIdList;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.Partition;
+import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.CompactionInfo;
+import org.apache.hadoop.hive.ql.io.AcidDirectory;
+
+/**
+ * A class which contains all information required for MR/Query based 
compaction.
+ */
+public class CompactorContext {
+
+  private final HiveConf conf;
+  private final Table table;
+  private final Partition partition;
+  private final StorageDescriptor sd;
+  private final ValidWriteIdList validWriteIdList;
+  private final CompactionInfo compactionInfo;
+  private final AcidDirectory dir;
+
+  CompactorContext(HiveConf conf, Table table, Partition p, StorageDescriptor 
sd, ValidWriteIdList tblValidWriteIds, CompactionInfo ci, AcidDirectory dir) {
+    this.conf = conf;
+    this.table = table;
+    this.partition = p;
+    this.sd = sd;
+    this.validWriteIdList = tblValidWriteIds;
+    this.compactionInfo = ci;
+    this.dir = dir;
+  }
+
+  public HiveConf getConf() {
+    return conf;
+  }
+
+  public Table getTable() {
+    return table;
+  }
+
+  public Partition getPartition() {
+    return partition;
+  }
+
+  public StorageDescriptor getSd() {
+    return sd;
+  }
+
+  public ValidWriteIdList getValidWriteIdList() {
+    return validWriteIdList;
+  }
+
+  public CompactionInfo getCompactionInfo() {
+    return compactionInfo;
+  }
+
+  public AcidDirectory getAcidDirectory() {
+    return dir;
+  }
+}
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorFactory.java 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorFactory.java
index b48071d226b..ba8b2d207f3 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorFactory.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorFactory.java
@@ -67,7 +67,7 @@ public final class CompactorFactory {
    * @param compactionInfo provides insight about the type of compaction, must 
be not null.
    * @return {@link QueryCompactor} or null.
    */
-  public Compactor getCompactor(Table table, HiveConf configuration, 
CompactionInfo compactionInfo,IMetaStoreClient msc)
+  public CompactorPipeline getCompactorPipeline(Table table, HiveConf 
configuration, CompactionInfo compactionInfo,IMetaStoreClient msc)
       throws HiveException {
     if (AcidUtils.isFullAcidTable(table.getParameters())) {
       if (!"tez".equalsIgnoreCase(HiveConf.getVar(configuration, 
HiveConf.ConfVars.HIVE_EXECUTION_ENGINE)) ||
@@ -80,15 +80,17 @@ public final class CompactorFactory {
             HiveConf.getBoolVar(configuration, 
HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED)) {
           LOG.warn("Query-based compaction is enabled, but it is only 
supported on tez. Falling back to MR compaction.");
         }
-        return new MRCompactor(msc);
+        return new CompactorPipeline(new MRCompactor(msc));
       }
       switch (compactionInfo.type) {
         case MINOR:
-          return new MinorQueryCompactor();
+          return new CompactorPipeline(new MergeCompactor())
+                  .addCompactor(new MinorQueryCompactor());
         case MAJOR:
-          return new MajorQueryCompactor();
+          return new CompactorPipeline(new MergeCompactor())
+                  .addCompactor(new MajorQueryCompactor());
         case REBALANCE:
-          return new RebalanceQueryCompactor();
+          return new CompactorPipeline(new RebalanceQueryCompactor());
       }
     } else if (AcidUtils.isInsertOnlyTable(table.getParameters())) {
       if 
(!configuration.getBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_COMPACT_MM)) {
@@ -97,14 +99,20 @@ public final class CompactorFactory {
       }
       switch (compactionInfo.type) {
         case MINOR:
-          return new MmMinorQueryCompactor();
+          return new CompactorPipeline(new MergeCompactor())
+                  .addCompactor(new MmMinorQueryCompactor());
         case MAJOR:
+          return new CompactorPipeline(new MergeCompactor())
+                  .addCompactor(new MmMajorQueryCompactor());
         case REBALANCE:
           // REBALANCE COMPACTION on an insert-only table is simply a MAJOR 
compaction. Since there is no ACID row data,
           // there is no acid row order to keep, and the number of buckets 
cannot be set at all (it will be calculated
           // and created by TEZ dynamically). Initiator won't schedule 
REBALANCE compactions for insert-only tables,
           // however users can request it. In these cases we simply fall back 
to MAJOR compaction
-          return new MmMajorQueryCompactor();
+          return new CompactorPipeline(new MmMajorQueryCompactor());
+        default:
+          throw new HiveException(
+              compactionInfo.type.name() + " compaction is not supported on 
insert only tables.");
       }
     } else {
       throw new HiveException("Only transactional tables can be compacted, " + 
table.getTableName() + "is not suitable " +
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorPipeline.java 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorPipeline.java
new file mode 100644
index 00000000000..a78c34037e0
--- /dev/null
+++ b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorPipeline.java
@@ -0,0 +1,69 @@
+/*
+ * 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.hadoop.hive.ql.txn.compactor;
+
+import org.apache.hadoop.hive.ql.metadata.HiveException;
+import java.io.IOException;
+
+/**
+ * Runs different compactions based on the order in which compactors are 
added.<br>
+ * Mainly used for fall back mechanism for Merge compaction.
+ */
+public class CompactorPipeline {
+
+  private Compactor compactor;
+  private final boolean isMR;
+
+  public CompactorPipeline(Compactor compactor) {
+    this.compactor = compactor;
+    this.isMR = compactor instanceof MRCompactor;
+  }
+
+  CompactorPipeline addCompactor(Compactor newCompactor) {
+    compactor = new FallbackCompactor(compactor, newCompactor);
+    return this;
+  }
+
+  public boolean isMRCompaction() {
+    return isMR;
+  }
+
+  public Boolean execute(CompactorContext input) throws IOException, 
HiveException, InterruptedException {
+    return compactor.run(input);
+  }
+
+  /**
+   * This class defines a way of handling fallback given any number of 
fallback compactors.<br>
+   * It can encapsulate other fallback compactors within itself.
+   */
+  static final class FallbackCompactor implements Compactor {
+    private final Compactor primaryCompactor;
+    private final Compactor secondaryCompactor;
+
+    FallbackCompactor(Compactor primaryCompactor, Compactor 
secondaryCompactor) {
+      this.primaryCompactor = primaryCompactor;
+      this.secondaryCompactor = secondaryCompactor;
+    }
+
+    @Override
+    public boolean run(CompactorContext context) throws IOException, 
HiveException, InterruptedException {
+      boolean result = primaryCompactor.run(context);
+      return !result ? secondaryCompactor.run(context) : result;
+    }
+  }
+}
\ No newline at end of file
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MRCompactor.java 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MRCompactor.java
index 765272d97f7..f9044fa3d29 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MRCompactor.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MRCompactor.java
@@ -44,7 +44,6 @@ import org.apache.hadoop.hive.conf.HiveConf;
 import org.apache.hadoop.hive.metastore.IMetaStoreClient;
 import org.apache.hadoop.hive.metastore.api.CompactionType;
 import org.apache.hadoop.hive.metastore.api.FieldSchema;
-import org.apache.hadoop.hive.metastore.api.Partition;
 import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
 import org.apache.hadoop.hive.metastore.api.Table;
 import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
@@ -118,25 +117,28 @@ public class MRCompactor implements Compactor {
     this.msc = msc;
   }
 
-   @Override
-  public void run(HiveConf conf, Table table, Partition partition, 
StorageDescriptor sd,
-                  ValidWriteIdList writeIds, CompactionInfo ci, AcidDirectory 
dir)
+  @Override
+  public boolean run(CompactorContext context)
        throws IOException, HiveException, InterruptedException {
-    if (ci.runAs.equals(System.getProperty("user.name"))) {
-      run(conf, table, sd, writeIds, ci, dir);
+    if 
(context.getCompactionInfo().runAs.equals(System.getProperty("user.name"))) {
+      run(context.getConf(), context.getTable(), context.getSd(),
+              context.getValidWriteIdList(), context.getCompactionInfo(), 
context.getAcidDirectory());
     } else {
-      UserGroupInformation ugi = 
UserGroupInformation.createProxyUser(ci.runAs, 
UserGroupInformation.getLoginUser());
+      UserGroupInformation ugi = 
UserGroupInformation.createProxyUser(context.getCompactionInfo().runAs,
+              UserGroupInformation.getLoginUser());
       ugi.doAs((PrivilegedExceptionAction<Object>) () -> {
-        run(conf, table, sd, writeIds, ci, dir);
+        run(context.getConf(), context.getTable(), context.getSd(),
+                context.getValidWriteIdList(), context.getCompactionInfo(), 
context.getAcidDirectory());
         return null;
       });
       try {
         FileSystem.closeAllForUGI(ugi);
       } catch (IOException exception) {
-        LOG.error("Could not clean up file-system handles for UGI: " + ugi + " 
for " + ci.getFullPartitionName(),
+        LOG.error("Could not clean up file-system handles for UGI: " + ugi + " 
for " + context.getCompactionInfo().getFullPartitionName(),
             exception);
       }
     }
+    return true;
   }
 
   @VisibleForTesting
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MajorQueryCompactor.java 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MajorQueryCompactor.java
index 4b2a2dadb7a..75fb798ac33 100644
--- 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MajorQueryCompactor.java
+++ 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MajorQueryCompactor.java
@@ -25,8 +25,6 @@ import org.apache.hadoop.hive.metastore.api.CompactionType;
 import org.apache.hadoop.hive.metastore.api.Partition;
 import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
 import org.apache.hadoop.hive.metastore.api.Table;
-import org.apache.hadoop.hive.metastore.txn.CompactionInfo;
-import org.apache.hadoop.hive.ql.io.AcidDirectory;
 import org.apache.hadoop.hive.ql.io.AcidUtils;
 
 import java.io.IOException;
@@ -38,10 +36,13 @@ import java.util.List;
 final class MajorQueryCompactor extends QueryCompactor {
 
   @Override
-  public void run(HiveConf hiveConf, Table table, Partition partition, 
StorageDescriptor storageDescriptor,
-                  ValidWriteIdList writeIds, CompactionInfo compactionInfo, 
AcidDirectory dir) throws IOException {
+  public boolean run(CompactorContext context) throws IOException {
+    HiveConf hiveConf = context.getConf();
+    Table table = context.getTable();
     AcidUtils
         .setAcidOperationalProperties(hiveConf, true, 
AcidUtils.getAcidOperationalProperties(table.getParameters()));
+    StorageDescriptor storageDescriptor = context.getSd();
+    ValidWriteIdList writeIds = context.getValidWriteIdList();
 
     HiveConf conf = new HiveConf(hiveConf);
     /*
@@ -55,11 +56,12 @@ final class MajorQueryCompactor extends QueryCompactor {
         conf, true, false, false, null);
 
     List<String> createQueries = getCreateQueries(tmpTableName, table, 
tmpTablePath.toString());
-    List<String> compactionQueries = getCompactionQueries(table, partition, 
tmpTableName);
+    List<String> compactionQueries = getCompactionQueries(table, 
context.getPartition(), tmpTableName);
     List<String> dropQueries = getDropQueries(tmpTableName);
-    runCompactionQueries(conf, tmpTableName, storageDescriptor, writeIds, 
compactionInfo,
+    runCompactionQueries(conf, tmpTableName, storageDescriptor, writeIds, 
context.getCompactionInfo(),
         Lists.newArrayList(tmpTablePath), createQueries, compactionQueries, 
dropQueries,
             table.getParameters());
+    return true;
   }
 
   /**
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MergeCompactor.java 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MergeCompactor.java
new file mode 100644
index 00000000000..295ebe56417
--- /dev/null
+++ b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MergeCompactor.java
@@ -0,0 +1,212 @@
+/*
+ * 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.hadoop.hive.ql.txn.compactor;
+
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.common.ValidWriteIdList;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.CompactionInfo;
+import org.apache.hadoop.hive.ql.io.AcidDirectory;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.orc.OrcFile;
+import org.apache.hadoop.hive.ql.io.orc.Reader;
+import org.apache.hadoop.hive.ql.metadata.HiveException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+
+final class MergeCompactor extends QueryCompactor {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(MergeCompactor.class.getName());
+
+  @Override
+  public boolean run(CompactorContext context) throws IOException, 
HiveException, InterruptedException {
+    HiveConf hiveConf = context.getConf();
+    Table table = context.getTable();
+    AcidDirectory dir = context.getAcidDirectory();
+    ValidWriteIdList writeIds = context.getValidWriteIdList();
+    StorageDescriptor storageDescriptor = context.getSd();
+    CompactionInfo compactionInfo = context.getCompactionInfo();
+
+    if (isMergeCompaction(hiveConf, dir, storageDescriptor)) {
+      // Only inserts happened, it is much more performant to merge the files 
than running a query
+      Path outputDirPath = getOutputDirPath(hiveConf, writeIds,
+              compactionInfo.isMajorCompaction(), storageDescriptor);
+      try {
+        return mergeFiles(hiveConf, compactionInfo.isMajorCompaction(),
+                dir, outputDirPath, 
AcidUtils.isInsertOnlyTable(table.getParameters()));
+      } catch (Throwable t) {
+        // Error handling, just delete the output directory,
+        // and fall back to query based compaction.
+        FileSystem fs = outputDirPath.getFileSystem(hiveConf);
+        if (fs.exists(outputDirPath)) {
+          fs.delete(outputDirPath, true);
+        }
+        return false;
+      }
+    } else {
+      return false;
+    }
+  }
+
+  /**
+   * Returns whether merge compaction must be enabled or not.
+   * @param conf Hive configuration
+   * @param directory the directory to be scanned
+   * @param storageDescriptor storage descriptor of the underlying table
+   * @return true, if merge compaction must be enabled
+   */
+  private boolean isMergeCompaction(HiveConf conf, AcidDirectory directory,
+                                   StorageDescriptor storageDescriptor) {
+    return HiveConf.getBoolVar(conf, 
HiveConf.ConfVars.HIVE_MERGE_COMPACTION_ENABLED)
+            && 
storageDescriptor.getOutputFormat().equalsIgnoreCase("org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat")
+            && !hasDeleteOrAbortedDirectories(directory);
+  }
+
+  /**
+   * Scan a directory for delete deltas or aborted directories.
+   * @param directory the directory to be scanned
+   * @return true, if delete or aborted directory found
+   */
+  private boolean hasDeleteOrAbortedDirectories(AcidDirectory directory) {
+    if (!directory.getCurrentDirectories().isEmpty()) {
+      return directory.getCurrentDirectories().stream()
+              .anyMatch(AcidUtils.ParsedDeltaLight::isDeleteDelta) || 
!directory.getAbortedDirectories().isEmpty();
+    }
+    return true;
+  }
+
+  /**
+   * Collect the list of all bucket file paths, which belong to the same 
bucket Id. This method scans all the base
+   * and delta dirs.
+   * @param conf hive configuration, must be not null
+   * @param dir the root directory of delta dirs
+   * @param includeBaseDir true, if the base directory should be scanned
+   * @param isMm true, if the table is an insert only table
+   * @return map of bucket ID -> bucket files
+   * @throws IOException an error happened during the reading of the 
directory/bucket file
+   */
+  private Map<Integer, List<Reader>> matchBucketIdToBucketFiles(HiveConf conf, 
AcidDirectory dir,
+                                                                       boolean 
includeBaseDir, boolean isMm) throws IOException {
+    Map<Integer, List<Reader>> result = new HashMap<>();
+    if (includeBaseDir && dir.getBaseDirectory() != null) {
+      result.putAll(getBucketFiles(conf, dir.getBaseDirectory(), isMm));
+    }
+    for (AcidUtils.ParsedDelta deltaDir : dir.getCurrentDirectories()) {
+      Path deltaDirPath = deltaDir.getPath();
+      Map<Integer, List<Reader>> intermediateResult = getBucketFiles(conf, 
deltaDirPath, isMm);
+      intermediateResult.forEach((k, v) -> result.merge(k, v, (v1, v2) -> {
+        v1.addAll(v2);
+        return v1;
+      }));
+    }
+    return result;
+  }
+
+  /**
+   * Collect the list of all bucket file paths, which belong to the same 
bucket Id. This method checks only one
+   * directory.
+   * @param conf hive configuration, must be not null
+   * @param dirPath the directory to be scanned.
+   * @param isMm collect bucket files fron insert only directories
+   * @throws IOException an error happened during the reading of the 
directory/bucket file
+   */
+  private Map<Integer, List<Reader>> getBucketFiles(HiveConf conf, Path 
dirPath, boolean isMm) throws IOException {
+    Map<Integer, List<Reader>> bucketIdToBucketFilePath = new HashMap<>();
+    FileSystem fs = dirPath.getFileSystem(conf);
+    FileStatus[] fileStatuses =
+            fs.listStatus(dirPath, isMm ? AcidUtils.originalBucketFilter : 
AcidUtils.bucketFileFilter);
+    for (FileStatus f : fileStatuses) {
+      final Path fPath = f.getPath();
+      Matcher matcher = isMm ? AcidUtils.LEGACY_BUCKET_DIGIT_PATTERN
+              .matcher(fPath.getName()) : 
AcidUtils.BUCKET_PATTERN.matcher(fPath.getName());
+      if (!matcher.find()) {
+        String errorMessage = String
+                .format("Found a bucket file which did not match the bucket 
pattern! %s Matcher=%s", fPath,
+                        matcher);
+        LOG.error(errorMessage);
+        throw new IllegalArgumentException(errorMessage);
+      }
+      int bucketNum = matcher.groupCount() > 0 ? 
Integer.parseInt(matcher.group(1)) : Integer.parseInt(matcher.group());
+      bucketIdToBucketFilePath.computeIfAbsent(bucketNum, ArrayList::new);
+      Reader reader = OrcFile.createReader(fs, fPath);
+      bucketIdToBucketFilePath.computeIfPresent(bucketNum, (k, v) -> 
v).add(reader);
+    }
+    return bucketIdToBucketFilePath;
+  }
+
+  /**
+   * Generate output path for compaction. This can be used to generate delta 
or base directories.
+   * @param conf hive configuration, must be non-null
+   * @param writeIds list of valid write IDs
+   * @param isBaseDir if base directory path should be generated
+   * @param sd the resolved storadge descriptor
+   * @return output path, always non-null
+   */
+  private Path getOutputDirPath(HiveConf conf, ValidWriteIdList writeIds, 
boolean isBaseDir,
+                                         StorageDescriptor sd) {
+    long minOpenWriteId = writeIds.getMinOpenWriteId() == null ? 1 : 
writeIds.getMinOpenWriteId();
+    long highWatermark = writeIds.getHighWatermark();
+    long compactorTxnId = Compactor.getCompactorTxnId(conf);
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf)
+            .writingBase(isBaseDir).writingDeleteDelta(false)
+            .isCompressed(false)
+            .minimumWriteId(minOpenWriteId).maximumWriteId(highWatermark)
+            .statementId(-1).visibilityTxnId(compactorTxnId);
+    return AcidUtils.baseOrDeltaSubdirPath(new Path(sd.getLocation()), 
options);
+  }
+
+  /**
+   * Merge files from base/delta directories. If the directories contains 
multiple buckets, the result will also
+   * contain the same amount.
+   * @param conf hive configuration
+   * @param includeBaseDir if base directory should be scanned for orc files
+   * @param dir the root directory of the table/partition
+   * @param outputDirPath the result directory path
+   * @param isMm merge orc files from insert only tables
+   * @throws IOException error occurred during file operation
+   */
+  private boolean mergeFiles(HiveConf conf, boolean includeBaseDir, 
AcidDirectory dir,
+                               Path outputDirPath, boolean isMm) throws 
IOException {
+    Map<Integer, List<Reader>> bucketIdToBucketFiles = 
matchBucketIdToBucketFiles(conf, dir, includeBaseDir, isMm);
+    OrcFileMerger fileMerger = new OrcFileMerger(conf);
+    boolean isCompatible = 
bucketIdToBucketFiles.values().stream().allMatch(fileMerger::checkCompatibility);
+    if (isCompatible) {
+      for (Map.Entry<Integer, List<Reader>> e : 
bucketIdToBucketFiles.entrySet()) {
+        Path path = isMm ? new Path(outputDirPath, 
String.format(AcidUtils.LEGACY_FILE_BUCKET_DIGITS,
+                e.getKey()) + "_0") : new Path(outputDirPath, 
AcidUtils.BUCKET_PREFIX + String.format(AcidUtils.BUCKET_DIGITS,
+                e.getKey()));
+        fileMerger.mergeFiles(e.getValue(), path);
+      }
+      return true;
+    } else {
+      return false;
+    }
+  }
+}
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MinorQueryCompactor.java 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MinorQueryCompactor.java
index 23a30393a9f..cc1c3e92167 100644
--- 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MinorQueryCompactor.java
+++ 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MinorQueryCompactor.java
@@ -22,10 +22,8 @@ import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.hive.common.ValidWriteIdList;
 import org.apache.hadoop.hive.conf.HiveConf;
 import org.apache.hadoop.hive.metastore.api.CompactionType;
-import org.apache.hadoop.hive.metastore.api.Partition;
 import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
 import org.apache.hadoop.hive.metastore.api.Table;
-import org.apache.hadoop.hive.metastore.txn.CompactionInfo;
 import org.apache.hadoop.hive.ql.io.AcidDirectory;
 import org.apache.hadoop.hive.ql.io.AcidUtils;
 import org.apache.hadoop.hive.ql.metadata.HiveException;
@@ -44,16 +42,21 @@ final class MinorQueryCompactor extends QueryCompactor {
   private static final Logger LOG = 
LoggerFactory.getLogger(MinorQueryCompactor.class.getName());
 
   @Override
-  public void run(HiveConf hiveConf, Table table, Partition partition, 
StorageDescriptor storageDescriptor,
-           ValidWriteIdList writeIds, CompactionInfo compactionInfo, 
AcidDirectory dir) throws IOException {
+  public boolean run(CompactorContext context) throws IOException {
     LOG.info("Running query based minor compaction");
+    HiveConf hiveConf = context.getConf();
+    Table table = context.getTable();
     AcidUtils
         .setAcidOperationalProperties(hiveConf, true, 
AcidUtils.getAcidOperationalProperties(table.getParameters()));
+    StorageDescriptor storageDescriptor = context.getSd();
+    AcidDirectory dir = context.getAcidDirectory();
+    ValidWriteIdList writeIds = context.getValidWriteIdList();
     // Set up the session for driver.
     HiveConf conf = new HiveConf(hiveConf);
     conf.set(HiveConf.ConfVars.SPLIT_GROUPING_MODE.varname, 
CompactorUtil.COMPACTOR);
     conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_FETCH_COLUMN_STATS, false);
     conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_ESTIMATE_STATS, false);
+
     String tmpTableName =
         table.getDbName() + "_tmp_compactor_" + table.getTableName() + "_" + 
System.currentTimeMillis();
 
@@ -67,9 +70,10 @@ final class MinorQueryCompactor extends QueryCompactor {
     List<String> compactionQueries = getCompactionQueries(tmpTableName, table, 
writeIds);
     List<String> dropQueries = getDropQueries(tmpTableName);
 
-    runCompactionQueries(conf, tmpTableName, storageDescriptor, writeIds, 
compactionInfo,
+    runCompactionQueries(conf, tmpTableName, storageDescriptor, writeIds, 
context.getCompactionInfo(),
         Lists.newArrayList(resultDeltaDir, resultDeleteDeltaDir), 
createQueries,
         compactionQueries, dropQueries, table.getParameters());
+    return true;
   }
 
 
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MmMajorQueryCompactor.java
 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MmMajorQueryCompactor.java
index 421c06ba302..ecdae6439ca 100644
--- 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MmMajorQueryCompactor.java
+++ 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MmMajorQueryCompactor.java
@@ -25,8 +25,6 @@ import org.apache.hadoop.hive.metastore.api.CompactionType;
 import org.apache.hadoop.hive.metastore.api.Partition;
 import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
 import org.apache.hadoop.hive.metastore.api.Table;
-import org.apache.hadoop.hive.metastore.txn.CompactionInfo;
-import org.apache.hadoop.hive.ql.io.AcidDirectory;
 import org.apache.hadoop.hive.ql.metadata.HiveException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -42,11 +40,14 @@ final class MmMajorQueryCompactor extends QueryCompactor {
   private static final Logger LOG = 
LoggerFactory.getLogger(MmMajorQueryCompactor.class.getName());
 
   @Override
-  public void run(HiveConf hiveConf, Table table, Partition partition, 
StorageDescriptor storageDescriptor,
-                     ValidWriteIdList writeIds, CompactionInfo compactionInfo, 
AcidDirectory dir) throws IOException {
+  public boolean run(CompactorContext context) throws IOException {
+    HiveConf hiveConf = context.getConf();
+    Table table = context.getTable();
     LOG.debug("Going to delete directories for aborted transactions for MM 
table " + table.getDbName() + "." + table
         .getTableName());
-    QueryCompactor.Util.removeFilesForMmTable(hiveConf, dir);
+    QueryCompactor.Util.removeFilesForMmTable(hiveConf, 
context.getAcidDirectory());
+    StorageDescriptor storageDescriptor = context.getSd();
+    ValidWriteIdList writeIds = context.getValidWriteIdList();
 
     // Set up the session for driver.
     HiveConf driverConf = new HiveConf(hiveConf);
@@ -59,11 +60,12 @@ final class MmMajorQueryCompactor extends QueryCompactor {
 
     List<String> createTableQueries = getCreateQueries(tmpTableName, table, 
storageDescriptor,
         resultBaseDir.toString());
-    List<String> compactionQueries = getCompactionQueries(table, partition, 
tmpTableName);
+    List<String> compactionQueries = getCompactionQueries(table, 
context.getPartition(), tmpTableName);
     List<String> dropQueries = getDropQueries(tmpTableName);
-    runCompactionQueries(driverConf, tmpTableName, storageDescriptor, 
writeIds, compactionInfo,
+    runCompactionQueries(driverConf, tmpTableName, storageDescriptor, 
writeIds, context.getCompactionInfo(),
         Lists.newArrayList(resultBaseDir), createTableQueries, 
compactionQueries, dropQueries,
             table.getParameters());
+    return true;
   }
 
   /**
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MmMinorQueryCompactor.java
 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MmMinorQueryCompactor.java
index 4c7ee742631..81e7b4cc19f 100644
--- 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MmMinorQueryCompactor.java
+++ 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/MmMinorQueryCompactor.java
@@ -22,10 +22,8 @@ import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.hive.common.ValidWriteIdList;
 import org.apache.hadoop.hive.conf.HiveConf;
 import org.apache.hadoop.hive.metastore.api.CompactionType;
-import org.apache.hadoop.hive.metastore.api.Partition;
 import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
 import org.apache.hadoop.hive.metastore.api.Table;
-import org.apache.hadoop.hive.metastore.txn.CompactionInfo;
 import org.apache.hadoop.hive.ql.io.AcidDirectory;
 import org.apache.hadoop.hive.ql.metadata.HiveException;
 import org.slf4j.Logger;
@@ -42,13 +40,16 @@ final class MmMinorQueryCompactor extends QueryCompactor {
   private static final Logger LOG = 
LoggerFactory.getLogger(MmMinorQueryCompactor.class.getName());
 
   @Override
-  public void run(HiveConf hiveConf, Table table, Partition partition,
-                     StorageDescriptor storageDescriptor, ValidWriteIdList 
writeIds, CompactionInfo compactionInfo,
-                     AcidDirectory dir) throws IOException {
+  public boolean run(CompactorContext context) throws IOException {
+    HiveConf hiveConf = context.getConf();
+    Table table = context.getTable();
+    AcidDirectory dir = context.getAcidDirectory();
     LOG.debug(
         "Going to delete directories for aborted transactions for MM table " + 
table.getDbName()
             + "." + table.getTableName());
     QueryCompactor.Util.removeFilesForMmTable(hiveConf, dir);
+    StorageDescriptor storageDescriptor = context.getSd();
+    ValidWriteIdList writeIds = context.getValidWriteIdList();
 
     HiveConf driverConf = setUpDriverSession(hiveConf);
 
@@ -61,8 +62,9 @@ final class MmMinorQueryCompactor extends QueryCompactor {
         writeIds, resultDeltaDir);
     List<String> compactionQueries = getCompactionQueries(tmpTableName, 
resultTmpTableName, table);
     List<String> dropQueries = getDropQueries(tmpTableName);
-    runCompactionQueries(driverConf, tmpTableName, storageDescriptor, 
writeIds, compactionInfo,
+    runCompactionQueries(driverConf, tmpTableName, storageDescriptor, 
writeIds, context.getCompactionInfo(),
         Lists.newArrayList(resultDeltaDir), createTableQueries, 
compactionQueries, dropQueries, table.getParameters());
+    return true;
   }
 
   /**
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/OrcFileMerger.java 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/OrcFileMerger.java
new file mode 100644
index 00000000000..7f3c1800a8f
--- /dev/null
+++ b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/OrcFileMerger.java
@@ -0,0 +1,114 @@
+/*
+ * 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.hadoop.hive.ql.txn.compactor;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
+import org.apache.hadoop.hive.ql.io.orc.CompressionKind;
+import org.apache.hadoop.hive.ql.io.orc.OrcFile;
+import org.apache.hadoop.hive.ql.io.orc.Reader;
+import org.apache.hadoop.hive.ql.io.orc.RecordReader;
+import org.apache.hadoop.hive.ql.io.orc.Writer;
+import org.apache.hadoop.fs.Path;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.List;
+
+/**
+ * Class to support fast merging of ORC files.
+ */
+public class OrcFileMerger {
+
+  private final Configuration conf;
+  private static final Logger LOG = 
LoggerFactory.getLogger(OrcFileMerger.class);
+
+  public OrcFileMerger(Configuration conf) {
+    this.conf = conf;
+  }
+
+  /**
+   * Merge orc files into a single file
+   * @param readers list of orc file paths to be merged
+   * @param outPath the path of output orc file
+   * @throws IOException error happened during file operations
+   */
+  public void mergeFiles(List<Reader> readers, Path outPath) throws 
IOException {
+    Writer writer = null;
+    try {
+      for (Reader reader : readers) {
+        if (writer == null) {
+          writer = setupWriter(reader, outPath);
+        }
+        VectorizedRowBatch batch = reader.getSchema().createRowBatchV2();
+        RecordReader rows = reader.rows();
+        while (rows.nextBatch(batch)) {
+          if (batch != null) {
+            writer.addRowBatch(batch);
+          }
+        }
+        rows.close();
+      }
+    } finally {
+      if (writer != null) {
+        writer.close();
+      }
+    }
+  }
+
+  /**
+   * Create a new instance of orc output writer. The writer parameters are 
collected from the orc reader.
+   * @param reader orc reader of file
+   * @param outPath the path of the output file
+   * @return a new instance of orc writer, always non-null
+   * @throws IOException error during file operation
+   */
+  private Writer setupWriter(Reader reader, Path outPath) throws IOException {
+    OrcFile.WriterOptions options =
+            
OrcFile.writerOptions(conf).compress(reader.getCompression()).version(reader.getFileVersion())
+                    
.rowIndexStride(reader.getRowIndexStride()).inspector(reader.getObjectInspector());
+    if (CompressionKind.NONE != reader.getCompression()) {
+      options.bufferSize(reader.getCompressionSize()).enforceBufferSize();
+    }
+    Writer writer = OrcFile.createWriter(outPath, options);
+    LOG.info("ORC merge file output path: {}", outPath);
+    return writer;
+  }
+
+  /**
+   * Check compatibility between readers.
+   * @param readers list of readers
+   * @return true, if the readers are compatible
+   */
+  public boolean checkCompatibility(final List<Reader> readers) {
+    if (readers == null || readers.isEmpty()) {
+      return false;
+    }
+
+    if (!readers.stream().allMatch(
+      r -> readers.get(0).getSchema().equals(r.getSchema()) && 
readers.get(0).getCompression()
+              .equals(r.getCompression()) && 
readers.get(0).getCompressionSize() == r.getCompressionSize() && readers
+              .get(0).getFileVersion().equals(r.getFileVersion()) && 
readers.get(0).getWriterVersion()
+              .equals(r.getWriterVersion()) && 
readers.get(0).getRowIndexStride() == r.getRowIndexStride())) {
+      LOG.warn("Incompatible ORC file merge!");
+      return false;
+    }
+    return true;
+  }
+}
\ No newline at end of file
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/QueryCompactor.java 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/QueryCompactor.java
index a1af5fc0c9b..6f0a0726360 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/QueryCompactor.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/QueryCompactor.java
@@ -18,11 +18,8 @@
 package org.apache.hadoop.hive.ql.txn.compactor;
 
 import org.apache.commons.lang3.exception.ExceptionUtils;
-import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.hive.common.ValidReadTxnList;
-import org.apache.hadoop.hive.common.ValidTxnList;
 import org.apache.hadoop.hive.common.ValidWriteIdList;
 import org.apache.hadoop.hive.conf.HiveConf;
 import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
@@ -38,7 +35,6 @@ import org.apache.hadoop.hive.ql.io.AcidUtils;
 import org.apache.hadoop.hive.ql.metadata.Hive;
 import org.apache.hadoop.hive.ql.metadata.HiveException;
 import org.apache.hadoop.hive.ql.session.SessionState;
-import org.apache.parquet.Strings;
 import org.apache.tez.dag.api.TezConfiguration;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/RebalanceQueryCompactor.java
 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/RebalanceQueryCompactor.java
index 5e80e52f63b..591a4b4dfb3 100644
--- 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/RebalanceQueryCompactor.java
+++ 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/RebalanceQueryCompactor.java
@@ -27,7 +27,6 @@ import org.apache.hadoop.hive.metastore.api.CompactionType;
 import org.apache.hadoop.hive.metastore.api.Partition;
 import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
 import org.apache.hadoop.hive.metastore.api.Table;
-import org.apache.hadoop.hive.metastore.txn.CompactionInfo;
 import org.apache.hadoop.hive.ql.io.AcidDirectory;
 import org.apache.hadoop.hive.ql.io.AcidUtils;
 import org.apache.hadoop.hive.ql.metadata.HiveException;
@@ -39,10 +38,14 @@ import java.util.stream.Collectors;
 final class RebalanceQueryCompactor extends QueryCompactor {
 
   @Override
-  public void run(HiveConf hiveConf, Table table, Partition partition, 
StorageDescriptor storageDescriptor,
-           ValidWriteIdList writeIds, CompactionInfo compactionInfo, 
AcidDirectory dir)
+  public boolean run(CompactorContext context)
       throws IOException, HiveException {
-    AcidUtils.setAcidOperationalProperties(hiveConf, true, 
AcidUtils.getAcidOperationalProperties(table.getParameters()));
+    HiveConf hiveConf = context.getConf();
+    Table table = context.getTable();
+    AcidUtils.setAcidOperationalProperties(context.getConf(), true, 
AcidUtils.getAcidOperationalProperties(table.getParameters()));
+    StorageDescriptor storageDescriptor = context.getSd();
+    AcidDirectory dir = context.getAcidDirectory();
+    ValidWriteIdList writeIds = context.getValidWriteIdList();
 
     // Set up the session for driver.
     HiveConf conf = new HiveConf(hiveConf);
@@ -50,7 +53,7 @@ final class RebalanceQueryCompactor extends QueryCompactor {
     String tmpTableName = getTempTableName(table);
     Path tmpTablePath = 
QueryCompactor.Util.getCompactionResultDir(storageDescriptor, writeIds,
         conf, true, false, false, null);
-    int numBuckets = compactionInfo.numberOfBuckets;
+    int numBuckets = context.getCompactionInfo().numberOfBuckets;
     if (numBuckets <= 0) {
       //TODO: This is quite expensive, a better way should be found to get the 
number of buckets for an implicitly bucketed table
       numBuckets = Streams.stream(new 
FileUtils.AdaptingIterator<>(FileUtils.listFiles(dir.getFs(), dir.getPath(), 
true, AcidUtils.bucketFileFilter)))
@@ -60,11 +63,12 @@ final class RebalanceQueryCompactor extends QueryCompactor {
 
 
     List<String> createQueries = getCreateQueries(tmpTableName, table, 
tmpTablePath.toString());
-    List<String> compactionQueries = getCompactionQueries(table, partition, 
tmpTableName, numBuckets);
+    List<String> compactionQueries = getCompactionQueries(table, 
context.getPartition(), tmpTableName, numBuckets);
     List<String> dropQueries = getDropQueries(tmpTableName);
-    runCompactionQueries(conf, tmpTableName, storageDescriptor, writeIds, 
compactionInfo,
+    runCompactionQueries(conf, tmpTableName, storageDescriptor, writeIds, 
context.getCompactionInfo(),
         Lists.newArrayList(tmpTablePath), createQueries, compactionQueries, 
dropQueries,
         table.getParameters());
+    return true;
   }
 
   private List<String> getCreateQueries(String fullName, Table t, String 
tmpTableLocation) {
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Worker.java 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Worker.java
index 2922e0f2e04..b8e94509b81 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Worker.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Worker.java
@@ -437,14 +437,14 @@ public class Worker extends RemoteCompactorThread 
implements MetaStoreThread {
         todo Find a more generic approach to collecting files in the same 
logical bucket to compact within the same
         task (currently we're using Tez split grouping).
         */
-        Compactor compactor = compactorFactory.getCompactor(table, conf, ci, 
msc);
-        computeStats = (compactor instanceof MRCompactor && collectMrStats) || 
collectGenericStats;
+        CompactorPipeline compactorPipeline = 
compactorFactory.getCompactorPipeline(table, conf, ci, msc);
+        computeStats = (compactorPipeline.isMRCompaction() && collectMrStats) 
|| collectGenericStats;
 
         LOG.info("Starting " + ci.type.toString() + " compaction for " + 
ci.getFullPartitionName() + ", id:" +
                 ci.id + " in " + compactionTxn + " with compute stats set to " 
+ computeStats);
-        LOG.debug("Will compact id: " + ci.id + " with compactor class: " + 
compactor.getClass().getName());
 
-        compactor.run(conf, table, p, sd, tblValidWriteIds, ci, dir);
+        CompactorContext compactorContext = new CompactorContext(conf, table, 
p, sd, tblValidWriteIds, ci, dir);
+        compactorPipeline.execute(compactorContext);
 
         LOG.info("Completed " + ci.type.toString() + " compaction for " + 
ci.getFullPartitionName() + " in "
             + compactionTxn + ", marking as compacted.");
diff --git a/ql/src/test/org/apache/hadoop/hive/ql/TestTxnCommands2.java 
b/ql/src/test/org/apache/hadoop/hive/ql/TestTxnCommands2.java
index 584f810d4eb..facb1d0b550 100644
--- a/ql/src/test/org/apache/hadoop/hive/ql/TestTxnCommands2.java
+++ b/ql/src/test/org/apache/hadoop/hive/ql/TestTxnCommands2.java
@@ -76,6 +76,7 @@ import 
org.apache.hadoop.hive.ql.scheduled.ScheduledQueryExecutionService;
 import org.apache.hadoop.hive.ql.schq.MockScheduledQueryService;
 import org.apache.hadoop.hive.ql.session.SessionState;
 import org.apache.hadoop.hive.ql.txn.compactor.CompactorFactory;
+import org.apache.hadoop.hive.ql.txn.compactor.CompactorPipeline;
 import org.apache.hadoop.hive.ql.txn.compactor.MRCompactor;
 import org.apache.hadoop.hive.ql.txn.compactor.Worker;
 import org.apache.hadoop.io.Writable;
@@ -1458,7 +1459,7 @@ public class TestTxnCommands2 extends 
TxnCommandsBaseForTests {
     }).when(mrCompactor).createBaseJobConf(any(), any(), any(), any(), any(), 
any());
 
     CompactorFactory mockedFactory = Mockito.mock(CompactorFactory.class);
-    when(mockedFactory.getCompactor(any(), any(), any(), 
any())).thenReturn(mrCompactor);
+    when(mockedFactory.getCompactorPipeline(any(), any(), any(), 
any())).thenReturn(new CompactorPipeline(mrCompactor));
 
     Worker worker = Mockito.spy(new Worker(mockedFactory));
     worker.setConf(hiveConf);
diff --git a/ql/src/test/org/apache/hadoop/hive/ql/TestTxnCommands3.java 
b/ql/src/test/org/apache/hadoop/hive/ql/TestTxnCommands3.java
index 300bf007221..1b9526b873b 100644
--- a/ql/src/test/org/apache/hadoop/hive/ql/TestTxnCommands3.java
+++ b/ql/src/test/org/apache/hadoop/hive/ql/TestTxnCommands3.java
@@ -36,6 +36,7 @@ import 
org.apache.hadoop.hive.ql.io.orc.TestVectorizedOrcAcidRowBatchReader;
 import org.apache.hadoop.hive.ql.lockmgr.HiveTxnManager;
 import org.apache.hadoop.hive.ql.lockmgr.TxnManagerFactory;
 import org.apache.hadoop.hive.ql.txn.compactor.CompactorFactory;
+import org.apache.hadoop.hive.ql.txn.compactor.CompactorPipeline;
 import org.apache.hadoop.hive.ql.txn.compactor.MRCompactor;
 import org.apache.hadoop.hive.ql.txn.compactor.Worker;
 import org.junit.Assert;
@@ -491,10 +492,10 @@ public class TestTxnCommands3 extends 
TxnCommandsBaseForTests {
       invocationOnMock.callRealMethod();
       throw new RuntimeException(
         "Will cause CompactorMR to fail all opening txn and creating 
directories for compaction.");
-    }).when(mrCompactor).run(any(), any(), any(), any(), any(), any(), any());
+    }).when(mrCompactor).run(any());
 
     CompactorFactory mockedFactory = Mockito.mock(CompactorFactory.class);
-    when(mockedFactory.getCompactor(any(), any(), any(), 
any())).thenReturn(mrCompactor);
+    when(mockedFactory.getCompactorPipeline(any(), any(), any(), 
any())).thenReturn(new CompactorPipeline(mrCompactor));
 
     Worker worker = Mockito.spy(new Worker(mockedFactory));
     worker.setConf(hiveConf);
@@ -548,10 +549,10 @@ public class TestTxnCommands3 extends 
TxnCommandsBaseForTests {
       invocationOnMock.callRealMethod();
       throw new RuntimeException(
         "Will cause CompactorMR to fail all opening txn and creating 
directories for compaction.");
-    }).when(mrCompactor).run(any(), any(), any(), any(), any(), any(), any());
+    }).when(mrCompactor).run(any());
 
     CompactorFactory mockedFactory = Mockito.mock(CompactorFactory.class);
-    when(mockedFactory.getCompactor(any(), any(), any(), 
any())).thenReturn(mrCompactor);
+    when(mockedFactory.getCompactorPipeline(any(), any(), any(), 
any())).thenReturn(new CompactorPipeline(mrCompactor));
 
     Worker worker = Mockito.spy(new Worker(mockedFactory));
     worker.setConf(hiveConf);
diff --git 
a/ql/src/test/org/apache/hadoop/hive/ql/txn/compactor/TestWorker.java 
b/ql/src/test/org/apache/hadoop/hive/ql/txn/compactor/TestWorker.java
index e5c2fd50f60..72fad1c1efc 100644
--- a/ql/src/test/org/apache/hadoop/hive/ql/txn/compactor/TestWorker.java
+++ b/ql/src/test/org/apache/hadoop/hive/ql/txn/compactor/TestWorker.java
@@ -1042,7 +1042,7 @@ public class TestWorker extends CompactorTest {
     txnHandler.compact(new CompactionRequest("default", "mtwb", 
CompactionType.MINOR));
 
     CompactorFactory mockedFactory = Mockito.mock(CompactorFactory.class);
-    when(mockedFactory.getCompactor(any(), any(), any(), any())).thenThrow(new 
RuntimeException());
+    when(mockedFactory.getCompactorPipeline(any(), any(), any(), 
any())).thenThrow(new RuntimeException());
 
     Worker worker = Mockito.spy(new Worker(mockedFactory));
     worker.setConf(conf);

Reply via email to