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

krisztiankasa 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 f2e908c562c HIVE-26717: Query based Rebalance compaction on 
insert-only tables (Laszlo Vegh, reviewed by Denys Kuzmenko, Krisztian Kasa)
f2e908c562c is described below

commit f2e908c562c0a621b279987a89967122501b1e17
Author: veghlaci05 <[email protected]>
AuthorDate: Wed Jan 18 09:45:40 2023 +0100

    HIVE-26717: Query based Rebalance compaction on insert-only tables (Laszlo 
Vegh, reviewed by Denys Kuzmenko, Krisztian Kasa)
---
 .../hive/ql/txn/compactor/CompactorTestUtil.java   |   6 +-
 .../ql/txn/compactor/TestCrudCompactorOnTez.java   | 108 +++++++++++++++++++++
 .../hive/ql/txn/compactor/CompactorFactory.java    |  14 ++-
 .../hadoop/hive/ql/txn/compactor/Initiator.java    |   5 +-
 .../hadoop/hive/ql/txn/compactor/StatsUpdater.java |   1 -
 .../hadoop/hive/ql/txn/compactor/Worker.java       |  18 +++-
 .../hive/metastore/txn/CompactionTxnHandler.java   |  18 ++--
 7 files changed, 148 insertions(+), 22 deletions(-)

diff --git 
a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorTestUtil.java
 
b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorTestUtil.java
index e157f641c56..8dd6087a66a 100644
--- 
a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorTestUtil.java
+++ 
b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/CompactorTestUtil.java
@@ -102,9 +102,13 @@ class CompactorTestUtil {
    */
   static List<String> getBucketFileNames(FileSystem fs, Table table, String 
partitionName, String deltaName)
       throws IOException {
+    boolean insertOnly = AcidUtils.isInsertOnlyTable(table.getParameters());
     Path path = partitionName == null ? new Path(table.getSd().getLocation(), 
deltaName) : new Path(
         new Path(table.getSd().getLocation()), new Path(partitionName, 
deltaName));
-    return Arrays.stream(fs.listStatus(path, 
AcidUtils.bucketFileFilter)).map(FileStatus::getPath).map(Path::getName).sorted()
+    return Arrays.stream(fs.listStatus(path, insertOnly? 
AcidUtils.originalBucketFilter : AcidUtils.bucketFileFilter))
+        .map(FileStatus::getPath)
+        .map(Path::getName)
+        .sorted()
         .collect(Collectors.toList());
   }
 
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 07971abac7f..2ab2e28adab 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
@@ -25,6 +25,7 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
 
 import com.google.common.collect.Lists;
 import org.apache.commons.lang3.StringUtils;
@@ -77,6 +78,7 @@ import org.apache.orc.impl.RecordReaderImpl;
 import org.junit.Assert;
 import org.junit.Test;
 import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
 import org.mockito.internal.util.reflection.FieldSetter;
 
 import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
@@ -456,6 +458,112 @@ public class TestCrudCompactorOnTez extends 
CompactorOnTezTest {
     }
   }
 
