You are viewing a plain text version of this content. The canonical link for it is here.
Posted to gitbox@hive.apache.org by "InvisibleProgrammer (via GitHub)" <gi...@apache.org> on 2026/05/15 07:34:20 UTC

[PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

InvisibleProgrammer opened a new pull request, #6487:
URL: https://github.com/apache/hive/pull/6487

   Rebalance tests are sensitive and the hard-coded assertions need to be modified regularly. 
   Some examples: 
   - https://github.com/apache/hive/commit/388e80690373a064d1fa464579a8b22173395ef2
   - https://github.com/apache/hive/commit/413069ea0faeb893fe78faa215b08a70ece80595#diff-dedd154465fd42855d9d6710d54553660dae87405ce2e4ea931475de1d5bb816
   - https://github.com/apache/hive/commit/6e1f1ccf2aca58af4be06d6ceea1aa2b877a5d08#diff-dedd154465fd42855d9d6710d54553660dae87405ce2e4ea931475de1d5bb816
   ... 
   
   There are two causes identified: 
   - Firstly, the number of buckets and even the order of the elements inside a bucket depends on the version string of Orc: https://issues.apache.org/jira/browse/HIVE-29536?focusedCommentId=18080335&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-18080335 (Thanks @thomasrebele to digging into it)
   - Secondly, the base directory can change as well (like here: https://github.com/apache/hive/commit/1a90d278be9af1dc5b8aeb4c4cca24febac91936#diff-dedd154465fd42855d9d6710d54553660dae87405ce2e4ea931475de1d5bb816L199) 
   
   ### What changes were proposed in this pull request?
   The goal of the change is to stabilize those tests by doing two things: 
   - Rebalance assertions are not hard-coded. Instead of that, we can check if the buckets are balanced or not and if all the data is available.
   - Base folder can be searched dinamically
   
   Please note: I also refactored the code little bit and extracted rebalance compaction tests into a new class. 
   
   ### Why are the changes needed?
   We experienced regular and serious regression issues due to the effect of the orc version number.
   
   
   ### Does this PR introduce _any_ user-facing change?
   No
   
   ### How was this patch tested?
   With the existing tests.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3274628547


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertTrue(rowInfo.writeId == writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);
+      }
+    }
+
+    // check if we got all the expected values
+    assertEquals(0, expectedData.size()); // we have found all the elements in a proper order
+  }
+
+  private TestDataProvider prepareRebalanceTestData(String tableName) throws Exception {
+    final String stageTableName = "stage_" + tableName;
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    testDataProvider.insertTestData(stageTableName, true);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "STORED AS ORC TBLPROPERTIES('transactional'='true')", 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);
+
+    /*
+     check if the test data is unbalanced
+     balanced if all the buckets contains between n / bucket count and n / bucket count + bucket count rows
+     where n is the number of rows in the table.
+     In our test case, we inserted 6 extra rows into the first bucket so we can say it is properly unbalanced
+     if the first bucket has 6 more elements than the second one.
+    */
+    Assert.assertFalse(isBalanced(tableName, testDataProvider));
+
+    // Please note, as the test tests rebalance compaction, not insert overwrite, it is not necessary to test if
+    // we have the exact same data after preparing the test data as we had at the source table.

Review Comment:
   Sure. Let me add a check on the number of records. Usually, I'm against doing assertions at the arrange part of the tests but as I saw, those tests are already full with them so I don't think if it can cause a misunderstanding. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3383505857


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {

Review Comment:
   The reason is not documented. My personal opinion is checking the data before compaction means we don't trust in a simple insert overwrite statement in Hive. 
   What do you think? Should we keep the original test logic or remove the checks before compaction? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "kuczoram (via GitHub)" <gi...@apache.org>.
kuczoram merged PR #6487:
URL: https://github.com/apache/hive/pull/6487


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3279676576


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestCrudCompactorOnTez.java:
##########
@@ -642,15 +167,15 @@ public void secondCompactionShouldBeRefusedBeforeEnqueueing() throws Exception {
     } catch (CommandProcessorException e) {
       String errorMessage = ErrorMsg.COMPACTION_REFUSED.format(dbName, tableName, "",
           "Compaction is already scheduled with state='ready for cleaning' and id=" + resp.getId());
-      Assert.assertEquals(errorMessage, e.getCauseMessage());
-      Assert.assertEquals(ErrorMsg.COMPACTION_REFUSED.getErrorCode(), e.getErrorCode());
+      assertEquals(errorMessage, e.getCauseMessage());
+      assertEquals(ErrorMsg.COMPACTION_REFUSED.getErrorCode(), e.getErrorCode());

Review Comment:
   I tried to find it but couldn't :( 
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "thomasrebele (via GitHub)" <gi...@apache.org>.
thomasrebele commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3248048830


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);

Review Comment:
   Maybe add a comment that without explicit ORDER BY, there's an implicit order defined by the rebalance compaction query that fixes the order?



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;

Review Comment:
   I think a different formula is needed here. For example, if we have 11 rows and 10 buckets, the optimal records in bucket would be `11/10 = 1`. Then `maximumRecordCountInABucket = 1 + 10 - 1 = 10`. If one bucket contains 10 rows, then another bucket contains 1 row, and the remaining 8 buckets are empty. I would not call that distribution "balanced".



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertTrue(rowInfo.writeId == writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);
+      }
+    }
+
+    // check if we got all the expected values
+    assertEquals(0, expectedData.size()); // we have found all the elements in a proper order
+  }
+
+  private TestDataProvider prepareRebalanceTestData(String tableName) throws Exception {
+    final String stageTableName = "stage_" + tableName;
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    testDataProvider.insertTestData(stageTableName, true);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "STORED AS ORC TBLPROPERTIES('transactional'='true')", 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);
+
+    /*
+     check if the test data is unbalanced
+     balanced if all the buckets contains between n / bucket count and n / bucket count + bucket count rows

Review Comment:
   See comment https://github.com/apache/hive/pull/6487/changes#r3248007538.
   
   Nit: `contain` (without s)



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertTrue(rowInfo.writeId == writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);
+      }
+    }
+
+    // check if we got all the expected values
+    assertEquals(0, expectedData.size()); // we have found all the elements in a proper order
+  }
+
+  private TestDataProvider prepareRebalanceTestData(String tableName) throws Exception {
+    final String stageTableName = "stage_" + tableName;
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    testDataProvider.insertTestData(stageTableName, true);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "STORED AS ORC TBLPROPERTIES('transactional'='true')", 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);
+
+    /*
+     check if the test data is unbalanced
+     balanced if all the buckets contains between n / bucket count and n / bucket count + bucket count rows
+     where n is the number of rows in the table.
+     In our test case, we inserted 6 extra rows into the first bucket so we can say it is properly unbalanced
+     if the first bucket has 6 more elements than the second one.
+    */
+    Assert.assertFalse(isBalanced(tableName, testDataProvider));
+
+    // Please note, as the test tests rebalance compaction, not insert overwrite, it is not necessary to test if
+    // we have the exact same data after preparing the test data as we had at the source table.