+  @Test
+  public void 
testMMRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws 
Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVESTATSAUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new 
config
+    conf.set("tez.grouping.min-size", "200");
+    conf.set("tez.grouping.max-size", "80000");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    testDataProvider.insertTestDataPartitioned(stageTableName);
+
+    executeStatementOnDriver("drop table if exists " + tableName, driver);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) 
" +
+        "STORED AS ORC TBLPROPERTIES('transactional'='true', 
'transactional_properties'='insert_only')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " select 
a, b from " + stageTableName, driver);
+
+    //do some single inserts to have more data in the first bucket.
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values 
('12',12)", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values 
('13',13)", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values 
('14',14)", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values 
('15',15)", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values 
('16',16)", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values 
('17',17)", driver);
+
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+
+    // Verify buckets and their content before rebalance
+    Path basePath = new Path(table.getSd().getLocation(), "base_0000001");
+    List<String> bucketFileNames = CompactorTestUtil.getBucketFileNames(fs, 
table, null, "base_0000001");
+
+    Assert.assertEquals("Test setup does not match the expected: different 
buckets",
+        Arrays.asList("000000_0", "000001_0", "000002_0", "000003_0", 
"000004_0", "000005_0", "000006_0"),
+        bucketFileNames);
+
+    Map<String, Integer> expectedRowCount = new HashMap<String, Integer>() {{
+      put("000000_0", 4);
+      put("000001_0", 2);
+      put("000002_0", 1);
+      put("000003_0", 2);
+      put("000004_0", 1);
+      put("000005_0", 1);
+      put("000006_0", 1);
+    }};
+    for (String bucketFileName : bucketFileNames) {
+      try(Reader reader = OrcFile.createReader(new Path(basePath, 
bucketFileName), OrcFile.readerOptions(conf))) {
+        Assert.assertEquals("Row count in bucket " + bucketFileName + " does 
not match before compaction",
+            (int) expectedRowCount.get(bucketFileName), (int) 
reader.getNumberOfRows());
+      }
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 
'rebalance'", driver);
+
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    AtomicReference<QueryCompactor> reference = new AtomicReference<>();
+    doAnswer(invocation -> {
+      QueryCompactor result = (QueryCompactor)invocation.callRealMethod();
+      reference.set(result);
+      return result;
+    }).when(factory).getCompactor(any(), any(), any(), any());
+
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.run();
+
+    //Check if MmMajorQueryCompactor was used as fallback.
+    Assert.assertEquals("Wrong compactor were chosen.", 
MmMajorQueryCompactor.class, reference.get().getClass());
+
+    //Check if the compaction succeed
+    List<ShowCompactResponseElement> compactions = verifyCompaction(1, 
TxnStore.CLEANING_RESPONSE);
+    Assert.assertTrue("no senor", compactions.get(0).getErrorMessage()
+        .contains("Falling back to MAJOR compaction as REBALANCE compaction is 
supported only on full-acid tables."));
+
+    // Verify buckets and their content after rebalance
+    basePath = new Path(table.getSd().getLocation(), "base_0000007_v0000017");
+    bucketFileNames = CompactorTestUtil.getBucketFileNames(fs, table, null, 
"base_0000007_v0000017");
+
+    Assert.assertEquals("Buckets does not match after compaction",
+        Arrays.asList("000000_0", "000001_0", "000002_0", "000003_0", 
"000004_0"),
+        bucketFileNames);
+
+    expectedRowCount = new HashMap<String, Integer>() {{
+      put("000000_0", 4);
+      put("000001_0", 4);
+      put("000002_0", 4);
+      put("000003_0", 4);
+      put("000004_0", 2);
+    }};
+    for (String bucketFileName : bucketFileNames) {
+      try(Reader reader = OrcFile.createReader(new Path(basePath, 
bucketFileName), OrcFile.readerOptions(conf))) {
+        Assert.assertEquals("Row count in bucket " + bucketFileName + " does 
not match before compaction",
+            (int) expectedRowCount.get(bucketFileName), (int) 
reader.getNumberOfRows());
+      }
+    }
+  }
+
   @Test
   public void testCompactionShouldNotFailOnPartitionsWithBooleanField() throws 
Exception {
     conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
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 02ee9ae812e..b48071d226b 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
@@ -99,14 +99,18 @@ public final class CompactorFactory {
         case MINOR:
           return new MmMinorQueryCompactor();
         case MAJOR:
+        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();
-        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 " +
+          "for compaction!");
     }
-    throw new HiveException("Only transactional tables can be compacted, " + 
table.getTableName() + "is not suitable " +
-        "for compaction!");
+    throw new HiveException("No suitable compactor found for table: " + 
table.getTableName());
   }
 
 }
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Initiator.java 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Initiator.java
index 96a778dfcb8..42de37668bc 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Initiator.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/Initiator.java
@@ -547,9 +547,8 @@ public class Initiator extends MetaStoreCompactorThread {
     // bucket size calculation can be resource intensive if there are numerous 
deltas, so we check for rebalance
     // compaction only if the table is in an acceptable shape: no major 
compaction required. This means the number of
     // files shouldn't be too high
-    if ("tez".equalsIgnoreCase(HiveConf.getVar(conf, 
HiveConf.ConfVars.HIVE_EXECUTION_ENGINE)) &&
-        HiveConf.getBoolVar(conf, 
HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED) &&
-        AcidUtils.isFullAcidTable(tblproperties)) {
+    if (AcidUtils.isFullAcidTable(tblproperties)) {
+      // We check only full-acid tables, for insert-only tables a MAJOR 
compaction will also rebalance bucket data.
       long totalSize = baseSize + deltaSize;
       long minimumSize = MetastoreConf.getLongVar(conf, 
MetastoreConf.ConfVars.COMPACTOR_INITIATOR_REBALANCE_MINIMUM_SIZE);
       if (totalSize > minimumSize) {
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/StatsUpdater.java 
b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/StatsUpdater.java
index 50d04f8b1b2..698346b9b72 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/StatsUpdater.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/txn/compactor/StatsUpdater.java
@@ -21,7 +21,6 @@ import org.apache.hadoop.hive.common.ValidTxnList;
 import org.apache.hadoop.hive.conf.HiveConf;
 import org.apache.hadoop.hive.metastore.IMetaStoreClient;
 import org.apache.hadoop.hive.metastore.Warehouse;
-import org.apache.hadoop.hive.metastore.api.CompactionType;
 import org.apache.hadoop.hive.metastore.txn.CompactionInfo;
 import org.apache.hadoop.hive.ql.DriverUtils;
 import org.apache.hadoop.hive.ql.session.SessionState;
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 74aa7a7be09..2922e0f2e04 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
@@ -268,6 +268,7 @@ public class Worker extends RemoteCompactorThread 
implements MetaStoreThread {
       findNextCompactRequest.setWorkerVersion(runtimeVersion);
       findNextCompactRequest.setPoolName(this.getPoolName());
       ci = 
CompactionInfo.optionalCompactionInfoStructToInfo(msc.findNextCompact(findNextCompactRequest));
+      ci.errorMessage = "";
       LOG.info("Processing compaction request {}", ci);
 
       if (ci == null) {
@@ -315,10 +316,19 @@ public class Worker extends RemoteCompactorThread 
implements MetaStoreThread {
         return false;
       }
 
-      if (!ci.type.equals(CompactionType.REBALANCE) && ci.numberOfBuckets > 0) 
{
-        if (LOG.isWarnEnabled()) {
-          LOG.warn("Only the REBALANCE compaction accepts the number of 
buckets clause (CLUSTERED INTO {N} BUCKETS). " +
-              "Since the compaction request is {}, it will be ignored.", 
ci.type);
+      if (LOG.isWarnEnabled()) {
+        boolean insertOnly = 
AcidUtils.isInsertOnlyTable(table.getParameters());
+        if (ci.type.equals(CompactionType.REBALANCE) && insertOnly) {
+          ci.errorMessage += "Falling back to MAJOR compaction as REBALANCE 
compaction is supported only on full-acid tables. ";
+          LOG.warn("REBALANCE compaction requested on an insert-only table 
({}). Falling back to MAJOR compaction as " +
+              "REBALANCE compaction is supported only on full-acid tables", 
table.getTableName());
+        }
+        if ((!ci.type.equals(CompactionType.REBALANCE) || insertOnly) && 
ci.numberOfBuckets > 0) {
+          ci.errorMessage += "Only REBALANCE compaction on a full-acid table 
accepts the number of buckets clause. " +
+              "(CLUSTERED INTO {N} BUCKETS).";
+          LOG.warn("Only REBALANCE compaction on a full-acid table accepts the 
number of buckets clause " +
+                  "(CLUSTERED INTO {N} BUCKETS). Since the compaction request 
is {} and the table is {}, it will be ignored.",
+              ci.type, insertOnly ? "insert-only" : "full-acid");
         }
       }
 
diff --git 
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/txn/CompactionTxnHandler.java
 
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/txn/CompactionTxnHandler.java
index 59350e32a3a..3a960756301 100644
--- 
a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/txn/CompactionTxnHandler.java
+++ 
b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/txn/CompactionTxnHandler.java
@@ -342,15 +342,17 @@ class CompactionTxnHandler extends TxnHandler {
   public void markCompacted(CompactionInfo info) throws MetaException {
     try {
       Connection dbConn = null;
-      Statement stmt = null;
+      PreparedStatement pstmt = null;
       try {
         dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED, 
connPoolCompaction);
-        stmt = dbConn.createStatement();
-        String s = "UPDATE \"COMPACTION_QUEUE\" SET \"CQ_STATE\" = '" + 
READY_FOR_CLEANING + "', "
-            + "\"CQ_WORKER_ID\" = NULL"
-            + " WHERE \"CQ_ID\" = " + info.id;
-        LOG.debug("Going to execute update <{}>", s);
-        int updCnt = stmt.executeUpdate(s);
+        String sql = "UPDATE \"COMPACTION_QUEUE\" SET \"CQ_STATE\" = ?, "
+            + "\"CQ_WORKER_ID\" = NULL, \"CQ_ERROR_MESSAGE\" = ? WHERE 
\"CQ_ID\" = ?";
+        pstmt = dbConn.prepareStatement(sql);
+        pstmt.setString(1, Character.toString(READY_FOR_CLEANING));
+        pstmt.setString(2, StringUtils.isNotBlank(info.errorMessage) ? 
info.errorMessage : null);
+        pstmt.setLong(3, info.id);
+        LOG.debug("Going to execute update <{}>", sql);
+        int updCnt = pstmt.executeUpdate();
         if (updCnt != 1) {
           LOG.error("Unable to set cq_state={} for compaction record: {}. 
updCnt={}", READY_FOR_CLEANING, info, updCnt);
           LOG.debug("Going to rollback");
@@ -366,7 +368,7 @@ class CompactionTxnHandler extends TxnHandler {
         throw new MetaException("Unable to connect to transaction database " +
           e.getMessage());
       } finally {
-        closeStmt(stmt);
+        closeStmt(pstmt);
         closeDbConn(dbConn);
       }
     } catch (RetryException e) {

Reply via email to