Review Comment:
   I think it would still be helpful to check the data here, in order to catch problems from other parts of Hive early. Maybe simply check the number of records in the table.



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestCrudCompactorOnTez.java:
##########
@@ -642,15 +167,15 @@ public void secondCompactionShouldBeRefusedBeforeEnqueueing() throws Exception {
     } catch (CommandProcessorException e) {
       String errorMessage = ErrorMsg.COMPACTION_REFUSED.format(dbName, tableName, "",
           "Compaction is already scheduled with state='ready for cleaning' and id=" + resp.getId());
-      Assert.assertEquals(errorMessage, e.getCauseMessage());
-      Assert.assertEquals(ErrorMsg.COMPACTION_REFUSED.getErrorCode(), e.getErrorCode());
+      assertEquals(errorMessage, e.getCauseMessage());
+      assertEquals(ErrorMsg.COMPACTION_REFUSED.getErrorCode(), e.getErrorCode());

Review Comment:
   I would prefer to do refactors in a separate ticket/commit. The [official guideline](https://hive.apache.org/community/resources/howtocontribute/#submitting-a-pr) says "reformat code unrelated to the issue being fixed: formatting changes should be separate patches/commits;". While this is not strictly a formatting change, it feels quite close to it.



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertTrue(rowInfo.writeId == writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);

Review Comment:
   To avoid looking up the element twice, the return value of [Set#remove()](https://docs.oracle.com/en/java/javase/26/docs/api/java.base/java/util/Set.html#remove(java.lang.Object)) could be used.



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertTrue(rowInfo.writeId == writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);
+      }
+    }
+
+    // check if we got all the expected values
+    assertEquals(0, expectedData.size()); // we have found all the elements in a proper order
+  }
+
+  private TestDataProvider prepareRebalanceTestData(String tableName) throws Exception {
+    final String stageTableName = "stage_" + tableName;
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    testDataProvider.insertTestData(stageTableName, true);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "STORED AS ORC TBLPROPERTIES('transactional'='true')", 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);
+
+    /*
+     check if the test data is unbalanced
+     balanced if all the buckets contains between n / bucket count and n / bucket count + bucket count rows
+     where n is the number of rows in the table.
+     In our test case, we inserted 6 extra rows into the first bucket so we can say it is properly unbalanced
+     if the first bucket has 6 more elements than the second one.
+    */
+    Assert.assertFalse(isBalanced(tableName, testDataProvider));
+
+    // Please note, as the test tests rebalance compaction, not insert overwrite, it is not necessary to test if
+    // we have the exact same data after preparing the test data as we had at the source table.
+    return testDataProvider;
+  }
+
+  private boolean isBalanced(String tableName, TestDataProvider testDataProvider ) throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+
+    // Assert that we have multiple buckets
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+    assertTrue(bucketFilenames.size() > 1);
+
+    int bucketCount = bucketFilenames.size();
+
+    if (bucketCount == 1) {
+      // nothing to rebalance with a single bucket
+      return true;
+    }
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+    List<String>[] bucketData = new ArrayList[bucketCount];
+    for (int i = 0; i < bucketCount; i++) {
+      bucketData[i] = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+    }
+
+    int allRecordCount = Arrays.stream(bucketData)
+        .map(bucket -> bucket.size())
+        .reduce(0, Integer::sum);
+
+    int optimalRecordsInBucket = allRecordCount / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;

Review Comment:
   See comment https://github.com/apache/hive/pull/6487/changes#r3248007538



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertTrue(rowInfo.writeId == writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);
+      }
+    }
+
+    // check if we got all the expected values
+    assertEquals(0, expectedData.size()); // we have found all the elements in a proper order
+  }
+
+  private TestDataProvider prepareRebalanceTestData(String tableName) throws Exception {
+    final String stageTableName = "stage_" + tableName;
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    testDataProvider.insertTestData(stageTableName, true);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "STORED AS ORC TBLPROPERTIES('transactional'='true')", 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);
+
+    /*
+     check if the test data is unbalanced
+     balanced if all the buckets contains between n / bucket count and n / bucket count + bucket count rows
+     where n is the number of rows in the table.
+     In our test case, we inserted 6 extra rows into the first bucket so we can say it is properly unbalanced
+     if the first bucket has 6 more elements than the second one.
+    */
+    Assert.assertFalse(isBalanced(tableName, testDataProvider));
+
+    // Please note, as the test tests rebalance compaction, not insert overwrite, it is not necessary to test if
+    // we have the exact same data after preparing the test data as we had at the source table.
+    return testDataProvider;
+  }
+
+  private boolean isBalanced(String tableName, TestDataProvider testDataProvider ) throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+
+    // Assert that we have multiple buckets
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+    assertTrue(bucketFilenames.size() > 1);

Review Comment:
   This assert should be removed (we're checking for `== 1` [later](https://github.com/apache/hive/pull/6487/changes#diff-8d6f209a650ce79ac88d045aa974a9c8adcebaf37054c86774b85f2ec87dcc31R605)).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6487:
URL: https://github.com/apache/hive/pull/6487#issuecomment-4665898879

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [7 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_duplicated_lines_density&view=list)  
     
   <!-- sqra-placement-anchor -->
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487)
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6487:
URL: https://github.com/apache/hive/pull/6487#issuecomment-4742184131

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [9 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_duplicated_lines_density&view=list)  
     
   <!-- sqra-placement-anchor -->
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487)
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "thomasrebele (via GitHub)" <gi...@apache.org>.
thomasrebele commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3279492877


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertTrue(rowInfo.writeId == writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);

Review Comment:
   What I wanted to say:
   With
   ```
   assertTrue(expectedData.remove(rowData));
   ```
   we could avoid the call to `expectedData.contains(rowData)`. It's a bit less readable, so I'll leave it up to you to decide which one to take.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "thomasrebele (via GitHub)" <gi...@apache.org>.
thomasrebele commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3279492877


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertTrue(rowInfo.writeId == writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);

Review Comment:
   What I wanted to say,
   with
   ```
   assertTrue(expectedData.remove(rowData));
   ```
   we could avoid the call to `expectedData.contains(rowData)`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6487:
URL: https://github.com/apache/hive/pull/6487#issuecomment-4500962307

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [17 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_duplicated_lines_density&view=list)  
     
   <!-- sqra-placement-anchor -->
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487)
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3279671446


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;

Review Comment:
   I tried to find it but couldn't :( 



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;

Review Comment:
   I tried to find it but couldn't :( 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3383483058


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,

Review Comment:
   I kept test cases that are not affected by the flakiness problem. For example, in this test case we run a compaction that defines the buckets explicitly (`CLUSTERED INTO 4 BUCKETS`) so that rebalance compaction always produces the exact same clusters. The flaky test cases are flaky because we cannot guarantee if it ends with 3 or 4 buckets.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6487:
URL: https://github.com/apache/hive/pull/6487#issuecomment-4458450460

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [21 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_duplicated_lines_density&view=list)  
     
   <!-- sqra-placement-anchor -->
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487)
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "thomasrebele (via GitHub)" <gi...@apache.org>.
thomasrebele commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3304223037


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);

Review Comment:
   Thanks for checking! That's what I meant, if there's no `ORDER BY` clause, then the order is automatically fixed based on writeId, bucketId, and rowId. For comparison, here the query for a test case with a rebalance compaction containing an `ORDER BY` clause (`TestCrudCompactorOnTez#testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock`):
   
   ```
   INSERT overwrite table default.tmp_compactor_rebalance_test_1778591703603
   select 0, t2.writeId, t2.rowId DIV CEIL(numRows / 4), t2.rowId, t2.writeId, t2.data
   from
     (select count(ROW__ID.writeId) over() as numRows,
       MAX(ROW__ID.writeId) over() as writeId,
       row_number() OVER (ORDER BY b DESC) - 1 AS rowId,
       NAMED_STRUCT('a', `a`, 'b', `b`) as data
       from default.rebalance_test ORDER BY b DESC) t2
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3373715980


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  @SuppressWarnings("java:S2925")
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(
+        fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int maximumRecordCountInABucket = (expectedData.size() + bucketCount - 1) / bucketCount;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertEquals(writeId, rowInfo.writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);
+      }
+    }
+
+    // check if we got all the expected values
+    assertEquals(0, expectedData.size()); // we have found all the elements in a proper order
+  }
+
+  private TestDataProvider prepareRebalanceTestData(String tableName) throws Exception {
+    final String stageTableName = "stage_" + tableName;
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    testDataProvider.insertTestData(stageTableName, true);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "STORED AS ORC TBLPROPERTIES('transactional'='true')", 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);
+
+    // Make sure we have all the records persisted
+    List<String> allRecords = execSelectAndDumpData(
+        "SELECT * FROM " + tableName, driver, "Dumping data from test table, " + tableName);
+    Assert.assertEquals(18, allRecords.size());
+
+    /*
+     check if the test data is unbalanced
+     Balanced if all the buckets contain between n / bucket count and n / bucket count + bucket count rows,
+     where n is the number of rows in the table.
+     In our test case, we inserted 6 extra rows into the first bucket so, we can say it is properly unbalanced
+     if the first bucket has 6 more elements than the second one.
+    */
+    Assert.assertFalse(isBalanced(tableName, testDataProvider));
+
+    // Please note, as the test tests rebalance compaction, not insert overwrite, it is not necessary to test if
+    // we have the exact same data after preparing the test data as we had at the source table.
+    return testDataProvider;
+  }
+
+  private boolean isBalanced(String tableName, TestDataProvider testDataProvider) throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+
+    // Assert that we have multiple buckets
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+    assertTrue(bucketFilenames.size() > 1);
+
+    int bucketCount = bucketFilenames.size();
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+    List<String>[] bucketData = new ArrayList[bucketCount];
+    for (int i = 0; i < bucketCount; i++) {
+      bucketData[i] = testDataProvider.getBucketData(
+          table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+    }
+
+    int allRecordCount = Arrays.stream(bucketData)
+        .map(Collection::size)
+        .reduce(0, Integer::sum);
+
+    int optimalRecordsInBucket = allRecordCount / bucketCount;
+    int maximumRecordCountInABucket = (allRecordCount + bucketCount - 1) / bucketCount;
+
+    for (int i = 0; i < bucketCount; i++) {
+      if (bucketData[i].size() > maximumRecordCountInABucket || bucketData[i].size() < optimalRecordsInBucket) {
+        return false;
+      }
+    }

Review Comment:
   Renamed. My next commit will contain the change. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3381060763


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  @SuppressWarnings("java:S2925")
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(
+        fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case

Review Comment:
   Done. The next commit will contain the change.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3383545959


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));

Review Comment:
   I'm pretty sure they are leftovers from various attempts. I had a couple of iterations when I tried to decide the proper data struct for those assertions. Let me check them. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3303778095


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertTrue(rowInfo.writeId == writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);
+      }
+    }
+
+    // check if we got all the expected values
+    assertEquals(0, expectedData.size()); // we have found all the elements in a proper order
+  }
+
+  private TestDataProvider prepareRebalanceTestData(String tableName) throws Exception {
+    final String stageTableName = "stage_" + tableName;
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    testDataProvider.insertTestData(stageTableName, true);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "STORED AS ORC TBLPROPERTIES('transactional'='true')", 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);
+
+    /*
+     check if the test data is unbalanced
+     balanced if all the buckets contains between n / bucket count and n / bucket count + bucket count rows
+     where n is the number of rows in the table.
+     In our test case, we inserted 6 extra rows into the first bucket so we can say it is properly unbalanced
+     if the first bucket has 6 more elements than the second one.
+    */
+    Assert.assertFalse(isBalanced(tableName, testDataProvider));
+
+    // Please note, as the test tests rebalance compaction, not insert overwrite, it is not necessary to test if
+    // we have the exact same data after preparing the test data as we had at the source table.
+    return testDataProvider;
+  }
+
+  private boolean isBalanced(String tableName, TestDataProvider testDataProvider ) throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+
+    // Assert that we have multiple buckets
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+    assertTrue(bucketFilenames.size() > 1);

Review Comment:
   Removed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3381146186


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  @SuppressWarnings("java:S2925")
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }

Review Comment:
   I checked the usages of TestDataProvider.getBucketData and also check agains similar queries, like `select ROW__ID, * from`. 
   Based on my findings, I wouldn't move it to a common place yet - all the other actual data tests are just simple String comparisons. 
   At this point I see no other place in the code when it would be useful. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3383574540


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config

Review Comment:
   No, I remove this.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3381095183


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  @SuppressWarnings("java:S2925")
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }

Review Comment:
   Interesting idea. Let me check if we have immediate gain sharing this code (can we use it at some other existing tests). 
   Forcing code to a common place right after when we introduce them is a tricky question: if we were right, there will be something that people tend to use and re-use. If we were wrong, we usually create 'shared' classes, DTOs, utility classes - with only one usage and make the code harder to understand and maintain. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6487:
URL: https://github.com/apache/hive/pull/6487#issuecomment-4506775535

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [2 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.7% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_duplicated_lines_density&view=list)  
     
   <!-- sqra-placement-anchor -->
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487)
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6487:
URL: https://github.com/apache/hive/pull/6487#issuecomment-4749870530

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_duplicated_lines_density&view=list)  
     
   <!-- sqra-placement-anchor -->
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487)
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3274460872


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);

Review Comment:
   It is a test case. I wonder how it helps understanding rebalance compaction or the test case itself. 
   
   It is an information that I would really like as part of a full description of the feature, in the class that responsible for doing the feature and in the official documentation. 
   
   What do you think? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6487:
URL: https://github.com/apache/hive/pull/6487#issuecomment-4547990537

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [2 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_duplicated_lines_density&view=list)  
     
   <!-- sqra-placement-anchor -->
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487)
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3383694006


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);

Review Comment:
   Extracted them into a method.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6487:
URL: https://github.com/apache/hive/pull/6487#issuecomment-4706847348

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [7 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_duplicated_lines_density&view=list)  
     
   <!-- sqra-placement-anchor -->
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487)
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3279665955


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);

Review Comment:
   I tried to find it but couldn't :( 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3274120820


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestCrudCompactorOnTez.java:
##########
@@ -642,15 +167,15 @@ public void secondCompactionShouldBeRefusedBeforeEnqueueing() throws Exception {
     } catch (CommandProcessorException e) {
       String errorMessage = ErrorMsg.COMPACTION_REFUSED.format(dbName, tableName, "",
           "Compaction is already scheduled with state='ready for cleaning' and id=" + resp.getId());
-      Assert.assertEquals(errorMessage, e.getCauseMessage());
-      Assert.assertEquals(ErrorMsg.COMPACTION_REFUSED.getErrorCode(), e.getErrorCode());
+      assertEquals(errorMessage, e.getCauseMessage());
+      assertEquals(ErrorMsg.COMPACTION_REFUSED.getErrorCode(), e.getErrorCode());

Review Comment:
   Errr... Sure. Let me check this. I suppose I have to reduce my IDE's capabilities and it can be done. Honestly, I just removed some code blocks from this class. Those changes were handled by the IDE and I didn't even notice them. 
   
   However, I think the official guideline is a little bit obsolete: I'm pretty sure I saw a discussion somewhere about the opposite, like please do not do trivial changes like small reformats, formatting, etc to reduce the load on the precommit jobs. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3303761896


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;

Review Comment:
   It makes sense. Let me rewrite it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3373726349


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  @SuppressWarnings("java:S2925")
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(
+        fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */

Review Comment:
   I can move it. As it is a private method in a test class, I don't see the difference. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3383442894


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  @SuppressWarnings("java:S2925")
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }

Review Comment:
   Refactored. The next commit will contain the change.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3383541108


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {

Review Comment:
   I wanted to minimize the changes and focus on tests that are flaky. I haven't seen a flakiness in that test case. Honestly, I don't know why it is so stable. 
   
   Should I rewrite all the rebalance test cases? It would be a future proof solution. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "kuczoram (via GitHub)" <gi...@apache.org>.
kuczoram commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3334180866


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);

Review Comment:
   Would it make sense to extract these config settings into one place? 



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  @SuppressWarnings("java:S2925")
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();

Review Comment:
   Why do you hard-code the expected values? Why not just run a select before and after the compaction and compare the results?



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  @SuppressWarnings("java:S2925")
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(
+        fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case

Review Comment:
   The rowId should be checked as well. It has to be increasing within a file, otherwise the delete operation won't work.



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,

Review Comment:
   I thought that the idea of this fix is to have one universal way of validating the result of the rebalance compaction and get rid of the hard-coded data. Why did you keep this? Now we have some tests which using the new way of validation and some tests which using the old way of validation. I don't really like it. We should use one approach to validate the data and use it in all rebalance tests. 



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {

Review Comment:
   I am just wondering why we need this data validation before the compaction? Do you know anything about the reason? Does it matter how the rows look like before the compaction or the intention here is rather to check if the data is imbalanced? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3373701310


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  @SuppressWarnings("java:S2925")
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(
+        fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int maximumRecordCountInABucket = (expectedData.size() + bucketCount - 1) / bucketCount;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertEquals(writeId, rowInfo.writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);
+      }
+    }
+
+    // check if we got all the expected values
+    assertEquals(0, expectedData.size()); // we have found all the elements in a proper order
+  }
+
+  private TestDataProvider prepareRebalanceTestData(String tableName) throws Exception {
+    final String stageTableName = "stage_" + tableName;
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    testDataProvider.insertTestData(stageTableName, true);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "STORED AS ORC TBLPROPERTIES('transactional'='true')", 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);
+
+    // Make sure we have all the records persisted
+    List<String> allRecords = execSelectAndDumpData(
+        "SELECT * FROM " + tableName, driver, "Dumping data from test table, " + tableName);
+    Assert.assertEquals(18, allRecords.size());
+
+    /*
+     check if the test data is unbalanced
+     Balanced if all the buckets contain between n / bucket count and n / bucket count + bucket count rows,
+     where n is the number of rows in the table.
+     In our test case, we inserted 6 extra rows into the first bucket so, we can say it is properly unbalanced
+     if the first bucket has 6 more elements than the second one.
+    */
+    Assert.assertFalse(isBalanced(tableName, testDataProvider));
+
+    // Please note, as the test tests rebalance compaction, not insert overwrite, it is not necessary to test if
+    // we have the exact same data after preparing the test data as we had at the source table.
+    return testDataProvider;
+  }
+
+  private boolean isBalanced(String tableName, TestDataProvider testDataProvider) throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+
+    // Assert that we have multiple buckets
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+    assertTrue(bucketFilenames.size() > 1);
+
+    int bucketCount = bucketFilenames.size();
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+    List<String>[] bucketData = new ArrayList[bucketCount];
+    for (int i = 0; i < bucketCount; i++) {
+      bucketData[i] = testDataProvider.getBucketData(
+          table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+    }
+
+    int allRecordCount = Arrays.stream(bucketData)
+        .map(Collection::size)
+        .reduce(0, Integer::sum);
+
+    int optimalRecordsInBucket = allRecordCount / bucketCount;
+    int maximumRecordCountInABucket = (allRecordCount + bucketCount - 1) / bucketCount;
+
+    for (int i = 0; i < bucketCount; i++) {
+      if (bucketData[i].size() > maximumRecordCountInABucket || bucketData[i].size() < optimalRecordsInBucket) {
+        return false;
+      }
+    }
+
+    return true;
+  }
+
+  private void verifyRebalance(TestDataProvider testDataProvider, String tableName, String partitionName,
+      String[][] expectedBucketContent, String[] bucketNames) throws Exception {
+    // Verify buckets and their content after rebalance
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Buckets does not match after compaction", Arrays.asList(bucketNames),
+        CompactorTestUtil.getBucketFileNames(fs, table, partitionName, findTheBaseFolder(table, partitionName, fs)));
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+    for (int i = 0; i < expectedBucketContent.length; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBucketContent[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+  }
+
+  private String findTheBaseFolder(Table table, String partitionName, FileSystem fs) throws IOException {
+    Path searchPath = partitionName == null ? new Path(table.getSd().getLocation(), "base_*_v*") : new Path(
+        new Path(table.getSd().getLocation()), new Path(partitionName,  "base_*_v*"));
+
+    return Arrays.stream(
+        fs.globStatus(searchPath, AcidUtils.baseFileFilter))
+        .map(FileStatus::getPath)
+        .map(Path::getName)
+        .sorted()

Review Comment:
   I know about two scenarios when we can have multiple base files: 
   
   - major compaction, after the compaction finished and we are waiting for the cleaner. 
   - partitioned table
   
   As far I remember, we have no such test case. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6487:
URL: https://github.com/apache/hive/pull/6487#issuecomment-4744756756

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [9 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6487&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6487&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6487&metric=new_duplicated_lines_density&view=list)  
     
   <!-- sqra-placement-anchor -->
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6487)
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3279665955


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);

Review Comment:
   I tried to find it but couldn't :( 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "thomasrebele (via GitHub)" <gi...@apache.org>.
thomasrebele commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3279622974


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;

Review Comment:
   I think you meant "if the optimal row count is exactly 1". I just used these numbers to make my point clear. If we distribute the 11 rows to 5 buckets, the `optimalRecordsInBucket` would be 2. Then `maximumRecordCountInABucket = 2 + 5 - 1 = 6`. So we could get a distribution of 6 rows in the first bucket, 5 rows in the second, and the remaining 3 buckets are empty.
   
   As far as I understood the rebalancing, we want to redistribute the $n :=$ `allRecordCount` rows to the $m :=$ `bucketCount` buckets, so that the number of rows of two buckets differs by at most 1. This is slightly related to the [Pigeonhole principle](https://en.wikipedia.org/wiki/Pigeonhole_principle).
   
   If we distribute $n$ rows to $m$ buckets under the above condition, the buckets have at least $\Big\lfloor \frac{n}{m} \Big\rfloor$ rows and at most $\Big\lceil \frac{n}{m} \Big\rceil$ rows. Using an integer division `/`, we can rewrite $\Big\lceil \frac{n}{m} \Big\rceil$ as
   ```
   int maximumRecordCountInABucket = (allRecordCount + bucketCount - 1) / bucketCount;
   ```
   
   Afaik, this is the exact upper limit to expect if the buckets are balanced. I think this formula should be used here.



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);

Review Comment:
   It would help understand why we assert the exact order of the rows is verified in this test case. I had wondered a short time, until I realized that the order is fixed.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3381146186


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  @SuppressWarnings("java:S2925")
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }

Review Comment:
   I checked the usages of TestDataProvider.getBucketData and also check agains similar queries, like `select ROW__ID, * from`. 
   Based on my findings, I wouldn't move it to a common place yet - all the other actual data tests are just simple String comparisons. 
   At this point I see no other place in the code when it would be useful. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3383466457


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  @SuppressWarnings("java:S2925")
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();

Review Comment:
   We had a discussion about this before. That solution is the closest to checking the data files themselves. And actually, this method runs a selects the data and checks the data based on a result of the select statement. For the select see TestData.getBucketData or getStructuredBucketData. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3303702262


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);

Review Comment:
   I double-checked it: I wouldn't say the query fixes the order. I see no explicit order by in case there is no order by in the rebalance compaction command. 
   But the compaction itself rewriting the order based on write id, bucket id and row id: 
   ```sql
   INSERT overwrite table default.tmp_compactor_rebalance_test_1779799240490 
   select 0, t2.writeId, t2.rowId DIV CEIL(numRows / 4), t2.rowId, t2.writeId, t2.data 
   from (
     select 
       count(ROW__ID.writeId) over() as numRows, 
       ROW__ID.writeId as writeId, 
       row_number() OVER (order by ROW__ID.writeId ASC, 
       ROW__ID.bucketId ASC, ROW__ID.rowId ASC) - 1 AS rowId, 
       NAMED_STRUCT('a', `a`, 'b', `b`) as data 
     from default.rebalance_test 
     order by ROW__ID.writeId ASC, ROW__ID.bucketId ASC, ROW__ID.rowId ASC) t2
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3303702262


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);

Review Comment:
   I double-checked it: I wouldn't say the query fixes the order. I see no explicit order by in case there is no order by in the rebalance compaction command. 
   But the compaction itself rewriting the order based on write id, bucket id and row id: 
   ```sql
   INSERT overwrite table default.tmp_compactor_rebalance_test_1779799240490 
   select 0, t2.writeId, t2.rowId DIV CEIL(numRows / 4), t2.rowId, t2.writeId, t2.data from (
     select 
       count(ROW__ID.writeId) over() as numRows, 
       ROW__ID.writeId as writeId, 
       row_number() OVER (order by ROW__ID.writeId ASC, 
       ROW__ID.bucketId ASC, ROW__ID.rowId ASC) - 1 AS rowId, 
       NAMED_STRUCT('a', `a`, 'b', `b`) as data 
     from default.rebalance_test 
     order by ROW__ID.writeId ASC, ROW__ID.bucketId ASC, ROW__ID.rowId ASC) t2
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3303702262


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);

Review Comment:
   I double-checked it: I wouldn't say the query fixes the order. I see no explicit order by in case there is no order by in the rebalance compaction command. 
   But the compaction itself rewriting the order based on write id, bucket id and row id: 
   ```sql
   INSERT overwrite table default.tmp_compactor_rebalance_test_1779799240490 select 0, t2.writeId, t2.rowId DIV CEIL(numRows / 4), t2.rowId, t2.writeId, t2.data from (select count(ROW__ID.writeId) over() as numRows, ROW__ID.writeId as writeId, row_number() OVER (order by ROW__ID.writeId ASC, ROW__ID.bucketId ASC, ROW__ID.rowId ASC) - 1 AS rowId, NAMED_STRUCT('a', `a`, 'b', `b`) as data from default.rebalance_test order by ROW__ID.writeId ASC, ROW__ID.bucketId ASC, ROW__ID.rowId ASC) t2
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3303770376


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertTrue(rowInfo.writeId == writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);

Review Comment:
   I keep it due to readability.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3274516197


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;

Review Comment:
   It makes totally sense. Let me think about that. What about maximumRecordCountInABucket = 2 * optimalRecordsInBucket - 1? 
   
   It wouldn't be totally accurate as your edge case is about what if the optimal bucket count is exactly 1. We have no test case for that and it more a theoretical than a practical question: for buckets with optimal element size 1, we should allow having buckets with 2 elements. But I cannot imagine a practical use case when it actually happens. For every other bucket size, 2 x bucketsize - 1 sounds fine: it allows 'bucket overflow', so when the row_id division happens, we have space to put the remainders. But it also says if we have 2x bucketsize number of elements, there is no way the table is balanced. 
   
   Does it makes sense? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "InvisibleProgrammer (via GitHub)" <gi...@apache.org>.
InvisibleProgrammer commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3274532684


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertTrue(rowInfo.writeId == writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);

Review Comment:
   The assertion right before this line does the exact same check. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "thomasrebele (via GitHub)" <gi...@apache.org>.
thomasrebele commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3274384450


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestCrudCompactorOnTez.java:
##########
@@ -642,15 +167,15 @@ public void secondCompactionShouldBeRefusedBeforeEnqueueing() throws Exception {
     } catch (CommandProcessorException e) {
       String errorMessage = ErrorMsg.COMPACTION_REFUSED.format(dbName, tableName, "",
           "Compaction is already scheduled with state='ready for cleaning' and id=" + resp.getId());
-      Assert.assertEquals(errorMessage, e.getCauseMessage());
-      Assert.assertEquals(ErrorMsg.COMPACTION_REFUSED.getErrorCode(), e.getErrorCode());
+      assertEquals(errorMessage, e.getCauseMessage());
+      assertEquals(ErrorMsg.COMPACTION_REFUSED.getErrorCode(), e.getErrorCode());

Review Comment:
   Hm, reducing the workload on the CI is indeed a valid concern. Is it possible to merge this PR with a rebase, instead of a squash? That way the import related changes could be move to a separate commit in the same PR. I wished Github had an interactive rebase feature for merging PRs.
   
   I had a quick search, but couldn't find the discussion. Do you have a link by chance?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "thomasrebele (via GitHub)" <gi...@apache.org>.
thomasrebele commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3279492877


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,654 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    Table table = msClient.getTable("default", tableName);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals("Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" + compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    Table table = msClient.getTable("default", tableName);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int optimalRecordsInBucket = expectedData.size() / bucketCount;
+    int maximumRecordCountInABucket = optimalRecordsInBucket + bucketCount - 1;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertTrue(rowInfo.writeId == writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);

Review Comment:
   What I wanted to say:
   With
   ```
   assertTrue(expectedData.remove(rowData));
   ```
   we could avoid the call to `expectedData.contains(rowData)`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29536: Stabilize rebalance compaction tests [hive]

Posted by "zabetak (via GitHub)" <gi...@apache.org>.
zabetak commented on code in PR #6487:
URL: https://github.com/apache/hive/pull/6487#discussion_r3340151159


##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config

Review Comment:
   Is the comment still relevant? Are we going to have 3 buckets at the end of the compaction?



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {

Review Comment:
   In some rebalance tests like this one we use explicit buckets (`exptectedBuckets`) along with `verifyRebalance` and in others we use just data (`expectedData`) together with `verifyDataAfterCompaction`. How do we determine if a test should use one or the other?



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  @SuppressWarnings("java:S2925")
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(
+        fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */

Review Comment:
   This could be a Javadoc comment since it seems to be more than just an implementation detail.



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));

Review Comment:
   It's a bit strange that for some data we use directly `Set#add` and for other we pass through `Set#addAll` and `List`.



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  @SuppressWarnings("java:S2925")
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }

Review Comment:
   This record classes could potentially be used by other compaction tests but putting them here makes them bit harder to find. Possibly a better fit would be `TestDataProvider` associated with APIs that return RowInfo objects instead of strings. Anyways just an idea, I am fine to leave them here as well.



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  @SuppressWarnings("java:S2925")
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(
+        fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int maximumRecordCountInABucket = (expectedData.size() + bucketCount - 1) / bucketCount;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertEquals(writeId, rowInfo.writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);
+      }
+    }
+
+    // check if we got all the expected values
+    assertEquals(0, expectedData.size()); // we have found all the elements in a proper order
+  }
+
+  private TestDataProvider prepareRebalanceTestData(String tableName) throws Exception {
+    final String stageTableName = "stage_" + tableName;
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    testDataProvider.insertTestData(stageTableName, true);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "STORED AS ORC TBLPROPERTIES('transactional'='true')", 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);
+
+    // Make sure we have all the records persisted
+    List<String> allRecords = execSelectAndDumpData(
+        "SELECT * FROM " + tableName, driver, "Dumping data from test table, " + tableName);
+    Assert.assertEquals(18, allRecords.size());
+
+    /*
+     check if the test data is unbalanced
+     Balanced if all the buckets contain between n / bucket count and n / bucket count + bucket count rows,
+     where n is the number of rows in the table.
+     In our test case, we inserted 6 extra rows into the first bucket so, we can say it is properly unbalanced
+     if the first bucket has 6 more elements than the second one.
+    */
+    Assert.assertFalse(isBalanced(tableName, testDataProvider));
+
+    // Please note, as the test tests rebalance compaction, not insert overwrite, it is not necessary to test if
+    // we have the exact same data after preparing the test data as we had at the source table.
+    return testDataProvider;
+  }
+
+  private boolean isBalanced(String tableName, TestDataProvider testDataProvider) throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+
+    // Assert that we have multiple buckets
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+    assertTrue(bucketFilenames.size() > 1);
+
+    int bucketCount = bucketFilenames.size();
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+    List<String>[] bucketData = new ArrayList[bucketCount];
+    for (int i = 0; i < bucketCount; i++) {
+      bucketData[i] = testDataProvider.getBucketData(
+          table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+    }
+
+    int allRecordCount = Arrays.stream(bucketData)
+        .map(Collection::size)
+        .reduce(0, Integer::sum);
+
+    int optimalRecordsInBucket = allRecordCount / bucketCount;
+    int maximumRecordCountInABucket = (allRecordCount + bucketCount - 1) / bucketCount;
+
+    for (int i = 0; i < bucketCount; i++) {
+      if (bucketData[i].size() > maximumRecordCountInABucket || bucketData[i].size() < optimalRecordsInBucket) {
+        return false;
+      }
+    }
+
+    return true;
+  }
+
+  private void verifyRebalance(TestDataProvider testDataProvider, String tableName, String partitionName,
+      String[][] expectedBucketContent, String[] bucketNames) throws Exception {
+    // Verify buckets and their content after rebalance
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Buckets does not match after compaction", Arrays.asList(bucketNames),
+        CompactorTestUtil.getBucketFileNames(fs, table, partitionName, findTheBaseFolder(table, partitionName, fs)));
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+    for (int i = 0; i < expectedBucketContent.length; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBucketContent[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+  }
+
+  private String findTheBaseFolder(Table table, String partitionName, FileSystem fs) throws IOException {
+    Path searchPath = partitionName == null ? new Path(table.getSd().getLocation(), "base_*_v*") : new Path(
+        new Path(table.getSd().getLocation()), new Path(partitionName,  "base_*_v*"));
+
+    return Arrays.stream(
+        fs.globStatus(searchPath, AcidUtils.baseFileFilter))
+        .map(FileStatus::getPath)
+        .map(Path::getName)
+        .sorted()

Review Comment:
   Can we have more than one base? If yes is it a valid scenario?



##########
itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/txn/compactor/TestRebalanceCompactor.java:
##########
@@ -0,0 +1,671 @@
+/*
+ * 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 com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.GetTableRequest;
+import org.apache.hadoop.hive.metastore.api.ShowCompactResponseElement;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.txn.TxnStore;
+import org.apache.hadoop.hive.ql.Driver;
+import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
+import org.apache.hadoop.hive.ql.io.AcidUtils;
+import org.apache.hadoop.hive.ql.io.BucketCodec;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.hadoop.hive.ql.ErrorMsg.TXN_ABORTED;
+import static org.apache.hadoop.hive.ql.TxnCommandsBaseForTests.runWorker;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.dropTables;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.execSelectAndDumpData;
+import static org.apache.hadoop.hive.ql.txn.compactor.TestCompactorBase.executeStatementOnDriver;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+
+public class TestRebalanceCompactor extends CompactorOnTezTest {
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondOptimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(true);
+  }
+
+  @Test
+  public void testRebalanceCompactionWithParallelDeleteAsSecondPessimisticLock() throws Exception {
+    testRebalanceCompactionWithParallelDeleteAsSecond(false);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTableWithOrder() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+    runWorker(conf);
+
+    driver.close();
+    driver = new Driver(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+    expectedData.add(new RowData("12", 12L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    // set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    // Run rebalance compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    // Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002","bucket_00003"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfPartitionedImplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "1");
+    driver = new Driver(conf);
+
+    final String stageTableName = "stage_rebalance_test";
+    final String tableName = "rebalance_test";
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    executeStatementOnDriver("insert into " + stageTableName +" values " +
+            "('1',1,'yesterday'), ('1',2,'yesterday'), ('1',3, 'yesterday'), ('1',4, 'yesterday'), " +
+            "('2',1,'today'), ('2',2,'today'), ('2',3,'today'), ('2',4, 'today'), " +
+            "('3',1,'tomorrow'), ('3',2,'tomorrow'), ('3',3,'tomorrow'), ('3',4,'tomorrow')",
+        driver);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "PARTITIONED BY (ds string) STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT OVERWRITE TABLE " + tableName + " partition (ds='tomorrow') 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,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('13',13,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('14',14,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('15',15,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('16',16,'tomorrow')", driver);
+    executeStatementOnDriver("INSERT INTO TABLE " + tableName + " values ('17',17,'tomorrow')", driver);
+
+    // Verify buckets and their content before rebalance in partition ds=tomorrow
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    FileSystem fs = FileSystem.get(conf);
+    assertEquals("Test setup does not match the expected: different buckets",
+        Arrays.asList("bucket_00000_0", "bucket_00001_0", "bucket_00002_0"),
+        CompactorTestUtil.getBucketFileNames(fs, table, "ds=tomorrow", "base_0000001"));
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":2,\"bucketid\":536870912,\"rowid\":0}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":536870912,\"rowid\":0}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":536870912,\"rowid\":0}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":536870912,\"rowid\":0}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":536870912,\"rowid\":0}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":536870912,\"rowid\":0}\t17\t17\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":0}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":1}\t3\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":2}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":3}\t3\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":0}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":1}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":2}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":3}\t1\t4\ttomorrow",
+        },
+    };
+    for(int i = 0; i < 3; i++) {
+      assertEquals("rebalanced bucket " + i, Arrays.asList(expectedBuckets[i]),
+          testDataProvider.getBucketData(tableName, BucketCodec.V1.encode(options.bucket(i)) + ""));
+    }
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " PARTITION (ds='tomorrow') COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t2\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t2\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t2\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t2\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t3\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":5}\t3\t2\ttomorrow",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t3\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t4\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t1\t1\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t1\t2\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":10}\t1\t3\ttomorrow",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":11}\t1\t4\ttomorrow",
+        },
+        {
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12\ttomorrow",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13\ttomorrow",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14\ttomorrow",
+            "{\"writeid\":5,\"bucketid\":537001984,\"rowid\":15}\t15\t15\ttomorrow",
+            "{\"writeid\":6,\"bucketid\":537001984,\"rowid\":16}\t16\t16\ttomorrow",
+            "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":17}\t17\t17\ttomorrow",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, "ds=tomorrow", expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002"});
+  }
+
+  @Test
+  public void testRebalanceCompactionOfNotPartitionedExplicitlyBucketedTable() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    final String tableName = "rebalance_test";
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "CLUSTERED BY(a) INTO 4 BUCKETS STORED AS ORC TBLPROPERTIES('transactional'='true')", driver);
+    executeStatementOnDriver(
+        "INSERT INTO TABLE " + tableName + " values ('11',11),('22',22),('33',33),('44',44)", driver
+    );
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance'", driver);
+    runWorker(conf);
+
+    //Check if the compaction is refused
+    List<ShowCompactResponseElement> compacts = verifyCompaction(1, TxnStore.REFUSED_RESPONSE);
+    assertEquals(
+        "Expecting error message 'Cannot execute rebalancing compaction on bucketed tables.' and found:" +
+              compacts.get(0).getState(),
+        "Cannot execute rebalancing compaction on bucketed tables.", compacts.get(0).getErrorMessage());
+  }
+
+  @Test
+  public void testRebalanceCompactionNotPartitionedExplicitBucketNumbers() throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' CLUSTERED INTO 4 BUCKETS", driver);
+    runWorker(conf);
+
+    verifyCompaction(1,  TxnStore.CLEANING_RESPONSE);
+
+    String[][] expectedBuckets = new String[][] {
+        {
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":0}\t5\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":1}\t6\t2",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":2}\t6\t3",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":3}\t6\t4",
+            "{\"writeid\":1,\"bucketid\":536870912,\"rowid\":4}\t5\t2",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":5}\t5\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":6}\t2\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":7}\t3\t3",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":8}\t4\t4",
+            "{\"writeid\":1,\"bucketid\":536936448,\"rowid\":9}\t4\t3",
+        },
+        {
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":10}\t2\t3",
+            "{\"writeid\":1,\"bucketid\":537001984,\"rowid\":11}\t3\t4",
+            "{\"writeid\":2,\"bucketid\":537001984,\"rowid\":12}\t12\t12",
+            "{\"writeid\":3,\"bucketid\":537001984,\"rowid\":13}\t13\t13",
+            "{\"writeid\":4,\"bucketid\":537001984,\"rowid\":14}\t14\t14",
+        },
+        {
+            "{\"writeid\":5,\"bucketid\":537067520,\"rowid\":15}\t15\t15",
+            "{\"writeid\":6,\"bucketid\":537067520,\"rowid\":16}\t16\t16",
+            "{\"writeid\":7,\"bucketid\":537067520,\"rowid\":17}\t17\t17",
+        },
+    };
+    verifyRebalance(testDataProvider, tableName, null, expectedBuckets,
+        new String[] {"bucket_00000", "bucket_00001", "bucket_00002", "bucket_00003"});
+  }
+
+  @SuppressWarnings("java:S2925")
+  private void testRebalanceCompactionWithParallelDeleteAsSecond(boolean optimisticLock) throws Exception {
+    conf.setBoolVar(HiveConf.ConfVars.COMPACTOR_CRUD_QUERY_BASED, true);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_COMPACTOR_GATHER_STATS, false);
+    conf.setBoolVar(HiveConf.ConfVars.HIVE_STATS_AUTOGATHER, false);
+    conf.setBoolVar(HiveConf.ConfVars.TXN_WRITE_X_LOCK, optimisticLock);
+
+    //set grouping size to have 3 buckets, and re-create driver with the new config
+    conf.set("tez.grouping.min-size", "400");
+    conf.set("tez.grouping.max-size", "5000");
+    driver = new Driver(conf);
+
+    final String tableName = "rebalance_test";
+    TestDataProvider testDataProvider = prepareRebalanceTestData(tableName);
+
+    //Try to do a rebalancing compaction
+    executeStatementOnDriver("ALTER TABLE " + tableName + " COMPACT 'rebalance' ORDER BY b DESC", driver);
+
+    CountDownLatch startDelete = new CountDownLatch(1);
+    CountDownLatch endDelete = new CountDownLatch(1);
+    CompactorFactory factory = Mockito.spy(CompactorFactory.getInstance());
+    doAnswer(invocation -> {
+      Object result = invocation.callRealMethod();
+      startDelete.countDown();
+      Thread.sleep(1000);
+      return result;
+    }).when(factory).getCompactorPipeline(any(), any(), any(), any());
+
+    Worker worker = new Worker(factory);
+    worker.setConf(conf);
+    worker.init(new AtomicBoolean(true));
+    worker.start();
+
+    if (!startDelete.await(10, TimeUnit.SECONDS)) {
+      throw new RuntimeException("Waiting for the compaction to start timed out!");
+    }
+
+    boolean aborted = false;
+    try {
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } catch (CommandProcessorException e) {
+      if (optimisticLock) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = true, the transaction must be retried instead of being aborted.");
+      }
+      aborted = true;
+      Assert.assertEquals(12, e.getResponseCode());
+      Assert.assertEquals(TXN_ABORTED.getErrorCode(), e.getErrorCode());
+
+      // Delete the record, so the rest of the test can be the same in both cases
+      executeStatementOnDriver("DELETE FROM " + tableName + " WHERE b = 12", driver);
+    } finally {
+      if(!optimisticLock && !aborted) {
+        Assert.fail("In case of TXN_WRITE_X_LOCK = false, the transaction must be aborted instead of being retried.");
+      }
+    }
+    endDelete.countDown();
+
+    worker.join();
+
+    driver.close();
+    driver = new Driver(conf);
+
+    List<String> result = execSelectAndDumpData("select * from " + tableName + " WHERE b = 12", driver,
+        "Dumping data for " + tableName + " after load:");
+    assertEquals(0, result.size());
+
+    //Check if the compaction succeed
+    verifyCompaction(1, TxnStore.CLEANING_RESPONSE);
+
+    // Populate expected data
+    Set<RowData> expectedData = new HashSet<>();
+
+    expectedData.add(new RowData("17", 17L));
+    expectedData.add(new RowData("16", 16L));
+    expectedData.add(new RowData("15", 15L));
+    expectedData.add(new RowData("14", 14L));
+    expectedData.add(new RowData("13", 13L));
+
+    // Adding the '4' group
+    expectedData.addAll(List.of(
+        new RowData("6", 4L),
+        new RowData("3", 4L),
+        new RowData("4", 4L),
+        new RowData("2", 4L),
+        new RowData("5", 4L)
+    ));
+
+    // Adding the '3' group
+    expectedData.addAll(List.of(
+        new RowData("2", 3L),
+        new RowData("3", 3L),
+        new RowData("6", 3L),
+        new RowData("4", 3L),
+        new RowData("5", 3L)
+    ));
+
+    // Adding the '2' group
+    expectedData.add(new RowData("6", 2L));
+    expectedData.add(new RowData("5", 2L));
+
+    verifyDataAfterCompaction(tableName, expectedData, testDataProvider);
+  }
+
+  record RowData(String colA, Long colB) {}
+
+  record RowInfo(long writeId, long bucketId, long rowId, RowData rowData) {
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static RowInfo fromRawString(String row) throws JsonProcessingException {
+      // Example row data to parse: "{\"writeid\":7,\"bucketid\":537001984,\"rowid\":10}\t5\t4",
+
+      String[] parts = row.split("\t", 3);
+
+      JsonNode json = MAPPER.readTree(parts[0]);
+
+      return new RowInfo(
+          json.get("writeid").asLong(),
+          json.get("bucketid").asLong(),
+          json.get("rowid").asLong(),
+          new RowData(
+              parts[1], // colA
+              Long.parseLong(parts[2])  // colB
+          )
+      );
+    }
+  }
+
+  private void verifyDataAfterCompaction(String tableName, Set<RowData> expectedData, TestDataProvider testDataProvider)
+      throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(
+        fs, table, null, "base_0000001");
+
+    int bucketCount = bucketFilenames.size();
+    assertTrue(bucketCount > 0);
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+
+    /*
+      Validate the data after the test case
+        - the table is balanced (or if not, only numberOfDeletedRows amount of rows are missing
+        - there is only one writeId
+        - buckets has unique bucketId and the bucketId doesn't change inside a bucket
+        - data is sorted by column b (so the order of column a is not predictable)
+        - all the required value present
+     */
+
+    int maximumRecordCountInABucket = (expectedData.size() + bucketCount - 1) / bucketCount;
+
+    long previousValueForColB = Long.MAX_VALUE;
+
+    for (int i = 0; i < bucketCount; i++) {
+      List<String> bucket = testDataProvider.getBucketData(table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+
+      int bucketSize = bucket.size();
+      assertTrue(bucketSize <= maximumRecordCountInABucket);
+
+      long bucketId = -1L;
+      long writeId = -1L;
+
+      for (String row : bucket) {
+        RowInfo rowInfo = RowInfo.fromRawString(row);
+
+        // Check if writeId doesn't change
+        if (writeId == -1L) {
+          // we are at the first element
+          writeId = rowInfo.writeId;
+        } else {
+          assertEquals(writeId, rowInfo.writeId);
+        }
+
+        // Check if bucketId doesn't change inside the bucket
+        if (bucketId == -1) {
+          // we are at the first element of the bucket
+          bucketId = rowInfo.bucketId;
+        } else {
+          assertEquals(bucketId, rowInfo.bucketId);
+        }
+
+        // Check if the data is sorted by colB desc
+        RowData rowData = rowInfo.rowData;
+        assertTrue(rowData.colB <= previousValueForColB);
+        previousValueForColB = rowData.colB;
+
+        // Check if all the necessary data persist
+        assertTrue(expectedData.contains(rowData));
+        expectedData.remove(rowData);
+      }
+    }
+
+    // check if we got all the expected values
+    assertEquals(0, expectedData.size()); // we have found all the elements in a proper order
+  }
+
+  private TestDataProvider prepareRebalanceTestData(String tableName) throws Exception {
+    final String stageTableName = "stage_" + tableName;
+
+    TestDataProvider testDataProvider = new TestDataProvider();
+    testDataProvider.createFullAcidTable(stageTableName, true, false);
+    testDataProvider.insertTestData(stageTableName, true);
+
+    dropTables(driver, tableName);
+    executeStatementOnDriver("CREATE TABLE " + tableName + "(a string, b int) " +
+        "STORED AS ORC TBLPROPERTIES('transactional'='true')", 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);
+
+    // Make sure we have all the records persisted
+    List<String> allRecords = execSelectAndDumpData(
+        "SELECT * FROM " + tableName, driver, "Dumping data from test table, " + tableName);
+    Assert.assertEquals(18, allRecords.size());
+
+    /*
+     check if the test data is unbalanced
+     Balanced if all the buckets contain between n / bucket count and n / bucket count + bucket count rows,
+     where n is the number of rows in the table.
+     In our test case, we inserted 6 extra rows into the first bucket so, we can say it is properly unbalanced
+     if the first bucket has 6 more elements than the second one.
+    */
+    Assert.assertFalse(isBalanced(tableName, testDataProvider));
+
+    // Please note, as the test tests rebalance compaction, not insert overwrite, it is not necessary to test if
+    // we have the exact same data after preparing the test data as we had at the source table.
+    return testDataProvider;
+  }
+
+  private boolean isBalanced(String tableName, TestDataProvider testDataProvider) throws Exception {
+    FileSystem fs = FileSystem.get(conf);
+    GetTableRequest getTableRequest = new GetTableRequest("default", tableName);
+    Table table = msClient.getTable(getTableRequest);
+
+    // Assert that we have multiple buckets
+    List<String> bucketFilenames = CompactorTestUtil.getBucketFileNames(fs, table, null, "base_0000001");
+    assertTrue(bucketFilenames.size() > 1);
+
+    int bucketCount = bucketFilenames.size();
+
+    AcidOutputFormat.Options options = new AcidOutputFormat.Options(conf);
+    List<String>[] bucketData = new ArrayList[bucketCount];
+    for (int i = 0; i < bucketCount; i++) {
+      bucketData[i] = testDataProvider.getBucketData(
+          table.getTableName(), BucketCodec.V1.encode(options.bucket(i)) + "");
+    }
+
+    int allRecordCount = Arrays.stream(bucketData)
+        .map(Collection::size)
+        .reduce(0, Integer::sum);
+
+    int optimalRecordsInBucket = allRecordCount / bucketCount;
+    int maximumRecordCountInABucket = (allRecordCount + bucketCount - 1) / bucketCount;
+
+    for (int i = 0; i < bucketCount; i++) {
+      if (bucketData[i].size() > maximumRecordCountInABucket || bucketData[i].size() < optimalRecordsInBucket) {
+        return false;
+      }
+    }

Review Comment:
   nit: As far as I understand, `optimalRecordsInBucket` is a `lowerBound` and `maximumRecordCountInAAbucket` is an `upperBound` for the bucket size. Using the lower/upperBound naming could make the code a bit more easier to follow.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org