You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hudi.apache.org by yi...@apache.org on 2024/05/15 00:34:19 UTC

(hudi) branch branch-0.x updated (b71f03776ba -> 31d24d7600b)

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

yihua pushed a change to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git


 discard b71f03776ba [HUDI-7637] Make StoragePathInfo Comparable (#11050)
 discard ab3741cd528 [HUDI-7635] Add default block size and openSeekable APIs to HoodieStorage (#11048)
 discard 6ac417341eb [HUDI-7636] Make StoragePath Serializable (#11049)
 discard 6238a9dd9a3 [MINOR] Remove redundant TestStringUtils in hudi-common (#11046)
 discard 07120a64e81 [HUDI-7633] Use try with resources for AutoCloseable (#11045)
 discard 74f91c70474 [HUDI-4228] Clean up literal usage in Hudi CLI argument check (#11042)
 discard 6df621aec1f [HUDI-7626] Propagate UserGroupInformation from the main thread to the new thread of timeline service threadpool (#11039)
 discard 1c2e2b5341c [HUDI-7625] Avoid unnecessary rewrite for metadata table (#11038)
 discard 9bca6153adc [HUDI-7578] Avoid unnecessary rewriting to improve performance (#11028)
 discard 6b0c67a5c9f [MINOR] Rename location to path in `makeQualified` (#11037)
 discard 862575a546b [MINOR] Remove redundant lines in StreamSync and TestStreamSyncUnitTests (#11027)
 discard 21a1b7806db [HUDI-6762] Removed usages of MetadataRecordsGenerationParams (#10962)
 discard 38701e37637 [HUDI-7619] Removed code duplicates in HoodieTableMetadataUtil (#11022)
 discard 3a9ca9ecd0a [HUDI-7584] Always read log block lazily and remove readBlockLazily argument (#11015)
 discard ba521081ff6 [HUDI-7615] Mark a few write configs with the correct sinceVersion (#11012)
 discard a5745c6d550 [HUDI-7606] Unpersist RDDs after table services, mainly compaction and clustering (#11000)
 discard b5b04af9d1e [HUDI-7616] Avoid multiple cleaner plans and deprecate hoodie.clean.allow.multiple (#11013)
 discard 3e6bb0d77bc [HUDI-7378] Fix Spark SQL DML with custom key generator (#10615)
 discard 50caab4ee11 [HUDI-7601] Add heartbeat mechanism to refresh lock (#10994)
 discard 1013610ee8b [HUDI-7290]  Don't assume ReplaceCommits are always Clustering (#10479)
 discard ca6c4f96dcc [HUDI-7605] Allow merger strategy to be set in spark sql writer (#10999)
 discard 804b88d212c [HUDI-6441] Passing custom Headers with Hudi Callback URL (#10970)
 discard 0caed098c35 [HUDI-7391] HoodieMetadataMetrics should use Metrics instance for metrics registry (#10635)
 discard 604c8fb7c81 [HUDI-7600] Shutdown ExecutorService when HiveMetastoreBasedLockProvider is closed (#10993)
 discard 271a22712c2 [MINOR] Fix BUG: HoodieLogFormatWriter: unable to close output stream for log file HoodieLogFile{xxx} (#10989)
 discard a1d601c5866 [HUDI-7597] Add logs of Kafka offsets when the checkpoint is out of bound (#10987)
 discard 92ee83c0c7c [HUDI-7583] Read log block header only for the schema and instant time (#10984)
 discard 1ed67a94fd4 [HUDI-7556] Fixing false positive validation with MDT validator (#10986)
     new 86968a6b9e4 [HUDI-7556] Fixing false positive validation with MDT validator (#10986)
     new a9c7eebd0fc [HUDI-7583] Read log block header only for the schema and instant time (#10984)
     new ef96676f39e [HUDI-7597] Add logs of Kafka offsets when the checkpoint is out of bound (#10987)
     new 705e5f59f28 [MINOR] Fix BUG: HoodieLogFormatWriter: unable to close output stream for log file HoodieLogFile{xxx} (#10989)
     new 86f6bdf991e [HUDI-7600] Shutdown ExecutorService when HiveMetastoreBasedLockProvider is closed (#10993)
     new 858fde11fdd [HUDI-7391] HoodieMetadataMetrics should use Metrics instance for metrics registry (#10635)
     new db53c7af20c [HUDI-6441] Passing custom Headers with Hudi Callback URL (#10970)
     new e9cd05376a3 [HUDI-7605] Allow merger strategy to be set in spark sql writer (#10999)
     new f9ffb646462 [HUDI-7290]  Don't assume ReplaceCommits are always Clustering (#10479)
     new 4aa23beec97 [HUDI-7601] Add heartbeat mechanism to refresh lock (#10994)
     new 922e1eb87d0 [HUDI-7378] Fix Spark SQL DML with custom key generator (#10615)
     new f12cd043095 [HUDI-7616] Avoid multiple cleaner plans and deprecate hoodie.clean.allow.multiple (#11013)
     new 7e5871a4634 [HUDI-7606] Unpersist RDDs after table services, mainly compaction and clustering (#11000)
     new 89ff73de175 [HUDI-7615] Mark a few write configs with the correct sinceVersion (#11012)
     new e39fedfa5b6 [HUDI-7584] Always read log block lazily and remove readBlockLazily argument (#11015)
     new 59a1b28849f [HUDI-7619] Removed code duplicates in HoodieTableMetadataUtil (#11022)
     new 566039010cf [HUDI-6762] Removed usages of MetadataRecordsGenerationParams (#10962)
     new f0cf58d8c99 [MINOR] Remove redundant lines in StreamSync and TestStreamSyncUnitTests (#11027)
     new 51f7557070d [MINOR] Rename location to path in `makeQualified` (#11037)
     new ce9ff1cb21a [HUDI-7578] Avoid unnecessary rewriting to improve performance (#11028)
     new a5304f586f4 [HUDI-7625] Avoid unnecessary rewrite for metadata table (#11038)
     new 3cdb6faefcb [HUDI-7626] Propagate UserGroupInformation from the main thread to the new thread of timeline service threadpool (#11039)
     new 6fc3ad4060e [HUDI-4228] Clean up literal usage in Hudi CLI argument check (#11042)
     new d20f8175b95 [HUDI-7633] Use try with resources for AutoCloseable (#11045)
     new bfb83c8eb8c [MINOR] Remove redundant TestStringUtils in hudi-common (#11046)
     new 9b0945c7817 [HUDI-7636] Make StoragePath Serializable (#11049)
     new 6c152dbef8a [HUDI-7635] Add default block size and openSeekable APIs to HoodieStorage (#11048)
     new 31d24d7600b [HUDI-7637] Make StoragePathInfo Comparable (#11050)

This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version.  This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:

 * -- * -- B -- O -- O -- O   (b71f03776ba)
            \
             N -- N -- N   refs/heads/branch-0.x (31d24d7600b)

You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.

Any revisions marked "omit" are not gone; other references still
refer to them.  Any revisions marked "discard" are gone forever.

The 28 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../apache/hudi/utilities/TestHoodieMetadataTableValidator.java    | 7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)


(hudi) 09/28: [HUDI-7290] Don't assume ReplaceCommits are always Clustering (#10479)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit f9ffb64646207ba595559c89fbd415e3b8c7f3f0
Author: Jon Vexler <jb...@gmail.com>
AuthorDate: Fri Apr 12 00:08:37 2024 -0400

    [HUDI-7290]  Don't assume ReplaceCommits are always Clustering (#10479)
    
    * fix all usages not in tests
    * do pass through and fix
    * fix test that didn't actually use a cluster commit
    * make method private and fix naming
    * revert write markers changes
    
    ---------
    
    Co-authored-by: Jonathan Vexler <=>
---
 .../hudi/client/BaseHoodieTableServiceClient.java  | 10 ++++---
 .../org/apache/hudi/table/marker/WriteMarkers.java |  2 ++
 .../table/timeline/HoodieDefaultTimeline.java      | 31 ++++++++++++++++++++--
 .../hudi/common/table/timeline/HoodieTimeline.java | 11 ++++++++
 .../table/view/AbstractTableFileSystemView.java    |  5 +---
 .../table/view/TestHoodieTableFileSystemView.java  | 30 +++++++++++++++++++--
 .../clustering/ClusteringPlanSourceFunction.java   |  2 +-
 .../java/org/apache/hudi/util/ClusteringUtil.java  |  2 +-
 .../apache/hudi/utilities/HoodieClusteringJob.java | 12 ++++-----
 9 files changed, 86 insertions(+), 19 deletions(-)

diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieTableServiceClient.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieTableServiceClient.java
index 909581687d4..e408dc7a779 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieTableServiceClient.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieTableServiceClient.java
@@ -444,8 +444,12 @@ public abstract class BaseHoodieTableServiceClient<I, T, O> extends BaseHoodieCl
     HoodieTimeline pendingClusteringTimeline = table.getActiveTimeline().filterPendingReplaceTimeline();
     HoodieInstant inflightInstant = HoodieTimeline.getReplaceCommitInflightInstant(clusteringInstant);
     if (pendingClusteringTimeline.containsInstant(inflightInstant)) {
-      table.rollbackInflightClustering(inflightInstant, commitToRollback -> getPendingRollbackInfo(table.getMetaClient(), commitToRollback, false));
-      table.getMetaClient().reloadActiveTimeline();
+      if (pendingClusteringTimeline.isPendingClusterInstant(inflightInstant.getTimestamp())) {
+        table.rollbackInflightClustering(inflightInstant, commitToRollback -> getPendingRollbackInfo(table.getMetaClient(), commitToRollback, false));
+        table.getMetaClient().reloadActiveTimeline();
+      } else {
+        throw new HoodieClusteringException("Non clustering replace-commit inflight at timestamp " + clusteringInstant);
+      }
     }
     clusteringTimer = metrics.getClusteringCtx();
     LOG.info("Starting clustering at {}", clusteringInstant);
@@ -575,7 +579,7 @@ public abstract class BaseHoodieTableServiceClient<I, T, O> extends BaseHoodieCl
 
     // if just inline schedule is enabled
     if (!config.inlineClusteringEnabled() && config.scheduleInlineClustering()
-        && table.getActiveTimeline().filterPendingReplaceTimeline().empty()) {
+        && !table.getActiveTimeline().getLastPendingClusterInstant().isPresent()) {
       // proceed only if there are no pending clustering
       metadata.addMetadata(HoodieClusteringConfig.SCHEDULE_INLINE_CLUSTERING.key(), "true");
       inlineScheduleClustering(extraMetadata);
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/marker/WriteMarkers.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/marker/WriteMarkers.java
index 01c8c99618a..f8fbd13b1c2 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/marker/WriteMarkers.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/marker/WriteMarkers.java
@@ -87,6 +87,7 @@ public abstract class WriteMarkers implements Serializable {
       HoodieTimeline pendingReplaceTimeline = activeTimeline.filterPendingReplaceTimeline();
       // TODO If current is compact or clustering then create marker directly without early conflict detection.
       // Need to support early conflict detection between table service and common writers.
+      // ok to use filterPendingReplaceTimeline().containsInstant because early conflict detection is not relevant for insert overwrite as well
       if (pendingCompactionTimeline.containsInstant(instantTime) || pendingReplaceTimeline.containsInstant(instantTime)) {
         return create(partitionPath, fileName, type, false);
       }
@@ -127,6 +128,7 @@ public abstract class WriteMarkers implements Serializable {
       HoodieTimeline pendingReplaceTimeline = activeTimeline.filterPendingReplaceTimeline();
       // TODO If current is compact or clustering then create marker directly without early conflict detection.
       // Need to support early conflict detection between table service and common writers.
+      // ok to use filterPendingReplaceTimeline().containsInstant because early conflict detection is not relevant for insert overwrite as well
       if (pendingCompactionTimeline.containsInstant(instantTime) || pendingReplaceTimeline.containsInstant(instantTime)) {
         return create(partitionPath, fileName, type, true);
       }
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/timeline/HoodieDefaultTimeline.java b/hudi-common/src/main/java/org/apache/hudi/common/table/timeline/HoodieDefaultTimeline.java
index a26bed061d6..737ec0ca5d9 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/timeline/HoodieDefaultTimeline.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/timeline/HoodieDefaultTimeline.java
@@ -503,13 +503,40 @@ public class HoodieDefaultTimeline implements HoodieTimeline {
         .findFirst());
   }
 
+  @Override
+  public Option<HoodieInstant> getFirstPendingClusterInstant() {
+    return getLastOrFirstPendingClusterInstant(false);
+  }
+
   @Override
   public Option<HoodieInstant> getLastPendingClusterInstant() {
-    return  Option.fromJavaOptional(filterPendingReplaceTimeline()
-        .getReverseOrderedInstants()
+    return getLastOrFirstPendingClusterInstant(true);
+  }
+
+  private Option<HoodieInstant> getLastOrFirstPendingClusterInstant(boolean isLast) {
+    HoodieTimeline replaceTimeline = filterPendingReplaceTimeline();
+    Stream<HoodieInstant> replaceStream;
+    if (isLast) {
+      replaceStream = replaceTimeline.getReverseOrderedInstants();
+    } else {
+      replaceStream = replaceTimeline.getInstantsAsStream();
+    }
+    return  Option.fromJavaOptional(replaceStream
         .filter(i -> ClusteringUtils.isClusteringInstant(this, i)).findFirst());
   }
   
+  @Override
+  public boolean isPendingClusterInstant(String instantTime) {
+    HoodieTimeline potentialTimeline = getCommitsTimeline().filterPendingReplaceTimeline().filter(i -> i.getTimestamp().equals(instantTime));
+    if (potentialTimeline.countInstants() == 0) {
+      return false;
+    }
+    if (potentialTimeline.countInstants() > 1) {
+      throw new IllegalStateException("Multiple instants with same timestamp: " + potentialTimeline);
+    }
+    return ClusteringUtils.isClusteringInstant(this, potentialTimeline.firstInstant().get());
+  }
+
   @Override
   public Option<byte[]> getInstantDetails(HoodieInstant instant) {
     return details.apply(instant);
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/timeline/HoodieTimeline.java b/hudi-common/src/main/java/org/apache/hudi/common/table/timeline/HoodieTimeline.java
index cdbe5b15fc5..a7344fc1512 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/timeline/HoodieTimeline.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/timeline/HoodieTimeline.java
@@ -406,6 +406,17 @@ public interface HoodieTimeline extends Serializable {
    */
   public Option<HoodieInstant> getLastPendingClusterInstant();
 
+
+  /**
+   * get the least recent pending cluster commit if present
+   */
+  public Option<HoodieInstant> getFirstPendingClusterInstant();
+
+  /**
+   * return true if instant is a pending clustering commit, otherwise false
+   */
+  public boolean isPendingClusterInstant(String instantTime);
+
   /**
    * Read the completed instant details.
    */
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/view/AbstractTableFileSystemView.java b/hudi-common/src/main/java/org/apache/hudi/common/table/view/AbstractTableFileSystemView.java
index 0f0f87c03c7..21ad0426a27 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/view/AbstractTableFileSystemView.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/view/AbstractTableFileSystemView.java
@@ -524,10 +524,7 @@ public abstract class AbstractTableFileSystemView implements SyncableFileSystemV
    * @param baseFile base File
    */
   protected boolean isBaseFileDueToPendingClustering(HoodieBaseFile baseFile) {
-    List<String> pendingReplaceInstants =
-        metaClient.getActiveTimeline().filterPendingReplaceTimeline().getInstantsAsStream().map(HoodieInstant::getTimestamp).collect(Collectors.toList());
-
-    return !pendingReplaceInstants.isEmpty() && pendingReplaceInstants.contains(baseFile.getCommitTime());
+    return metaClient.getActiveTimeline().isPendingClusterInstant(baseFile.getCommitTime());
   }
 
   /**
diff --git a/hudi-common/src/test/java/org/apache/hudi/common/table/view/TestHoodieTableFileSystemView.java b/hudi-common/src/test/java/org/apache/hudi/common/table/view/TestHoodieTableFileSystemView.java
index 216af429335..b9a7b840f36 100644
--- a/hudi-common/src/test/java/org/apache/hudi/common/table/view/TestHoodieTableFileSystemView.java
+++ b/hudi-common/src/test/java/org/apache/hudi/common/table/view/TestHoodieTableFileSystemView.java
@@ -19,6 +19,7 @@
 package org.apache.hudi.common.table.view;
 
 import org.apache.hudi.avro.model.HoodieClusteringPlan;
+import org.apache.hudi.avro.model.HoodieClusteringStrategy;
 import org.apache.hudi.avro.model.HoodieCompactionPlan;
 import org.apache.hudi.avro.model.HoodieFSPermission;
 import org.apache.hudi.avro.model.HoodieFileStatus;
@@ -57,6 +58,7 @@ import org.apache.hudi.common.util.CompactionUtils;
 import org.apache.hudi.common.util.Option;
 import org.apache.hudi.common.util.collection.ImmutablePair;
 import org.apache.hudi.common.util.collection.Pair;
+import org.apache.hudi.exception.HoodieIOException;
 import org.apache.hudi.hadoop.fs.HoodieWrapperFileSystem;
 
 import org.apache.hadoop.fs.FileStatus;
@@ -1442,6 +1444,30 @@ public class TestHoodieTableFileSystemView extends HoodieCommonTestHarness {
     }
   }
 
+  private void saveAsCompleteCluster(HoodieActiveTimeline timeline, HoodieInstant inflight, Option<byte[]> data) {
+    assertEquals(HoodieTimeline.REPLACE_COMMIT_ACTION, inflight.getAction());
+    HoodieInstant clusteringInstant = new HoodieInstant(State.REQUESTED, inflight.getAction(), inflight.getTimestamp());
+    HoodieClusteringPlan plan = new HoodieClusteringPlan();
+    plan.setExtraMetadata(new HashMap<>());
+    plan.setInputGroups(Collections.emptyList());
+    plan.setStrategy(HoodieClusteringStrategy.newBuilder().build());
+    plan.setVersion(1);
+    plan.setPreserveHoodieMetadata(false);
+    try {
+      HoodieRequestedReplaceMetadata requestedReplaceMetadata = HoodieRequestedReplaceMetadata.newBuilder()
+          .setOperationType(WriteOperationType.CLUSTER.name())
+          .setExtraMetadata(Collections.emptyMap())
+          .setClusteringPlan(plan)
+          .build();
+      timeline.saveToPendingReplaceCommit(clusteringInstant,
+          TimelineMetadataUtils.serializeRequestedReplaceMetadata(requestedReplaceMetadata));
+    } catch (IOException ioe) {
+      throw new HoodieIOException("Exception scheduling clustering", ioe);
+    }
+    timeline.transitionRequestedToInflight(clusteringInstant, Option.empty());
+    timeline.saveAsComplete(inflight, data);
+  }
+
   @Test
   public void testReplaceWithTimeTravel() throws IOException {
     String partitionPath1 = "2020/06/27";
@@ -1765,8 +1791,8 @@ public class TestHoodieTableFileSystemView extends HoodieCommonTestHarness {
     List<HoodieWriteStat> writeStats2 = buildWriteStats(partitionToFile2, commitTime2);
 
     HoodieCommitMetadata commitMetadata2 =
-        CommitUtils.buildMetadata(writeStats2, partitionToReplaceFileIds, Option.empty(), WriteOperationType.INSERT_OVERWRITE, "", HoodieTimeline.REPLACE_COMMIT_ACTION);
-    saveAsComplete(commitTimeline, instant2, Option.of(getUTF8Bytes(commitMetadata2.toJsonString())));
+        CommitUtils.buildMetadata(writeStats2, partitionToReplaceFileIds, Option.empty(), WriteOperationType.CLUSTER, "", HoodieTimeline.REPLACE_COMMIT_ACTION);
+    saveAsCompleteCluster(commitTimeline, instant2, Option.of(getUTF8Bytes(commitMetadata2.toJsonString())));
 
     // another insert commit
     String commitTime3 = "3";
diff --git a/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/sink/clustering/ClusteringPlanSourceFunction.java b/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/sink/clustering/ClusteringPlanSourceFunction.java
index ed78e33c10f..292e3bba5cc 100644
--- a/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/sink/clustering/ClusteringPlanSourceFunction.java
+++ b/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/sink/clustering/ClusteringPlanSourceFunction.java
@@ -76,7 +76,7 @@ public class ClusteringPlanSourceFunction extends AbstractRichFunction implement
 
   @Override
   public void run(SourceContext<ClusteringPlanEvent> sourceContext) throws Exception {
-    boolean isPending = StreamerUtil.createMetaClient(conf).getActiveTimeline().filterPendingReplaceTimeline().containsInstant(clusteringInstantTime);
+    boolean isPending = StreamerUtil.createMetaClient(conf).getActiveTimeline().isPendingClusterInstant(clusteringInstantTime);
     if (isPending) {
       for (HoodieClusteringGroup clusteringGroup : clusteringPlan.getInputGroups()) {
         LOG.info("Execute clustering plan for instant {} as {} file slices", clusteringInstantTime, clusteringGroup.getSlices().size());
diff --git a/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/util/ClusteringUtil.java b/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/util/ClusteringUtil.java
index ac81b4e7af4..6f0bb97a053 100644
--- a/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/util/ClusteringUtil.java
+++ b/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/util/ClusteringUtil.java
@@ -109,7 +109,7 @@ public class ClusteringUtil {
    */
   public static void rollbackClustering(HoodieFlinkTable<?> table, HoodieFlinkWriteClient<?> writeClient, String instantTime) {
     HoodieInstant inflightInstant = HoodieTimeline.getReplaceCommitInflightInstant(instantTime);
-    if (table.getMetaClient().reloadActiveTimeline().filterPendingReplaceTimeline().containsInstant(inflightInstant)) {
+    if (table.getMetaClient().reloadActiveTimeline().isPendingClusterInstant(instantTime)) {
       LOG.warn("Rollback failed clustering instant: [" + instantTime + "]");
       table.rollbackInflightClustering(inflightInstant,
           commitToRollback -> writeClient.getTableServiceClient().getPendingRollbackInfo(table.getMetaClient(), commitToRollback, false));
diff --git a/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieClusteringJob.java b/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieClusteringJob.java
index 9415a80b4d5..90c7d493705 100644
--- a/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieClusteringJob.java
+++ b/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieClusteringJob.java
@@ -25,7 +25,6 @@ import org.apache.hudi.common.model.HoodieRecordPayload;
 import org.apache.hudi.common.table.HoodieTableMetaClient;
 import org.apache.hudi.common.table.timeline.HoodieActiveTimeline;
 import org.apache.hudi.common.table.timeline.HoodieInstant;
-import org.apache.hudi.common.table.timeline.HoodieTimeline;
 import org.apache.hudi.common.util.Option;
 import org.apache.hudi.common.util.StringUtils;
 import org.apache.hudi.config.HoodieCleanConfig;
@@ -216,7 +215,7 @@ public class HoodieClusteringJob {
         // Instant time is not specified
         // Find the earliest scheduled clustering instant for execution
         Option<HoodieInstant> firstClusteringInstant =
-            metaClient.getActiveTimeline().filterPendingReplaceTimeline().firstInstant();
+            metaClient.getActiveTimeline().getFirstPendingClusterInstant();
         if (firstClusteringInstant.isPresent()) {
           cfg.clusteringInstantTime = firstClusteringInstant.get().getTimestamp();
           LOG.info("Found the earliest scheduled clustering instant which will be executed: "
@@ -262,14 +261,15 @@ public class HoodieClusteringJob {
 
       if (cfg.retryLastFailedClusteringJob) {
         HoodieSparkTable<HoodieRecordPayload> table = HoodieSparkTable.create(client.getConfig(), client.getEngineContext());
-        HoodieTimeline inflightHoodieTimeline = table.getActiveTimeline().filterPendingReplaceTimeline().filterInflights();
-        if (!inflightHoodieTimeline.empty()) {
-          HoodieInstant inflightClusteringInstant = inflightHoodieTimeline.lastInstant().get();
+        Option<HoodieInstant> lastClusterOpt = table.getActiveTimeline().getLastPendingClusterInstant();
+
+        if (lastClusterOpt.isPresent()) {
+          HoodieInstant inflightClusteringInstant = lastClusterOpt.get();
           Date clusteringStartTime = HoodieActiveTimeline.parseDateFromInstantTime(inflightClusteringInstant.getTimestamp());
           if (clusteringStartTime.getTime() + cfg.maxProcessingTimeMs < System.currentTimeMillis()) {
             // if there has failed clustering, then we will use the failed clustering instant-time to trigger next clustering action which will rollback and clustering.
             LOG.info("Found failed clustering instant at : " + inflightClusteringInstant + "; Will rollback the failed clustering and re-trigger again.");
-            instantTime = Option.of(inflightHoodieTimeline.lastInstant().get().getTimestamp());
+            instantTime = Option.of(inflightClusteringInstant.getTimestamp());
           } else {
             LOG.info(inflightClusteringInstant + " might still be in progress, will trigger a new clustering job.");
           }


(hudi) 21/28: [HUDI-7625] Avoid unnecessary rewrite for metadata table (#11038)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit a5304f586f456333d6a19479ccee67fd7d75fb56
Author: Danny Chan <yu...@gmail.com>
AuthorDate: Wed Apr 17 14:37:28 2024 +0800

    [HUDI-7625] Avoid unnecessary rewrite for metadata table (#11038)
---
 .../src/main/java/org/apache/hudi/io/HoodieMergeHandle.java         | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergeHandle.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergeHandle.java
index 749b08c3e7e..3f9aa2981c1 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergeHandle.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergeHandle.java
@@ -332,7 +332,11 @@ public class HoodieMergeHandle<T, I, K, O> extends HoodieWriteHandle<T, I, K, O>
    * Go through an old record. Here if we detect a newer version shows up, we write the new one to the file.
    */
   public void write(HoodieRecord<T> oldRecord) {
-    Schema oldSchema = config.populateMetaFields() ? writeSchemaWithMetaFields : writeSchema;
+    // Use schema with metadata files no matter whether 'hoodie.populate.meta.fields' is enabled
+    // to avoid unnecessary rewrite. Even with metadata table(whereas the option 'hoodie.populate.meta.fields' is configured as false),
+    // the record is deserialized with schema including metadata fields,
+    // see HoodieMergeHelper#runMerge for more details.
+    Schema oldSchema = writeSchemaWithMetaFields;
     Schema newSchema = preserveMetadata ? writeSchemaWithMetaFields : writeSchema;
     boolean copyOldRecord = true;
     String key = oldRecord.getRecordKey(oldSchema, keyGeneratorOpt);


(hudi) 06/28: [HUDI-7391] HoodieMetadataMetrics should use Metrics instance for metrics registry (#10635)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 858fde11fdd2daf118c0a951f6772e3e0b61004d
Author: Lokesh Jain <lj...@apache.org>
AuthorDate: Tue May 14 16:04:34 2024 -0700

    [HUDI-7391] HoodieMetadataMetrics should use Metrics instance for metrics registry (#10635)
    
    Currently HoodieMetadataMetrics stores metrics in memory and these metrics are not pushed by the metric reporters. The metric reporters are configured within Metrics instance. List of changes in the PR:
    
    Metrics related classes have been moved from hudi-client-common to hudi-common.
    HoodieMetadataMetrics now uses Metrics class so that all the reporters can be supported with it.
    Some gaps in configs which are added in HoodieMetadataWriteUtils
    Some metrics related apis and functionality has been moved to HoodieMetricsConfig. The HoodieWriteConfig APIs now delegate to HoodieMetricsConfig for the functionality.
---
 hudi-client/hudi-client-common/pom.xml             |  46 -----
 .../lock/metrics/HoodieLockMetrics.java            |   2 +-
 .../org/apache/hudi/config/HoodieWriteConfig.java  |  98 +++++-----
 .../hudi/metadata/HoodieMetadataWriteUtils.java    |   9 +-
 .../org/apache/hudi/metrics/HoodieMetrics.java     |   2 +-
 .../cloudwatch/CloudWatchMetricsReporter.java      |  29 ++-
 .../table/action/index/RunIndexActionExecutor.java |   3 +-
 .../hudi/metrics/TestHoodieConsoleMetrics.java     |  16 +-
 .../hudi/metrics/TestHoodieGraphiteMetrics.java    |  22 ++-
 .../apache/hudi/metrics/TestHoodieJmxMetrics.java  |  19 +-
 .../org/apache/hudi/metrics/TestHoodieMetrics.java |  17 +-
 .../hudi/metrics/TestMetricsReporterFactory.java   |  20 +-
 .../cloudwatch/TestCloudWatchMetricsReporter.java  |  27 ++-
 .../datadog/TestDatadogMetricsReporter.java        |  60 +++---
 .../org/apache/hudi/metrics/m3/TestM3Metrics.java  |  54 +++---
 .../metrics/prometheus/TestPrometheusReporter.java |  19 +-
 .../prometheus/TestPushGateWayReporter.java        |  52 +++---
 .../FlinkHoodieBackedTableMetadataWriter.java      |   4 +-
 .../JavaHoodieBackedTableMetadataWriter.java       |   4 +-
 .../hudi/client/TestJavaHoodieBackedMetadata.java  |  21 ++-
 .../SparkHoodieBackedTableMetadataWriter.java      |   2 +-
 .../functional/TestHoodieBackedMetadata.java       |  18 +-
 hudi-common/pom.xml                                |  47 +++++
 .../hudi/common/config/HoodieCommonConfig.java     |   8 +
 .../metrics/HoodieMetricsCloudWatchConfig.java     |   0
 .../hudi/config/metrics/HoodieMetricsConfig.java   | 201 +++++++++++++++++++++
 .../config/metrics/HoodieMetricsDatadogConfig.java |   0
 .../metrics/HoodieMetricsGraphiteConfig.java       |   0
 .../config/metrics/HoodieMetricsJmxConfig.java     |   0
 .../hudi/config/metrics/HoodieMetricsM3Config.java |   0
 .../metrics/HoodieMetricsPrometheusConfig.java     |   0
 .../apache/hudi/metadata/BaseTableMetadata.java    |   4 +-
 .../hudi/metadata/HoodieMetadataMetrics.java       |  21 ++-
 .../hudi/metrics/ConsoleMetricsReporter.java       |   0
 .../java/org/apache/hudi/metrics/HoodieGauge.java  |   0
 .../hudi/metrics/InMemoryMetricsReporter.java      |   0
 .../apache/hudi/metrics/JmxMetricsReporter.java    |   4 +-
 .../org/apache/hudi/metrics/JmxReporterServer.java |   0
 .../java/org/apache/hudi/metrics/MetricUtils.java  |   0
 .../main/java/org/apache/hudi/metrics/Metrics.java |  43 +++--
 .../hudi/metrics/MetricsGraphiteReporter.java      |  16 +-
 .../org/apache/hudi/metrics/MetricsReporter.java   |   0
 .../hudi/metrics/MetricsReporterFactory.java       |  27 ++-
 .../apache/hudi/metrics/MetricsReporterType.java   |   0
 .../custom/CustomizableMetricsReporter.java        |   0
 .../hudi/metrics/datadog/DatadogHttpClient.java    |   0
 .../metrics/datadog/DatadogMetricsReporter.java    |   4 +-
 .../hudi/metrics/datadog/DatadogReporter.java      |   0
 .../apache/hudi/metrics/m3/M3MetricsReporter.java  |  16 +-
 .../hudi/metrics/m3/M3ScopeReporterAdaptor.java    |   0
 .../metrics/prometheus/PrometheusReporter.java     |  10 +-
 .../prometheus/PushGatewayMetricsReporter.java     |  18 +-
 .../metrics/prometheus/PushGatewayReporter.java    |   0
 .../AbstractUserDefinedMetricsReporter.java        |   0
 .../deltastreamer/HoodieDeltaStreamerMetrics.java  |   8 +-
 .../ingestion/HoodieIngestionMetrics.java          |   7 +-
 .../utilities/streamer/HoodieStreamerMetrics.java  |   5 +
 .../apache/hudi/utilities/streamer/StreamSync.java |   2 +-
 58 files changed, 650 insertions(+), 335 deletions(-)

diff --git a/hudi-client/hudi-client-common/pom.xml b/hudi-client/hudi-client-common/pom.xml
index 6caccd0b0a6..022f5d6faa0 100644
--- a/hudi-client/hudi-client-common/pom.xml
+++ b/hudi-client/hudi-client-common/pom.xml
@@ -85,52 +85,6 @@
       <version>0.2.2</version>
     </dependency>
 
-    <!-- Dropwizard Metrics -->
-    <dependency>
-      <groupId>io.dropwizard.metrics</groupId>
-      <artifactId>metrics-graphite</artifactId>
-      <exclusions>
-        <exclusion>
-          <groupId>com.rabbitmq</groupId>
-          <artifactId>*</artifactId>
-        </exclusion>
-      </exclusions>
-    </dependency>
-    <dependency>
-      <groupId>io.dropwizard.metrics</groupId>
-      <artifactId>metrics-core</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>io.dropwizard.metrics</groupId>
-      <artifactId>metrics-jmx</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>io.prometheus</groupId>
-      <artifactId>simpleclient</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>io.prometheus</groupId>
-      <artifactId>simpleclient_httpserver</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>io.prometheus</groupId>
-      <artifactId>simpleclient_dropwizard</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>io.prometheus</groupId>
-      <artifactId>simpleclient_pushgateway</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>com.uber.m3</groupId>
-      <artifactId>tally-m3</artifactId>
-      <version>${tally.version}</version>
-    </dependency>
-    <dependency>
-      <groupId>com.uber.m3</groupId>
-      <artifactId>tally-core</artifactId>
-      <version>${tally.version}</version>
-    </dependency>
-
     <!-- Lock -->
     <dependency>
       <groupId>org.apache.curator</groupId>
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/transaction/lock/metrics/HoodieLockMetrics.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/transaction/lock/metrics/HoodieLockMetrics.java
index 25603d5655c..bbf3d6876d8 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/transaction/lock/metrics/HoodieLockMetrics.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/transaction/lock/metrics/HoodieLockMetrics.java
@@ -54,7 +54,7 @@ public class HoodieLockMetrics {
     this.writeConfig = writeConfig;
 
     if (isMetricsEnabled) {
-      metrics = Metrics.getInstance(writeConfig);
+      metrics = Metrics.getInstance(writeConfig.getMetricsConfig());
       MetricRegistry registry = metrics.getRegistry();
 
       lockAttempts = registry.counter(getMetricsName(LOCK_ACQUIRE_ATTEMPTS_COUNTER_NAME));
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieWriteConfig.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieWriteConfig.java
index 558aba5b17b..e8f327faecb 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieWriteConfig.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieWriteConfig.java
@@ -57,13 +57,10 @@ import org.apache.hudi.common.util.StringUtils;
 import org.apache.hudi.common.util.VisibleForTesting;
 import org.apache.hudi.common.util.queue.DisruptorWaitStrategyType;
 import org.apache.hudi.common.util.queue.ExecutorType;
-import org.apache.hudi.config.metrics.HoodieMetricsCloudWatchConfig;
 import org.apache.hudi.config.metrics.HoodieMetricsConfig;
-import org.apache.hudi.config.metrics.HoodieMetricsDatadogConfig;
 import org.apache.hudi.config.metrics.HoodieMetricsGraphiteConfig;
 import org.apache.hudi.config.metrics.HoodieMetricsJmxConfig;
 import org.apache.hudi.config.metrics.HoodieMetricsM3Config;
-import org.apache.hudi.config.metrics.HoodieMetricsPrometheusConfig;
 import org.apache.hudi.exception.HoodieNotSupportedException;
 import org.apache.hudi.execution.bulkinsert.BulkInsertSortMode;
 import org.apache.hudi.index.HoodieIndex;
@@ -99,7 +96,6 @@ import java.util.Locale;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Properties;
-import java.util.function.Supplier;
 import java.util.stream.Collectors;
 
 import static org.apache.hudi.common.util.ValidationUtils.checkArgument;
@@ -766,6 +762,7 @@ public class HoodieWriteConfig extends HoodieConfig {
   private FileSystemViewStorageConfig viewStorageConfig;
   private HoodiePayloadConfig hoodiePayloadConfig;
   private HoodieMetadataConfig metadataConfig;
+  private HoodieMetricsConfig metricsConfig;
   private HoodieMetaserverConfig metaserverConfig;
   private HoodieTableServiceManagerConfig tableServiceManagerConfig;
   private HoodieCommonConfig commonConfig;
@@ -1160,6 +1157,7 @@ public class HoodieWriteConfig extends HoodieConfig {
     this.viewStorageConfig = clientSpecifiedViewStorageConfig;
     this.hoodiePayloadConfig = HoodiePayloadConfig.newBuilder().fromProperties(newProps).build();
     this.metadataConfig = HoodieMetadataConfig.newBuilder().fromProperties(props).build();
+    this.metricsConfig = HoodieMetricsConfig.newBuilder().fromProperties(props).build();
     this.metaserverConfig = HoodieMetaserverConfig.newBuilder().fromProperties(props).build();
     this.tableServiceManagerConfig = HoodieTableServiceManagerConfig.newBuilder().fromProperties(props).build();
     this.commonConfig = HoodieCommonConfig.newBuilder().fromProperties(props).build();
@@ -2140,172 +2138,162 @@ public class HoodieWriteConfig extends HoodieConfig {
    * metrics properties.
    */
   public boolean isMetricsOn() {
-    return getBoolean(HoodieMetricsConfig.TURN_METRICS_ON);
+    return metricsConfig.isMetricsOn();
   }
 
   /**
    * metrics properties.
    */
   public boolean isCompactionLogBlockMetricsOn() {
-    return getBoolean(HoodieMetricsConfig.TURN_METRICS_COMPACTION_LOG_BLOCKS_ON);
+    return metricsConfig.isCompactionLogBlockMetricsOn();
   }
 
   public boolean isExecutorMetricsEnabled() {
-    return Boolean.parseBoolean(
-        getStringOrDefault(HoodieMetricsConfig.EXECUTOR_METRICS_ENABLE, "false"));
+    return metricsConfig.isExecutorMetricsEnabled();
   }
 
   public boolean isLockingMetricsEnabled() {
-    return getBoolean(HoodieMetricsConfig.LOCK_METRICS_ENABLE);
+    return metricsConfig.isLockingMetricsEnabled();
   }
 
   public MetricsReporterType getMetricsReporterType() {
-    return MetricsReporterType.valueOf(getString(HoodieMetricsConfig.METRICS_REPORTER_TYPE_VALUE));
+    return metricsConfig.getMetricsReporterType();
   }
 
   public String getGraphiteServerHost() {
-    return getString(HoodieMetricsGraphiteConfig.GRAPHITE_SERVER_HOST_NAME);
+    return metricsConfig.getGraphiteServerHost();
   }
 
   public int getGraphiteServerPort() {
-    return getInt(HoodieMetricsGraphiteConfig.GRAPHITE_SERVER_PORT_NUM);
+    return metricsConfig.getGraphiteServerPort();
   }
 
   public String getGraphiteMetricPrefix() {
-    return getString(HoodieMetricsGraphiteConfig.GRAPHITE_METRIC_PREFIX_VALUE);
+    return metricsConfig.getGraphiteMetricPrefix();
   }
 
   public int getGraphiteReportPeriodSeconds() {
-    return getInt(HoodieMetricsGraphiteConfig.GRAPHITE_REPORT_PERIOD_IN_SECONDS);
+    return metricsConfig.getGraphiteReportPeriodSeconds();
   }
 
   public String getM3ServerHost() {
-    return getString(HoodieMetricsM3Config.M3_SERVER_HOST_NAME);
+    return metricsConfig.getM3ServerHost();
   }
 
   public int getM3ServerPort() {
-    return getInt(HoodieMetricsM3Config.M3_SERVER_PORT_NUM);
+    return metricsConfig.getM3ServerPort();
   }
 
   public String getM3Tags() {
-    return getString(HoodieMetricsM3Config.M3_TAGS);
+    return metricsConfig.getM3Tags();
   }
 
   public String getM3Env() {
-    return getString(HoodieMetricsM3Config.M3_ENV);
+    return metricsConfig.getM3Env();
   }
 
   public String getM3Service() {
-    return getString(HoodieMetricsM3Config.M3_SERVICE);
+    return metricsConfig.getM3Service();
   }
 
   public String getJmxHost() {
-    return getString(HoodieMetricsJmxConfig.JMX_HOST_NAME);
+    return metricsConfig.getJmxHost();
   }
 
   public String getJmxPort() {
-    return getString(HoodieMetricsJmxConfig.JMX_PORT_NUM);
+    return metricsConfig.getJmxPort();
   }
 
   public int getDatadogReportPeriodSeconds() {
-    return getInt(HoodieMetricsDatadogConfig.REPORT_PERIOD_IN_SECONDS);
+    return metricsConfig.getDatadogReportPeriodSeconds();
   }
 
   public ApiSite getDatadogApiSite() {
-    return ApiSite.valueOf(getString(HoodieMetricsDatadogConfig.API_SITE_VALUE));
+    return metricsConfig.getDatadogApiSite();
   }
 
   public String getDatadogApiKey() {
-    if (props.containsKey(HoodieMetricsDatadogConfig.API_KEY.key())) {
-      return getString(HoodieMetricsDatadogConfig.API_KEY);
-
-    } else {
-      Supplier<String> apiKeySupplier = ReflectionUtils.loadClass(
-          getString(HoodieMetricsDatadogConfig.API_KEY_SUPPLIER));
-      return apiKeySupplier.get();
-    }
+    return metricsConfig.getDatadogApiKey();
   }
 
   public boolean getDatadogApiKeySkipValidation() {
-    return getBoolean(HoodieMetricsDatadogConfig.API_KEY_SKIP_VALIDATION);
+    return metricsConfig.getDatadogApiKeySkipValidation();
   }
 
   public int getDatadogApiTimeoutSeconds() {
-    return getInt(HoodieMetricsDatadogConfig.API_TIMEOUT_IN_SECONDS);
+    return metricsConfig.getDatadogApiTimeoutSeconds();
   }
 
   public String getDatadogMetricPrefix() {
-    return getString(HoodieMetricsDatadogConfig.METRIC_PREFIX_VALUE);
+    return metricsConfig.getDatadogMetricPrefix();
   }
 
   public String getDatadogMetricHost() {
-    return getString(HoodieMetricsDatadogConfig.METRIC_HOST_NAME);
+    return metricsConfig.getDatadogMetricHost();
   }
 
   public List<String> getDatadogMetricTags() {
-    return Arrays.stream(getStringOrDefault(
-        HoodieMetricsDatadogConfig.METRIC_TAG_VALUES, ",").split("\\s*,\\s*")).collect(Collectors.toList());
+    return metricsConfig.getDatadogMetricTags();
   }
 
   public int getCloudWatchReportPeriodSeconds() {
-    return getInt(HoodieMetricsCloudWatchConfig.REPORT_PERIOD_SECONDS);
+    return metricsConfig.getCloudWatchReportPeriodSeconds();
   }
 
   public String getCloudWatchMetricPrefix() {
-    return getString(HoodieMetricsCloudWatchConfig.METRIC_PREFIX);
+    return metricsConfig.getCloudWatchMetricPrefix();
   }
 
   public String getCloudWatchMetricNamespace() {
-    return getString(HoodieMetricsCloudWatchConfig.METRIC_NAMESPACE);
+    return metricsConfig.getCloudWatchMetricNamespace();
   }
 
   public int getCloudWatchMaxDatumsPerRequest() {
-    return getInt(HoodieMetricsCloudWatchConfig.MAX_DATUMS_PER_REQUEST);
+    return metricsConfig.getCloudWatchMaxDatumsPerRequest();
   }
 
   public String getMetricReporterClassName() {
-    return getString(HoodieMetricsConfig.METRICS_REPORTER_CLASS_NAME);
+    return metricsConfig.getMetricReporterClassName();
   }
 
   public int getPrometheusPort() {
-    return getInt(HoodieMetricsPrometheusConfig.PROMETHEUS_PORT_NUM);
+    return metricsConfig.getPrometheusPort();
   }
 
   public String getPushGatewayHost() {
-    return getString(HoodieMetricsPrometheusConfig.PUSHGATEWAY_HOST_NAME);
+    return metricsConfig.getPushGatewayHost();
   }
 
   public int getPushGatewayPort() {
-    return getInt(HoodieMetricsPrometheusConfig.PUSHGATEWAY_PORT_NUM);
+    return metricsConfig.getPushGatewayPort();
   }
 
   public int getPushGatewayReportPeriodSeconds() {
-    return getInt(HoodieMetricsPrometheusConfig.PUSHGATEWAY_REPORT_PERIOD_IN_SECONDS);
+    return metricsConfig.getPushGatewayReportPeriodSeconds();
   }
 
   public boolean getPushGatewayDeleteOnShutdown() {
-    return getBoolean(HoodieMetricsPrometheusConfig.PUSHGATEWAY_DELETE_ON_SHUTDOWN_ENABLE);
+    return metricsConfig.getPushGatewayDeleteOnShutdown();
   }
 
   public String getPushGatewayJobName() {
-    return getString(HoodieMetricsPrometheusConfig.PUSHGATEWAY_JOBNAME);
+    return metricsConfig.getPushGatewayJobName();
   }
 
   public String getPushGatewayLabels() {
-    return getString(HoodieMetricsPrometheusConfig.PUSHGATEWAY_LABELS);
+    return metricsConfig.getPushGatewayLabels();
   }
 
   public boolean getPushGatewayRandomJobNameSuffix() {
-    return getBoolean(HoodieMetricsPrometheusConfig.PUSHGATEWAY_RANDOM_JOBNAME_SUFFIX);
+    return metricsConfig.getPushGatewayRandomJobNameSuffix();
   }
 
   public String getMetricReporterMetricsNamePrefix() {
-    // Metrics prefixes should not have a dot as this is usually a separator
-    return getStringOrDefault(HoodieMetricsConfig.METRICS_REPORTER_PREFIX).replaceAll("\\.", "_");
+    return metricsConfig.getMetricReporterMetricsNamePrefix();
   }
 
   public String getMetricReporterFileBasedConfigs() {
-    return getStringOrDefault(HoodieMetricsConfig.METRICS_REPORTER_FILE_BASED_CONFIGS_PATH);
+    return metricsConfig.getMetricReporterFileBasedConfigs();
   }
 
   /**
@@ -2360,6 +2348,10 @@ public class HoodieWriteConfig extends HoodieConfig {
     return metadataConfig;
   }
 
+  public HoodieMetricsConfig getMetricsConfig() {
+    return metricsConfig;
+  }
+
   public HoodieTableServiceManagerConfig getTableServiceManagerConfig() {
     return tableServiceManagerConfig;
   }
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metadata/HoodieMetadataWriteUtils.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metadata/HoodieMetadataWriteUtils.java
index 48cfb46b49f..dfad3b13c11 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metadata/HoodieMetadataWriteUtils.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metadata/HoodieMetadataWriteUtils.java
@@ -187,14 +187,14 @@ public class HoodieMetadataWriteUtils {
               .build());
           break;
         case PROMETHEUS_PUSHGATEWAY:
-          HoodieMetricsPrometheusConfig prometheusConfig = HoodieMetricsPrometheusConfig.newBuilder()
+          HoodieMetricsPrometheusConfig pushGatewayConfig = HoodieMetricsPrometheusConfig.newBuilder()
               .withPushgatewayJobname(writeConfig.getPushGatewayJobName())
               .withPushgatewayRandomJobnameSuffix(writeConfig.getPushGatewayRandomJobNameSuffix())
               .withPushgatewayLabels(writeConfig.getPushGatewayLabels())
               .withPushgatewayReportPeriodInSeconds(String.valueOf(writeConfig.getPushGatewayReportPeriodSeconds()))
               .withPushgatewayHostName(writeConfig.getPushGatewayHost())
               .withPushgatewayPortNum(writeConfig.getPushGatewayPort()).build();
-          builder.withProperties(prometheusConfig.getProps());
+          builder.withProperties(pushGatewayConfig.getProps());
           break;
         case M3:
           HoodieMetricsM3Config m3Config = HoodieMetricsM3Config.newBuilder()
@@ -223,6 +223,11 @@ public class HoodieMetadataWriteUtils {
           builder.withProperties(datadogConfig.build().getProps());
           break;
         case PROMETHEUS:
+          HoodieMetricsPrometheusConfig prometheusConfig = HoodieMetricsPrometheusConfig.newBuilder()
+              .withPushgatewayLabels(writeConfig.getPushGatewayLabels())
+              .withPrometheusPortNum(writeConfig.getPrometheusPort()).build();
+          builder.withProperties(prometheusConfig.getProps());
+          break;
         case CONSOLE:
         case INMEMORY:
         case CLOUDWATCH:
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/HoodieMetrics.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/HoodieMetrics.java
index feca84a5e73..efb9be2414b 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/HoodieMetrics.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/HoodieMetrics.java
@@ -92,7 +92,7 @@ public class HoodieMetrics {
     this.config = config;
     this.tableName = config.getTableName();
     if (config.isMetricsOn()) {
-      metrics = Metrics.getInstance(config);
+      metrics = Metrics.getInstance(config.getMetricsConfig());
       this.rollbackTimerName = getMetricsName("timer", HoodieTimeline.ROLLBACK_ACTION);
       this.cleanTimerName = getMetricsName("timer", HoodieTimeline.CLEAN_ACTION);
       this.commitTimerName = getMetricsName("timer", HoodieTimeline.COMMIT_ACTION);
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/cloudwatch/CloudWatchMetricsReporter.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/cloudwatch/CloudWatchMetricsReporter.java
index d05632b9bbf..68e4951f74f 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/cloudwatch/CloudWatchMetricsReporter.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/cloudwatch/CloudWatchMetricsReporter.java
@@ -20,6 +20,7 @@ package org.apache.hudi.metrics.cloudwatch;
 
 import org.apache.hudi.aws.cloudwatch.CloudWatchReporter;
 import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.metrics.MetricsReporter;
 
 import com.codahale.metrics.MetricRegistry;
@@ -37,33 +38,41 @@ public class CloudWatchMetricsReporter extends MetricsReporter {
   private static final Logger LOG = LoggerFactory.getLogger(CloudWatchMetricsReporter.class);
 
   private final MetricRegistry registry;
-  private final HoodieWriteConfig config;
+  private final HoodieMetricsConfig metricsConfig;
   private final CloudWatchReporter reporter;
 
-  public CloudWatchMetricsReporter(HoodieWriteConfig config, MetricRegistry registry) {
-    this.config = config;
+  public CloudWatchMetricsReporter(HoodieWriteConfig writeConfig, MetricRegistry registry) {
+    this(writeConfig.getMetricsConfig(), registry);
+  }
+
+  CloudWatchMetricsReporter(HoodieWriteConfig writeConfig, MetricRegistry registry, CloudWatchReporter reporter) {
+    this(writeConfig.getMetricsConfig(), registry, reporter);
+  }
+
+  public CloudWatchMetricsReporter(HoodieMetricsConfig metricsConfig, MetricRegistry registry) {
+    this.metricsConfig = metricsConfig;
     this.registry = registry;
     this.reporter = createCloudWatchReporter();
   }
 
-  CloudWatchMetricsReporter(HoodieWriteConfig config, MetricRegistry registry, CloudWatchReporter reporter) {
-    this.config = config;
+  CloudWatchMetricsReporter(HoodieMetricsConfig metricsConfig, MetricRegistry registry, CloudWatchReporter reporter) {
+    this.metricsConfig = metricsConfig;
     this.registry = registry;
     this.reporter = reporter;
   }
 
   private CloudWatchReporter createCloudWatchReporter() {
     return CloudWatchReporter.forRegistry(registry)
-        .prefixedWith(config.getCloudWatchMetricPrefix())
-        .namespace(config.getCloudWatchMetricNamespace())
-        .maxDatumsPerRequest(config.getCloudWatchMaxDatumsPerRequest())
-        .build(config.getProps());
+        .prefixedWith(metricsConfig.getCloudWatchMetricPrefix())
+        .namespace(metricsConfig.getCloudWatchMetricNamespace())
+        .maxDatumsPerRequest(metricsConfig.getCloudWatchMaxDatumsPerRequest())
+        .build(metricsConfig.getProps());
   }
 
   @Override
   public void start() {
     LOG.info("Starting CloudWatch Metrics Reporter.");
-    reporter.start(config.getCloudWatchReportPeriodSeconds(), TimeUnit.SECONDS);
+    reporter.start(metricsConfig.getCloudWatchReportPeriodSeconds(), TimeUnit.SECONDS);
   }
 
   @Override
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/action/index/RunIndexActionExecutor.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/action/index/RunIndexActionExecutor.java
index 2f006965417..cb29173db63 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/action/index/RunIndexActionExecutor.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/action/index/RunIndexActionExecutor.java
@@ -24,7 +24,6 @@ import org.apache.hudi.avro.model.HoodieIndexPartitionInfo;
 import org.apache.hudi.avro.model.HoodieIndexPlan;
 import org.apache.hudi.client.transaction.TransactionManager;
 import org.apache.hudi.common.engine.HoodieEngineContext;
-import org.apache.hudi.common.metrics.Registry;
 import org.apache.hudi.common.table.HoodieTableConfig;
 import org.apache.hudi.common.table.HoodieTableMetaClient;
 import org.apache.hudi.common.table.timeline.HoodieInstant;
@@ -100,7 +99,7 @@ public class RunIndexActionExecutor<T, I, K, O> extends BaseActionExecutor<T, I,
     super(context, config, table, instantTime);
     this.txnManager = new TransactionManager(config, table.getMetaClient().getFs());
     if (config.getMetadataConfig().enableMetrics()) {
-      this.metrics = Option.of(new HoodieMetadataMetrics(Registry.getRegistry("HoodieIndexer")));
+      this.metrics = Option.of(new HoodieMetadataMetrics(config.getMetricsConfig()));
     } else {
       this.metrics = Option.empty();
     }
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieConsoleMetrics.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieConsoleMetrics.java
index 4a0de10512e..43748e96833 100644
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieConsoleMetrics.java
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieConsoleMetrics.java
@@ -19,6 +19,8 @@
 package org.apache.hudi.metrics;
 
 import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
+
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
@@ -35,17 +37,19 @@ import static org.mockito.Mockito.when;
 public class TestHoodieConsoleMetrics {
 
   @Mock
-  HoodieWriteConfig config;
+  HoodieWriteConfig writeConfig;
+  @Mock
+  HoodieMetricsConfig metricsConfig;
   HoodieMetrics hoodieMetrics;
   Metrics metrics;
 
   @BeforeEach
   public void start() {
-    when(config.getTableName()).thenReturn("console_metrics_test");
-    when(config.isMetricsOn()).thenReturn(true);
-    when(config.getMetricsReporterType()).thenReturn(MetricsReporterType.CONSOLE);
-    when(config.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
-    hoodieMetrics = new HoodieMetrics(config);
+    when(writeConfig.getMetricsConfig()).thenReturn(metricsConfig);
+    when(writeConfig.isMetricsOn()).thenReturn(true);
+    when(metricsConfig.getMetricsReporterType()).thenReturn(MetricsReporterType.CONSOLE);
+    when(metricsConfig.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
+    hoodieMetrics = new HoodieMetrics(writeConfig);
     metrics = hoodieMetrics.getMetrics();
   }
 
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieGraphiteMetrics.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieGraphiteMetrics.java
index dc1d0ae0cf5..63a6704b02f 100644
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieGraphiteMetrics.java
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieGraphiteMetrics.java
@@ -20,6 +20,8 @@ package org.apache.hudi.metrics;
 
 import org.apache.hudi.common.testutils.NetworkTestUtils;
 import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
+
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.ExtendWith;
@@ -38,7 +40,9 @@ import static org.mockito.Mockito.when;
 public class TestHoodieGraphiteMetrics {
 
   @Mock
-  HoodieWriteConfig config;
+  HoodieWriteConfig writeConfig;
+  @Mock
+  HoodieMetricsConfig metricsConfig;
   HoodieMetrics hoodieMetrics;
   Metrics metrics;
 
@@ -49,14 +53,14 @@ public class TestHoodieGraphiteMetrics {
 
   @Test
   public void testRegisterGauge() {
-    when(config.isMetricsOn()).thenReturn(true);
-    when(config.getTableName()).thenReturn("table1");
-    when(config.getMetricsReporterType()).thenReturn(MetricsReporterType.GRAPHITE);
-    when(config.getGraphiteServerHost()).thenReturn("localhost");
-    when(config.getGraphiteServerPort()).thenReturn(NetworkTestUtils.nextFreePort());
-    when(config.getGraphiteReportPeriodSeconds()).thenReturn(30);
-    when(config.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
-    hoodieMetrics = new HoodieMetrics(config);
+    when(writeConfig.getMetricsConfig()).thenReturn(metricsConfig);
+    when(writeConfig.isMetricsOn()).thenReturn(true);
+    when(metricsConfig.getMetricsReporterType()).thenReturn(MetricsReporterType.GRAPHITE);
+    when(metricsConfig.getGraphiteServerHost()).thenReturn("localhost");
+    when(metricsConfig.getGraphiteServerPort()).thenReturn(NetworkTestUtils.nextFreePort());
+    when(metricsConfig.getGraphiteReportPeriodSeconds()).thenReturn(30);
+    when(metricsConfig.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
+    hoodieMetrics = new HoodieMetrics(writeConfig);
     metrics = hoodieMetrics.getMetrics();
     metrics.registerGauge("graphite_metric", 123L);
     assertEquals("123", metrics.getRegistry().getGauges()
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieJmxMetrics.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieJmxMetrics.java
index a2ec03263a7..3b776c104cd 100644
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieJmxMetrics.java
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieJmxMetrics.java
@@ -20,6 +20,7 @@ package org.apache.hudi.metrics;
 
 import org.apache.hudi.common.testutils.NetworkTestUtils;
 import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
@@ -40,19 +41,21 @@ import static org.mockito.Mockito.when;
 public class TestHoodieJmxMetrics {
 
   @Mock
-  HoodieWriteConfig config;
+  HoodieWriteConfig writeConfig;
+  @Mock
+  HoodieMetricsConfig metricsConfig;
   HoodieMetrics hoodieMetrics;
   Metrics metrics;
 
   @BeforeEach
   void setup() {
-    when(config.isMetricsOn()).thenReturn(true);
-    when(config.getTableName()).thenReturn("foo");
-    when(config.getMetricsReporterType()).thenReturn(MetricsReporterType.JMX);
-    when(config.getJmxHost()).thenReturn("localhost");
-    when(config.getJmxPort()).thenReturn(String.valueOf(NetworkTestUtils.nextFreePort()));
-    when(config.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
-    hoodieMetrics = new HoodieMetrics(config);
+    when(writeConfig.getMetricsConfig()).thenReturn(metricsConfig);
+    when(writeConfig.isMetricsOn()).thenReturn(true);
+    when(metricsConfig.getMetricsReporterType()).thenReturn(MetricsReporterType.JMX);
+    when(metricsConfig.getJmxHost()).thenReturn("localhost");
+    when(metricsConfig.getJmxPort()).thenReturn(String.valueOf(NetworkTestUtils.nextFreePort()));
+    when(metricsConfig.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
+    hoodieMetrics = new HoodieMetrics(writeConfig);
     metrics = hoodieMetrics.getMetrics();
   }
 
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieMetrics.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieMetrics.java
index f305c9d1776..8c34931d93e 100755
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieMetrics.java
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestHoodieMetrics.java
@@ -22,6 +22,7 @@ import org.apache.hudi.common.model.HoodieCommitMetadata;
 import org.apache.hudi.common.util.Option;
 import org.apache.hudi.common.util.collection.Pair;
 import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 
 import com.codahale.metrics.Timer;
 import org.junit.jupiter.api.AfterEach;
@@ -44,17 +45,19 @@ import static org.mockito.Mockito.when;
 public class TestHoodieMetrics {
 
   @Mock
-  HoodieWriteConfig config;
+  HoodieWriteConfig writeConfig;
+  @Mock
+  HoodieMetricsConfig metricsConfig;
   HoodieMetrics hoodieMetrics;
   Metrics metrics;
 
   @BeforeEach
   void setUp() {
-    when(config.isMetricsOn()).thenReturn(true);
-    when(config.getTableName()).thenReturn("raw_table");
-    when(config.getMetricsReporterType()).thenReturn(MetricsReporterType.INMEMORY);
-    when(config.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
-    hoodieMetrics = new HoodieMetrics(config);
+    when(writeConfig.getMetricsConfig()).thenReturn(metricsConfig);
+    when(writeConfig.isMetricsOn()).thenReturn(true);
+    when(metricsConfig.getMetricsReporterType()).thenReturn(MetricsReporterType.INMEMORY);
+    when(metricsConfig.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
+    hoodieMetrics = new HoodieMetrics(writeConfig);
     metrics = hoodieMetrics.getMetrics();
   }
 
@@ -143,7 +146,7 @@ public class TestHoodieMetrics {
       when(metadata.getTotalCorruptLogBlocks()).thenReturn(randomValue + 15);
       when(metadata.getTotalRollbackLogBlocks()).thenReturn(randomValue + 16);
       when(metadata.getMinAndMaxEventTime()).thenReturn(Pair.of(Option.empty(), Option.empty()));
-      when(config.isCompactionLogBlockMetricsOn()).thenReturn(true);
+      when(writeConfig.isCompactionLogBlockMetricsOn()).thenReturn(true);
 
       hoodieMetrics.updateCommitMetrics(randomValue + 17, commitTimer.stop(), metadata, action);
 
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestMetricsReporterFactory.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestMetricsReporterFactory.java
index a44443d9bd5..dd0ada87693 100644
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestMetricsReporterFactory.java
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/TestMetricsReporterFactory.java
@@ -20,7 +20,7 @@
 package org.apache.hudi.metrics;
 
 import org.apache.hudi.common.config.TypedProperties;
-import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.exception.HoodieException;
 import org.apache.hudi.metrics.custom.CustomizableMetricsReporter;
 
@@ -41,27 +41,27 @@ import static org.mockito.Mockito.when;
 public class TestMetricsReporterFactory {
 
   @Mock
-  HoodieWriteConfig config;
+  HoodieMetricsConfig metricsConfig;
 
   @Mock
   MetricRegistry registry;
 
   @Test
   public void metricsReporterFactoryShouldReturnReporter() {
-    when(config.getMetricsReporterType()).thenReturn(MetricsReporterType.INMEMORY);
-    MetricsReporter reporter = MetricsReporterFactory.createReporter(config, registry).get();
+    when(metricsConfig.getMetricsReporterType()).thenReturn(MetricsReporterType.INMEMORY);
+    MetricsReporter reporter = MetricsReporterFactory.createReporter(metricsConfig, registry).get();
     assertTrue(reporter instanceof InMemoryMetricsReporter);
   }
 
   @Test
   public void metricsReporterFactoryShouldReturnUserDefinedReporter() {
-    when(config.getMetricReporterClassName()).thenReturn(DummyMetricsReporter.class.getName());
+    when(metricsConfig.getMetricReporterClassName()).thenReturn(DummyMetricsReporter.class.getName());
 
     TypedProperties props = new TypedProperties();
     props.setProperty("testKey", "testValue");
 
-    when(config.getProps()).thenReturn(props);
-    MetricsReporter reporter = MetricsReporterFactory.createReporter(config, registry).get();
+    when(metricsConfig.getProps()).thenReturn(props);
+    MetricsReporter reporter = MetricsReporterFactory.createReporter(metricsConfig, registry).get();
     assertTrue(reporter instanceof CustomizableMetricsReporter);
     assertEquals(props, ((DummyMetricsReporter) reporter).getProps());
     assertEquals(registry, ((DummyMetricsReporter) reporter).getRegistry());
@@ -69,9 +69,9 @@ public class TestMetricsReporterFactory {
 
   @Test
   public void metricsReporterFactoryShouldThrowExceptionWhenMetricsReporterClassIsIllegal() {
-    when(config.getMetricReporterClassName()).thenReturn(IllegalTestMetricsReporter.class.getName());
-    when(config.getProps()).thenReturn(new TypedProperties());
-    assertThrows(HoodieException.class, () -> MetricsReporterFactory.createReporter(config, registry));
+    when(metricsConfig.getMetricReporterClassName()).thenReturn(IllegalTestMetricsReporter.class.getName());
+    when(metricsConfig.getProps()).thenReturn(new TypedProperties());
+    assertThrows(HoodieException.class, () -> MetricsReporterFactory.createReporter(metricsConfig, registry));
   }
 
   public static class DummyMetricsReporter extends CustomizableMetricsReporter {
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/cloudwatch/TestCloudWatchMetricsReporter.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/cloudwatch/TestCloudWatchMetricsReporter.java
index 7901d802465..4b1aaffbf86 100644
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/cloudwatch/TestCloudWatchMetricsReporter.java
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/cloudwatch/TestCloudWatchMetricsReporter.java
@@ -19,7 +19,9 @@
 package org.apache.hudi.metrics.cloudwatch;
 
 import org.apache.hudi.aws.cloudwatch.CloudWatchReporter;
-import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
+import org.apache.hudi.metrics.MetricsReporterFactory;
+import org.apache.hudi.metrics.MetricsReporterType;
 
 import com.codahale.metrics.MetricRegistry;
 import org.junit.jupiter.api.Test;
@@ -27,8 +29,11 @@ import org.junit.jupiter.api.extension.ExtendWith;
 import org.mockito.Mock;
 import org.mockito.junit.jupiter.MockitoExtension;
 
+import java.lang.reflect.InvocationTargetException;
+import java.util.Arrays;
 import java.util.concurrent.TimeUnit;
 
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -37,7 +42,7 @@ import static org.mockito.Mockito.when;
 public class TestCloudWatchMetricsReporter {
 
   @Mock
-  private HoodieWriteConfig config;
+  private HoodieMetricsConfig metricsConfig;
 
   @Mock
   private MetricRegistry registry;
@@ -47,8 +52,8 @@ public class TestCloudWatchMetricsReporter {
 
   @Test
   public void testReporter() {
-    when(config.getCloudWatchReportPeriodSeconds()).thenReturn(30);
-    CloudWatchMetricsReporter metricsReporter = new CloudWatchMetricsReporter(config, registry, reporter);
+    when(metricsConfig.getCloudWatchReportPeriodSeconds()).thenReturn(30);
+    CloudWatchMetricsReporter metricsReporter = new CloudWatchMetricsReporter(metricsConfig, registry, reporter);
 
     metricsReporter.start();
     verify(reporter, times(1)).start(30, TimeUnit.SECONDS);
@@ -59,4 +64,18 @@ public class TestCloudWatchMetricsReporter {
     metricsReporter.stop();
     verify(reporter, times(1)).stop();
   }
+
+  @Test
+  public void testReporterViaReporterFactory() {
+    try {
+      when(metricsConfig.getMetricsReporterType()).thenReturn(MetricsReporterType.CLOUDWATCH);
+      // MetricsReporterFactory uses reflection to create CloudWatchMetricsReporter
+      // This test verifies that reflection is working well and is able to invoke the CloudWatchMetricsReporter constructor
+      MetricsReporterFactory.createReporter(metricsConfig, registry).get();
+    } catch (Exception e) {
+      assertTrue(e.getCause() instanceof InvocationTargetException);
+      assertTrue(Arrays.stream(((InvocationTargetException) e.getCause()).getTargetException().getStackTrace()).anyMatch(
+          ste -> ste.toString().contains("org.apache.hudi.aws.cloudwatch.CloudWatchReporter.getAmazonCloudWatchClient")));
+    }
+  }
 }
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/datadog/TestDatadogMetricsReporter.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/datadog/TestDatadogMetricsReporter.java
index 16120fe2f24..55637a241e2 100644
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/datadog/TestDatadogMetricsReporter.java
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/datadog/TestDatadogMetricsReporter.java
@@ -19,6 +19,7 @@
 package org.apache.hudi.metrics.datadog;
 
 import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.metrics.HoodieMetrics;
 import org.apache.hudi.metrics.Metrics;
 import org.apache.hudi.metrics.MetricsReporterType;
@@ -43,7 +44,9 @@ import static org.mockito.Mockito.when;
 public class TestDatadogMetricsReporter {
 
   @Mock
-  HoodieWriteConfig config;
+  HoodieWriteConfig writeConfig;
+  @Mock
+  HoodieMetricsConfig metricsConfig;
   HoodieMetrics hoodieMetrics;
   Metrics metrics;
 
@@ -59,14 +62,15 @@ public class TestDatadogMetricsReporter {
 
   @Test
   public void instantiationShouldFailWhenNoApiKey() {
-    when(config.isMetricsOn()).thenReturn(true);
-    when(config.getTableName()).thenReturn("table1");
-    when(config.getMetricsReporterType()).thenReturn(MetricsReporterType.DATADOG);
-    when(config.getDatadogApiKey()).thenReturn("");
-    when(config.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
+    when(writeConfig.getMetricsConfig()).thenReturn(metricsConfig);
+    when(writeConfig.isMetricsOn()).thenReturn(true);
+
+    when(metricsConfig.getMetricsReporterType()).thenReturn(MetricsReporterType.DATADOG);
+    when(metricsConfig.getDatadogApiKey()).thenReturn("");
+    when(metricsConfig.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
 
     Throwable t = assertThrows(IllegalStateException.class, () -> {
-      hoodieMetrics = new HoodieMetrics(config);
+      hoodieMetrics = new HoodieMetrics(writeConfig);
       metrics = hoodieMetrics.getMetrics();
     });
     assertEquals("Datadog cannot be initialized: API key is null or empty.", t.getMessage());
@@ -74,14 +78,15 @@ public class TestDatadogMetricsReporter {
 
   @Test
   public void instantiationShouldFailWhenNoMetricPrefix() {
-    when(config.isMetricsOn()).thenReturn(true);
-    when(config.getTableName()).thenReturn("table1");
-    when(config.getMetricsReporterType()).thenReturn(MetricsReporterType.DATADOG);
-    when(config.getDatadogApiKey()).thenReturn("foo");
-    when(config.getDatadogMetricPrefix()).thenReturn("");
-    when(config.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
+    when(writeConfig.getMetricsConfig()).thenReturn(metricsConfig);
+    when(writeConfig.isMetricsOn()).thenReturn(true);
+
+    when(metricsConfig.getMetricsReporterType()).thenReturn(MetricsReporterType.DATADOG);
+    when(metricsConfig.getDatadogApiKey()).thenReturn("foo");
+    when(metricsConfig.getDatadogMetricPrefix()).thenReturn("");
+    when(metricsConfig.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
     Throwable t = assertThrows(IllegalStateException.class, () -> {
-      hoodieMetrics = new HoodieMetrics(config);
+      hoodieMetrics = new HoodieMetrics(writeConfig);
       metrics = hoodieMetrics.getMetrics();
     });
     assertEquals("Datadog cannot be initialized: Metric prefix is null or empty.", t.getMessage());
@@ -89,20 +94,21 @@ public class TestDatadogMetricsReporter {
 
   @Test
   public void instantiationShouldSucceed() {
-    when(config.isMetricsOn()).thenReturn(true);
-    when(config.getTableName()).thenReturn("table1");
-    when(config.getMetricsReporterType()).thenReturn(MetricsReporterType.DATADOG);
-    when(config.getDatadogApiSite()).thenReturn(ApiSite.EU);
-    when(config.getDatadogApiKey()).thenReturn("foo");
-    when(config.getDatadogApiKeySkipValidation()).thenReturn(true);
-    when(config.getDatadogMetricPrefix()).thenReturn("bar");
-    when(config.getDatadogMetricHost()).thenReturn("foo");
-    when(config.getDatadogMetricTags()).thenReturn(Arrays.asList("baz", "foo"));
-    when(config.getDatadogReportPeriodSeconds()).thenReturn(10);
-    when(config.getMetricReporterMetricsNamePrefix()).thenReturn("");
-    when(config.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
+    when(writeConfig.getMetricsConfig()).thenReturn(metricsConfig);
+    when(writeConfig.isMetricsOn()).thenReturn(true);
+
+    when(metricsConfig.getMetricsReporterType()).thenReturn(MetricsReporterType.DATADOG);
+    when(metricsConfig.getDatadogApiSite()).thenReturn(ApiSite.EU);
+    when(metricsConfig.getDatadogApiKey()).thenReturn("foo");
+    when(metricsConfig.getDatadogApiKeySkipValidation()).thenReturn(true);
+    when(metricsConfig.getDatadogMetricPrefix()).thenReturn("bar");
+    when(metricsConfig.getDatadogMetricHost()).thenReturn("foo");
+    when(metricsConfig.getDatadogMetricTags()).thenReturn(Arrays.asList("baz", "foo"));
+    when(metricsConfig.getDatadogReportPeriodSeconds()).thenReturn(10);
+    when(metricsConfig.getMetricReporterMetricsNamePrefix()).thenReturn("");
+    when(metricsConfig.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
     assertDoesNotThrow(() -> {
-      hoodieMetrics = new HoodieMetrics(config);
+      hoodieMetrics = new HoodieMetrics(writeConfig);
       metrics = hoodieMetrics.getMetrics();
     });
   }
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/m3/TestM3Metrics.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/m3/TestM3Metrics.java
index e7299d706b8..65c4b1d4aba 100644
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/m3/TestM3Metrics.java
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/m3/TestM3Metrics.java
@@ -25,6 +25,7 @@ import static org.mockito.Mockito.when;
 import java.util.UUID;
 import org.apache.hudi.common.testutils.NetworkTestUtils;
 import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.metrics.HoodieMetrics;
 import org.apache.hudi.metrics.Metrics;
 import org.apache.hudi.metrics.MetricsReporterType;
@@ -38,27 +39,30 @@ import org.mockito.junit.jupiter.MockitoExtension;
 public class TestM3Metrics {
 
   @Mock
-  HoodieWriteConfig config;
+  HoodieWriteConfig writeConfig;
+  @Mock
+  HoodieMetricsConfig metricsConfig;
   HoodieMetrics hoodieMetrics;
   Metrics metrics;
 
   @BeforeEach
   public void start() {
-    when(config.isMetricsOn()).thenReturn(true);
-    when(config.getMetricsReporterType()).thenReturn(MetricsReporterType.M3);
-    when(config.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
+    when(metricsConfig.getMetricsReporterType()).thenReturn(MetricsReporterType.M3);
+    when(metricsConfig.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
   }
 
   @Test
   public void testRegisterGauge() {
-    when(config.getM3ServerHost()).thenReturn("localhost");
-    when(config.getM3ServerPort()).thenReturn(NetworkTestUtils.nextFreePort());
-    when(config.getTableName()).thenReturn("raw_table");
-    when(config.getM3Env()).thenReturn("dev");
-    when(config.getM3Service()).thenReturn("hoodie");
-    when(config.getM3Tags()).thenReturn("tag1=value1,tag2=value2");
-    when(config.getMetricReporterMetricsNamePrefix()).thenReturn("");
-    hoodieMetrics = new HoodieMetrics(config);
+    when(writeConfig.getTableName()).thenReturn("raw_table");
+    when(writeConfig.getMetricsConfig()).thenReturn(metricsConfig);
+    when(writeConfig.isMetricsOn()).thenReturn(true);
+    when(metricsConfig.getM3ServerHost()).thenReturn("localhost");
+    when(metricsConfig.getM3ServerPort()).thenReturn(NetworkTestUtils.nextFreePort());
+    when(metricsConfig.getM3Env()).thenReturn("dev");
+    when(metricsConfig.getM3Service()).thenReturn("hoodie");
+    when(metricsConfig.getM3Tags()).thenReturn("tag1=value1,tag2=value2");
+    when(metricsConfig.getMetricReporterMetricsNamePrefix()).thenReturn("");
+    hoodieMetrics = new HoodieMetrics(writeConfig);
     metrics = hoodieMetrics.getMetrics();
     metrics.registerGauge("metric1", 123L);
     assertEquals("123", metrics.getRegistry().getGauges().get("metric1").getValue().toString());
@@ -67,14 +71,16 @@ public class TestM3Metrics {
 
   @Test
   public void testEmptyM3Tags() {
-    when(config.getM3ServerHost()).thenReturn("localhost");
-    when(config.getM3ServerPort()).thenReturn(NetworkTestUtils.nextFreePort());
-    when(config.getTableName()).thenReturn("raw_table");
-    when(config.getM3Env()).thenReturn("dev");
-    when(config.getM3Service()).thenReturn("hoodie");
-    when(config.getM3Tags()).thenReturn("");
-    when(config.getMetricReporterMetricsNamePrefix()).thenReturn("");
-    hoodieMetrics = new HoodieMetrics(config);
+    when(writeConfig.getTableName()).thenReturn("raw_table");
+    when(writeConfig.getMetricsConfig()).thenReturn(metricsConfig);
+    when(writeConfig.isMetricsOn()).thenReturn(true);
+    when(metricsConfig.getM3ServerHost()).thenReturn("localhost");
+    when(metricsConfig.getM3ServerPort()).thenReturn(NetworkTestUtils.nextFreePort());
+    when(metricsConfig.getM3Env()).thenReturn("dev");
+    when(metricsConfig.getM3Service()).thenReturn("hoodie");
+    when(metricsConfig.getM3Tags()).thenReturn("");
+    when(metricsConfig.getMetricReporterMetricsNamePrefix()).thenReturn("");
+    hoodieMetrics = new HoodieMetrics(writeConfig);
     metrics = hoodieMetrics.getMetrics();
     metrics.registerGauge("metric1", 123L);
     assertEquals("123", metrics.getRegistry().getGauges().get("metric1").getValue().toString());
@@ -83,10 +89,12 @@ public class TestM3Metrics {
 
   @Test
   public void testInvalidM3Tags() {
-    when(config.getTableName()).thenReturn("raw_table");
-    when(config.getMetricReporterMetricsNamePrefix()).thenReturn("");
+    when(writeConfig.getTableName()).thenReturn("raw_table");
+    when(writeConfig.getMetricsConfig()).thenReturn(metricsConfig);
+    when(writeConfig.isMetricsOn()).thenReturn(true);
+    when(metricsConfig.getMetricReporterMetricsNamePrefix()).thenReturn("");
     assertThrows(RuntimeException.class, () -> {
-      hoodieMetrics = new HoodieMetrics(config);
+      hoodieMetrics = new HoodieMetrics(writeConfig);
     });
   }
 }
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/prometheus/TestPrometheusReporter.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/prometheus/TestPrometheusReporter.java
index 4e94ece52c9..9ad2b8388a2 100644
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/prometheus/TestPrometheusReporter.java
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/prometheus/TestPrometheusReporter.java
@@ -19,6 +19,7 @@
 package org.apache.hudi.metrics.prometheus;
 
 import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.metrics.HoodieMetrics;
 import org.apache.hudi.metrics.Metrics;
 import org.apache.hudi.metrics.MetricsReporterType;
@@ -38,7 +39,9 @@ import static org.mockito.Mockito.when;
 public class TestPrometheusReporter {
 
   @Mock
-  HoodieWriteConfig config;
+  HoodieWriteConfig writeConfig;
+  @Mock
+  HoodieMetricsConfig metricsConfig;
   HoodieMetrics hoodieMetrics;
   Metrics metrics;
 
@@ -51,14 +54,14 @@ public class TestPrometheusReporter {
 
   @Test
   public void testRegisterGauge() {
-    when(config.isMetricsOn()).thenReturn(true);
-    when(config.getTableName()).thenReturn("foo");
-    when(config.getMetricsReporterType()).thenReturn(MetricsReporterType.PROMETHEUS);
-    when(config.getPrometheusPort()).thenReturn(9090);
-    when(config.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
+    when(writeConfig.getMetricsConfig()).thenReturn(metricsConfig);
+    when(writeConfig.isMetricsOn()).thenReturn(true);
+    when(metricsConfig.getMetricsReporterType()).thenReturn(MetricsReporterType.PROMETHEUS);
+    when(metricsConfig.getPrometheusPort()).thenReturn(9090);
+    when(metricsConfig.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
     assertDoesNotThrow(() -> {
-      new HoodieMetrics(config);
-      hoodieMetrics = new HoodieMetrics(config);
+      new HoodieMetrics(writeConfig);
+      hoodieMetrics = new HoodieMetrics(writeConfig);
       metrics = hoodieMetrics.getMetrics();
     });
   }
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/prometheus/TestPushGateWayReporter.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/prometheus/TestPushGateWayReporter.java
index 27f7c5a8345..aa1c3f06b6f 100644
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/prometheus/TestPushGateWayReporter.java
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/metrics/prometheus/TestPushGateWayReporter.java
@@ -20,6 +20,7 @@ package org.apache.hudi.metrics.prometheus;
 
 import org.apache.hudi.common.util.Option;
 import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.metrics.HoodieMetrics;
 import org.apache.hudi.metrics.MetricUtils;
 import org.apache.hudi.metrics.Metrics;
@@ -56,7 +57,9 @@ public class TestPushGateWayReporter {
   static final URL PROP_FILE_DATADOG_URL = TestPushGateWayReporter.class.getClassLoader().getResource("datadog.properties");
 
   @Mock
-  HoodieWriteConfig config;
+  HoodieWriteConfig writeConfig;
+  @Mock
+  HoodieMetricsConfig metricsConfig;
 
   HoodieMetrics hoodieMetrics;
   Metrics metrics;
@@ -70,10 +73,12 @@ public class TestPushGateWayReporter {
 
   @Test
   public void testRegisterGauge() {
-    when(config.isMetricsOn()).thenReturn(true);
+    when(writeConfig.isMetricsOn()).thenReturn(true);
+    when(writeConfig.getMetricsConfig()).thenReturn(metricsConfig);
+    configureDefaultReporter();
 
     assertDoesNotThrow(() -> {
-      hoodieMetrics = new HoodieMetrics(config);
+      hoodieMetrics = new HoodieMetrics(writeConfig);
       metrics = hoodieMetrics.getMetrics();
     });
 
@@ -85,21 +90,20 @@ public class TestPushGateWayReporter {
   @ParameterizedTest
   @ValueSource(booleans = {true, false})
   public void testMultiReporter(boolean addDefaultReporter) throws IOException, InterruptedException, URISyntaxException {
+    when(writeConfig.getMetricsConfig()).thenReturn(metricsConfig);
+    when(writeConfig.isMetricsOn()).thenReturn(true);
 
     String propPrometheusPath = Objects.requireNonNull(PROP_FILE_PROMETHEUS_URL).toURI().getPath();
     String propDatadogPath = Objects.requireNonNull(PROP_FILE_DATADOG_URL).toURI().getPath();
     if (addDefaultReporter) {
-      when(config.isMetricsOn()).thenReturn(true);
-      when(config.getMetricsReporterType()).thenReturn(MetricsReporterType.PROMETHEUS_PUSHGATEWAY);
-      when(config.getPushGatewayReportPeriodSeconds()).thenReturn(30);
+      configureDefaultReporter();
     } else {
-      when(config.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
-      when(config.getMetricReporterMetricsNamePrefix()).thenReturn(TestPushGateWayReporter.class.getSimpleName());
-      when(config.getMetricReporterFileBasedConfigs()).thenReturn(propPrometheusPath + "," + propDatadogPath);
-      when(config.isMetricsOn()).thenReturn(true);
+      when(metricsConfig.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
+      when(metricsConfig.getMetricReporterMetricsNamePrefix()).thenReturn(TestPushGateWayReporter.class.getSimpleName());
+      when(metricsConfig.getMetricReporterFileBasedConfigs()).thenReturn(propPrometheusPath + "," + propDatadogPath);
     }
 
-    hoodieMetrics = new HoodieMetrics(config);
+    hoodieMetrics = new HoodieMetrics(writeConfig);
     metrics = hoodieMetrics.getMetrics();
 
     Map<String, Long> metricsMap = new HashMap<>();
@@ -123,29 +127,29 @@ public class TestPushGateWayReporter {
     PushGatewayMetricsReporter reporter;
     Map<String, String> labels;
 
-    when(config.getPushGatewayLabels()).thenReturn("hudi:prometheus");
-    reporter = new PushGatewayMetricsReporter(config, null);
+    when(metricsConfig.getPushGatewayLabels()).thenReturn("hudi:prometheus");
+    reporter = new PushGatewayMetricsReporter(metricsConfig, null);
     labels = reporter.getLabels();
     assertEquals(1, labels.size());
     assertTrue(labels.containsKey("hudi"));
     assertTrue(labels.containsValue("prometheus"));
 
-    when(config.getPushGatewayLabels()).thenReturn("hudi:prome:theus");
-    reporter = new PushGatewayMetricsReporter(config, null);
+    when(metricsConfig.getPushGatewayLabels()).thenReturn("hudi:prome:theus");
+    reporter = new PushGatewayMetricsReporter(metricsConfig, null);
     labels = reporter.getLabels();
     assertEquals(1, labels.size());
     assertTrue(labels.containsKey("hudi"));
     assertTrue(labels.containsValue("prome:theus"));
 
-    when(config.getPushGatewayLabels()).thenReturn("hudiprometheus");
-    reporter = new PushGatewayMetricsReporter(config, null);
+    when(metricsConfig.getPushGatewayLabels()).thenReturn("hudiprometheus");
+    reporter = new PushGatewayMetricsReporter(metricsConfig, null);
     labels = reporter.getLabels();
     assertEquals(1, labels.size());
     assertTrue(labels.containsKey("hudiprometheus"));
     assertTrue(labels.containsValue(""));
 
-    when(config.getPushGatewayLabels()).thenReturn("hudi1:prometheus,hudi2:prometheus");
-    reporter = new PushGatewayMetricsReporter(config, null);
+    when(metricsConfig.getPushGatewayLabels()).thenReturn("hudi1:prometheus,hudi2:prometheus");
+    reporter = new PushGatewayMetricsReporter(metricsConfig, null);
     labels = reporter.getLabels();
     assertEquals(2, labels.size());
     assertTrue(labels.containsKey("hudi1"));
@@ -153,11 +157,17 @@ public class TestPushGateWayReporter {
     assertTrue(labels.containsValue("prometheus"));
 
     try {
-      when(config.getPushGatewayLabels()).thenReturn("hudi:prometheus,hudi:prom");
-      reporter = new PushGatewayMetricsReporter(config, null);
+      when(metricsConfig.getPushGatewayLabels()).thenReturn("hudi:prometheus,hudi:prom");
+      reporter = new PushGatewayMetricsReporter(metricsConfig, null);
       fail("Should fail");
     } catch (IllegalStateException e) {
       assertTrue(e.getMessage().contains("Multiple values {prometheus, prom} for same key"));
     }
   }
+
+  private void configureDefaultReporter() {
+    when(metricsConfig.getBasePath()).thenReturn("s3://test" + UUID.randomUUID());
+    when(metricsConfig.getMetricsReporterType()).thenReturn(MetricsReporterType.PROMETHEUS_PUSHGATEWAY);
+    when(metricsConfig.getPushGatewayReportPeriodSeconds()).thenReturn(30);
+  }
 }
diff --git a/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/metadata/FlinkHoodieBackedTableMetadataWriter.java b/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/metadata/FlinkHoodieBackedTableMetadataWriter.java
index 61999c44b6e..bafee7295c3 100644
--- a/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/metadata/FlinkHoodieBackedTableMetadataWriter.java
+++ b/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/metadata/FlinkHoodieBackedTableMetadataWriter.java
@@ -23,7 +23,6 @@ import org.apache.hudi.client.HoodieFlinkWriteClient;
 import org.apache.hudi.client.WriteStatus;
 import org.apache.hudi.common.data.HoodieData;
 import org.apache.hudi.common.engine.HoodieEngineContext;
-import org.apache.hudi.common.metrics.Registry;
 import org.apache.hudi.common.model.HoodieFailedWritesCleaningPolicy;
 import org.apache.hudi.common.model.HoodieRecord;
 import org.apache.hudi.common.table.HoodieTableMetaClient;
@@ -87,8 +86,7 @@ public class FlinkHoodieBackedTableMetadataWriter extends HoodieBackedTableMetad
   protected void initRegistry() {
     if (metadataWriteConfig.isMetricsOn()) {
       // should support executor metrics
-      Registry registry = Registry.getRegistry("HoodieMetadata");
-      this.metrics = Option.of(new HoodieMetadataMetrics(registry));
+      this.metrics = Option.of(new HoodieMetadataMetrics(metadataWriteConfig.getMetricsConfig()));
     } else {
       this.metrics = Option.empty();
     }
diff --git a/hudi-client/hudi-java-client/src/main/java/org/apache/hudi/metadata/JavaHoodieBackedTableMetadataWriter.java b/hudi-client/hudi-java-client/src/main/java/org/apache/hudi/metadata/JavaHoodieBackedTableMetadataWriter.java
index f16392378c8..cca1b883882 100644
--- a/hudi-client/hudi-java-client/src/main/java/org/apache/hudi/metadata/JavaHoodieBackedTableMetadataWriter.java
+++ b/hudi-client/hudi-java-client/src/main/java/org/apache/hudi/metadata/JavaHoodieBackedTableMetadataWriter.java
@@ -22,7 +22,6 @@ import org.apache.hudi.client.BaseHoodieWriteClient;
 import org.apache.hudi.client.HoodieJavaWriteClient;
 import org.apache.hudi.common.data.HoodieData;
 import org.apache.hudi.common.engine.HoodieEngineContext;
-import org.apache.hudi.common.metrics.Registry;
 import org.apache.hudi.common.model.HoodieFailedWritesCleaningPolicy;
 import org.apache.hudi.common.model.HoodieRecord;
 import org.apache.hudi.common.table.timeline.HoodieActiveTimeline;
@@ -74,8 +73,7 @@ public class JavaHoodieBackedTableMetadataWriter extends HoodieBackedTableMetada
   @Override
   protected void initRegistry() {
     if (metadataWriteConfig.isMetricsOn()) {
-      Registry registry = Registry.getRegistry("HoodieMetadata");
-      this.metrics = Option.of(new HoodieMetadataMetrics(registry));
+      this.metrics = Option.of(new HoodieMetadataMetrics(metadataWriteConfig.getMetricsConfig()));
     } else {
       this.metrics = Option.empty();
     }
diff --git a/hudi-client/hudi-java-client/src/test/java/org/apache/hudi/client/TestJavaHoodieBackedMetadata.java b/hudi-client/hudi-java-client/src/test/java/org/apache/hudi/client/TestJavaHoodieBackedMetadata.java
index 8e1bbc84b4b..22f46e58f62 100644
--- a/hudi-client/hudi-java-client/src/test/java/org/apache/hudi/client/TestJavaHoodieBackedMetadata.java
+++ b/hudi-client/hudi-java-client/src/test/java/org/apache/hudi/client/TestJavaHoodieBackedMetadata.java
@@ -33,7 +33,6 @@ import org.apache.hudi.common.config.SerializableConfiguration;
 import org.apache.hudi.common.engine.HoodieEngineContext;
 import org.apache.hudi.common.fs.ConsistencyGuardConfig;
 import org.apache.hudi.common.fs.FSUtils;
-import org.apache.hudi.common.metrics.Registry;
 import org.apache.hudi.common.model.FileSlice;
 import org.apache.hudi.common.model.HoodieAvroRecord;
 import org.apache.hudi.common.model.HoodieBaseFile;
@@ -98,6 +97,7 @@ import org.apache.hudi.metadata.HoodieTableMetadata;
 import org.apache.hudi.metadata.HoodieTableMetadataUtil;
 import org.apache.hudi.metadata.JavaHoodieBackedTableMetadataWriter;
 import org.apache.hudi.metadata.MetadataPartitionType;
+import org.apache.hudi.metrics.Metrics;
 import org.apache.hudi.storage.StoragePath;
 import org.apache.hudi.table.HoodieJavaTable;
 import org.apache.hudi.table.HoodieTable;
@@ -2340,7 +2340,8 @@ public class TestJavaHoodieBackedMetadata extends TestHoodieMetadataBase {
     init(HoodieTableType.COPY_ON_WRITE, false);
     HoodieEngineContext engineContext = new HoodieJavaEngineContext(hadoopConf);
 
-    try (HoodieJavaWriteClient client = new HoodieJavaWriteClient(engineContext, getWriteConfigBuilder(true, true, true).build())) {
+    HoodieWriteConfig writeConfig = getWriteConfigBuilder(true, true, true).build();
+    try (HoodieJavaWriteClient client = new HoodieJavaWriteClient(engineContext, writeConfig)) {
       // Write
       String newCommitTime = HoodieActiveTimeline.createNewInstantTime();
       List<HoodieRecord> records = dataGen.generateInserts(newCommitTime, 20);
@@ -2349,15 +2350,15 @@ public class TestJavaHoodieBackedMetadata extends TestHoodieMetadataBase {
       assertNoWriteErrors(writeStatuses);
       validateMetadata(client);
 
-      Registry metricsRegistry = Registry.getRegistry("HoodieMetadata");
-      assertTrue(metricsRegistry.getAllCounts().containsKey(HoodieMetadataMetrics.INITIALIZE_STR + ".count"));
-      assertTrue(metricsRegistry.getAllCounts().containsKey(HoodieMetadataMetrics.INITIALIZE_STR + ".totalDuration"));
-      assertTrue(metricsRegistry.getAllCounts().get(HoodieMetadataMetrics.INITIALIZE_STR + ".count") >= 1L);
+      Metrics metrics = Metrics.getInstance(writeConfig.getMetricsConfig());
+      assertTrue(metrics.getRegistry().getGauges().containsKey(HoodieMetadataMetrics.INITIALIZE_STR + ".count"));
+      assertTrue(metrics.getRegistry().getGauges().containsKey(HoodieMetadataMetrics.INITIALIZE_STR + ".totalDuration"));
+      assertTrue((Long) metrics.getRegistry().getGauges().get(HoodieMetadataMetrics.INITIALIZE_STR + ".count").getValue() >= 1L);
       final String prefix = FILES.getPartitionPath() + ".";
-      assertTrue(metricsRegistry.getAllCounts().containsKey(prefix + HoodieMetadataMetrics.STAT_COUNT_BASE_FILES));
-      assertTrue(metricsRegistry.getAllCounts().containsKey(prefix + HoodieMetadataMetrics.STAT_COUNT_LOG_FILES));
-      assertTrue(metricsRegistry.getAllCounts().containsKey(prefix + HoodieMetadataMetrics.STAT_TOTAL_BASE_FILE_SIZE));
-      assertTrue(metricsRegistry.getAllCounts().containsKey(prefix + HoodieMetadataMetrics.STAT_TOTAL_LOG_FILE_SIZE));
+      assertTrue(metrics.getRegistry().getGauges().containsKey(prefix + HoodieMetadataMetrics.STAT_COUNT_BASE_FILES));
+      assertTrue(metrics.getRegistry().getGauges().containsKey(prefix + HoodieMetadataMetrics.STAT_COUNT_LOG_FILES));
+      assertTrue(metrics.getRegistry().getGauges().containsKey(prefix + HoodieMetadataMetrics.STAT_TOTAL_BASE_FILE_SIZE));
+      assertTrue(metrics.getRegistry().getGauges().containsKey(prefix + HoodieMetadataMetrics.STAT_TOTAL_LOG_FILE_SIZE));
     }
   }
 
diff --git a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/metadata/SparkHoodieBackedTableMetadataWriter.java b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/metadata/SparkHoodieBackedTableMetadataWriter.java
index 15b527a0fe3..d6e964e7faf 100644
--- a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/metadata/SparkHoodieBackedTableMetadataWriter.java
+++ b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/metadata/SparkHoodieBackedTableMetadataWriter.java
@@ -106,7 +106,7 @@ public class SparkHoodieBackedTableMetadataWriter extends HoodieBackedTableMetad
       } else {
         registry = Registry.getRegistry("HoodieMetadata");
       }
-      this.metrics = Option.of(new HoodieMetadataMetrics(registry));
+      this.metrics = Option.of(new HoodieMetadataMetrics(metadataWriteConfig.getMetricsConfig()));
     } else {
       this.metrics = Option.empty();
     }
diff --git a/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/client/functional/TestHoodieBackedMetadata.java b/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/client/functional/TestHoodieBackedMetadata.java
index ba78f18efae..6cc474676de 100644
--- a/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/client/functional/TestHoodieBackedMetadata.java
+++ b/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/client/functional/TestHoodieBackedMetadata.java
@@ -33,7 +33,6 @@ import org.apache.hudi.common.config.LockConfiguration;
 import org.apache.hudi.common.config.SerializableConfiguration;
 import org.apache.hudi.common.fs.ConsistencyGuardConfig;
 import org.apache.hudi.common.fs.FSUtils;
-import org.apache.hudi.common.metrics.Registry;
 import org.apache.hudi.common.model.FileSlice;
 import org.apache.hudi.common.model.HoodieAvroRecord;
 import org.apache.hudi.common.model.HoodieBaseFile;
@@ -101,6 +100,7 @@ import org.apache.hudi.metadata.HoodieTableMetadata;
 import org.apache.hudi.metadata.HoodieTableMetadataUtil;
 import org.apache.hudi.metadata.MetadataPartitionType;
 import org.apache.hudi.metadata.SparkHoodieBackedTableMetadataWriter;
+import org.apache.hudi.metrics.Metrics;
 import org.apache.hudi.storage.StoragePath;
 import org.apache.hudi.table.HoodieSparkTable;
 import org.apache.hudi.table.HoodieTable;
@@ -2981,15 +2981,15 @@ public class TestHoodieBackedMetadata extends TestHoodieMetadataBase {
       assertNoWriteErrors(writeStatuses);
       validateMetadata(client);
 
-      Registry metricsRegistry = Registry.getRegistry("HoodieMetadata");
-      assertTrue(metricsRegistry.getAllCounts().containsKey(HoodieMetadataMetrics.INITIALIZE_STR + ".count"));
-      assertTrue(metricsRegistry.getAllCounts().containsKey(HoodieMetadataMetrics.INITIALIZE_STR + ".totalDuration"));
-      assertTrue(metricsRegistry.getAllCounts().get(HoodieMetadataMetrics.INITIALIZE_STR + ".count") >= 1L);
+      Metrics metrics = Metrics.getInstance(writeConfig.getMetricsConfig());
+      assertTrue(metrics.getRegistry().getGauges().containsKey(HoodieMetadataMetrics.INITIALIZE_STR + ".count"));
+      assertTrue(metrics.getRegistry().getGauges().containsKey(HoodieMetadataMetrics.INITIALIZE_STR + ".totalDuration"));
+      assertTrue((Long) metrics.getRegistry().getGauges().get(HoodieMetadataMetrics.INITIALIZE_STR + ".count").getValue() >= 1L);
       final String prefix = FILES.getPartitionPath() + ".";
-      assertTrue(metricsRegistry.getAllCounts().containsKey(prefix + HoodieMetadataMetrics.STAT_COUNT_BASE_FILES));
-      assertTrue(metricsRegistry.getAllCounts().containsKey(prefix + HoodieMetadataMetrics.STAT_COUNT_LOG_FILES));
-      assertTrue(metricsRegistry.getAllCounts().containsKey(prefix + HoodieMetadataMetrics.STAT_TOTAL_BASE_FILE_SIZE));
-      assertTrue(metricsRegistry.getAllCounts().containsKey(prefix + HoodieMetadataMetrics.STAT_TOTAL_LOG_FILE_SIZE));
+      assertTrue(metrics.getRegistry().getGauges().containsKey(prefix + HoodieMetadataMetrics.STAT_COUNT_BASE_FILES));
+      assertTrue(metrics.getRegistry().getGauges().containsKey(prefix + HoodieMetadataMetrics.STAT_COUNT_LOG_FILES));
+      assertTrue(metrics.getRegistry().getGauges().containsKey(prefix + HoodieMetadataMetrics.STAT_TOTAL_BASE_FILE_SIZE));
+      assertTrue(metrics.getRegistry().getGauges().containsKey(prefix + HoodieMetadataMetrics.STAT_TOTAL_LOG_FILE_SIZE));
     }
   }
 
diff --git a/hudi-common/pom.xml b/hudi-common/pom.xml
index 3cb5bcc233e..6e2aee560f4 100644
--- a/hudi-common/pom.xml
+++ b/hudi-common/pom.xml
@@ -316,5 +316,52 @@
       <artifactId>disruptor</artifactId>
       <version>${disruptor.version}</version>
     </dependency>
+
+    <!-- Dropwizard Metrics -->
+    <dependency>
+          <groupId>io.dropwizard.metrics</groupId>
+          <artifactId>metrics-graphite</artifactId>
+          <exclusions>
+              <exclusion>
+                  <groupId>com.rabbitmq</groupId>
+                  <artifactId>*</artifactId>
+              </exclusion>
+          </exclusions>
+      </dependency>
+      <dependency>
+          <groupId>io.dropwizard.metrics</groupId>
+          <artifactId>metrics-core</artifactId>
+      </dependency>
+      <dependency>
+          <groupId>io.dropwizard.metrics</groupId>
+          <artifactId>metrics-jmx</artifactId>
+      </dependency>
+      <dependency>
+          <groupId>io.prometheus</groupId>
+          <artifactId>simpleclient</artifactId>
+      </dependency>
+      <dependency>
+          <groupId>io.prometheus</groupId>
+          <artifactId>simpleclient_httpserver</artifactId>
+      </dependency>
+      <dependency>
+          <groupId>io.prometheus</groupId>
+          <artifactId>simpleclient_dropwizard</artifactId>
+      </dependency>
+      <dependency>
+          <groupId>io.prometheus</groupId>
+          <artifactId>simpleclient_pushgateway</artifactId>
+      </dependency>
+    <dependency>
+      <groupId>com.uber.m3</groupId>
+      <artifactId>tally-m3</artifactId>
+      <version>${tally.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>com.uber.m3</groupId>
+      <artifactId>tally-core</artifactId>
+      <version>${tally.version}</version>
+    </dependency>
+
   </dependencies>
 </project>
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/config/HoodieCommonConfig.java b/hudi-common/src/main/java/org/apache/hudi/common/config/HoodieCommonConfig.java
index afb22a4a27e..1a4c2e31780 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/config/HoodieCommonConfig.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/config/HoodieCommonConfig.java
@@ -38,6 +38,14 @@ import static org.apache.hudi.common.util.ConfigUtils.enumNames;
     description = "The following set of configurations are common across Hudi.")
 public class HoodieCommonConfig extends HoodieConfig {
 
+  public static final ConfigProperty<String> BASE_PATH = ConfigProperty
+      .key("hoodie.base.path")
+      .noDefaultValue()
+      .withDocumentation("Base path on lake storage, under which all the table data is stored. "
+          + "Always prefix it explicitly with the storage scheme (e.g hdfs://, s3:// etc). "
+          + "Hudi stores all the main meta-data about commits, savepoints, cleaning audit logs "
+          + "etc in .hoodie directory under this base path directory.");
+
   public static final ConfigProperty<Boolean> SCHEMA_EVOLUTION_ENABLE = ConfigProperty
       .key("hoodie.schema.on.read.enable")
       .defaultValue(false)
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsCloudWatchConfig.java b/hudi-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsCloudWatchConfig.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsCloudWatchConfig.java
rename to hudi-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsCloudWatchConfig.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsConfig.java b/hudi-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsConfig.java
similarity index 60%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsConfig.java
rename to hudi-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsConfig.java
index 328619f5e9c..6ad389c05d7 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsConfig.java
+++ b/hudi-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsConfig.java
@@ -21,17 +21,25 @@ package org.apache.hudi.config.metrics;
 import org.apache.hudi.common.config.ConfigClassProperty;
 import org.apache.hudi.common.config.ConfigGroups;
 import org.apache.hudi.common.config.ConfigProperty;
+import org.apache.hudi.common.config.HoodieCommonConfig;
 import org.apache.hudi.common.config.HoodieConfig;
 import org.apache.hudi.common.table.HoodieTableConfig;
 import org.apache.hudi.common.util.Option;
+import org.apache.hudi.common.util.ReflectionUtils;
 import org.apache.hudi.metrics.MetricsReporterType;
+import org.apache.hudi.metrics.datadog.DatadogHttpClient;
 
 import javax.annotation.concurrent.Immutable;
 
 import java.io.File;
 import java.io.FileReader;
 import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.List;
 import java.util.Properties;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
 
 /**
  * Fetch the configurations used by the Metrics system.
@@ -156,6 +164,185 @@ public class HoodieMetricsConfig extends HoodieConfig {
     return new Builder();
   }
 
+  /**
+   * base properties.
+   */
+  public String getBasePath() {
+    return getString(HoodieCommonConfig.BASE_PATH);
+  }
+
+  /**
+   * metrics properties.
+   */
+  public boolean isMetricsOn() {
+    return getBoolean(HoodieMetricsConfig.TURN_METRICS_ON);
+  }
+
+  /**
+   * metrics properties.
+   */
+  public boolean isCompactionLogBlockMetricsOn() {
+    return getBoolean(HoodieMetricsConfig.TURN_METRICS_COMPACTION_LOG_BLOCKS_ON);
+  }
+
+  public boolean isExecutorMetricsEnabled() {
+    return Boolean.parseBoolean(
+        getStringOrDefault(HoodieMetricsConfig.EXECUTOR_METRICS_ENABLE, "false"));
+  }
+
+  public boolean isLockingMetricsEnabled() {
+    return getBoolean(HoodieMetricsConfig.LOCK_METRICS_ENABLE);
+  }
+
+  public MetricsReporterType getMetricsReporterType() {
+    return MetricsReporterType.valueOf(getString(HoodieMetricsConfig.METRICS_REPORTER_TYPE_VALUE));
+  }
+
+  public String getGraphiteServerHost() {
+    return getString(HoodieMetricsGraphiteConfig.GRAPHITE_SERVER_HOST_NAME);
+  }
+
+  public int getGraphiteServerPort() {
+    return getInt(HoodieMetricsGraphiteConfig.GRAPHITE_SERVER_PORT_NUM);
+  }
+
+  public String getGraphiteMetricPrefix() {
+    return getString(HoodieMetricsGraphiteConfig.GRAPHITE_METRIC_PREFIX_VALUE);
+  }
+
+  public int getGraphiteReportPeriodSeconds() {
+    return getInt(HoodieMetricsGraphiteConfig.GRAPHITE_REPORT_PERIOD_IN_SECONDS);
+  }
+
+  public String getM3ServerHost() {
+    return getString(HoodieMetricsM3Config.M3_SERVER_HOST_NAME);
+  }
+
+  public int getM3ServerPort() {
+    return getInt(HoodieMetricsM3Config.M3_SERVER_PORT_NUM);
+  }
+
+  public String getM3Tags() {
+    return getString(HoodieMetricsM3Config.M3_TAGS);
+  }
+
+  public String getM3Env() {
+    return getString(HoodieMetricsM3Config.M3_ENV);
+  }
+
+  public String getM3Service() {
+    return getString(HoodieMetricsM3Config.M3_SERVICE);
+  }
+
+  public String getJmxHost() {
+    return getString(HoodieMetricsJmxConfig.JMX_HOST_NAME);
+  }
+
+  public String getJmxPort() {
+    return getString(HoodieMetricsJmxConfig.JMX_PORT_NUM);
+  }
+
+  public int getDatadogReportPeriodSeconds() {
+    return getInt(HoodieMetricsDatadogConfig.REPORT_PERIOD_IN_SECONDS);
+  }
+
+  public DatadogHttpClient.ApiSite getDatadogApiSite() {
+    return DatadogHttpClient.ApiSite.valueOf(getString(HoodieMetricsDatadogConfig.API_SITE_VALUE));
+  }
+
+  public String getDatadogApiKey() {
+    if (props.containsKey(HoodieMetricsDatadogConfig.API_KEY.key())) {
+      return getString(HoodieMetricsDatadogConfig.API_KEY);
+
+    } else {
+      Supplier<String> apiKeySupplier = ReflectionUtils.loadClass(
+          getString(HoodieMetricsDatadogConfig.API_KEY_SUPPLIER));
+      return apiKeySupplier.get();
+    }
+  }
+
+  public boolean getDatadogApiKeySkipValidation() {
+    return getBoolean(HoodieMetricsDatadogConfig.API_KEY_SKIP_VALIDATION);
+  }
+
+  public int getDatadogApiTimeoutSeconds() {
+    return getInt(HoodieMetricsDatadogConfig.API_TIMEOUT_IN_SECONDS);
+  }
+
+  public String getDatadogMetricPrefix() {
+    return getString(HoodieMetricsDatadogConfig.METRIC_PREFIX_VALUE);
+  }
+
+  public String getDatadogMetricHost() {
+    return getString(HoodieMetricsDatadogConfig.METRIC_HOST_NAME);
+  }
+
+  public List<String> getDatadogMetricTags() {
+    return Arrays.stream(getStringOrDefault(
+        HoodieMetricsDatadogConfig.METRIC_TAG_VALUES, ",").split("\\s*,\\s*")).collect(Collectors.toList());
+  }
+
+  public int getCloudWatchReportPeriodSeconds() {
+    return getInt(HoodieMetricsCloudWatchConfig.REPORT_PERIOD_SECONDS);
+  }
+
+  public String getCloudWatchMetricPrefix() {
+    return getString(HoodieMetricsCloudWatchConfig.METRIC_PREFIX);
+  }
+
+  public String getCloudWatchMetricNamespace() {
+    return getString(HoodieMetricsCloudWatchConfig.METRIC_NAMESPACE);
+  }
+
+  public int getCloudWatchMaxDatumsPerRequest() {
+    return getInt(HoodieMetricsCloudWatchConfig.MAX_DATUMS_PER_REQUEST);
+  }
+
+  public String getMetricReporterClassName() {
+    return getString(HoodieMetricsConfig.METRICS_REPORTER_CLASS_NAME);
+  }
+
+  public int getPrometheusPort() {
+    return getInt(HoodieMetricsPrometheusConfig.PROMETHEUS_PORT_NUM);
+  }
+
+  public String getPushGatewayHost() {
+    return getString(HoodieMetricsPrometheusConfig.PUSHGATEWAY_HOST_NAME);
+  }
+
+  public int getPushGatewayPort() {
+    return getInt(HoodieMetricsPrometheusConfig.PUSHGATEWAY_PORT_NUM);
+  }
+
+  public int getPushGatewayReportPeriodSeconds() {
+    return getInt(HoodieMetricsPrometheusConfig.PUSHGATEWAY_REPORT_PERIOD_IN_SECONDS);
+  }
+
+  public boolean getPushGatewayDeleteOnShutdown() {
+    return getBoolean(HoodieMetricsPrometheusConfig.PUSHGATEWAY_DELETE_ON_SHUTDOWN_ENABLE);
+  }
+
+  public String getPushGatewayJobName() {
+    return getString(HoodieMetricsPrometheusConfig.PUSHGATEWAY_JOBNAME);
+  }
+
+  public String getPushGatewayLabels() {
+    return getString(HoodieMetricsPrometheusConfig.PUSHGATEWAY_LABELS);
+  }
+
+  public boolean getPushGatewayRandomJobNameSuffix() {
+    return getBoolean(HoodieMetricsPrometheusConfig.PUSHGATEWAY_RANDOM_JOBNAME_SUFFIX);
+  }
+
+  public String getMetricReporterMetricsNamePrefix() {
+    // Metrics prefixes should not have a dot as this is usually a separator
+    return getStringOrDefault(HoodieMetricsConfig.METRICS_REPORTER_PREFIX).replaceAll("\\.", "_");
+  }
+
+  public String getMetricReporterFileBasedConfigs() {
+    return getStringOrDefault(HoodieMetricsConfig.METRICS_REPORTER_FILE_BASED_CONFIGS_PATH);
+  }
+
   public static class Builder {
 
     private final HoodieMetricsConfig hoodieMetricsConfig = new HoodieMetricsConfig();
@@ -167,6 +354,15 @@ public class HoodieMetricsConfig extends HoodieConfig {
       }
     }
 
+    public Builder fromInputStream(InputStream inputStream) throws IOException {
+      try {
+        this.hoodieMetricsConfig.getProps().load(inputStream);
+        return this;
+      } finally {
+        inputStream.close();
+      }
+    }
+
     public Builder fromProperties(Properties props) {
       this.hoodieMetricsConfig.getProps().putAll(props);
       return this;
@@ -182,6 +378,11 @@ public class HoodieMetricsConfig extends HoodieConfig {
       return this;
     }
 
+    public Builder withPath(String basePath) {
+      hoodieMetricsConfig.setValue(HoodieCommonConfig.BASE_PATH, basePath);
+      return this;
+    }
+
     public Builder withReporterType(String reporterType) {
       hoodieMetricsConfig.setValue(METRICS_REPORTER_TYPE_VALUE, reporterType);
       return this;
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsDatadogConfig.java b/hudi-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsDatadogConfig.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsDatadogConfig.java
rename to hudi-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsDatadogConfig.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsGraphiteConfig.java b/hudi-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsGraphiteConfig.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsGraphiteConfig.java
rename to hudi-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsGraphiteConfig.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsJmxConfig.java b/hudi-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsJmxConfig.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsJmxConfig.java
rename to hudi-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsJmxConfig.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsM3Config.java b/hudi-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsM3Config.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsM3Config.java
rename to hudi-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsM3Config.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsPrometheusConfig.java b/hudi-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsPrometheusConfig.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsPrometheusConfig.java
rename to hudi-common/src/main/java/org/apache/hudi/config/metrics/HoodieMetricsPrometheusConfig.java
diff --git a/hudi-common/src/main/java/org/apache/hudi/metadata/BaseTableMetadata.java b/hudi-common/src/main/java/org/apache/hudi/metadata/BaseTableMetadata.java
index ccb0968b169..4702b8db056 100644
--- a/hudi-common/src/main/java/org/apache/hudi/metadata/BaseTableMetadata.java
+++ b/hudi-common/src/main/java/org/apache/hudi/metadata/BaseTableMetadata.java
@@ -27,7 +27,6 @@ import org.apache.hudi.common.config.HoodieMetadataConfig;
 import org.apache.hudi.common.engine.HoodieEngineContext;
 import org.apache.hudi.common.engine.HoodieLocalEngineContext;
 import org.apache.hudi.common.fs.FSUtils;
-import org.apache.hudi.common.metrics.Registry;
 import org.apache.hudi.common.model.HoodieRecord;
 import org.apache.hudi.common.table.HoodieTableMetaClient;
 import org.apache.hudi.common.model.HoodieRecordGlobalLocation;
@@ -39,6 +38,7 @@ import org.apache.hudi.common.util.collection.Pair;
 import org.apache.hudi.common.util.hash.ColumnIndexID;
 import org.apache.hudi.common.util.hash.FileIndexID;
 import org.apache.hudi.common.util.hash.PartitionIndexID;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.exception.HoodieIOException;
 import org.apache.hudi.exception.HoodieMetadataException;
 
@@ -97,7 +97,7 @@ public abstract class BaseTableMetadata extends AbstractHoodieTableMetadata {
     this.isMetadataTableInitialized = dataMetaClient.getTableConfig().isMetadataTableAvailable();
 
     if (metadataConfig.enableMetrics()) {
-      this.metrics = Option.of(new HoodieMetadataMetrics(Registry.getRegistry("HoodieMetadata")));
+      this.metrics = Option.of(new HoodieMetadataMetrics(HoodieMetricsConfig.newBuilder().fromProperties(metadataConfig.getProps()).build()));
     } else {
       this.metrics = Option.empty();
     }
diff --git a/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieMetadataMetrics.java b/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieMetadataMetrics.java
index ca9bf7b0834..7b73fc6d2d7 100644
--- a/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieMetadataMetrics.java
+++ b/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieMetadataMetrics.java
@@ -18,13 +18,17 @@
 
 package org.apache.hudi.metadata;
 
-import org.apache.hudi.common.metrics.Registry;
 import org.apache.hudi.common.model.FileSlice;
 import org.apache.hudi.common.model.HoodieLogFile;
 import org.apache.hudi.common.table.HoodieTableMetaClient;
 import org.apache.hudi.common.table.view.HoodieTableFileSystemView;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.exception.HoodieIOException;
+import org.apache.hudi.metrics.HoodieGauge;
+import org.apache.hudi.metrics.Metrics;
 
+import com.codahale.metrics.MetricRegistry;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -73,10 +77,12 @@ public class HoodieMetadataMetrics implements Serializable {
 
   private static final Logger LOG = LoggerFactory.getLogger(HoodieMetadataMetrics.class);
 
-  private final Registry metricsRegistry;
+  private final transient MetricRegistry metricsRegistry;
+  private final transient Metrics metrics;
 
-  public HoodieMetadataMetrics(Registry metricsRegistry) {
-    this.metricsRegistry = metricsRegistry;
+  public HoodieMetadataMetrics(HoodieMetricsConfig metricsConfig) {
+    this.metrics = Metrics.getInstance(metricsConfig);
+    this.metricsRegistry = metrics.getRegistry();
   }
 
   public Map<String, String> getStats(boolean detailed, HoodieTableMetaClient metaClient, HoodieTableMetadata metadata, Set<String> metadataPartitions) {
@@ -148,14 +154,15 @@ public class HoodieMetadataMetrics implements Serializable {
 
   protected void incrementMetric(String action, long value) {
     LOG.info(String.format("Updating metadata metrics (%s=%d) in %s", action, value, metricsRegistry));
-    metricsRegistry.add(action, value);
+    Option<HoodieGauge<Long>> gaugeOpt = metrics.registerGauge(action);
+    gaugeOpt.ifPresent(gauge -> gauge.setValue(gauge.getValue() + value));
   }
 
   protected void setMetric(String action, long value) {
-    metricsRegistry.set(action, value);
+    metrics.registerGauge(action, value);
   }
 
-  public Registry registry() {
+  public MetricRegistry registry() {
     return metricsRegistry;
   }
 }
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/ConsoleMetricsReporter.java b/hudi-common/src/main/java/org/apache/hudi/metrics/ConsoleMetricsReporter.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/ConsoleMetricsReporter.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/ConsoleMetricsReporter.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/HoodieGauge.java b/hudi-common/src/main/java/org/apache/hudi/metrics/HoodieGauge.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/HoodieGauge.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/HoodieGauge.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/InMemoryMetricsReporter.java b/hudi-common/src/main/java/org/apache/hudi/metrics/InMemoryMetricsReporter.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/InMemoryMetricsReporter.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/InMemoryMetricsReporter.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/JmxMetricsReporter.java b/hudi-common/src/main/java/org/apache/hudi/metrics/JmxMetricsReporter.java
similarity index 96%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/JmxMetricsReporter.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/JmxMetricsReporter.java
index c64d5fd6b51..b341fc356f1 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/JmxMetricsReporter.java
+++ b/hudi-common/src/main/java/org/apache/hudi/metrics/JmxMetricsReporter.java
@@ -18,7 +18,7 @@
 
 package org.apache.hudi.metrics;
 
-import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.exception.HoodieException;
 
 import com.codahale.metrics.MetricRegistry;
@@ -41,7 +41,7 @@ public class JmxMetricsReporter extends MetricsReporter {
   private final MetricRegistry registry;
   private JmxReporterServer jmxReporterServer;
 
-  public JmxMetricsReporter(HoodieWriteConfig config, MetricRegistry registry) {
+  public JmxMetricsReporter(HoodieMetricsConfig config, MetricRegistry registry) {
     try {
       this.registry = registry;
       // Check the host and port here
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/JmxReporterServer.java b/hudi-common/src/main/java/org/apache/hudi/metrics/JmxReporterServer.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/JmxReporterServer.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/JmxReporterServer.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/MetricUtils.java b/hudi-common/src/main/java/org/apache/hudi/metrics/MetricUtils.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/MetricUtils.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/MetricUtils.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/Metrics.java b/hudi-common/src/main/java/org/apache/hudi/metrics/Metrics.java
similarity index 80%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/Metrics.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/Metrics.java
index ef088091732..17e21254593 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/Metrics.java
+++ b/hudi-common/src/main/java/org/apache/hudi/metrics/Metrics.java
@@ -19,9 +19,10 @@
 package org.apache.hudi.metrics;
 
 import org.apache.hudi.common.metrics.Registry;
+import org.apache.hudi.common.table.HoodieTableMetaClient;
 import org.apache.hudi.common.util.Option;
 import org.apache.hudi.common.util.StringUtils;
-import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.hadoop.fs.HadoopFSUtils;
 
 import com.codahale.metrics.MetricRegistry;
@@ -33,9 +34,9 @@ import org.slf4j.LoggerFactory;
 
 import java.io.IOException;
 import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
 
 /**
  * This is the main class of the metrics system.
@@ -44,15 +45,16 @@ public class Metrics {
 
   private static final Logger LOG = LoggerFactory.getLogger(Metrics.class);
 
-  private static final Map<String, Metrics> METRICS_INSTANCE_PER_BASEPATH = new HashMap<>();
+  private static final Map<String, Metrics> METRICS_INSTANCE_PER_BASEPATH = new ConcurrentHashMap<>();
 
   private final MetricRegistry registry;
   private final List<MetricsReporter> reporters;
   private final String commonMetricPrefix;
+  private final String basePath;
   private boolean initialized = false;
   private transient Thread shutdownThread = null;
 
-  public Metrics(HoodieWriteConfig metricConfig) {
+  public Metrics(HoodieMetricsConfig metricConfig) {
     registry = new MetricRegistry();
     commonMetricPrefix = metricConfig.getMetricReporterMetricsNamePrefix();
     reporters = new ArrayList<>();
@@ -65,6 +67,7 @@ public class Metrics {
       throw new RuntimeException("Cannot initialize Reporters.");
     }
     reporters.forEach(MetricsReporter::start);
+    basePath = getBasePath(metricConfig);
 
     shutdownThread = new Thread(() -> shutdown(true));
     Runtime.getRuntime().addShutdownHook(shutdownThread);
@@ -75,8 +78,8 @@ public class Metrics {
     registerGauges(Registry.getAllMetrics(true, true), Option.of(commonMetricPrefix));
   }
 
-  public static synchronized Metrics getInstance(HoodieWriteConfig metricConfig) {
-    String basePath = metricConfig.getBasePath();
+  public static synchronized Metrics getInstance(HoodieMetricsConfig metricConfig) {
+    String basePath = getBasePath(metricConfig);
     if (METRICS_INSTANCE_PER_BASEPATH.containsKey(basePath)) {
       return METRICS_INSTANCE_PER_BASEPATH.get(basePath);
     }
@@ -92,12 +95,12 @@ public class Metrics {
     METRICS_INSTANCE_PER_BASEPATH.clear();
   }
 
-  private List<MetricsReporter> addAdditionalMetricsExporters(HoodieWriteConfig metricConfig) {
+  private List<MetricsReporter> addAdditionalMetricsExporters(HoodieMetricsConfig metricConfig) {
     List<MetricsReporter> reporterList = new ArrayList<>();
     List<String> propPathList = StringUtils.split(metricConfig.getMetricReporterFileBasedConfigs(), ",");
     try (FileSystem fs = HadoopFSUtils.getFs(propPathList.get(0), new Configuration())) {
       for (String propPath : propPathList) {
-        HoodieWriteConfig secondarySourceConfig = HoodieWriteConfig.newBuilder().fromInputStream(
+        HoodieMetricsConfig secondarySourceConfig = HoodieMetricsConfig.newBuilder().fromInputStream(
             fs.open(new Path(propPath))).withPath(metricConfig.getBasePath()).build();
         Option<MetricsReporter> reporter = MetricsReporterFactory.createReporter(secondarySourceConfig, registry);
         if (reporter.isPresent()) {
@@ -155,15 +158,21 @@ public class Metrics {
     metricsMap.forEach((k, v) -> registerGauge(metricPrefix + k, v));
   }
 
-  public void registerGauge(String metricName, final long value) {
+  public Option<HoodieGauge<Long>> registerGauge(String metricName, final long value) {
+    HoodieGauge<Long> gauge = null;
     try {
-      HoodieGauge guage = (HoodieGauge) registry.gauge(metricName, () -> new HoodieGauge<>(value));
-      guage.setValue(value);
+      gauge = (HoodieGauge) registry.gauge(metricName, () -> new HoodieGauge<>(value));
+      gauge.setValue(value);
     } catch (Exception e) {
       // Here we catch all exception, so the major upsert pipeline will not be affected if the
       // metrics system has some issues.
       LOG.error("Failed to send metrics: ", e);
     }
+    return Option.ofNullable(gauge);
+  }
+
+  public Option<HoodieGauge<Long>> registerGauge(String metricName) {
+    return registerGauge(metricName, 0);
   }
 
   public MetricRegistry getRegistry() {
@@ -176,4 +185,16 @@ public class Metrics {
     }
     return false;
   }
+
+  /**
+   * Use the same base path as the hudi table so that Metrics instance is shared.
+   */
+  private static String getBasePath(HoodieMetricsConfig metricsConfig) {
+    String basePath = metricsConfig.getBasePath();
+    if (basePath.endsWith(HoodieTableMetaClient.METADATA_TABLE_FOLDER_PATH)) {
+      String toRemoveSuffix = Path.SEPARATOR + HoodieTableMetaClient.METADATA_TABLE_FOLDER_PATH;
+      basePath = basePath.substring(0, basePath.length() - toRemoveSuffix.length());
+    }
+    return basePath;
+  }
 }
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/MetricsGraphiteReporter.java b/hudi-common/src/main/java/org/apache/hudi/metrics/MetricsGraphiteReporter.java
similarity index 84%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/MetricsGraphiteReporter.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/MetricsGraphiteReporter.java
index c62edea8b1c..e3acab9a90b 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/MetricsGraphiteReporter.java
+++ b/hudi-common/src/main/java/org/apache/hudi/metrics/MetricsGraphiteReporter.java
@@ -18,7 +18,7 @@
 
 package org.apache.hudi.metrics;
 
-import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 
 import com.codahale.metrics.MetricFilter;
 import com.codahale.metrics.MetricRegistry;
@@ -38,25 +38,25 @@ public class MetricsGraphiteReporter extends MetricsReporter {
   private static final Logger LOG = LoggerFactory.getLogger(MetricsGraphiteReporter.class);
   private final MetricRegistry registry;
   private final GraphiteReporter graphiteReporter;
-  private final HoodieWriteConfig config;
+  private final HoodieMetricsConfig metricsConfig;
   private String serverHost;
   private int serverPort;
   private final int periodSeconds;
 
-  public MetricsGraphiteReporter(HoodieWriteConfig config, MetricRegistry registry) {
+  public MetricsGraphiteReporter(HoodieMetricsConfig metricsConfig, MetricRegistry registry) {
     this.registry = registry;
-    this.config = config;
+    this.metricsConfig = metricsConfig;
 
     // Check the serverHost and serverPort here
-    this.serverHost = config.getGraphiteServerHost();
-    this.serverPort = config.getGraphiteServerPort();
+    this.serverHost = metricsConfig.getGraphiteServerHost();
+    this.serverPort = metricsConfig.getGraphiteServerPort();
     if (serverHost == null || serverPort == 0) {
       throw new RuntimeException(String.format("Graphite cannot be initialized with serverHost[%s] and serverPort[%s].",
           serverHost, serverPort));
     }
 
     this.graphiteReporter = createGraphiteReport();
-    this.periodSeconds = config.getGraphiteReportPeriodSeconds();
+    this.periodSeconds = metricsConfig.getGraphiteReportPeriodSeconds();
   }
 
   @Override
@@ -79,7 +79,7 @@ public class MetricsGraphiteReporter extends MetricsReporter {
 
   private GraphiteReporter createGraphiteReport() {
     Graphite graphite = new Graphite(new InetSocketAddress(serverHost, serverPort));
-    String reporterPrefix = config.getGraphiteMetricPrefix();
+    String reporterPrefix = metricsConfig.getGraphiteMetricPrefix();
     return GraphiteReporter.forRegistry(registry).prefixedWith(reporterPrefix).convertRatesTo(TimeUnit.SECONDS)
         .convertDurationsTo(TimeUnit.MILLISECONDS).filter(MetricFilter.ALL).build(graphite);
   }
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/MetricsReporter.java b/hudi-common/src/main/java/org/apache/hudi/metrics/MetricsReporter.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/MetricsReporter.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/MetricsReporter.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/MetricsReporterFactory.java b/hudi-common/src/main/java/org/apache/hudi/metrics/MetricsReporterFactory.java
similarity index 73%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/MetricsReporterFactory.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/MetricsReporterFactory.java
index 0d20337fa5c..455cf8de1c5 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/MetricsReporterFactory.java
+++ b/hudi-common/src/main/java/org/apache/hudi/metrics/MetricsReporterFactory.java
@@ -21,10 +21,8 @@ package org.apache.hudi.metrics;
 import org.apache.hudi.common.util.Option;
 import org.apache.hudi.common.util.ReflectionUtils;
 import org.apache.hudi.common.util.StringUtils;
-import org.apache.hudi.config.HoodieWriteConfig;
 import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.exception.HoodieException;
-import org.apache.hudi.metrics.cloudwatch.CloudWatchMetricsReporter;
 import org.apache.hudi.metrics.custom.CustomizableMetricsReporter;
 import org.apache.hudi.metrics.datadog.DatadogMetricsReporter;
 import org.apache.hudi.metrics.m3.M3MetricsReporter;
@@ -44,20 +42,20 @@ public class MetricsReporterFactory {
 
   private static final Logger LOG = LoggerFactory.getLogger(MetricsReporterFactory.class);
 
-  public static Option<MetricsReporter> createReporter(HoodieWriteConfig config, MetricRegistry registry) {
-    String reporterClassName = config.getMetricReporterClassName();
+  public static Option<MetricsReporter> createReporter(HoodieMetricsConfig metricsConfig, MetricRegistry registry) {
+    String reporterClassName = metricsConfig.getMetricReporterClassName();
 
     if (!StringUtils.isNullOrEmpty(reporterClassName)) {
       Object instance = ReflectionUtils.loadClass(
-          reporterClassName, new Class<?>[] {Properties.class, MetricRegistry.class}, config.getProps(), registry);
+          reporterClassName, new Class<?>[] {Properties.class, MetricRegistry.class}, metricsConfig.getProps(), registry);
       if (!(instance instanceof CustomizableMetricsReporter)) {
-        throw new HoodieException(config.getMetricReporterClassName()
+        throw new HoodieException(metricsConfig.getMetricReporterClassName()
             + " is not a subclass of CustomizableMetricsReporter");
       }
       return Option.of((MetricsReporter) instance);
     }
 
-    MetricsReporterType type = config.getMetricsReporterType();
+    MetricsReporterType type = metricsConfig.getMetricsReporterType();
     MetricsReporter reporter = null;
     if (type == null) {
       LOG.warn(String.format("Metric creation failed. %s is not configured",
@@ -67,31 +65,32 @@ public class MetricsReporterFactory {
 
     switch (type) {
       case GRAPHITE:
-        reporter = new MetricsGraphiteReporter(config, registry);
+        reporter = new MetricsGraphiteReporter(metricsConfig, registry);
         break;
       case INMEMORY:
         reporter = new InMemoryMetricsReporter();
         break;
       case JMX:
-        reporter = new JmxMetricsReporter(config, registry);
+        reporter = new JmxMetricsReporter(metricsConfig, registry);
         break;
       case DATADOG:
-        reporter = new DatadogMetricsReporter(config, registry);
+        reporter = new DatadogMetricsReporter(metricsConfig, registry);
         break;
       case PROMETHEUS_PUSHGATEWAY:
-        reporter = new PushGatewayMetricsReporter(config, registry);
+        reporter = new PushGatewayMetricsReporter(metricsConfig, registry);
         break;
       case PROMETHEUS:
-        reporter = new PrometheusReporter(config, registry);
+        reporter = new PrometheusReporter(metricsConfig, registry);
         break;
       case CONSOLE:
         reporter = new ConsoleMetricsReporter(registry);
         break;
       case CLOUDWATCH:
-        reporter = new CloudWatchMetricsReporter(config, registry);
+        reporter = (MetricsReporter) ReflectionUtils.loadClass("org.apache.hudi.metrics.cloudwatch.CloudWatchMetricsReporter",
+            new Class[]{HoodieMetricsConfig.class, MetricRegistry.class}, metricsConfig, registry);
         break;
       case M3:
-        reporter = new M3MetricsReporter(config, registry);
+        reporter = new M3MetricsReporter(metricsConfig, registry);
         break;
       default:
         LOG.error("Reporter type[" + type + "] is not supported.");
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/MetricsReporterType.java b/hudi-common/src/main/java/org/apache/hudi/metrics/MetricsReporterType.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/MetricsReporterType.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/MetricsReporterType.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/custom/CustomizableMetricsReporter.java b/hudi-common/src/main/java/org/apache/hudi/metrics/custom/CustomizableMetricsReporter.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/custom/CustomizableMetricsReporter.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/custom/CustomizableMetricsReporter.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/datadog/DatadogHttpClient.java b/hudi-common/src/main/java/org/apache/hudi/metrics/datadog/DatadogHttpClient.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/datadog/DatadogHttpClient.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/datadog/DatadogHttpClient.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/datadog/DatadogMetricsReporter.java b/hudi-common/src/main/java/org/apache/hudi/metrics/datadog/DatadogMetricsReporter.java
similarity index 95%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/datadog/DatadogMetricsReporter.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/datadog/DatadogMetricsReporter.java
index 3f598f34a2d..e13539d5924 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/datadog/DatadogMetricsReporter.java
+++ b/hudi-common/src/main/java/org/apache/hudi/metrics/datadog/DatadogMetricsReporter.java
@@ -21,7 +21,7 @@ package org.apache.hudi.metrics.datadog;
 import org.apache.hudi.common.util.Option;
 import org.apache.hudi.common.util.StringUtils;
 import org.apache.hudi.common.util.ValidationUtils;
-import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.metrics.MetricsReporter;
 import org.apache.hudi.metrics.datadog.DatadogHttpClient.ApiSite;
 
@@ -43,7 +43,7 @@ public class DatadogMetricsReporter extends MetricsReporter {
   private final DatadogReporter reporter;
   private final int reportPeriodSeconds;
 
-  public DatadogMetricsReporter(HoodieWriteConfig config, MetricRegistry registry) {
+  public DatadogMetricsReporter(HoodieMetricsConfig config, MetricRegistry registry) {
     reportPeriodSeconds = config.getDatadogReportPeriodSeconds();
     ApiSite apiSite = config.getDatadogApiSite();
     String apiKey = config.getDatadogApiKey();
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/datadog/DatadogReporter.java b/hudi-common/src/main/java/org/apache/hudi/metrics/datadog/DatadogReporter.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/datadog/DatadogReporter.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/datadog/DatadogReporter.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/m3/M3MetricsReporter.java b/hudi-common/src/main/java/org/apache/hudi/metrics/m3/M3MetricsReporter.java
similarity index 88%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/m3/M3MetricsReporter.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/m3/M3MetricsReporter.java
index a658476ef75..869b721f4d8 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/m3/M3MetricsReporter.java
+++ b/hudi-common/src/main/java/org/apache/hudi/metrics/m3/M3MetricsReporter.java
@@ -29,7 +29,7 @@ import java.util.Arrays;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.concurrent.TimeUnit;
-import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.metrics.MetricsReporter;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -40,18 +40,18 @@ import org.slf4j.LoggerFactory;
 public class M3MetricsReporter extends MetricsReporter {
 
   private static final Logger LOG = LoggerFactory.getLogger(M3MetricsReporter.class);
-  private final HoodieWriteConfig config;
+  private final HoodieMetricsConfig metricsConfig;
   private final MetricRegistry registry;
   private final ImmutableMap<String, String> tags;
 
-  public M3MetricsReporter(HoodieWriteConfig config, MetricRegistry registry) {
-    this.config = config;
+  public M3MetricsReporter(HoodieMetricsConfig metricsConfig, MetricRegistry registry) {
+    this.metricsConfig = metricsConfig;
     this.registry = registry;
 
     ImmutableMap.Builder tagBuilder = new ImmutableMap.Builder<>();
-    tagBuilder.putAll(parseOptionalTags(config.getM3Tags()));
-    tagBuilder.put("service", config.getM3Service());
-    tagBuilder.put("env", config.getM3Env());
+    tagBuilder.putAll(parseOptionalTags(metricsConfig.getM3Tags()));
+    tagBuilder.put("service", metricsConfig.getM3Service());
+    tagBuilder.put("env", metricsConfig.getM3Env());
     this.tags = tagBuilder.build();
     LOG.info(String.format("Building M3 Reporter with M3 tags mapping: %s", tags));
   }
@@ -93,7 +93,7 @@ public class M3MetricsReporter extends MetricsReporter {
     synchronized (this) {
       try (Scope scope = new RootScopeBuilder()
           .reporter(new M3Reporter.Builder(
-              new InetSocketAddress(config.getM3ServerHost(), config.getM3ServerPort()))
+              new InetSocketAddress(metricsConfig.getM3ServerHost(), metricsConfig.getM3ServerPort()))
               .includeHost(true).commonTags(tags)
               .build())
           .reportEvery(Duration.ofSeconds(Integer.MAX_VALUE))
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/m3/M3ScopeReporterAdaptor.java b/hudi-common/src/main/java/org/apache/hudi/metrics/m3/M3ScopeReporterAdaptor.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/m3/M3ScopeReporterAdaptor.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/m3/M3ScopeReporterAdaptor.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/prometheus/PrometheusReporter.java b/hudi-common/src/main/java/org/apache/hudi/metrics/prometheus/PrometheusReporter.java
similarity index 92%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/prometheus/PrometheusReporter.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/prometheus/PrometheusReporter.java
index 34fd7a07f65..44fd9f9175d 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/prometheus/PrometheusReporter.java
+++ b/hudi-common/src/main/java/org/apache/hudi/metrics/prometheus/PrometheusReporter.java
@@ -19,7 +19,7 @@
 package org.apache.hudi.metrics.prometheus;
 
 import org.apache.hudi.common.util.StringUtils;
-import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.exception.HoodieException;
 import org.apache.hudi.metrics.MetricsReporter;
 
@@ -55,15 +55,15 @@ public class PrometheusReporter extends MetricsReporter {
   private final CollectorRegistry collectorRegistry;
   private final int serverPort;
 
-  public PrometheusReporter(HoodieWriteConfig config, MetricRegistry registry) {
-    this.serverPort = config.getPrometheusPort();
+  public PrometheusReporter(HoodieMetricsConfig metricsConfig, MetricRegistry registry) {
+    this.serverPort = metricsConfig.getPrometheusPort();
     if (!PORT_TO_SERVER.containsKey(serverPort) || !PORT_TO_COLLECTOR_REGISTRY.containsKey(serverPort)) {
       startHttpServer(serverPort);
     }
     List<String> labelNames = new ArrayList<>();
     List<String> labelValues = new ArrayList<>();
-    if (StringUtils.nonEmpty(config.getPushGatewayLabels())) {
-      LABEL_PATTERN.splitAsStream(config.getPushGatewayLabels().trim()).map(s -> s.split(":", 2))
+    if (StringUtils.nonEmpty(metricsConfig.getPushGatewayLabels())) {
+      LABEL_PATTERN.splitAsStream(metricsConfig.getPushGatewayLabels().trim()).map(s -> s.split(":", 2))
           .forEach(parts -> {
             labelNames.add(parts[0]);
             labelValues.add(parts[1]);
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/prometheus/PushGatewayMetricsReporter.java b/hudi-common/src/main/java/org/apache/hudi/metrics/prometheus/PushGatewayMetricsReporter.java
similarity index 79%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/prometheus/PushGatewayMetricsReporter.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/prometheus/PushGatewayMetricsReporter.java
index 805e5d7c0d7..ddd4155bce9 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/prometheus/PushGatewayMetricsReporter.java
+++ b/hudi-common/src/main/java/org/apache/hudi/metrics/prometheus/PushGatewayMetricsReporter.java
@@ -19,7 +19,7 @@
 package org.apache.hudi.metrics.prometheus;
 
 import org.apache.hudi.common.util.StringUtils;
-import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.metrics.MetricUtils;
 import org.apache.hudi.metrics.MetricsReporter;
 
@@ -40,15 +40,15 @@ public class PushGatewayMetricsReporter extends MetricsReporter {
   private final Map<String, String> configuredLabels;
   private final boolean randomSuffix;
 
-  public PushGatewayMetricsReporter(HoodieWriteConfig config, MetricRegistry registry) {
+  public PushGatewayMetricsReporter(HoodieMetricsConfig metricsConfig, MetricRegistry registry) {
 
-    String serverHost = config.getPushGatewayHost();
-    int serverPort = config.getPushGatewayPort();
-    periodSeconds = config.getPushGatewayReportPeriodSeconds();
-    deleteShutdown = config.getPushGatewayDeleteOnShutdown();
-    configuredJobName = config.getPushGatewayJobName();
-    configuredLabels = Collections.unmodifiableMap(parseLabels(config.getPushGatewayLabels()));
-    randomSuffix = config.getPushGatewayRandomJobNameSuffix();
+    String serverHost = metricsConfig.getPushGatewayHost();
+    int serverPort = metricsConfig.getPushGatewayPort();
+    periodSeconds = metricsConfig.getPushGatewayReportPeriodSeconds();
+    deleteShutdown = metricsConfig.getPushGatewayDeleteOnShutdown();
+    configuredJobName = metricsConfig.getPushGatewayJobName();
+    configuredLabels = Collections.unmodifiableMap(parseLabels(metricsConfig.getPushGatewayLabels()));
+    randomSuffix = metricsConfig.getPushGatewayRandomJobNameSuffix();
 
     pushGatewayReporter = new PushGatewayReporter(
         registry,
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/prometheus/PushGatewayReporter.java b/hudi-common/src/main/java/org/apache/hudi/metrics/prometheus/PushGatewayReporter.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/prometheus/PushGatewayReporter.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/prometheus/PushGatewayReporter.java
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/userdefined/AbstractUserDefinedMetricsReporter.java b/hudi-common/src/main/java/org/apache/hudi/metrics/userdefined/AbstractUserDefinedMetricsReporter.java
similarity index 100%
rename from hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metrics/userdefined/AbstractUserDefinedMetricsReporter.java
rename to hudi-common/src/main/java/org/apache/hudi/metrics/userdefined/AbstractUserDefinedMetricsReporter.java
diff --git a/hudi-utilities/src/main/java/org/apache/hudi/utilities/deltastreamer/HoodieDeltaStreamerMetrics.java b/hudi-utilities/src/main/java/org/apache/hudi/utilities/deltastreamer/HoodieDeltaStreamerMetrics.java
index 0a15745483d..cd7867edf3e 100644
--- a/hudi-utilities/src/main/java/org/apache/hudi/utilities/deltastreamer/HoodieDeltaStreamerMetrics.java
+++ b/hudi-utilities/src/main/java/org/apache/hudi/utilities/deltastreamer/HoodieDeltaStreamerMetrics.java
@@ -20,6 +20,7 @@
 package org.apache.hudi.utilities.deltastreamer;
 
 import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.utilities.streamer.HoodieStreamerMetrics;
 
 /**
@@ -28,7 +29,12 @@ import org.apache.hudi.utilities.streamer.HoodieStreamerMetrics;
  */
 @Deprecated
 public class HoodieDeltaStreamerMetrics extends HoodieStreamerMetrics {
+
   public HoodieDeltaStreamerMetrics(HoodieWriteConfig writeConfig) {
-    super(writeConfig);
+    super(writeConfig.getMetricsConfig());
+  }
+
+  public HoodieDeltaStreamerMetrics(HoodieMetricsConfig metricsConfig) {
+    super(metricsConfig);
   }
 }
diff --git a/hudi-utilities/src/main/java/org/apache/hudi/utilities/ingestion/HoodieIngestionMetrics.java b/hudi-utilities/src/main/java/org/apache/hudi/utilities/ingestion/HoodieIngestionMetrics.java
index bd31b8f2b46..3d07610993d 100644
--- a/hudi-utilities/src/main/java/org/apache/hudi/utilities/ingestion/HoodieIngestionMetrics.java
+++ b/hudi-utilities/src/main/java/org/apache/hudi/utilities/ingestion/HoodieIngestionMetrics.java
@@ -19,6 +19,7 @@
 package org.apache.hudi.utilities.ingestion;
 
 import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 
 import com.codahale.metrics.Timer;
 
@@ -29,9 +30,13 @@ import java.io.Serializable;
  */
 public abstract class HoodieIngestionMetrics implements Serializable {
 
-  protected final HoodieWriteConfig writeConfig;
+  protected final HoodieMetricsConfig writeConfig;
 
   public HoodieIngestionMetrics(HoodieWriteConfig writeConfig) {
+    this(writeConfig.getMetricsConfig());
+  }
+
+  public HoodieIngestionMetrics(HoodieMetricsConfig writeConfig) {
     this.writeConfig = writeConfig;
   }
 
diff --git a/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/HoodieStreamerMetrics.java b/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/HoodieStreamerMetrics.java
index 7f1e0a29792..fcbf431ed6f 100644
--- a/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/HoodieStreamerMetrics.java
+++ b/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/HoodieStreamerMetrics.java
@@ -20,6 +20,7 @@
 package org.apache.hudi.utilities.streamer;
 
 import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.config.metrics.HoodieMetricsConfig;
 import org.apache.hudi.metrics.Metrics;
 import org.apache.hudi.utilities.ingestion.HoodieIngestionMetrics;
 
@@ -37,6 +38,10 @@ public class HoodieStreamerMetrics extends HoodieIngestionMetrics {
   private transient Timer metaSyncTimer;
 
   public HoodieStreamerMetrics(HoodieWriteConfig writeConfig) {
+    this(writeConfig.getMetricsConfig());
+  }
+
+  public HoodieStreamerMetrics(HoodieMetricsConfig writeConfig) {
     super(writeConfig);
     if (writeConfig.isMetricsOn()) {
       metrics = Metrics.getInstance(writeConfig);
diff --git a/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/StreamSync.java b/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/StreamSync.java
index 42d218a5b4a..2b0d94da74a 100644
--- a/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/StreamSync.java
+++ b/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/StreamSync.java
@@ -304,7 +304,7 @@ public class StreamSync implements Serializable, Closeable {
     this.conf = conf;
 
     HoodieWriteConfig hoodieWriteConfig = getHoodieClientConfig();
-    this.metrics = (HoodieIngestionMetrics) ReflectionUtils.loadClass(cfg.ingestionMetricsClass, hoodieWriteConfig);
+    this.metrics = (HoodieIngestionMetrics) ReflectionUtils.loadClass(cfg.ingestionMetricsClass, hoodieWriteConfig.getMetricsConfig());
     this.hoodieMetrics = new HoodieMetrics(hoodieWriteConfig);
     if (props.getBoolean(ERROR_TABLE_ENABLED.key(), ERROR_TABLE_ENABLED.defaultValue())) {
       this.errorTableWriter = ErrorTableUtils.getErrorTableWriter(cfg, sparkSession, props, hoodieSparkContext, fs);


(hudi) 15/28: [HUDI-7584] Always read log block lazily and remove readBlockLazily argument (#11015)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit e39fedfa5b6c554ecfaf332f60d95fbcddf10b03
Author: Vova Kolmakov <wo...@gmail.com>
AuthorDate: Mon Apr 15 11:31:11 2024 +0700

    [HUDI-7584] Always read log block lazily and remove readBlockLazily argument (#11015)
---
 .../hudi/cli/commands/HoodieLogFileCommand.java    |   3 -
 .../cli/commands/TestHoodieLogFileCommand.java     |   3 -
 .../org/apache/hudi/io/HoodieMergedReadHandle.java |   1 -
 .../hudi/table/action/compact/HoodieCompactor.java |   1 -
 .../run/strategy/JavaExecutionStrategy.java        |   1 -
 .../MultipleSparkJobExecutionStrategy.java         |   1 -
 .../hudi/common/table/TableSchemaResolver.java     |  21 ++--
 .../table/log/AbstractHoodieLogRecordReader.java   |  65 +++++------
 .../table/log/HoodieCDCLogRecordIterator.java      |   3 +-
 .../hudi/common/table/log/HoodieLogFileReader.java |  69 +++++------
 .../hudi/common/table/log/HoodieLogFormat.java     |  13 +--
 .../common/table/log/HoodieLogFormatReader.java    |  14 +--
 .../table/log/HoodieMergedLogRecordScanner.java    |  27 ++---
 .../table/log/HoodieUnMergedLogRecordScanner.java  |  12 +-
 .../hudi/common/table/log/LogReaderUtils.java      |   2 +-
 .../metadata/HoodieMetadataLogRecordReader.java    |   1 -
 .../hudi/metadata/HoodieTableMetadataUtil.java     |   1 -
 .../common/functional/TestHoodieLogFormat.java     | 128 +++++++--------------
 .../examples/quickstart/TestQuickstartData.java    |   1 -
 .../hudi/sink/clustering/ClusteringOperator.java   |   1 -
 .../org/apache/hudi/table/format/FormatUtils.java  |   6 -
 .../test/java/org/apache/hudi/utils/TestData.java  |   1 -
 .../realtime/HoodieMergeOnReadSnapshotReader.java  |   3 -
 .../realtime/RealtimeCompactedRecordReader.java    |   1 -
 .../realtime/RealtimeUnmergedRecordReader.java     |   1 -
 .../reader/DFSHoodieDatasetInputReader.java        |   1 -
 .../src/main/scala/org/apache/hudi/Iterators.scala |   4 -
 .../ShowHoodieLogFileRecordsProcedure.scala        |   1 -
 .../utilities/HoodieMetadataTableValidator.java    | 126 +++++++++-----------
 29 files changed, 188 insertions(+), 324 deletions(-)

diff --git a/hudi-cli/src/main/java/org/apache/hudi/cli/commands/HoodieLogFileCommand.java b/hudi-cli/src/main/java/org/apache/hudi/cli/commands/HoodieLogFileCommand.java
index 46a9e787ea6..77d9392fcd0 100644
--- a/hudi-cli/src/main/java/org/apache/hudi/cli/commands/HoodieLogFileCommand.java
+++ b/hudi-cli/src/main/java/org/apache/hudi/cli/commands/HoodieLogFileCommand.java
@@ -238,9 +238,6 @@ public class HoodieLogFileCommand {
               .withLatestInstantTime(
                   client.getActiveTimeline()
                       .getCommitTimeline().lastInstant().get().getTimestamp())
-              .withReadBlocksLazily(
-                  Boolean.parseBoolean(
-                      HoodieCompactionConfig.COMPACTION_LAZY_BLOCK_READ_ENABLE.defaultValue()))
               .withReverseReader(
                   Boolean.parseBoolean(
                       HoodieCompactionConfig.COMPACTION_REVERSE_LOG_READ_ENABLE.defaultValue()))
diff --git a/hudi-cli/src/test/java/org/apache/hudi/cli/commands/TestHoodieLogFileCommand.java b/hudi-cli/src/test/java/org/apache/hudi/cli/commands/TestHoodieLogFileCommand.java
index 6f75074ff29..dc9cdd1aaf1 100644
--- a/hudi-cli/src/test/java/org/apache/hudi/cli/commands/TestHoodieLogFileCommand.java
+++ b/hudi-cli/src/test/java/org/apache/hudi/cli/commands/TestHoodieLogFileCommand.java
@@ -241,9 +241,6 @@ public class TestHoodieLogFileCommand extends CLIFunctionalTestHarness {
         .withLatestInstantTime(INSTANT_TIME)
         .withMaxMemorySizeInBytes(
             HoodieMemoryConfig.DEFAULT_MAX_MEMORY_FOR_SPILLABLE_MAP_IN_BYTES)
-        .withReadBlocksLazily(
-            Boolean.parseBoolean(
-                HoodieCompactionConfig.COMPACTION_LAZY_BLOCK_READ_ENABLE.defaultValue()))
         .withReverseReader(
             Boolean.parseBoolean(
                 HoodieCompactionConfig.COMPACTION_REVERSE_LOG_READ_ENABLE.defaultValue()))
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergedReadHandle.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergedReadHandle.java
index e74ab37f4b6..280e24e46b9 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergedReadHandle.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergedReadHandle.java
@@ -126,7 +126,6 @@ public class HoodieMergedReadHandle<T, I, K, O> extends HoodieReadHandle<T, I, K
         .withReaderSchema(readerSchema)
         .withLatestInstantTime(instantTime)
         .withMaxMemorySizeInBytes(IOUtils.getMaxMemoryPerCompaction(hoodieTable.getTaskContextSupplier(), config))
-        .withReadBlocksLazily(config.getCompactionLazyBlockReadEnabled())
         .withReverseReader(config.getCompactionReverseLogReadEnabled())
         .withBufferSize(config.getMaxDFSStreamBufferSize())
         .withSpillableMapBasePath(config.getSpillableMapBasePath())
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/action/compact/HoodieCompactor.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/action/compact/HoodieCompactor.java
index 940ab9886c3..461794a8f75 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/action/compact/HoodieCompactor.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/table/action/compact/HoodieCompactor.java
@@ -197,7 +197,6 @@ public abstract class HoodieCompactor<T, I, K, O> implements Serializable {
         .withInstantRange(instantRange)
         .withInternalSchema(internalSchemaOption.orElse(InternalSchema.getEmptyInternalSchema()))
         .withMaxMemorySizeInBytes(maxMemoryPerCompaction)
-        .withReadBlocksLazily(config.getCompactionLazyBlockReadEnabled())
         .withReverseReader(config.getCompactionReverseLogReadEnabled())
         .withBufferSize(config.getMaxDFSStreamBufferSize())
         .withSpillableMapBasePath(config.getSpillableMapBasePath())
diff --git a/hudi-client/hudi-java-client/src/main/java/org/apache/hudi/client/clustering/run/strategy/JavaExecutionStrategy.java b/hudi-client/hudi-java-client/src/main/java/org/apache/hudi/client/clustering/run/strategy/JavaExecutionStrategy.java
index f73238d0210..70e8de465df 100644
--- a/hudi-client/hudi-java-client/src/main/java/org/apache/hudi/client/clustering/run/strategy/JavaExecutionStrategy.java
+++ b/hudi-client/hudi-java-client/src/main/java/org/apache/hudi/client/clustering/run/strategy/JavaExecutionStrategy.java
@@ -181,7 +181,6 @@ public abstract class JavaExecutionStrategy<T>
             .withReaderSchema(readerSchema)
             .withLatestInstantTime(instantTime)
             .withMaxMemorySizeInBytes(maxMemoryPerCompaction)
-            .withReadBlocksLazily(config.getCompactionLazyBlockReadEnabled())
             .withReverseReader(config.getCompactionReverseLogReadEnabled())
             .withBufferSize(config.getMaxDFSStreamBufferSize())
             .withSpillableMapBasePath(config.getSpillableMapBasePath())
diff --git a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/clustering/run/strategy/MultipleSparkJobExecutionStrategy.java b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/clustering/run/strategy/MultipleSparkJobExecutionStrategy.java
index b1fd74a6169..62a510a0b3c 100644
--- a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/clustering/run/strategy/MultipleSparkJobExecutionStrategy.java
+++ b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/clustering/run/strategy/MultipleSparkJobExecutionStrategy.java
@@ -309,7 +309,6 @@ public abstract class MultipleSparkJobExecutionStrategy<T>
               .withReaderSchema(readerSchema)
               .withLatestInstantTime(instantTime)
               .withMaxMemorySizeInBytes(maxMemoryPerCompaction)
-              .withReadBlocksLazily(config.getCompactionLazyBlockReadEnabled())
               .withReverseReader(config.getCompactionReverseLogReadEnabled())
               .withBufferSize(config.getMaxDFSStreamBufferSize())
               .withSpillableMapBasePath(config.getSpillableMapBasePath())
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/TableSchemaResolver.java b/hudi-common/src/main/java/org/apache/hudi/common/table/TableSchemaResolver.java
index 0344331ab75..c5d55cdd2c6 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/TableSchemaResolver.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/TableSchemaResolver.java
@@ -32,6 +32,7 @@ import org.apache.hudi.common.table.log.block.HoodieLogBlock;
 import org.apache.hudi.common.table.timeline.HoodieActiveTimeline;
 import org.apache.hudi.common.table.timeline.HoodieInstant;
 import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.util.ConfigUtils;
 import org.apache.hudi.common.util.Option;
 import org.apache.hudi.common.util.StringUtils;
 import org.apache.hudi.common.util.collection.Pair;
@@ -74,7 +75,6 @@ import java.util.function.Supplier;
 import static org.apache.hudi.avro.AvroSchemaUtils.appendFieldsToSchema;
 import static org.apache.hudi.avro.AvroSchemaUtils.containsFieldInSchema;
 import static org.apache.hudi.avro.AvroSchemaUtils.createNullableSchema;
-import static org.apache.hudi.common.util.ConfigUtils.DEFAULT_HUDI_CONFIG_FOR_READER;
 
 /**
  * Helper class to read schema from data files and log files and to convert it between different formats.
@@ -284,13 +284,12 @@ public class TableSchemaResolver {
             Iterator<String> filePaths = commitMetadata.getFileIdAndFullPaths(metaClient.getBasePathV2()).values().iterator();
             return Option.of(fetchSchemaFromFiles(filePaths));
           } else {
-            LOG.warn("Could not find any data file written for commit, "
-                + "so could not get schema for table " + metaClient.getBasePath());
+            LOG.warn("Could not find any data file written for commit, so could not get schema for table {}", metaClient.getBasePathV2());
             return Option.empty();
           }
         default:
-          LOG.error("Unknown table type " + metaClient.getTableType());
-          throw new InvalidTableException(metaClient.getBasePath());
+          LOG.error("Unknown table type {}", metaClient.getTableType());
+          throw new InvalidTableException(metaClient.getBasePathV2().toString());
       }
     } catch (IOException e) {
       throw new HoodieException("Failed to read data schema", e);
@@ -328,7 +327,7 @@ public class TableSchemaResolver {
   }
 
   private MessageType readSchemaFromParquetBaseFile(Path parquetFilePath) throws IOException {
-    LOG.info("Reading schema from " + parquetFilePath);
+    LOG.info("Reading schema from {}", parquetFilePath);
 
     FileSystem fs = metaClient.getRawFs();
     ParquetMetadata fileFooter =
@@ -337,18 +336,18 @@ public class TableSchemaResolver {
   }
 
   private MessageType readSchemaFromHFileBaseFile(Path hFilePath) throws IOException {
-    LOG.info("Reading schema from " + hFilePath);
+    LOG.info("Reading schema from {}", hFilePath);
 
     FileSystem fs = metaClient.getRawFs();
     try (HoodieFileReader fileReader =
              HoodieFileReaderFactory.getReaderFactory(HoodieRecord.HoodieRecordType.AVRO)
-                 .getFileReader(DEFAULT_HUDI_CONFIG_FOR_READER, fs.getConf(), hFilePath)) {
+                 .getFileReader(ConfigUtils.DEFAULT_HUDI_CONFIG_FOR_READER, fs.getConf(), hFilePath)) {
       return convertAvroSchemaToParquet(fileReader.getSchema());
     }
   }
 
   private MessageType readSchemaFromORCBaseFile(Path orcFilePath) throws IOException {
-    LOG.info("Reading schema from " + orcFilePath);
+    LOG.info("Reading schema from {}", orcFilePath);
 
     FileSystem fs = metaClient.getRawFs();
     HoodieAvroOrcReader orcReader = new HoodieAvroOrcReader(fs.getConf(), orcFilePath);
@@ -388,7 +387,7 @@ public class TableSchemaResolver {
     // We only need to read the schema from the log block header,
     // so we read the block lazily to avoid reading block content
     // containing the records
-    try (Reader reader = HoodieLogFormat.newReader(fs, new HoodieLogFile(path), null, true, false)) {
+    try (Reader reader = HoodieLogFormat.newReader(fs, new HoodieLogFile(path), null, false)) {
       HoodieDataBlock lastBlock = null;
       while (reader.hasNext()) {
         HoodieLogBlock block = reader.next();
@@ -473,7 +472,7 @@ public class TableSchemaResolver {
       Schema tableAvroSchema = getTableAvroSchemaFromDataFile();
       return tableAvroSchema.getField(HoodieRecord.OPERATION_METADATA_FIELD) != null;
     } catch (Exception e) {
-      LOG.info(String.format("Failed to read operation field from avro schema (%s)", e.getMessage()));
+      LOG.info("Failed to read operation field from avro schema ({})", e.getMessage());
       return false;
     }
   }
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/log/AbstractHoodieLogRecordReader.java b/hudi-common/src/main/java/org/apache/hudi/common/table/log/AbstractHoodieLogRecordReader.java
index 6ce80da6d4a..affde833721 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/log/AbstractHoodieLogRecordReader.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/log/AbstractHoodieLogRecordReader.java
@@ -66,7 +66,6 @@ import java.util.concurrent.atomic.AtomicLong;
 import java.util.function.Function;
 import java.util.stream.Collectors;
 
-import static org.apache.hudi.common.table.log.block.HoodieCommandBlock.HoodieCommandBlockTypeEnum.ROLLBACK_BLOCK;
 import static org.apache.hudi.common.table.log.block.HoodieLogBlock.HeaderMetadataType.BLOCK_IDENTIFIER;
 import static org.apache.hudi.common.table.log.block.HoodieLogBlock.HeaderMetadataType.COMPACTED_BLOCK_TIMES;
 import static org.apache.hudi.common.table.log.block.HoodieLogBlock.HeaderMetadataType.INSTANT_TIME;
@@ -150,7 +149,7 @@ public abstract class AbstractHoodieLogRecordReader {
   private final boolean enableOptimizedLogBlocksScan;
 
   protected AbstractHoodieLogRecordReader(FileSystem fs, String basePath, List<String> logFilePaths,
-                                          Schema readerSchema, String latestInstantTime, boolean readBlocksLazily,
+                                          Schema readerSchema, String latestInstantTime,
                                           boolean reverseReader, int bufferSize, Option<InstantRange> instantRange,
                                           boolean withOperationField, boolean forceFullScan,
                                           Option<String> partitionNameOverride,
@@ -243,12 +242,12 @@ public abstract class AbstractHoodieLogRecordReader {
       // Iterate over the paths
       logFormatReaderWrapper = new HoodieLogFormatReader(fs,
           logFilePaths.stream().map(logFile -> new HoodieLogFile(new CachingPath(logFile))).collect(Collectors.toList()),
-          readerSchema, true, reverseReader, bufferSize, shouldLookupRecords(), recordKeyField, internalSchema);
+          readerSchema, reverseReader, bufferSize, shouldLookupRecords(), recordKeyField, internalSchema);
 
       Set<HoodieLogFile> scannedLogFiles = new HashSet<>();
       while (logFormatReaderWrapper.hasNext()) {
         HoodieLogFile logFile = logFormatReaderWrapper.getLogFile();
-        LOG.info("Scanning log file " + logFile);
+        LOG.info("Scanning log file {}", logFile);
         scannedLogFiles.add(logFile);
         totalLogFiles.set(scannedLogFiles.size());
         // Use the HoodieLogFileReader to iterate through the blocks in the log file
@@ -284,14 +283,14 @@ public abstract class AbstractHoodieLogRecordReader {
           case HFILE_DATA_BLOCK:
           case AVRO_DATA_BLOCK:
           case PARQUET_DATA_BLOCK:
-            LOG.info("Reading a data block from file " + logFile.getPath() + " at instant " + instantTime);
+            LOG.info("Reading a data block from file {} at instant {}", logFile.getPath(), instantTime);
             // store the current block
             currentInstantLogBlocks.push(logBlock);
             validLogBlockInstants.add(logBlock);
             updateBlockSequenceTracker(logBlock, instantTime, blockSeqNumber, attemptNumber, blockSequenceMapPerCommit, blockIdentifiersPresent);
             break;
           case DELETE_BLOCK:
-            LOG.info("Reading a delete block from file " + logFile.getPath());
+            LOG.info("Reading a delete block from file {}", logFile.getPath());
             // store deletes so can be rolled back
             currentInstantLogBlocks.push(logBlock);
             validLogBlockInstants.add(logBlock);
@@ -314,8 +313,7 @@ public abstract class AbstractHoodieLogRecordReader {
             HoodieCommandBlock commandBlock = (HoodieCommandBlock) logBlock;
             String targetInstantForCommandBlock =
                 logBlock.getLogBlockHeader().get(HoodieLogBlock.HeaderMetadataType.TARGET_INSTANT_TIME);
-            LOG.info(String.format("Reading a command block %s with targetInstantTime %s from file %s", commandBlock.getType(), targetInstantForCommandBlock,
-                logFile.getPath()));
+            LOG.info("Reading a command block {} with targetInstantTime {} from file {}", commandBlock.getType(), targetInstantForCommandBlock, logFile.getPath());
             switch (commandBlock.getType()) { // there can be different types of command blocks
               case ROLLBACK_BLOCK:
                 // Rollback older read log block(s)
@@ -328,13 +326,12 @@ public abstract class AbstractHoodieLogRecordReader {
                 currentInstantLogBlocks.removeIf(block -> {
                   // handle corrupt blocks separately since they may not have metadata
                   if (block.getBlockType() == CORRUPT_BLOCK) {
-                    LOG.info("Rolling back the last corrupted log block read in " + logFile.getPath());
+                    LOG.info("Rolling back the last corrupted log block read in {}", logFile.getPath());
                     return true;
                   }
                   if (targetInstantForCommandBlock.contentEquals(block.getLogBlockHeader().get(INSTANT_TIME))) {
                     // rollback older data block or delete block
-                    LOG.info(String.format("Rolling back an older log block read from %s with instantTime %s",
-                        logFile.getPath(), targetInstantForCommandBlock));
+                    LOG.info("Rolling back an older log block read from {} with instantTime {}", logFile.getPath(), targetInstantForCommandBlock);
                     return true;
                   }
                   return false;
@@ -347,13 +344,12 @@ public abstract class AbstractHoodieLogRecordReader {
                 validLogBlockInstants = validLogBlockInstants.stream().filter(block -> {
                   // handle corrupt blocks separately since they may not have metadata
                   if (block.getBlockType() == CORRUPT_BLOCK) {
-                    LOG.info("Rolling back the last corrupted log block read in " + logFile.getPath());
+                    LOG.info("Rolling back the last corrupted log block read in {}", logFile.getPath());
                     return true;
                   }
                   if (targetInstantForCommandBlock.contentEquals(block.getLogBlockHeader().get(INSTANT_TIME))) {
                     // rollback older data block or delete block
-                    LOG.info(String.format("Rolling back an older log block read from %s with instantTime %s",
-                        logFile.getPath(), targetInstantForCommandBlock));
+                    LOG.info("Rolling back an older log block read from {} with instantTime {}", logFile.getPath(), targetInstantForCommandBlock);
                     return false;
                   }
                   return true;
@@ -361,10 +357,9 @@ public abstract class AbstractHoodieLogRecordReader {
 
                 final int numBlocksRolledBack = instantLogBlockSizeBeforeRollback - currentInstantLogBlocks.size();
                 totalRollbacks.addAndGet(numBlocksRolledBack);
-                LOG.info("Number of applied rollback blocks " + numBlocksRolledBack);
+                LOG.info("Number of applied rollback blocks {}", numBlocksRolledBack);
                 if (numBlocksRolledBack == 0) {
-                  LOG.warn(String.format("TargetInstantTime %s invalid or extra rollback command block in %s",
-                      targetInstantForCommandBlock, logFile.getPath()));
+                  LOG.warn("TargetInstantTime {} invalid or extra rollback command block in {}", targetInstantForCommandBlock, logFile.getPath());
                 }
                 break;
               default:
@@ -372,7 +367,7 @@ public abstract class AbstractHoodieLogRecordReader {
             }
             break;
           case CORRUPT_BLOCK:
-            LOG.info("Found a corrupt block in " + logFile.getPath());
+            LOG.info("Found a corrupt block in {}", logFile.getPath());
             totalCorruptBlocks.incrementAndGet();
             // If there is a corrupt block - we will assume that this was the next data block
             currentInstantLogBlocks.push(logBlock);
@@ -460,10 +455,8 @@ public abstract class AbstractHoodieLogRecordReader {
           for (Map.Entry<Long, List<Pair<Integer, HoodieLogBlock>>> perAttemptEntries : perCommitBlockSequences.entrySet()) {
             Long attemptNo = perAttemptEntries.getKey();
             if (maxAttemptNo != attemptNo) {
-              List<HoodieLogBlock> logBlocksToRemove = perCommitBlockSequences.get(attemptNo).stream().map(pair -> pair.getValue()).collect(Collectors.toList());
-              logBlocksToRemove.forEach(logBlockToRemove -> {
-                allValidLogBlocks.remove(logBlockToRemove);
-              });
+              List<HoodieLogBlock> logBlocksToRemove = perCommitBlockSequences.get(attemptNo).stream().map(Pair::getValue).collect(Collectors.toList());
+              logBlocksToRemove.forEach(logBlockToRemove -> allValidLogBlocks.remove(logBlockToRemove));
             }
           }
         }
@@ -478,12 +471,12 @@ public abstract class AbstractHoodieLogRecordReader {
     LOG.warn("Duplicate log blocks found ");
     for (Map.Entry<String, Map<Long, List<Pair<Integer, HoodieLogBlock>>>> entry : blockSequenceMapPerCommit.entrySet()) {
       if (entry.getValue().size() > 1) {
-        LOG.warn("\tCommit time " + entry.getKey());
+        LOG.warn("\tCommit time {}", entry.getKey());
         Map<Long, List<Pair<Integer, HoodieLogBlock>>> value = entry.getValue();
         for (Map.Entry<Long, List<Pair<Integer, HoodieLogBlock>>> attemptsSeq : value.entrySet()) {
-          LOG.warn("\t\tAttempt number " + attemptsSeq.getKey());
-          attemptsSeq.getValue().forEach(entryValue -> LOG.warn("\t\t\tLog block sequence no : " + entryValue.getKey() + ", log file "
-              + entryValue.getValue().getBlockContentLocation().get().getLogFile().getPath().toString()));
+          LOG.warn("\t\tAttempt number {}", attemptsSeq.getKey());
+          attemptsSeq.getValue().forEach(entryValue -> LOG.warn("\t\t\tLog block sequence no : {}, log file {}",
+              entryValue.getKey(), entryValue.getValue().getBlockContentLocation().get().getLogFile().getPath().toString()));
         }
       }
     }
@@ -556,7 +549,7 @@ public abstract class AbstractHoodieLogRecordReader {
       // Iterate over the paths
       logFormatReaderWrapper = new HoodieLogFormatReader(fs,
           logFilePaths.stream().map(logFile -> new HoodieLogFile(new CachingPath(logFile))).collect(Collectors.toList()),
-          readerSchema, true, reverseReader, bufferSize, shouldLookupRecords(), recordKeyField, internalSchema);
+          readerSchema, reverseReader, bufferSize, shouldLookupRecords(), recordKeyField, internalSchema);
 
       /**
        * Scanning log blocks and placing the compacted blocks at the right place require two traversals.
@@ -603,7 +596,7 @@ public abstract class AbstractHoodieLogRecordReader {
        */
       while (logFormatReaderWrapper.hasNext()) {
         HoodieLogFile logFile = logFormatReaderWrapper.getLogFile();
-        LOG.info("Scanning log file " + logFile);
+        LOG.info("Scanning log file {}", logFile);
         scannedLogFiles.add(logFile);
         totalLogFiles.set(scannedLogFiles.size());
         // Use the HoodieLogFileReader to iterate through the blocks in the log file
@@ -612,7 +605,7 @@ public abstract class AbstractHoodieLogRecordReader {
         totalLogBlocks.incrementAndGet();
         // Ignore the corrupt blocks. No further handling is required for them.
         if (logBlock.getBlockType().equals(CORRUPT_BLOCK)) {
-          LOG.info("Found a corrupt block in " + logFile.getPath());
+          LOG.info("Found a corrupt block in {}", logFile.getPath());
           totalCorruptBlocks.incrementAndGet();
           continue;
         }
@@ -647,12 +640,12 @@ public abstract class AbstractHoodieLogRecordReader {
             instantToBlocksMap.put(instantTime, logBlocksList);
             break;
           case COMMAND_BLOCK:
-            LOG.info("Reading a command block from file " + logFile.getPath());
+            LOG.info("Reading a command block from file {}", logFile.getPath());
             // This is a command block - take appropriate action based on the command
             HoodieCommandBlock commandBlock = (HoodieCommandBlock) logBlock;
 
             // Rollback blocks contain information of instants that are failed, collect them in a set..
-            if (commandBlock.getType().equals(ROLLBACK_BLOCK)) {
+            if (commandBlock.getType().equals(HoodieCommandBlock.HoodieCommandBlockTypeEnum.ROLLBACK_BLOCK)) {
               totalRollbacks.incrementAndGet();
               String targetInstantForCommandBlock =
                   logBlock.getLogBlockHeader().get(TARGET_INSTANT_TIME);
@@ -669,7 +662,7 @@ public abstract class AbstractHoodieLogRecordReader {
       }
 
       if (LOG.isDebugEnabled()) {
-        LOG.debug("Ordered instant times seen " + orderedInstantsList);
+        LOG.debug("Ordered instant times seen {}", orderedInstantsList);
       }
 
       int numBlocksRolledBack = 0;
@@ -725,10 +718,10 @@ public abstract class AbstractHoodieLogRecordReader {
           validBlockInstants.add(compactedFinalInstantTime);
         }
       }
-      LOG.info("Number of applied rollback blocks " + numBlocksRolledBack);
+      LOG.info("Number of applied rollback blocks {}", numBlocksRolledBack);
 
       if (LOG.isDebugEnabled()) {
-        LOG.info("Final view of the Block time to compactionBlockMap " + blockTimeToCompactionBlockTimeMap);
+        LOG.info("Final view of the Block time to compactionBlockMap {}", blockTimeToCompactionBlockTimeMap);
       }
 
       // merge the last read block when all the blocks are done reading
@@ -816,7 +809,7 @@ public abstract class AbstractHoodieLogRecordReader {
   private void processQueuedBlocksForInstant(Deque<HoodieLogBlock> logBlocks, int numLogFilesSeen,
                                              Option<KeySpec> keySpecOpt) throws Exception {
     while (!logBlocks.isEmpty()) {
-      LOG.info("Number of remaining logblocks to merge " + logBlocks.size());
+      LOG.info("Number of remaining logblocks to merge {}", logBlocks.size());
       // poll the element at the bottom of the stack since that's the order it was inserted
       HoodieLogBlock lastBlock = logBlocks.pollLast();
       switch (lastBlock.getBlockType()) {
@@ -1022,8 +1015,6 @@ public abstract class AbstractHoodieLogRecordReader {
 
     public abstract Builder withLatestInstantTime(String latestInstantTime);
 
-    public abstract Builder withReadBlocksLazily(boolean readBlocksLazily);
-
     public abstract Builder withReverseReader(boolean reverseReader);
 
     public abstract Builder withBufferSize(int bufferSize);
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieCDCLogRecordIterator.java b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieCDCLogRecordIterator.java
index b2464345a1d..e5938bdefb0 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieCDCLogRecordIterator.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieCDCLogRecordIterator.java
@@ -82,8 +82,7 @@ public class HoodieCDCLogRecordIterator implements ClosableIterator<IndexedRecor
     try {
       closeReader();
       if (cdcLogFileIter.hasNext()) {
-        reader = new HoodieLogFileReader(fs, cdcLogFileIter.next(), cdcSchema,
-            HoodieLogFileReader.DEFAULT_BUFFER_SIZE, false);
+        reader = new HoodieLogFileReader(fs, cdcLogFileIter.next(), cdcSchema, HoodieLogFileReader.DEFAULT_BUFFER_SIZE);
         return reader.hasNext();
       }
       return false;
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFileReader.java b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFileReader.java
index c7289106f48..c1daf5e32d1 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFileReader.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFileReader.java
@@ -18,6 +18,7 @@
 
 package org.apache.hudi.common.table.log;
 
+import org.apache.hudi.common.config.HoodieReaderConfig;
 import org.apache.hudi.common.fs.FSUtils;
 import org.apache.hudi.common.model.HoodieLogFile;
 import org.apache.hudi.common.model.HoodieRecord;
@@ -64,7 +65,6 @@ import java.util.HashMap;
 import java.util.Map;
 import java.util.Objects;
 
-import static org.apache.hudi.common.config.HoodieReaderConfig.USE_NATIVE_HFILE_READER;
 import static org.apache.hudi.common.util.ValidationUtils.checkArgument;
 import static org.apache.hudi.common.util.ValidationUtils.checkState;
 
@@ -77,6 +77,7 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
   public static final int DEFAULT_BUFFER_SIZE = 16 * 1024 * 1024; // 16 MB
   private static final int BLOCK_SCAN_READ_BUFFER_SIZE = 1024 * 1024; // 1 MB
   private static final Logger LOG = LoggerFactory.getLogger(HoodieLogFileReader.class);
+  private static final String REVERSE_LOG_READER_HAS_NOT_BEEN_ENABLED = "Reverse log reader has not been enabled";
 
   private final FileSystem fs;
   private final Configuration hadoopConf;
@@ -86,7 +87,6 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
   private final Schema readerSchema;
   private final InternalSchema internalSchema;
   private final String keyField;
-  private final boolean readBlockLazily;
   private long reverseLogFilePosition;
   private long lastReverseLogFilePosition;
   private final boolean reverseReader;
@@ -94,26 +94,22 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
   private boolean closed = false;
   private SeekableDataInputStream inputStream;
 
-  public HoodieLogFileReader(FileSystem fs, HoodieLogFile logFile, Schema readerSchema, int bufferSize,
-                             boolean readBlockLazily) throws IOException {
-    this(fs, logFile, readerSchema, bufferSize, readBlockLazily, false);
+  public HoodieLogFileReader(FileSystem fs, HoodieLogFile logFile, Schema readerSchema, int bufferSize) throws IOException {
+    this(fs, logFile, readerSchema, bufferSize, false);
   }
 
   public HoodieLogFileReader(FileSystem fs, HoodieLogFile logFile, Schema readerSchema, int bufferSize,
-                             boolean readBlockLazily, boolean reverseReader) throws IOException {
-    this(fs, logFile, readerSchema, bufferSize, readBlockLazily, reverseReader, false,
-        HoodieRecord.RECORD_KEY_METADATA_FIELD);
+                             boolean reverseReader) throws IOException {
+    this(fs, logFile, readerSchema, bufferSize, reverseReader, false, HoodieRecord.RECORD_KEY_METADATA_FIELD);
   }
 
-  public HoodieLogFileReader(FileSystem fs, HoodieLogFile logFile, Schema readerSchema, int bufferSize,
-                             boolean readBlockLazily, boolean reverseReader, boolean enableRecordLookups,
-                             String keyField) throws IOException {
-    this(fs, logFile, readerSchema, bufferSize, readBlockLazily, reverseReader, enableRecordLookups, keyField, InternalSchema.getEmptyInternalSchema());
+  public HoodieLogFileReader(FileSystem fs, HoodieLogFile logFile, Schema readerSchema, int bufferSize, boolean reverseReader,
+                             boolean enableRecordLookups, String keyField) throws IOException {
+    this(fs, logFile, readerSchema, bufferSize, reverseReader, enableRecordLookups, keyField, InternalSchema.getEmptyInternalSchema());
   }
 
-  public HoodieLogFileReader(FileSystem fs, HoodieLogFile logFile, Schema readerSchema, int bufferSize,
-                             boolean readBlockLazily, boolean reverseReader, boolean enableRecordLookups,
-                             String keyField, InternalSchema internalSchema) throws IOException {
+  public HoodieLogFileReader(FileSystem fs, HoodieLogFile logFile, Schema readerSchema, int bufferSize, boolean reverseReader,
+                             boolean enableRecordLookups, String keyField, InternalSchema internalSchema) throws IOException {
     this.fs = fs;
     this.hadoopConf = fs.getConf();
     // NOTE: We repackage {@code HoodieLogFile} here to make sure that the provided path
@@ -124,7 +120,6 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
     this.bufferSize = bufferSize;
     this.inputStream = getDataInputStream(fs, this.logFile, bufferSize);
     this.readerSchema = readerSchema;
-    this.readBlockLazily = readBlockLazily;
     this.reverseReader = reverseReader;
     this.enableRecordLookups = enableRecordLookups;
     this.keyField = keyField;
@@ -180,7 +175,7 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
 
     // 6. Read the content or skip content based on IO vs Memory trade-off by client
     long contentPosition = inputStream.getPos();
-    boolean shouldReadLazily = readBlockLazily && nextBlockVersion.getVersion() != HoodieLogFormatVersion.DEFAULT_VERSION;
+    boolean shouldReadLazily = nextBlockVersion.getVersion() != HoodieLogFormatVersion.DEFAULT_VERSION;
     Option<byte[]> content = HoodieLogBlock.tryReadContent(inputStream, contentLength, shouldReadLazily);
 
     // 7. Read footer if any
@@ -204,7 +199,7 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
         if (nextBlockVersion.getVersion() == HoodieLogFormatVersion.DEFAULT_VERSION) {
           return HoodieAvroDataBlock.getBlock(content.get(), readerSchema, internalSchema);
         } else {
-          return new HoodieAvroDataBlock(() -> getDataInputStream(fs, this.logFile, bufferSize), content, readBlockLazily, logBlockContentLoc,
+          return new HoodieAvroDataBlock(() -> getDataInputStream(fs, this.logFile, bufferSize), content, true, logBlockContentLoc,
               getTargetReaderSchemaForBlock(), header, footer, keyField);
         }
 
@@ -212,25 +207,25 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
         checkState(nextBlockVersion.getVersion() != HoodieLogFormatVersion.DEFAULT_VERSION,
             String.format("HFile block could not be of version (%d)", HoodieLogFormatVersion.DEFAULT_VERSION));
         return new HoodieHFileDataBlock(
-            () -> getDataInputStream(fs, this.logFile, bufferSize), content, readBlockLazily, logBlockContentLoc,
+            () -> getDataInputStream(fs, this.logFile, bufferSize), content, true, logBlockContentLoc,
             Option.ofNullable(readerSchema), header, footer, enableRecordLookups, logFile.getPath(),
-            ConfigUtils.getBooleanWithAltKeys(fs.getConf(), USE_NATIVE_HFILE_READER));
+            ConfigUtils.getBooleanWithAltKeys(fs.getConf(), HoodieReaderConfig.USE_NATIVE_HFILE_READER));
 
       case PARQUET_DATA_BLOCK:
         checkState(nextBlockVersion.getVersion() != HoodieLogFormatVersion.DEFAULT_VERSION,
             String.format("Parquet block could not be of version (%d)", HoodieLogFormatVersion.DEFAULT_VERSION));
 
-        return new HoodieParquetDataBlock(() -> getDataInputStream(fs, this.logFile, bufferSize), content, readBlockLazily, logBlockContentLoc,
+        return new HoodieParquetDataBlock(() -> getDataInputStream(fs, this.logFile, bufferSize), content, true, logBlockContentLoc,
             getTargetReaderSchemaForBlock(), header, footer, keyField);
 
       case DELETE_BLOCK:
-        return new HoodieDeleteBlock(content, () -> getDataInputStream(fs, this.logFile, bufferSize), readBlockLazily, Option.of(logBlockContentLoc), header, footer);
+        return new HoodieDeleteBlock(content, () -> getDataInputStream(fs, this.logFile, bufferSize), true, Option.of(logBlockContentLoc), header, footer);
 
       case COMMAND_BLOCK:
-        return new HoodieCommandBlock(content, () -> getDataInputStream(fs, this.logFile, bufferSize), readBlockLazily, Option.of(logBlockContentLoc), header, footer);
+        return new HoodieCommandBlock(content, () -> getDataInputStream(fs, this.logFile, bufferSize), true, Option.of(logBlockContentLoc), header, footer);
 
       case CDC_DATA_BLOCK:
-        return new HoodieCDCDataBlock(() -> getDataInputStream(fs, this.logFile, bufferSize), content, readBlockLazily, logBlockContentLoc, readerSchema, header, keyField);
+        return new HoodieCDCDataBlock(() -> getDataInputStream(fs, this.logFile, bufferSize), content, true, logBlockContentLoc, readerSchema, header, keyField);
 
       default:
         throw new HoodieNotSupportedException("Unsupported Block " + blockType);
@@ -261,18 +256,18 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
   }
 
   private HoodieLogBlock createCorruptBlock(long blockStartPos) throws IOException {
-    LOG.info("Log " + logFile + " has a corrupted block at " + blockStartPos);
+    LOG.info("Log {} has a corrupted block at {}", logFile, blockStartPos);
     inputStream.seek(blockStartPos);
     long nextBlockOffset = scanForNextAvailableBlockOffset();
     // Rewind to the initial start and read corrupted bytes till the nextBlockOffset
     inputStream.seek(blockStartPos);
-    LOG.info("Next available block in " + logFile + " starts at " + nextBlockOffset);
+    LOG.info("Next available block in {} starts at {}", logFile, nextBlockOffset);
     int corruptedBlockSize = (int) (nextBlockOffset - blockStartPos);
     long contentPosition = inputStream.getPos();
-    Option<byte[]> corruptedBytes = HoodieLogBlock.tryReadContent(inputStream, corruptedBlockSize, readBlockLazily);
+    Option<byte[]> corruptedBytes = HoodieLogBlock.tryReadContent(inputStream, corruptedBlockSize, true);
     HoodieLogBlock.HoodieLogBlockContentLocation logBlockContentLoc =
         new HoodieLogBlock.HoodieLogBlockContentLocation(hadoopConf, logFile, contentPosition, corruptedBlockSize, nextBlockOffset);
-    return new HoodieCorruptBlock(corruptedBytes, () -> getDataInputStream(fs, this.logFile, bufferSize), readBlockLazily, Option.of(logBlockContentLoc), new HashMap<>(), new HashMap<>());
+    return new HoodieCorruptBlock(corruptedBytes, () -> getDataInputStream(fs, this.logFile, bufferSize), true, Option.of(logBlockContentLoc), new HashMap<>(), new HashMap<>());
   }
 
   private boolean isBlockCorrupted(int blocksize) throws IOException {
@@ -293,7 +288,7 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
       // So we have to shorten the footer block size by the size of magic hash
       blockSizeFromFooter = inputStream.readLong() - magicBuffer.length;
     } catch (EOFException e) {
-      LOG.info("Found corrupted block in file " + logFile + " with block size(" + blocksize + ") running past EOF");
+      LOG.info("Found corrupted block in file {} with block size({}) running past EOF", logFile, blocksize);
       // this is corrupt
       // This seek is required because contract of seek() is different for naked DFSInputStream vs BufferedFSInputStream
       // release-3.1.0-RC1/DFSInputStream.java#L1455
@@ -303,8 +298,7 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
     }
 
     if (blocksize != blockSizeFromFooter) {
-      LOG.info("Found corrupted block in file " + logFile + ". Header block size(" + blocksize
-          + ") did not match the footer block size(" + blockSizeFromFooter + ")");
+      LOG.info("Found corrupted block in file {}. Header block size({}) did not match the footer block size({})", logFile, blocksize, blockSizeFromFooter);
       inputStream.seek(currentPos);
       return true;
     }
@@ -315,7 +309,7 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
       return false;
     } catch (CorruptedLogFileException e) {
       // This is a corrupted block
-      LOG.info("Found corrupted block in file " + logFile + ". No magic hash found right after footer block size entry");
+      LOG.info("Found corrupted block in file {}. No magic hash found right after footer block size entry", logFile);
       return true;
     } finally {
       inputStream.seek(currentPos);
@@ -348,7 +342,7 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
   @Override
   public void close() throws IOException {
     if (!closed) {
-      LOG.info("Closing Log file reader " +  logFile.getFileName());
+      LOG.info("Closing Log file reader {}",  logFile.getFileName());
       if (null != this.inputStream) {
         this.inputStream.close();
       }
@@ -411,7 +405,7 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
   public boolean hasPrev() {
     try {
       if (!this.reverseReader) {
-        throw new HoodieNotSupportedException("Reverse log reader has not been enabled");
+        throw new HoodieNotSupportedException(REVERSE_LOG_READER_HAS_NOT_BEEN_ENABLED);
       }
       reverseLogFilePosition = lastReverseLogFilePosition;
       reverseLogFilePosition -= Long.BYTES;
@@ -433,7 +427,7 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
   public HoodieLogBlock prev() throws IOException {
 
     if (!this.reverseReader) {
-      throw new HoodieNotSupportedException("Reverse log reader has not been enabled");
+      throw new HoodieNotSupportedException(REVERSE_LOG_READER_HAS_NOT_BEEN_ENABLED);
     }
     long blockSize = inputStream.readLong();
     long blockEndPos = inputStream.getPos();
@@ -443,8 +437,7 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
     } catch (Exception e) {
       // this could be a corrupt block
       inputStream.seek(blockEndPos);
-      throw new CorruptedLogFileException("Found possible corrupted block, cannot read log file in reverse, "
-          + "fallback to forward reading of logfile");
+      throw new CorruptedLogFileException("Found possible corrupted block, cannot read log file in reverse, fallback to forward reading of logfile");
     }
     boolean hasNext = hasNext();
     reverseLogFilePosition -= blockSize;
@@ -460,7 +453,7 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
   public long moveToPrev() throws IOException {
 
     if (!this.reverseReader) {
-      throw new HoodieNotSupportedException("Reverse log reader has not been enabled");
+      throw new HoodieNotSupportedException(REVERSE_LOG_READER_HAS_NOT_BEEN_ENABLED);
     }
     inputStream.seek(lastReverseLogFilePosition);
     long blockSize = inputStream.readLong();
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFormat.java b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFormat.java
index 5e7d0806fae..12a80c07a91 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFormat.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFormat.java
@@ -258,8 +258,7 @@ public interface HoodieLogFormat {
           // Use rollover write token as write token to create new log file with tokens
           logWriteToken = rolloverLogWriteToken;
         }
-        LOG.info("Computed the next log version for " + logFileId + " in " + parentPath + " as " + logVersion
-            + " with write-token " + logWriteToken);
+        LOG.info("Computed the next log version for {} in {} as {} with write-token {}", logFileId, parentPath, logVersion, logWriteToken);
       }
 
       if (logWriteToken == null) {
@@ -279,7 +278,7 @@ public interface HoodieLogFormat {
 
       Path logPath = new Path(parentPath,
           FSUtils.makeLogFileName(logFileId, fileExtension, instantTime, logVersion, logWriteToken));
-      LOG.info("HoodieLogFile on path " + logPath);
+      LOG.info("HoodieLogFile on path {}", logPath);
       HoodieLogFile logFile = new HoodieLogFile(logPath, fileLen);
 
       if (bufferSize == null) {
@@ -302,13 +301,11 @@ public interface HoodieLogFormat {
 
   static HoodieLogFormat.Reader newReader(FileSystem fs, HoodieLogFile logFile, Schema readerSchema)
       throws IOException {
-    return new HoodieLogFileReader(fs, logFile, readerSchema, HoodieLogFileReader.DEFAULT_BUFFER_SIZE, false);
+    return new HoodieLogFileReader(fs, logFile, readerSchema, HoodieLogFileReader.DEFAULT_BUFFER_SIZE);
   }
 
-  static HoodieLogFormat.Reader newReader(FileSystem fs, HoodieLogFile logFile, Schema readerSchema,
-      boolean readBlockLazily, boolean reverseReader) throws IOException {
-    return new HoodieLogFileReader(fs, logFile, readerSchema, HoodieLogFileReader.DEFAULT_BUFFER_SIZE, readBlockLazily,
-        reverseReader);
+  static HoodieLogFormat.Reader newReader(FileSystem fs, HoodieLogFile logFile, Schema readerSchema, boolean reverseReader) throws IOException {
+    return new HoodieLogFileReader(fs, logFile, readerSchema, HoodieLogFileReader.DEFAULT_BUFFER_SIZE, reverseReader);
   }
 
   /**
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFormatReader.java b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFormatReader.java
index 3c4737af8d0..f21091e5df0 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFormatReader.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFormatReader.java
@@ -41,27 +41,25 @@ public class HoodieLogFormatReader implements HoodieLogFormat.Reader {
   private final FileSystem fs;
   private final Schema readerSchema;
   private final InternalSchema internalSchema;
-  private final boolean readBlocksLazily;
   private final String recordKeyField;
   private final boolean enableInlineReading;
   private final int bufferSize;
 
   private static final Logger LOG = LoggerFactory.getLogger(HoodieLogFormatReader.class);
 
-  HoodieLogFormatReader(FileSystem fs, List<HoodieLogFile> logFiles, Schema readerSchema, boolean readBlocksLazily,
+  HoodieLogFormatReader(FileSystem fs, List<HoodieLogFile> logFiles, Schema readerSchema,
                         boolean reverseLogReader, int bufferSize, boolean enableRecordLookups,
                         String recordKeyField, InternalSchema internalSchema) throws IOException {
     this.logFiles = logFiles;
     this.fs = fs;
     this.readerSchema = readerSchema;
-    this.readBlocksLazily = readBlocksLazily;
     this.bufferSize = bufferSize;
     this.recordKeyField = recordKeyField;
     this.enableInlineReading = enableRecordLookups;
     this.internalSchema = internalSchema == null ? InternalSchema.getEmptyInternalSchema() : internalSchema;
-    if (logFiles.size() > 0) {
+    if (!logFiles.isEmpty()) {
       HoodieLogFile nextLogFile = logFiles.remove(0);
-      this.currentReader = new HoodieLogFileReader(fs, nextLogFile, readerSchema, bufferSize, readBlocksLazily, false,
+      this.currentReader = new HoodieLogFileReader(fs, nextLogFile, readerSchema, bufferSize, false,
           enableRecordLookups, recordKeyField, internalSchema);
     }
   }
@@ -83,16 +81,16 @@ public class HoodieLogFormatReader implements HoodieLogFormat.Reader {
       return false;
     } else if (currentReader.hasNext()) {
       return true;
-    } else if (logFiles.size() > 0) {
+    } else if (!logFiles.isEmpty()) {
       try {
         HoodieLogFile nextLogFile = logFiles.remove(0);
         this.currentReader.close();
-        this.currentReader = new HoodieLogFileReader(fs, nextLogFile, readerSchema, bufferSize, readBlocksLazily, false,
+        this.currentReader = new HoodieLogFileReader(fs, nextLogFile, readerSchema, bufferSize, false,
             enableInlineReading, recordKeyField, internalSchema);
       } catch (IOException io) {
         throw new HoodieIOException("unable to initialize read with log file ", io);
       }
-      LOG.info("Moving to the next reader for logfile " + currentReader.getLogFile());
+      LOG.info("Moving to the next reader for logfile {}", currentReader.getLogFile());
       return hasNext();
     }
     return false;
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieMergedLogRecordScanner.java b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieMergedLogRecordScanner.java
index 9062641f1a7..c3cf2f97ab8 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieMergedLogRecordScanner.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieMergedLogRecordScanner.java
@@ -92,7 +92,7 @@ public class HoodieMergedLogRecordScanner extends AbstractHoodieLogRecordReader
 
   @SuppressWarnings("unchecked")
   private HoodieMergedLogRecordScanner(FileSystem fs, String basePath, List<String> logFilePaths, Schema readerSchema,
-                                       String latestInstantTime, Long maxMemorySizeInBytes, boolean readBlocksLazily,
+                                       String latestInstantTime, Long maxMemorySizeInBytes,
                                        boolean reverseReader, int bufferSize, String spillableMapBasePath,
                                        Option<InstantRange> instantRange,
                                        ExternalSpillableMap.DiskMapType diskMapType,
@@ -103,7 +103,7 @@ public class HoodieMergedLogRecordScanner extends AbstractHoodieLogRecordReader
                                        Option<String> keyFieldOverride,
                                        boolean enableOptimizedLogBlocksScan, HoodieRecordMerger recordMerger,
                                       Option<HoodieTableMetaClient> hoodieTableMetaClientOption) {
-    super(fs, basePath, logFilePaths, readerSchema, latestInstantTime, readBlocksLazily, reverseReader, bufferSize,
+    super(fs, basePath, logFilePaths, readerSchema, latestInstantTime, reverseReader, bufferSize,
         instantRange, withOperationField, forceFullScan, partitionName, internalSchema, keyFieldOverride, enableOptimizedLogBlocksScan, recordMerger,
         hoodieTableMetaClientOption);
     try {
@@ -206,12 +206,14 @@ public class HoodieMergedLogRecordScanner extends AbstractHoodieLogRecordReader
     this.totalTimeTakenToReadAndMergeBlocks = timer.endTimer();
     this.numMergedRecordsInLog = records.size();
 
-    LOG.info("Number of log files scanned => " + logFilePaths.size());
-    LOG.info("MaxMemoryInBytes allowed for compaction => " + maxMemorySizeInBytes);
-    LOG.info("Number of entries in MemoryBasedMap in ExternalSpillableMap => " + records.getInMemoryMapNumEntries());
-    LOG.info("Total size in bytes of MemoryBasedMap in ExternalSpillableMap => " + records.getCurrentInMemoryMapSize());
-    LOG.info("Number of entries in DiskBasedMap in ExternalSpillableMap => " + records.getDiskBasedMapNumEntries());
-    LOG.info("Size of file spilled to disk => " + records.getSizeOfFileOnDiskInBytes());
+    if (LOG.isInfoEnabled()) {
+      LOG.info("Number of log files scanned => {}", logFilePaths.size());
+      LOG.info("MaxMemoryInBytes allowed for compaction => {}", maxMemorySizeInBytes);
+      LOG.info("Number of entries in MemoryBasedMap in ExternalSpillableMap => {}", records.getInMemoryMapNumEntries());
+      LOG.info("Total size in bytes of MemoryBasedMap in ExternalSpillableMap => {}", records.getCurrentInMemoryMapSize());
+      LOG.info("Number of entries in DiskBasedMap in ExternalSpillableMap => {}", records.getDiskBasedMapNumEntries());
+      LOG.info("Size of file spilled to disk => {}", records.getSizeOfFileOnDiskInBytes());
+    }
   }
 
   @Override
@@ -321,7 +323,6 @@ public class HoodieMergedLogRecordScanner extends AbstractHoodieLogRecordReader
     private Schema readerSchema;
     private InternalSchema internalSchema = InternalSchema.getEmptyInternalSchema();
     private String latestInstantTime;
-    private boolean readBlocksLazily;
     private boolean reverseReader;
     private int bufferSize;
     // specific configurations
@@ -373,12 +374,6 @@ public class HoodieMergedLogRecordScanner extends AbstractHoodieLogRecordReader
       return this;
     }
 
-    @Override
-    public Builder withReadBlocksLazily(boolean readBlocksLazily) {
-      this.readBlocksLazily = readBlocksLazily;
-      return this;
-    }
-
     @Override
     public Builder withReverseReader(boolean reverseReader) {
       this.reverseReader = reverseReader;
@@ -470,7 +465,7 @@ public class HoodieMergedLogRecordScanner extends AbstractHoodieLogRecordReader
       ValidationUtils.checkArgument(recordMerger != null);
 
       return new HoodieMergedLogRecordScanner(fs, basePath, logFilePaths, readerSchema,
-          latestInstantTime, maxMemorySizeInBytes, readBlocksLazily, reverseReader,
+          latestInstantTime, maxMemorySizeInBytes, reverseReader,
           bufferSize, spillableMapBasePath, instantRange,
           diskMapType, isBitCaskDiskMapCompressionEnabled, withOperationField, forceFullScan,
           Option.ofNullable(partitionName), internalSchema, Option.ofNullable(keyFieldOverride), enableOptimizedLogBlocksScan, recordMerger,
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieUnMergedLogRecordScanner.java b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieUnMergedLogRecordScanner.java
index 4d870618e7b..492d6299a0d 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieUnMergedLogRecordScanner.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieUnMergedLogRecordScanner.java
@@ -43,11 +43,11 @@ public class HoodieUnMergedLogRecordScanner extends AbstractHoodieLogRecordReade
   private final LogRecordScannerCallback callback;
 
   private HoodieUnMergedLogRecordScanner(FileSystem fs, String basePath, List<String> logFilePaths, Schema readerSchema,
-                                         String latestInstantTime, boolean readBlocksLazily, boolean reverseReader, int bufferSize,
+                                         String latestInstantTime, boolean reverseReader, int bufferSize,
                                          LogRecordScannerCallback callback, Option<InstantRange> instantRange, InternalSchema internalSchema,
                                          boolean enableOptimizedLogBlocksScan, HoodieRecordMerger recordMerger,
                                          Option<HoodieTableMetaClient> hoodieTableMetaClientOption) {
-    super(fs, basePath, logFilePaths, readerSchema, latestInstantTime, readBlocksLazily, reverseReader, bufferSize, instantRange,
+    super(fs, basePath, logFilePaths, readerSchema, latestInstantTime, reverseReader, bufferSize, instantRange,
         false, true, Option.empty(), internalSchema, Option.empty(), enableOptimizedLogBlocksScan, recordMerger,
          hoodieTableMetaClientOption);
     this.callback = callback;
@@ -104,7 +104,6 @@ public class HoodieUnMergedLogRecordScanner extends AbstractHoodieLogRecordReade
     private Schema readerSchema;
     private InternalSchema internalSchema;
     private String latestInstantTime;
-    private boolean readBlocksLazily;
     private boolean reverseReader;
     private int bufferSize;
     private Option<InstantRange> instantRange = Option.empty();
@@ -147,11 +146,6 @@ public class HoodieUnMergedLogRecordScanner extends AbstractHoodieLogRecordReade
       return this;
     }
 
-    public Builder withReadBlocksLazily(boolean readBlocksLazily) {
-      this.readBlocksLazily = readBlocksLazily;
-      return this;
-    }
-
     public Builder withReverseReader(boolean reverseReader) {
       this.reverseReader = reverseReader;
       return this;
@@ -196,7 +190,7 @@ public class HoodieUnMergedLogRecordScanner extends AbstractHoodieLogRecordReade
       ValidationUtils.checkArgument(recordMerger != null);
 
       return new HoodieUnMergedLogRecordScanner(fs, basePath, logFilePaths, readerSchema,
-          latestInstantTime, readBlocksLazily, reverseReader, bufferSize, callback, instantRange,
+          latestInstantTime, reverseReader, bufferSize, callback, instantRange,
           internalSchema, enableOptimizedLogBlocksScan, recordMerger, Option.ofNullable(hoodieTableMetaClient));
     }
   }
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/log/LogReaderUtils.java b/hudi-common/src/main/java/org/apache/hudi/common/table/log/LogReaderUtils.java
index 768085c322c..93383df332f 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/log/LogReaderUtils.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/log/LogReaderUtils.java
@@ -52,7 +52,7 @@ public class LogReaderUtils {
   private static Schema readSchemaFromLogFileInReverse(FileSystem fs, HoodieActiveTimeline activeTimeline, HoodieLogFile hoodieLogFile)
       throws IOException {
     // set length for the HoodieLogFile as it will be leveraged by HoodieLogFormat.Reader with reverseReading enabled
-    Reader reader = HoodieLogFormat.newReader(fs, hoodieLogFile, null, true, true);
+    Reader reader = HoodieLogFormat.newReader(fs, hoodieLogFile, null, true);
     Schema writerSchema = null;
     HoodieTimeline completedTimeline = activeTimeline.getCommitsTimeline().filterCompletedInstants();
     while (reader.hasPrev()) {
diff --git a/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieMetadataLogRecordReader.java b/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieMetadataLogRecordReader.java
index 900260b9413..3cd0a9b0da1 100644
--- a/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieMetadataLogRecordReader.java
+++ b/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieMetadataLogRecordReader.java
@@ -139,7 +139,6 @@ public class HoodieMetadataLogRecordReader implements Closeable {
             // NOTE: Merging of Metadata Table's records is currently handled using {@code HoodiePreCombineAvroRecordMerger}
             //       for compatibility purposes; In the future it {@code HoodieMetadataPayload} semantic
             //       will be migrated to its own custom instance of {@code RecordMerger}
-            .withReadBlocksLazily(true)
             .withReverseReader(false)
             .withOperationField(false);
 
diff --git a/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieTableMetadataUtil.java b/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieTableMetadataUtil.java
index 480ae76a5a1..b25d6741b83 100644
--- a/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieTableMetadataUtil.java
+++ b/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieTableMetadataUtil.java
@@ -1801,7 +1801,6 @@ public class HoodieTableMetadataUtil {
             .withLogFilePaths(logFilePaths)
             .withReaderSchema(HoodieAvroUtils.getRecordKeySchema())
             .withLatestInstantTime(metaClient.getActiveTimeline().filterCompletedInstants().lastInstant().map(HoodieInstant::getTimestamp).orElse(""))
-            .withReadBlocksLazily(configuration.get().getBoolean("", true))
             .withReverseReader(false)
             .withMaxMemorySizeInBytes(configuration.get().getLongBytes(MAX_MEMORY_FOR_COMPACTION.key(), DEFAULT_MAX_MEMORY_FOR_SPILLABLE_MAP_IN_BYTES))
             .withSpillableMapBasePath(FileIOUtils.getDefaultSpillableMapBasePath())
diff --git a/hudi-common/src/test/java/org/apache/hudi/common/functional/TestHoodieLogFormat.java b/hudi-common/src/test/java/org/apache/hudi/common/functional/TestHoodieLogFormat.java
index d4cb5021afc..9e7314cf245 100755
--- a/hudi-common/src/test/java/org/apache/hudi/common/functional/TestHoodieLogFormat.java
+++ b/hudi-common/src/test/java/org/apache/hudi/common/functional/TestHoodieLogFormat.java
@@ -440,8 +440,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     }
     writer.close();
 
-    Reader reader = HoodieLogFormat.newReader(fs, writer.getLogFile(), SchemaTestUtil.getSimpleSchema(),
-        true, true);
+    Reader reader = HoodieLogFormat.newReader(fs, writer.getLogFile(), SchemaTestUtil.getSimpleSchema(), true);
     assertTrue(reader.hasNext(), "We wrote a block, we should be able to read it");
     HoodieLogBlock nextBlock = reader.next();
     assertEquals(DEFAULT_DATA_BLOCK_TYPE, nextBlock.getBlockType(), "The next block should be a data block");
@@ -635,7 +634,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @MethodSource("testArguments")
   public void testBasicAppendAndScanMultipleFiles(ExternalSpillableMap.DiskMapType diskMapType,
                                                   boolean isCompressionEnabled,
-                                                  boolean readBlocksLazily,
                                                   boolean enableOptimizedLogBlocksScan)
       throws IOException, URISyntaxException, InterruptedException {
 
@@ -657,7 +655,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
         .withReaderSchema(schema)
         .withLatestInstantTime("100")
         .withMaxMemorySizeInBytes(10240L)
-        .withReadBlocksLazily(readBlocksLazily)
         .withReverseReader(false)
         .withBufferSize(BUFFER_SIZE)
         .withSpillableMapBasePath(spillableBasePath)
@@ -763,7 +760,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
         .withReaderSchema(schema)
         .withLatestInstantTime("100")
         .withMaxMemorySizeInBytes(10240L)
-        .withReadBlocksLazily(true)
         .withReverseReader(false)
         .withBufferSize(BUFFER_SIZE)
         .withSpillableMapBasePath(spillableBasePath)
@@ -783,7 +779,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @MethodSource("testArguments")
   public void testBasicAppendAndPartialScanning(ExternalSpillableMap.DiskMapType diskMapType,
                                                 boolean isCompressionEnabled,
-                                                boolean readBlocksLazily,
                                                 boolean enableOptimizedLogBlocksScan)
       throws IOException, URISyntaxException, InterruptedException {
     // Generate 3 delta-log files w/ random records
@@ -805,7 +800,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
         .withReaderSchema(schema)
         .withLatestInstantTime("100")
         .withMaxMemorySizeInBytes(10240L)
-        .withReadBlocksLazily(readBlocksLazily)
         .withReverseReader(false)
         .withBufferSize(BUFFER_SIZE)
         .withSpillableMapBasePath(spillableBasePath)
@@ -873,7 +867,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @MethodSource("testArguments")
   public void testBasicAppendAndPartialScanningByKeyPrefixes(ExternalSpillableMap.DiskMapType diskMapType,
                                                              boolean isCompressionEnabled,
-                                                             boolean readBlocksLazily,
                                                              boolean enableOptimizedLogBlocksScan)
       throws IOException, URISyntaxException, InterruptedException {
     // Generate 3 delta-log files w/ random records
@@ -895,7 +888,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
         .withReaderSchema(schema)
         .withLatestInstantTime("100")
         .withMaxMemorySizeInBytes(10240L)
-        .withReadBlocksLazily(readBlocksLazily)
         .withReverseReader(false)
         .withBufferSize(BUFFER_SIZE)
         .withSpillableMapBasePath(spillableBasePath)
@@ -1158,7 +1150,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @MethodSource("testArguments")
   public void testAvroLogRecordReaderBasic(ExternalSpillableMap.DiskMapType diskMapType,
                                            boolean isCompressionEnabled,
-                                           boolean readBlocksLazily,
                                            boolean enableOptimizedLogBlocksScan)
       throws IOException, URISyntaxException, InterruptedException {
     Schema schema = HoodieAvroUtils.addMetadataFields(getSimpleSchema());
@@ -1194,7 +1185,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     Set<String> originalKeys =
         copyOfRecords1.stream().map(s -> ((GenericRecord) s).get(HoodieRecord.RECORD_KEY_METADATA_FIELD).toString())
             .collect(Collectors.toSet());
-    checkLogBlocksAndKeys("100", schema, readBlocksLazily, diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan,
+    checkLogBlocksAndKeys("100", schema, diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan,
         200, 200, Option.of(originalKeys));
   }
 
@@ -1202,7 +1193,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @MethodSource("testArguments")
   public void testAvroLogRecordReaderWithRollbackTombstone(ExternalSpillableMap.DiskMapType diskMapType,
                                                            boolean isCompressionEnabled,
-                                                           boolean readBlocksLazily,
                                                            boolean enableOptimizedLogBlocksScan)
       throws IOException, URISyntaxException, InterruptedException {
     Schema schema = HoodieAvroUtils.addMetadataFields(getSimpleSchema());
@@ -1258,7 +1248,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     Set<String> originalKeys =
         copyOfRecords1.stream().map(s -> ((GenericRecord) s).get(HoodieRecord.RECORD_KEY_METADATA_FIELD).toString())
             .collect(Collectors.toSet());
-    checkLogBlocksAndKeys("102", schema, readBlocksLazily, diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan,
+    checkLogBlocksAndKeys("102", schema, diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan,
         200, 200, Option.of(originalKeys));
   }
 
@@ -1327,7 +1317,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     Set<String> originalKeys =
         copyOfRecords1.stream().map(s -> ((GenericRecord) s).get(HoodieRecord.RECORD_KEY_METADATA_FIELD).toString())
             .collect(Collectors.toSet());
-    checkLogBlocksAndKeys("103", schema, true, diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan,
+    checkLogBlocksAndKeys("103", schema, diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan,
         200, 200, Option.of(originalKeys));
   }
 
@@ -1335,7 +1325,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @MethodSource("testArguments")
   public void testAvroLogRecordReaderWithDeleteAndRollback(ExternalSpillableMap.DiskMapType diskMapType,
                                                            boolean isCompressionEnabled,
-                                                           boolean readBlocksLazily,
                                                            boolean enableOptimizedLogBlocksScan)
       throws IOException, URISyntaxException, InterruptedException {
     Schema schema = HoodieAvroUtils.addMetadataFields(getSimpleSchema());
@@ -1393,7 +1382,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
         .withReaderSchema(schema)
         .withLatestInstantTime("102")
         .withMaxMemorySizeInBytes(10240L)
-        .withReadBlocksLazily(readBlocksLazily)
         .withReverseReader(false)
         .withBufferSize(BUFFER_SIZE)
         .withSpillableMapBasePath(spillableBasePath)
@@ -1441,7 +1429,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
         .withReaderSchema(schema)
         .withLatestInstantTime("103")
         .withMaxMemorySizeInBytes(10240L)
-        .withReadBlocksLazily(readBlocksLazily)
         .withReverseReader(false)
         .withBufferSize(BUFFER_SIZE)
         .withSpillableMapBasePath(spillableBasePath)
@@ -1476,7 +1463,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @MethodSource("testArguments")
   public void testAvroLogRecordReaderWithCommitBeforeAndAfterRollback(ExternalSpillableMap.DiskMapType diskMapType,
                                                                       boolean isCompressionEnabled,
-                                                                      boolean readBlocksLazily,
                                                                       boolean enableOptimizedLogBlocksScan)
       throws IOException, URISyntaxException, InterruptedException {
     Schema schema = HoodieAvroUtils.addMetadataFields(getSimpleSchema());
@@ -1549,7 +1535,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
         .withReaderSchema(schema)
         .withLatestInstantTime("103")
         .withMaxMemorySizeInBytes(10240L)
-        .withReadBlocksLazily(readBlocksLazily)
         .withReverseReader(false)
         .withBufferSize(BUFFER_SIZE)
         .withSpillableMapBasePath(spillableBasePath)
@@ -1582,8 +1567,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @ParameterizedTest
   @MethodSource("testArguments")
   public void testAvroLogRecordReaderWithDisorderDelete(ExternalSpillableMap.DiskMapType diskMapType,
-                                                        boolean isCompressionEnabled,
-                                                        boolean readBlocksLazily)
+                                                        boolean isCompressionEnabled)
       throws IOException, URISyntaxException, InterruptedException {
     Schema schema = HoodieAvroUtils.addMetadataFields(getSimpleSchema());
     // Set a small threshold so that every block is a new version
@@ -1664,7 +1648,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
         .withReaderSchema(schema)
         .withLatestInstantTime("104")
         .withMaxMemorySizeInBytes(10240L)
-        .withReadBlocksLazily(readBlocksLazily)
         .withReverseReader(false)
         .withBufferSize(BUFFER_SIZE)
         .withSpillableMapBasePath(spillableBasePath)
@@ -1703,7 +1686,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @MethodSource("testArguments")
   public void testAvroLogRecordReaderWithFailedRollbacks(ExternalSpillableMap.DiskMapType diskMapType,
                                                          boolean isCompressionEnabled,
-                                                         boolean readBlocksLazily,
                                                          boolean enableOptimizedLogBlocksScan)
       throws IOException, URISyntaxException, InterruptedException {
 
@@ -1760,7 +1742,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     writer.appendBlock(commandBlock);
     writer.close();
 
-    checkLogBlocksAndKeys("100", schema, readBlocksLazily, diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan,
+    checkLogBlocksAndKeys("100", schema, diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan,
         0, 0, Option.empty());
     FileCreateUtils.deleteDeltaCommit(basePath, "100", fs);
   }
@@ -1769,7 +1751,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @MethodSource("testArguments")
   public void testAvroLogRecordReaderWithInsertDeleteAndRollback(ExternalSpillableMap.DiskMapType diskMapType,
                                                                  boolean isCompressionEnabled,
-                                                                 boolean readBlocksLazily,
                                                                  boolean enableOptimizedLogBlocksScan)
       throws IOException, URISyntaxException, InterruptedException {
 
@@ -1810,7 +1791,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     writer.appendBlock(commandBlock);
     writer.close();
 
-    checkLogBlocksAndKeys("100", schema, readBlocksLazily, diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan,
+    checkLogBlocksAndKeys("100", schema, diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan,
         0, 0, Option.empty());
     FileCreateUtils.deleteDeltaCommit(basePath, "100", fs);
   }
@@ -1819,7 +1800,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @MethodSource("testArguments")
   public void testAvroLogRecordReaderWithInvalidRollback(ExternalSpillableMap.DiskMapType diskMapType,
                                                          boolean isCompressionEnabled,
-                                                         boolean readBlocksLazily,
                                                          boolean enableOptimizedLogBlocksScan)
       throws IOException, URISyntaxException, InterruptedException {
     Schema schema = HoodieAvroUtils.addMetadataFields(getSimpleSchema());
@@ -1847,7 +1827,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     writer.appendBlock(commandBlock);
     writer.close();
 
-    checkLogBlocksAndKeys("100", schema, readBlocksLazily, diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan,
+    checkLogBlocksAndKeys("100", schema, diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan,
         100, 100, Option.empty());
   }
 
@@ -1855,7 +1835,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @MethodSource("testArguments")
   public void testAvroLogRecordReaderWithInsertsDeleteAndRollback(ExternalSpillableMap.DiskMapType diskMapType,
                                                                   boolean isCompressionEnabled,
-                                                                  boolean readBlocksLazily,
                                                                   boolean enableOptimizedLogBlocksScan)
       throws IOException, URISyntaxException, InterruptedException {
 
@@ -1900,7 +1879,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     writer.appendBlock(commandBlock);
     writer.close();
 
-    checkLogBlocksAndKeys("101", schema, readBlocksLazily, diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan,
+    checkLogBlocksAndKeys("101", schema, diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan,
         0, 0, Option.empty());
   }
 
@@ -1909,7 +1888,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @MethodSource("testArguments")
   public void testLogReaderWithDifferentVersionsOfDeleteBlocks(ExternalSpillableMap.DiskMapType diskMapType,
                                                                boolean isCompressionEnabled,
-                                                               boolean readBlocksLazily,
                                                                boolean enableOptimizedLogBlocksScan)
       throws IOException, URISyntaxException, InterruptedException {
     Schema schema = HoodieAvroUtils.addMetadataFields(getSimpleSchema());
@@ -1990,7 +1968,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
         .withReaderSchema(schema)
         .withLatestInstantTime("103")
         .withMaxMemorySizeInBytes(10240L)
-        .withReadBlocksLazily(readBlocksLazily)
         .withReverseReader(false)
         .withBufferSize(BUFFER_SIZE)
         .withSpillableMapBasePath(spillableBasePath)
@@ -2057,7 +2034,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     FileCreateUtils.createDeltaCommit(basePath, "101", fs);
 
     // Should be able to read all 110 records
-    checkLogBlocksAndKeys("101", schema, true, ExternalSpillableMap.DiskMapType.BITCASK, false,
+    checkLogBlocksAndKeys("101", schema, ExternalSpillableMap.DiskMapType.BITCASK, false,
         false, 110, 110, Option.empty());
 
     // Write a rollback for commit 100 which is not the latest commit
@@ -2068,7 +2045,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     writer.appendBlock(commandBlock);
 
     // Should only be able to read 10 records from commit 101
-    checkLogBlocksAndKeys("101", schema, true, ExternalSpillableMap.DiskMapType.BITCASK, false,
+    checkLogBlocksAndKeys("101", schema, ExternalSpillableMap.DiskMapType.BITCASK, false,
         false, 10, 10, Option.empty());
 
     // Write a rollback for commit 101 which is the latest commit
@@ -2080,7 +2057,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     writer.close();
 
     // Should not read any records as both commits are rolled back
-    checkLogBlocksAndKeys("101", schema, true, ExternalSpillableMap.DiskMapType.BITCASK, false,
+    checkLogBlocksAndKeys("101", schema, ExternalSpillableMap.DiskMapType.BITCASK, false,
         false, 0, 0, Option.empty());
   }
 
@@ -2088,7 +2065,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @MethodSource("testArguments")
   public void testAvroLogRecordReaderWithMixedInsertsCorruptsAndRollback(ExternalSpillableMap.DiskMapType diskMapType,
                                                                          boolean isCompressionEnabled,
-                                                                         boolean readBlocksLazily,
                                                                          boolean enableOptimizedLogBlocksScan)
       throws IOException, URISyntaxException, InterruptedException {
 
@@ -2171,7 +2147,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     writer.appendBlock(commandBlock);
     writer.close();
 
-    checkLogBlocksAndKeys("101", schema, true, ExternalSpillableMap.DiskMapType.BITCASK, false,
+    checkLogBlocksAndKeys("101", schema, ExternalSpillableMap.DiskMapType.BITCASK, false,
         false, 0, 0, Option.empty());
     FileCreateUtils.deleteDeltaCommit(basePath, "100", fs);
   }
@@ -2179,8 +2155,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @ParameterizedTest
   @MethodSource("testArgumentsWithoutOptimizedScanArg")
   public void testAvroLogRecordReaderWithMixedInsertsCorruptsRollbackAndMergedLogBlock(ExternalSpillableMap.DiskMapType diskMapType,
-                                                                                       boolean isCompressionEnabled,
-                                                                                       boolean readBlocksLazily)
+                                                                                       boolean isCompressionEnabled)
       throws IOException, URISyntaxException, InterruptedException {
 
     // Write blocks in this manner.
@@ -2344,7 +2319,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
         .withReaderSchema(schema)
         .withLatestInstantTime("108")
         .withMaxMemorySizeInBytes(10240L)
-        .withReadBlocksLazily(readBlocksLazily)
         .withReverseReader(false)
         .withBufferSize(BUFFER_SIZE)
         .withSpillableMapBasePath(spillableBasePath)
@@ -2384,7 +2358,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   private void testAvroLogRecordReaderMergingMultipleLogFiles(int numRecordsInLog1, int numRecordsInLog2,
                                                               ExternalSpillableMap.DiskMapType diskMapType,
                                                               boolean isCompressionEnabled,
-                                                              boolean readBlocksLazily,
                                                               boolean enableOptimizedLogBlocksScan) {
     try {
       // Write one Data block with same InstantTime (written in same batch)
@@ -2433,7 +2406,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
           .withReaderSchema(schema)
           .withLatestInstantTime("100")
           .withMaxMemorySizeInBytes(10240L)
-          .withReadBlocksLazily(readBlocksLazily)
           .withReverseReader(false)
           .withBufferSize(BUFFER_SIZE)
           .withSpillableMapBasePath(spillableBasePath)
@@ -2454,47 +2426,43 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   @MethodSource("testArguments")
   public void testAvroLogRecordReaderWithFailedTaskInFirstStageAttempt(ExternalSpillableMap.DiskMapType diskMapType,
                                                                        boolean isCompressionEnabled,
-                                                                       boolean readBlocksLazily,
                                                                        boolean enableOptimizedLogBlocksScan) {
     /*
      * FIRST_ATTEMPT_FAILED:
      * Original task from the stage attempt failed, but subsequent stage retry succeeded.
      */
     testAvroLogRecordReaderMergingMultipleLogFiles(77, 100,
-        diskMapType, isCompressionEnabled, readBlocksLazily, enableOptimizedLogBlocksScan);
+        diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan);
   }
 
   @ParameterizedTest
   @MethodSource("testArguments")
   public void testAvroLogRecordReaderWithFailedTaskInSecondStageAttempt(ExternalSpillableMap.DiskMapType diskMapType,
                                                                         boolean isCompressionEnabled,
-                                                                        boolean readBlocksLazily,
                                                                         boolean enableOptimizedLogBlocksScan) {
     /*
      * SECOND_ATTEMPT_FAILED:
      * Original task from stage attempt succeeded, but subsequent retry attempt failed.
      */
     testAvroLogRecordReaderMergingMultipleLogFiles(100, 66,
-        diskMapType, isCompressionEnabled, readBlocksLazily, enableOptimizedLogBlocksScan);
+        diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan);
   }
 
   @ParameterizedTest
   @MethodSource("testArguments")
   public void testAvroLogRecordReaderTasksSucceededInBothStageAttempts(ExternalSpillableMap.DiskMapType diskMapType,
                                                                        boolean isCompressionEnabled,
-                                                                       boolean readBlocksLazily,
                                                                        boolean enableOptimizedLogBlocksScan) {
     /*
      * BOTH_ATTEMPTS_SUCCEEDED:
      * Original task from the stage attempt and duplicate task from the stage retry succeeded.
      */
     testAvroLogRecordReaderMergingMultipleLogFiles(100, 100,
-        diskMapType, isCompressionEnabled, readBlocksLazily, enableOptimizedLogBlocksScan);
+        diskMapType, isCompressionEnabled, enableOptimizedLogBlocksScan);
   }
 
-  @ParameterizedTest
-  @ValueSource(booleans = {true, false})
-  public void testBasicAppendAndReadInReverse(boolean readBlocksLazily)
+  @Test
+  public void testBasicAppendAndReadInReverse()
       throws IOException, URISyntaxException, InterruptedException {
     Writer writer =
         HoodieLogFormat.newWriterBuilder().onParentPath(partitionPath).withFileExtension(HoodieLogFile.DELTA_EXTENSION)
@@ -2534,7 +2502,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     FileCreateUtils.createDeltaCommit(basePath, "100", fs);
 
     HoodieLogFile logFile = new HoodieLogFile(writer.getLogFile().getPath(), fs.getFileStatus(writer.getLogFile().getPath()).getLen());
-    try (HoodieLogFileReader reader = new HoodieLogFileReader(fs, logFile, SchemaTestUtil.getSimpleSchema(), BUFFER_SIZE, readBlocksLazily, true)) {
+    try (HoodieLogFileReader reader = new HoodieLogFileReader(fs, logFile, SchemaTestUtil.getSimpleSchema(), BUFFER_SIZE, true)) {
 
       assertTrue(reader.hasPrev(), "Last block should be available");
       HoodieLogBlock prevBlock = reader.prev();
@@ -2568,9 +2536,8 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     }
   }
 
-  @ParameterizedTest
-  @ValueSource(booleans = {true, false})
-  public void testAppendAndReadOnCorruptedLogInReverse(boolean readBlocksLazily)
+  @Test
+  public void testAppendAndReadOnCorruptedLogInReverse()
       throws IOException, URISyntaxException, InterruptedException {
     Writer writer =
         HoodieLogFormat.newWriterBuilder().onParentPath(partitionPath).withFileExtension(HoodieLogFile.DELTA_EXTENSION)
@@ -2615,8 +2582,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     // First round of reads - we should be able to read the first block and then EOF
     HoodieLogFile logFile = new HoodieLogFile(writer.getLogFile().getPath(), fs.getFileStatus(writer.getLogFile().getPath()).getLen());
 
-    try (HoodieLogFileReader reader =
-             new HoodieLogFileReader(fs, logFile, schema, BUFFER_SIZE, readBlocksLazily, true)) {
+    try (HoodieLogFileReader reader = new HoodieLogFileReader(fs, logFile, schema, BUFFER_SIZE, true)) {
 
       assertTrue(reader.hasPrev(), "Last block should be available");
       HoodieLogBlock block = reader.prev();
@@ -2629,9 +2595,8 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     }
   }
 
-  @ParameterizedTest
-  @ValueSource(booleans = {true, false})
-  public void testBasicAppendAndTraverseInReverse(boolean readBlocksLazily)
+  @Test
+  public void testBasicAppendAndTraverseInReverse()
       throws IOException, URISyntaxException, InterruptedException {
     Writer writer =
         HoodieLogFormat.newWriterBuilder().onParentPath(partitionPath).withFileExtension(HoodieLogFile.DELTA_EXTENSION)
@@ -2668,7 +2633,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
 
     HoodieLogFile logFile = new HoodieLogFile(writer.getLogFile().getPath(), fs.getFileStatus(writer.getLogFile().getPath()).getLen());
     try (HoodieLogFileReader reader =
-             new HoodieLogFileReader(fs, logFile, SchemaTestUtil.getSimpleSchema(), BUFFER_SIZE, readBlocksLazily, true)) {
+             new HoodieLogFileReader(fs, logFile, SchemaTestUtil.getSimpleSchema(), BUFFER_SIZE, true)) {
 
       assertTrue(reader.hasPrev(), "Third block should be available");
       reader.moveToPrev();
@@ -2758,7 +2723,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
 
     List<GenericRecord> projectedRecords = HoodieAvroUtils.rewriteRecords(records, projectedSchema);
 
-    try (Reader reader = HoodieLogFormat.newReader(fs, writer.getLogFile(), projectedSchema, true, false)) {
+    try (Reader reader = HoodieLogFormat.newReader(fs, writer.getLogFile(), projectedSchema, false)) {
       assertTrue(reader.hasNext(), "First block should be available");
 
       HoodieLogBlock nextBlock = reader.next();
@@ -2826,29 +2791,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
   }
 
   private static Stream<Arguments> testArguments() {
-    // Arg1: ExternalSpillableMap Type, Arg2: isDiskMapCompressionEnabled, Arg3: readBlocksLazily, Arg4: enableOptimizedLogBlocksScan
-    return Stream.of(
-        arguments(ExternalSpillableMap.DiskMapType.BITCASK, false, false, true),
-        arguments(ExternalSpillableMap.DiskMapType.ROCKS_DB, false, false, true),
-        arguments(ExternalSpillableMap.DiskMapType.BITCASK, true, false, true),
-        arguments(ExternalSpillableMap.DiskMapType.ROCKS_DB, true, false, true),
-        arguments(ExternalSpillableMap.DiskMapType.BITCASK, false, true, true),
-        arguments(ExternalSpillableMap.DiskMapType.ROCKS_DB, false, true, true),
-        arguments(ExternalSpillableMap.DiskMapType.BITCASK, true, true, true),
-        arguments(ExternalSpillableMap.DiskMapType.ROCKS_DB, true, true, true),
-        arguments(ExternalSpillableMap.DiskMapType.BITCASK, false, false, false),
-        arguments(ExternalSpillableMap.DiskMapType.ROCKS_DB, false, false, false),
-        arguments(ExternalSpillableMap.DiskMapType.BITCASK, true, false, false),
-        arguments(ExternalSpillableMap.DiskMapType.ROCKS_DB, true, false, false),
-        arguments(ExternalSpillableMap.DiskMapType.BITCASK, false, true, false),
-        arguments(ExternalSpillableMap.DiskMapType.ROCKS_DB, false, true, false),
-        arguments(ExternalSpillableMap.DiskMapType.BITCASK, true, true, false),
-        arguments(ExternalSpillableMap.DiskMapType.ROCKS_DB, true, true, false)
-    );
-  }
-
-  private static Stream<Arguments> testArgumentsWithoutOptimizedScanArg() {
-    // Arg1: ExternalSpillableMap Type, Arg2: isDiskMapCompressionEnabled, Arg3: readBlocksLazily
+    // Arg1: ExternalSpillableMap Type, Arg2: isDiskMapCompressionEnabled, Arg3: enableOptimizedLogBlocksScan
     return Stream.of(
         arguments(ExternalSpillableMap.DiskMapType.BITCASK, false, false),
         arguments(ExternalSpillableMap.DiskMapType.ROCKS_DB, false, false),
@@ -2861,6 +2804,16 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     );
   }
 
+  private static Stream<Arguments> testArgumentsWithoutOptimizedScanArg() {
+    // Arg1: ExternalSpillableMap Type, Arg2: isDiskMapCompressionEnabled
+    return Stream.of(
+        arguments(ExternalSpillableMap.DiskMapType.BITCASK, false),
+        arguments(ExternalSpillableMap.DiskMapType.ROCKS_DB, false),
+        arguments(ExternalSpillableMap.DiskMapType.BITCASK, true),
+        arguments(ExternalSpillableMap.DiskMapType.ROCKS_DB, true)
+    );
+  }
+
   private static Set<HoodieLogFile> writeLogFiles(Path partitionPath,
                                                   Schema schema,
                                                   List<IndexedRecord> records,
@@ -2970,8 +2923,8 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     return reader;
   }
 
-  private void checkLogBlocksAndKeys(String latestInstantTime, Schema schema, boolean readBlocksLazily,
-                                     ExternalSpillableMap.DiskMapType diskMapType, boolean isCompressionEnabled, boolean enableOptimizedLogBlocksScan, int expectedTotalRecords,
+  private void checkLogBlocksAndKeys(String latestInstantTime, Schema schema, ExternalSpillableMap.DiskMapType diskMapType,
+                                     boolean isCompressionEnabled, boolean enableOptimizedLogBlocksScan, int expectedTotalRecords,
                                      int expectedTotalKeys, Option<Set<String>> expectedKeys) throws IOException {
     List<String> allLogFiles =
         FSUtils.getAllLogFiles(fs, partitionPath, "test-fileid1", HoodieLogFile.DELTA_EXTENSION, "100")
@@ -2984,7 +2937,6 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
         .withReaderSchema(schema)
         .withLatestInstantTime(latestInstantTime)
         .withMaxMemorySizeInBytes(10240L)
-        .withReadBlocksLazily(readBlocksLazily)
         .withReverseReader(false)
         .withBufferSize(BUFFER_SIZE)
         .withSpillableMapBasePath(spillableBasePath)
diff --git a/hudi-examples/hudi-examples-flink/src/test/java/org/apache/hudi/examples/quickstart/TestQuickstartData.java b/hudi-examples/hudi-examples-flink/src/test/java/org/apache/hudi/examples/quickstart/TestQuickstartData.java
index 7fc93c776f5..6790b602186 100644
--- a/hudi-examples/hudi-examples-flink/src/test/java/org/apache/hudi/examples/quickstart/TestQuickstartData.java
+++ b/hudi-examples/hudi-examples-flink/src/test/java/org/apache/hudi/examples/quickstart/TestQuickstartData.java
@@ -353,7 +353,6 @@ public class TestQuickstartData {
         .withLogFilePaths(logPaths)
         .withReaderSchema(readSchema)
         .withLatestInstantTime(instant)
-        .withReadBlocksLazily(false)
         .withReverseReader(false)
         .withBufferSize(16 * 1024 * 1024)
         .withMaxMemorySizeInBytes(1024 * 1024L)
diff --git a/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/sink/clustering/ClusteringOperator.java b/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/sink/clustering/ClusteringOperator.java
index ecfc26a10dc..5970dc782b6 100644
--- a/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/sink/clustering/ClusteringOperator.java
+++ b/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/sink/clustering/ClusteringOperator.java
@@ -282,7 +282,6 @@ public class ClusteringOperator extends TableStreamOperator<ClusteringCommitEven
             .withReaderSchema(readerSchema)
             .withLatestInstantTime(instantTime)
             .withMaxMemorySizeInBytes(maxMemoryPerCompaction)
-            .withReadBlocksLazily(writeConfig.getCompactionLazyBlockReadEnabled())
             .withReverseReader(writeConfig.getCompactionReverseLogReadEnabled())
             .withBufferSize(writeConfig.getMaxDFSStreamBufferSize())
             .withSpillableMapBasePath(writeConfig.getSpillableMapBasePath())
diff --git a/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/table/format/FormatUtils.java b/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/table/format/FormatUtils.java
index baa9f21216b..b10b5be9c47 100644
--- a/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/table/format/FormatUtils.java
+++ b/hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/table/format/FormatUtils.java
@@ -159,7 +159,6 @@ public class FormatUtils {
         .withReaderSchema(logSchema)
         .withInternalSchema(internalSchema)
         .withLatestInstantTime(split.getLatestCommit())
-        .withReadBlocksLazily(writeConfig.getCompactionLazyBlockReadEnabled())
         .withReverseReader(false)
         .withBufferSize(writeConfig.getMaxDFSStreamBufferSize())
         .withMaxMemorySizeInBytes(split.getMaxCompactionMemoryInBytes())
@@ -201,10 +200,6 @@ public class FormatUtils {
           .withReaderSchema(logSchema)
           .withInternalSchema(internalSchema)
           .withLatestInstantTime(split.getLatestCommit())
-          .withReadBlocksLazily(
-              string2Boolean(
-                  flinkConf.getString(HoodieRealtimeConfig.COMPACTION_LAZY_BLOCK_READ_ENABLED_PROP,
-                      HoodieRealtimeConfig.DEFAULT_COMPACTION_LAZY_BLOCK_READ_ENABLED)))
           .withReverseReader(false)
           .withBufferSize(
               flinkConf.getInteger(HoodieRealtimeConfig.MAX_DFS_STREAM_BUFFER_SIZE_PROP,
@@ -265,7 +260,6 @@ public class FormatUtils {
         .withLogFilePaths(logPaths)
         .withReaderSchema(logSchema)
         .withLatestInstantTime(latestInstantTime)
-        .withReadBlocksLazily(writeConfig.getCompactionLazyBlockReadEnabled())
         .withReverseReader(false)
         .withBufferSize(writeConfig.getMaxDFSStreamBufferSize())
         .withMaxMemorySizeInBytes(writeConfig.getMaxMemoryPerPartitionMerge())
diff --git a/hudi-flink-datasource/hudi-flink/src/test/java/org/apache/hudi/utils/TestData.java b/hudi-flink-datasource/hudi-flink/src/test/java/org/apache/hudi/utils/TestData.java
index 65c8e82ada1..91e10a3fb9c 100644
--- a/hudi-flink-datasource/hudi-flink/src/test/java/org/apache/hudi/utils/TestData.java
+++ b/hudi-flink-datasource/hudi-flink/src/test/java/org/apache/hudi/utils/TestData.java
@@ -949,7 +949,6 @@ public class TestData {
         .withLogFilePaths(logPaths)
         .withReaderSchema(readSchema)
         .withLatestInstantTime(instant)
-        .withReadBlocksLazily(false)
         .withReverseReader(false)
         .withBufferSize(16 * 1024 * 1024)
         .withMaxMemorySizeInBytes(1024 * 1024L)
diff --git a/hudi-hadoop-mr/src/main/java/org/apache/hudi/hadoop/realtime/HoodieMergeOnReadSnapshotReader.java b/hudi-hadoop-mr/src/main/java/org/apache/hudi/hadoop/realtime/HoodieMergeOnReadSnapshotReader.java
index 4a39b6548f9..b7ec3b12403 100644
--- a/hudi-hadoop-mr/src/main/java/org/apache/hudi/hadoop/realtime/HoodieMergeOnReadSnapshotReader.java
+++ b/hudi-hadoop-mr/src/main/java/org/apache/hudi/hadoop/realtime/HoodieMergeOnReadSnapshotReader.java
@@ -48,8 +48,6 @@ import java.util.stream.Collectors;
 
 import static org.apache.hudi.common.config.HoodieCommonConfig.DISK_MAP_BITCASK_COMPRESSION_ENABLED;
 import static org.apache.hudi.common.config.HoodieCommonConfig.SPILLABLE_DISK_MAP_TYPE;
-import static org.apache.hudi.hadoop.config.HoodieRealtimeConfig.COMPACTION_LAZY_BLOCK_READ_ENABLED_PROP;
-import static org.apache.hudi.hadoop.config.HoodieRealtimeConfig.DEFAULT_COMPACTION_LAZY_BLOCK_READ_ENABLED;
 import static org.apache.hudi.hadoop.config.HoodieRealtimeConfig.DEFAULT_MAX_DFS_STREAM_BUFFER_SIZE;
 import static org.apache.hudi.hadoop.config.HoodieRealtimeConfig.DEFAULT_SPILLABLE_MAP_BASE_PATH;
 import static org.apache.hudi.hadoop.config.HoodieRealtimeConfig.ENABLE_OPTIMIZED_LOG_BLOCKS_SCAN;
@@ -185,7 +183,6 @@ public class HoodieMergeOnReadSnapshotReader extends AbstractRealtimeRecordReade
         .withReaderSchema(readerSchema)
         .withLatestInstantTime(latestInstantTime)
         .withMaxMemorySizeInBytes(getMaxCompactionMemoryInBytes(jobConf))
-        .withReadBlocksLazily(Boolean.parseBoolean(jobConf.get(COMPACTION_LAZY_BLOCK_READ_ENABLED_PROP, DEFAULT_COMPACTION_LAZY_BLOCK_READ_ENABLED)))
         .withReverseReader(false)
         .withBufferSize(jobConf.getInt(MAX_DFS_STREAM_BUFFER_SIZE_PROP, DEFAULT_MAX_DFS_STREAM_BUFFER_SIZE))
         .withSpillableMapBasePath(jobConf.get(SPILLABLE_MAP_BASE_PATH_PROP, DEFAULT_SPILLABLE_MAP_BASE_PATH))
diff --git a/hudi-hadoop-mr/src/main/java/org/apache/hudi/hadoop/realtime/RealtimeCompactedRecordReader.java b/hudi-hadoop-mr/src/main/java/org/apache/hudi/hadoop/realtime/RealtimeCompactedRecordReader.java
index 61933608e94..5ef1c8d692d 100644
--- a/hudi-hadoop-mr/src/main/java/org/apache/hudi/hadoop/realtime/RealtimeCompactedRecordReader.java
+++ b/hudi-hadoop-mr/src/main/java/org/apache/hudi/hadoop/realtime/RealtimeCompactedRecordReader.java
@@ -89,7 +89,6 @@ public class RealtimeCompactedRecordReader extends AbstractRealtimeRecordReader
         .withReaderSchema(getLogScannerReaderSchema())
         .withLatestInstantTime(split.getMaxCommitTime())
         .withMaxMemorySizeInBytes(HoodieRealtimeRecordReaderUtils.getMaxCompactionMemoryInBytes(jobConf))
-        .withReadBlocksLazily(Boolean.parseBoolean(jobConf.get(HoodieRealtimeConfig.COMPACTION_LAZY_BLOCK_READ_ENABLED_PROP, HoodieRealtimeConfig.DEFAULT_COMPACTION_LAZY_BLOCK_READ_ENABLED)))
         .withReverseReader(false)
         .withBufferSize(jobConf.getInt(HoodieRealtimeConfig.MAX_DFS_STREAM_BUFFER_SIZE_PROP, HoodieRealtimeConfig.DEFAULT_MAX_DFS_STREAM_BUFFER_SIZE))
         .withSpillableMapBasePath(jobConf.get(HoodieRealtimeConfig.SPILLABLE_MAP_BASE_PATH_PROP, HoodieRealtimeConfig.DEFAULT_SPILLABLE_MAP_BASE_PATH))
diff --git a/hudi-hadoop-mr/src/main/java/org/apache/hudi/hadoop/realtime/RealtimeUnmergedRecordReader.java b/hudi-hadoop-mr/src/main/java/org/apache/hudi/hadoop/realtime/RealtimeUnmergedRecordReader.java
index dd0ef5bf15d..ed40f4dd47c 100644
--- a/hudi-hadoop-mr/src/main/java/org/apache/hudi/hadoop/realtime/RealtimeUnmergedRecordReader.java
+++ b/hudi-hadoop-mr/src/main/java/org/apache/hudi/hadoop/realtime/RealtimeUnmergedRecordReader.java
@@ -81,7 +81,6 @@ class RealtimeUnmergedRecordReader extends AbstractRealtimeRecordReader
           .withLogFilePaths(split.getDeltaLogPaths())
           .withReaderSchema(getReaderSchema())
           .withLatestInstantTime(split.getMaxCommitTime())
-          .withReadBlocksLazily(Boolean.parseBoolean(this.jobConf.get(HoodieRealtimeConfig.COMPACTION_LAZY_BLOCK_READ_ENABLED_PROP, HoodieRealtimeConfig.DEFAULT_COMPACTION_LAZY_BLOCK_READ_ENABLED)))
           .withReverseReader(false)
           .withBufferSize(this.jobConf.getInt(HoodieRealtimeConfig.MAX_DFS_STREAM_BUFFER_SIZE_PROP, HoodieRealtimeConfig.DEFAULT_MAX_DFS_STREAM_BUFFER_SIZE));
 
diff --git a/hudi-integ-test/src/main/java/org/apache/hudi/integ/testsuite/reader/DFSHoodieDatasetInputReader.java b/hudi-integ-test/src/main/java/org/apache/hudi/integ/testsuite/reader/DFSHoodieDatasetInputReader.java
index 02d534d5b98..edd68ca7baa 100644
--- a/hudi-integ-test/src/main/java/org/apache/hudi/integ/testsuite/reader/DFSHoodieDatasetInputReader.java
+++ b/hudi-integ-test/src/main/java/org/apache/hudi/integ/testsuite/reader/DFSHoodieDatasetInputReader.java
@@ -287,7 +287,6 @@ public class DFSHoodieDatasetInputReader extends DFSDeltaInputReader {
               .filterCompletedInstants().lastInstant().get().getTimestamp())
           .withMaxMemorySizeInBytes(
               HoodieMemoryConfig.DEFAULT_MAX_MEMORY_FOR_SPILLABLE_MAP_IN_BYTES)
-          .withReadBlocksLazily(true)
           .withReverseReader(false)
           .withBufferSize(HoodieMemoryConfig.MAX_DFS_STREAM_BUFFER_SIZE.defaultValue())
           .withSpillableMapBasePath(FileIOUtils.getDefaultSpillableMapBasePath())
diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/Iterators.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/Iterators.scala
index 3a86a2cc738..b6a5ae7a956 100644
--- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/Iterators.scala
+++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/Iterators.scala
@@ -385,10 +385,6 @@ object LogFileIterator extends SparkAdapterSupport {
         // NOTE: This part shall only be reached when at least one log is present in the file-group
         //       entailing that table has to have at least one commit
         .withLatestInstantTime(tableState.latestCommitTimestamp.get)
-        .withReadBlocksLazily(
-          Try(hadoopConf.get(HoodieRealtimeConfig.COMPACTION_LAZY_BLOCK_READ_ENABLED_PROP,
-            HoodieRealtimeConfig.DEFAULT_COMPACTION_LAZY_BLOCK_READ_ENABLED).toBoolean)
-            .getOrElse(false))
         .withReverseReader(false)
         .withInternalSchema(internalSchema)
         .withBufferSize(
diff --git a/hudi-spark-datasource/hudi-spark/src/main/scala/org/apache/spark/sql/hudi/command/procedures/ShowHoodieLogFileRecordsProcedure.scala b/hudi-spark-datasource/hudi-spark/src/main/scala/org/apache/spark/sql/hudi/command/procedures/ShowHoodieLogFileRecordsProcedure.scala
index cca1fd1da0d..fa220acf7b2 100644
--- a/hudi-spark-datasource/hudi-spark/src/main/scala/org/apache/spark/sql/hudi/command/procedures/ShowHoodieLogFileRecordsProcedure.scala
+++ b/hudi-spark-datasource/hudi-spark/src/main/scala/org/apache/spark/sql/hudi/command/procedures/ShowHoodieLogFileRecordsProcedure.scala
@@ -71,7 +71,6 @@ class ShowHoodieLogFileRecordsProcedure extends BaseProcedure with ProcedureBuil
         .withLogFilePaths(logFilePaths.asJava)
         .withReaderSchema(schema)
         .withLatestInstantTime(client.getActiveTimeline.getCommitTimeline.lastInstant.get.getTimestamp)
-        .withReadBlocksLazily(java.lang.Boolean.parseBoolean(HoodieCompactionConfig.COMPACTION_LAZY_BLOCK_READ_ENABLE.defaultValue))
         .withReverseReader(java.lang.Boolean.parseBoolean(HoodieCompactionConfig.COMPACTION_REVERSE_LOG_READ_ENABLE.defaultValue))
         .withBufferSize(HoodieMemoryConfig.MAX_DFS_STREAM_BUFFER_SIZE.defaultValue)
         .withMaxMemorySizeInBytes(HoodieMemoryConfig.DEFAULT_MAX_MEMORY_FOR_SPILLABLE_MAP_IN_BYTES)
diff --git a/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieMetadataTableValidator.java b/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieMetadataTableValidator.java
index 9d91999bac5..cd8ef0f059a 100644
--- a/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieMetadataTableValidator.java
+++ b/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieMetadataTableValidator.java
@@ -24,6 +24,7 @@ import org.apache.hudi.client.common.HoodieSparkEngineContext;
 import org.apache.hudi.common.bloom.BloomFilter;
 import org.apache.hudi.common.config.HoodieConfig;
 import org.apache.hudi.common.config.HoodieMetadataConfig;
+import org.apache.hudi.common.config.HoodieReaderConfig;
 import org.apache.hudi.common.config.TypedProperties;
 import org.apache.hudi.common.engine.HoodieEngineContext;
 import org.apache.hudi.common.fs.FSUtils;
@@ -36,6 +37,7 @@ import org.apache.hudi.common.model.HoodieFileFormat;
 import org.apache.hudi.common.model.HoodieFileGroup;
 import org.apache.hudi.common.model.HoodieLogFile;
 import org.apache.hudi.common.model.HoodiePartitionMetadata;
+import org.apache.hudi.common.model.HoodieRecord;
 import org.apache.hudi.common.model.HoodieRecord.HoodieRecordType;
 import org.apache.hudi.common.model.HoodieRecordGlobalLocation;
 import org.apache.hudi.common.model.HoodieWriteStat;
@@ -99,13 +101,6 @@ import java.util.stream.Collectors;
 
 import scala.Tuple2;
 
-import static org.apache.hudi.common.config.HoodieReaderConfig.USE_NATIVE_HFILE_READER;
-import static org.apache.hudi.common.model.HoodieRecord.FILENAME_METADATA_FIELD;
-import static org.apache.hudi.common.model.HoodieRecord.PARTITION_PATH_METADATA_FIELD;
-import static org.apache.hudi.common.model.HoodieRecord.RECORD_KEY_METADATA_FIELD;
-import static org.apache.hudi.common.table.log.block.HoodieLogBlock.HeaderMetadataType.INSTANT_TIME;
-import static org.apache.hudi.common.table.timeline.HoodieTimeline.GREATER_THAN;
-import static org.apache.hudi.common.table.timeline.HoodieTimeline.LESSER_THAN_OR_EQUALS;
 import static org.apache.hudi.common.util.StringUtils.getUTF8Bytes;
 import static org.apache.hudi.hadoop.fs.CachingPath.getPathWithoutSchemeAndAuthority;
 import static org.apache.hudi.metadata.HoodieTableMetadata.getMetadataTableBasePath;
@@ -498,11 +493,9 @@ public class HoodieMetadataTableValidator implements Serializable {
           instant = new HoodieInstant(HoodieInstant.State.REQUESTED, instant.getAction(), instant.getTimestamp());
           HoodieCleanerPlan cleanerPlan = CleanerUtils.getCleanerPlan(metaClient, instant);
 
-          return cleanerPlan.getFilePathsToBeDeletedPerPartition().values().stream().flatMap(cleanerFileInfoList -> {
-            return cleanerFileInfoList.stream().map(fileInfo -> {
-              return new Path(fileInfo.getFilePath()).getName();
-            });
-          });
+          return cleanerPlan.getFilePathsToBeDeletedPerPartition().values().stream().flatMap(cleanerFileInfoList ->
+            cleanerFileInfoList.stream().map(fileInfo -> new Path(fileInfo.getFilePath()).getName())
+          );
 
         } catch (IOException e) {
           throw new HoodieIOException("Error reading cleaner metadata for " + instant);
@@ -533,7 +526,7 @@ public class HoodieMetadataTableValidator implements Serializable {
           engineContext.parallelize(allPartitions, allPartitions.size()).map(partitionPath -> {
             try {
               validateFilesInPartition(metadataTableBasedContext, fsBasedContext, partitionPath, finalBaseFilesForCleaning);
-              LOG.info(String.format("Metadata table validation succeeded for partition %s (partition %s)", partitionPath, taskLabels));
+              LOG.info("Metadata table validation succeeded for partition {} (partition {})", partitionPath, taskLabels);
               return Pair.<Boolean, Exception>of(true, null);
             } catch (HoodieValidationException e) {
               LOG.error(
@@ -569,10 +562,10 @@ public class HoodieMetadataTableValidator implements Serializable {
       }
 
       if (finalResult) {
-        LOG.info(String.format("Metadata table validation succeeded (%s).", taskLabels));
+        LOG.info("Metadata table validation succeeded ({}).", taskLabels);
         return true;
       } else {
-        LOG.warn(String.format("Metadata table validation failed (%s).", taskLabels));
+        LOG.warn("Metadata table validation failed ({}).", taskLabels);
         return false;
       }
     } catch (Exception e) {
@@ -644,9 +637,9 @@ public class HoodieMetadataTableValidator implements Serializable {
           if (partitionCreationTimeOpt.isPresent() && !completedTimeline.containsInstant(partitionCreationTimeOpt.get())) {
             Option<HoodieInstant> lastInstant = completedTimeline.lastInstant();
             if (lastInstant.isPresent()
-                && HoodieTimeline.compareTimestamps(partitionCreationTimeOpt.get(), GREATER_THAN, lastInstant.get().getTimestamp())) {
-              LOG.warn("Ignoring additional partition " + partitionFromDMT + ", as it was deduced to be part of a "
-                  + "latest completed commit which was inflight when FS based listing was polled.");
+                && HoodieTimeline.compareTimestamps(partitionCreationTimeOpt.get(), HoodieTimeline.GREATER_THAN, lastInstant.get().getTimestamp())) {
+              LOG.warn("Ignoring additional partition {}, as it was deduced to be part of a "
+                  + "latest completed commit which was inflight when FS based listing was polled.", partitionFromDMT);
               actualAdditionalPartitionsInMDT.remove(partitionFromDMT);
             }
           }
@@ -702,7 +695,7 @@ public class HoodieMetadataTableValidator implements Serializable {
           Option<HoodieInstant> lastInstant = completedTimeline.lastInstant();
           return lastInstant.isPresent()
               && HoodieTimeline.compareTimestamps(
-              instantTime, LESSER_THAN_OR_EQUALS, lastInstant.get().getTimestamp());
+              instantTime, HoodieTimeline.LESSER_THAN_OR_EQUALS, lastInstant.get().getTimestamp());
         }
         return true;
       } else {
@@ -782,8 +775,8 @@ public class HoodieMetadataTableValidator implements Serializable {
           .collect(Collectors.toList());
     }
 
-    LOG.debug("All file slices from metadata: " + allFileSlicesFromMeta + ". For partitions " + partitionPath);
-    LOG.debug("All file slices from direct listing: " + allFileSlicesFromFS + ". For partitions " + partitionPath);
+    LOG.debug("All file slices from metadata: {}. For partitions {}", allFileSlicesFromMeta, partitionPath);
+    LOG.debug("All file slices from direct listing: {}. For partitions {}", allFileSlicesFromFS, partitionPath);
     validateFileSlices(
         allFileSlicesFromMeta, allFileSlicesFromFS, partitionPath,
         fsBasedContext.getMetaClient(), "all file groups");
@@ -809,8 +802,8 @@ public class HoodieMetadataTableValidator implements Serializable {
       latestFilesFromFS = fsBasedContext.getSortedLatestBaseFileList(partitionPath);
     }
 
-    LOG.debug("Latest base file from metadata: " + latestFilesFromMetadata + ". For partitions " + partitionPath);
-    LOG.debug("Latest base file from direct listing: " + latestFilesFromFS + ". For partitions " + partitionPath);
+    LOG.debug("Latest base file from metadata: {}. For partitions {}", latestFilesFromMetadata, partitionPath);
+    LOG.debug("Latest base file from direct listing: {}. For partitions {}", latestFilesFromFS, partitionPath);
 
     validate(latestFilesFromMetadata, latestFilesFromFS, partitionPath, "latest base files");
   }
@@ -834,8 +827,8 @@ public class HoodieMetadataTableValidator implements Serializable {
       latestFileSlicesFromFS = fsBasedContext.getSortedLatestFileSliceList(partitionPath);
     }
 
-    LOG.debug("Latest file list from metadata: " + latestFileSlicesFromMetadataTable + ". For partition " + partitionPath);
-    LOG.debug("Latest file list from direct listing: " + latestFileSlicesFromFS + ". For partition " + partitionPath);
+    LOG.debug("Latest file list from metadata: {}. For partition {}", latestFileSlicesFromMetadataTable, partitionPath);
+    LOG.debug("Latest file list from direct listing: {}. For partition {}", latestFileSlicesFromFS, partitionPath);
 
     validateFileSlices(
         latestFileSlicesFromMetadataTable, latestFileSlicesFromFS, partitionPath,
@@ -906,7 +899,7 @@ public class HoodieMetadataTableValidator implements Serializable {
     String basePath = metaClient.getBasePathV2().toString();
     long countKeyFromTable = sparkEngineContext.getSqlContext().read().format("hudi")
         .load(basePath)
-        .select(RECORD_KEY_METADATA_FIELD)
+        .select(HoodieRecord.RECORD_KEY_METADATA_FIELD)
         .count();
     long countKeyFromRecordIndex = sparkEngineContext.getSqlContext().read().format("hudi")
         .load(getMetadataTableBasePath(basePath))
@@ -915,14 +908,12 @@ public class HoodieMetadataTableValidator implements Serializable {
         .count();
 
     if (countKeyFromTable != countKeyFromRecordIndex) {
-      String message = String.format("Validation of record index count failed: "
-              + "%s entries from record index metadata, %s keys from the data table: " + cfg.basePath,
-          countKeyFromRecordIndex, countKeyFromTable);
+      String message = String.format("Validation of record index count failed: %s entries from record index metadata, %s keys from the data table: %s",
+          countKeyFromRecordIndex, countKeyFromTable, cfg.basePath);
       LOG.error(message);
       throw new HoodieValidationException(message);
     } else {
-      LOG.info(String.format(
-          "Validation of record index count succeeded: %s entries. Table: %s", countKeyFromRecordIndex, cfg.basePath));
+      LOG.info("Validation of record index count succeeded: {} entries. Table: {}", countKeyFromRecordIndex, cfg.basePath);
     }
   }
 
@@ -932,11 +923,11 @@ public class HoodieMetadataTableValidator implements Serializable {
     String basePath = metaClient.getBasePathV2().toString();
     JavaPairRDD<String, Pair<String, String>> keyToLocationOnFsRdd =
         sparkEngineContext.getSqlContext().read().format("hudi").load(basePath)
-            .select(RECORD_KEY_METADATA_FIELD, PARTITION_PATH_METADATA_FIELD, FILENAME_METADATA_FIELD)
+            .select(HoodieRecord.RECORD_KEY_METADATA_FIELD, HoodieRecord.PARTITION_PATH_METADATA_FIELD, HoodieRecord.FILENAME_METADATA_FIELD)
             .toJavaRDD()
-            .mapToPair(row -> new Tuple2<>(row.getString(row.fieldIndex(RECORD_KEY_METADATA_FIELD)),
-                Pair.of(row.getString(row.fieldIndex(PARTITION_PATH_METADATA_FIELD)),
-                    FSUtils.getFileId(row.getString(row.fieldIndex(FILENAME_METADATA_FIELD))))))
+            .mapToPair(row -> new Tuple2<>(row.getString(row.fieldIndex(HoodieRecord.RECORD_KEY_METADATA_FIELD)),
+                Pair.of(row.getString(row.fieldIndex(HoodieRecord.PARTITION_PATH_METADATA_FIELD)),
+                    FSUtils.getFileId(row.getString(row.fieldIndex(HoodieRecord.FILENAME_METADATA_FIELD))))))
             .cache();
 
     JavaPairRDD<String, Pair<String, String>> keyToLocationFromRecordIndexRdd =
@@ -970,7 +961,6 @@ public class HoodieMetadataTableValidator implements Serializable {
         .map(e -> {
           Optional<Pair<String, String>> locationOnFs = e._2._1;
           Optional<Pair<String, String>> locationFromRecordIndex = e._2._2;
-          StringBuilder sb = new StringBuilder();
           List<String> errorSampleList = new ArrayList<>();
           if (locationOnFs.isPresent() && locationFromRecordIndex.isPresent()) {
             if (locationOnFs.get().getLeft().equals(locationFromRecordIndex.get().getLeft())
@@ -1036,8 +1026,7 @@ public class HoodieMetadataTableValidator implements Serializable {
       LOG.error(message);
       throw new HoodieValidationException(message);
     } else {
-      LOG.info(String.format(
-          "Validation of record index content succeeded: %s entries. Table: %s", countKey, cfg.basePath));
+      LOG.info("Validation of record index content succeeded: {} entries. Table: {}", countKey, cfg.basePath);
     }
   }
 
@@ -1082,7 +1071,7 @@ public class HoodieMetadataTableValidator implements Serializable {
       LOG.error(message);
       throw new HoodieValidationException(message);
     } else {
-      LOG.info(String.format("Validation of %s succeeded for partition %s for table: %s", label, partitionPath, cfg.basePath));
+      LOG.info("Validation of {} succeeded for partition {} for table: {}", label, partitionPath, cfg.basePath);
     }
   }
 
@@ -1109,8 +1098,7 @@ public class HoodieMetadataTableValidator implements Serializable {
           mismatch = true;
           break;
         } else {
-          LOG.warn(String.format("There are uncommitted log files in the latest file slices "
-              + "but the committed log files match: %s %s", fileSlice1, fileSlice2));
+          LOG.warn("There are uncommitted log files in the latest file slices but the committed log files match: {} {}", fileSlice1, fileSlice2);
         }
       }
     }
@@ -1122,7 +1110,7 @@ public class HoodieMetadataTableValidator implements Serializable {
       LOG.error(message);
       throw new HoodieValidationException(message);
     } else {
-      LOG.info(String.format("Validation of %s succeeded for partition %s for table: %s ", label, partitionPath, cfg.basePath));
+      LOG.info("Validation of {} succeeded for partition {} for table: {}", label, partitionPath, cfg.basePath);
     }
   }
 
@@ -1154,13 +1142,11 @@ public class HoodieMetadataTableValidator implements Serializable {
     FileSystem fileSystem = metaClient.getFs();
 
     if (hasCommittedLogFiles(fileSystem, fs1LogPathSet, metaClient, committedFilesMap)) {
-      LOG.error("The first file slice has committed log files that cause mismatching: " + fs1
-          + "; Different log files are: " + fs1LogPathSet);
+      LOG.error("The first file slice has committed log files that cause mismatching: {}; Different log files are: {}", fs1, fs1LogPathSet);
       return false;
     }
     if (hasCommittedLogFiles(fileSystem, fs2LogPathSet, metaClient, committedFilesMap)) {
-      LOG.error("The second file slice has committed log files that cause mismatching: " + fs2
-          + "; Different log files are: " + fs2LogPathSet);
+      LOG.error("The second file slice has committed log files that cause mismatching: {}; Different log files are: {}", fs2, fs2LogPathSet);
       return false;
     }
     return true;
@@ -1187,17 +1173,16 @@ public class HoodieMetadataTableValidator implements Serializable {
         MessageType messageType =
             TableSchemaResolver.readSchemaFromLogFile(fs, new Path(logFilePathStr));
         if (messageType == null) {
-          LOG.warn(String.format("Cannot read schema from log file %s. "
-              + "Skip the check as it's likely being written by an inflight instant.", logFilePathStr));
+          LOG.warn("Cannot read schema from log file {}. Skip the check as it's likely being written by an inflight instant.", logFilePathStr);
           continue;
         }
         Schema readerSchema = converter.convert(messageType);
         reader =
-            HoodieLogFormat.newReader(fs, new HoodieLogFile(logFilePathStr), readerSchema, true, false);
+            HoodieLogFormat.newReader(fs, new HoodieLogFile(logFilePathStr), readerSchema, false);
         // read the avro blocks
         if (reader.hasNext()) {
           HoodieLogBlock block = reader.next();
-          final String instantTime = block.getLogBlockHeader().get(INSTANT_TIME);
+          final String instantTime = block.getLogBlockHeader().get(HoodieLogBlock.HeaderMetadataType.INSTANT_TIME);
           if (completedInstantsTimeline.containsInstant(instantTime)) {
             // The instant is completed, in active timeline
             // Checking commit metadata only as log files can only be written by COMMIT or DELTA_COMMIT
@@ -1225,36 +1210,30 @@ public class HoodieMetadataTableValidator implements Serializable {
             // behavior.
             String relativeLogFilePathStr = getRelativePath(basePath, logFilePathStr);
             if (committedFilesMap.get(instantTime).contains(relativeLogFilePathStr)) {
-              LOG.warn("Log file is committed in an instant in active timeline: instantTime="
-                  + instantTime + " " + logFilePathStr);
+              LOG.warn("Log file is committed in an instant in active timeline: instantTime={} {}", instantTime, logFilePathStr);
               return true;
             } else {
-              LOG.warn("Log file is uncommitted in a completed instant, likely due to retry: "
-                  + "instantTime=" + instantTime + " " + logFilePathStr);
+              LOG.warn("Log file is uncommitted in a completed instant, likely due to retry: instantTime={} {}", instantTime, logFilePathStr);
             }
           } else if (completedInstantsTimeline.isBeforeTimelineStarts(instantTime)) {
             // The instant is in archived timeline
-            LOG.warn("Log file is committed in an instant in archived timeline: instantTime="
-                + instantTime + " " + logFilePathStr);
+            LOG.warn("Log file is committed in an instant in archived timeline: instantTime={} {}", instantTime, logFilePathStr);
             return true;
           } else if (inflightInstantsTimeline.containsInstant(instantTime)) {
             // The instant is inflight in active timeline
             // hit an uncommitted block possibly from a failed write
-            LOG.warn("Log file is uncommitted because of an inflight instant: instantTime="
-                + instantTime + " " + logFilePathStr);
+            LOG.warn("Log file is uncommitted because of an inflight instant: instantTime={} {}", instantTime, logFilePathStr);
           } else {
             // The instant is after the start of the active timeline,
             // but it cannot be found in the active timeline
-            LOG.warn("Log file is uncommitted because the instant is after the start of the "
-                + "active timeline but absent or in requested in the active timeline: instantTime="
-                + instantTime + " " + logFilePathStr);
+            LOG.warn("Log file is uncommitted because the instant is after the start of the active timeline but absent or in requested in the active timeline: instantTime={} {}",
+                instantTime, logFilePathStr);
           }
         } else {
-          LOG.warn("There is no log block in " + logFilePathStr);
+          LOG.warn("There is no log block in {}", logFilePathStr);
         }
       } catch (IOException e) {
-        LOG.warn(String.format("Cannot read log file %s: %s. "
-                + "Skip the check as it's likely being written by an inflight instant.",
+        LOG.warn(String.format("Cannot read log file %s: %s. Skip the check as it's likely being written by an inflight instant.",
             logFilePathStr, e.getMessage()), e);
       } finally {
         FileIOUtils.closeQuietly(reader);
@@ -1289,8 +1268,7 @@ public class HoodieMetadataTableValidator implements Serializable {
             long toSleepMs = cfg.minValidateIntervalSeconds * 1000 - (System.currentTimeMillis() - start);
 
             if (toSleepMs > 0) {
-              LOG.info("Last validate ran less than min validate interval: " + cfg.minValidateIntervalSeconds + " s, sleep: "
-                  + toSleepMs + " ms.");
+              LOG.info("Last validate ran less than min validate interval: {} s, sleep: {} ms.", cfg.minValidateIntervalSeconds, toSleepMs);
               Thread.sleep(toSleepMs);
             }
           } catch (HoodieValidationException e) {
@@ -1376,7 +1354,7 @@ public class HoodieMetadataTableValidator implements Serializable {
           .build();
       this.fileSystemView = FileSystemViewManager.createInMemoryFileSystemView(engineContext,
           metaClient, metadataConfig);
-      this.tableMetadata = HoodieTableMetadata.create(engineContext, metadataConfig, metaClient.getBasePath());
+      this.tableMetadata = HoodieTableMetadata.create(engineContext, metadataConfig, metaClient.getBasePathV2().toString());
       if (metaClient.getCommitsTimeline().filterCompletedInstants().countInstants() > 0) {
         this.allColumnNameList = getAllColumnNames();
       }
@@ -1408,7 +1386,7 @@ public class HoodieMetadataTableValidator implements Serializable {
     @SuppressWarnings({"rawtypes", "unchecked"})
     public List<HoodieColumnRangeMetadata<Comparable>> getSortedColumnStatsList(
         String partitionPath, List<String> baseFileNameList) {
-      LOG.info("All column names for getting column stats: " + allColumnNameList);
+      LOG.info("All column names for getting column stats: {}", allColumnNameList);
       if (enableMetadataTable) {
         List<Pair<String, String>> partitionFileNameList = baseFileNameList.stream()
             .map(filename -> Pair.of(partitionPath, filename)).collect(Collectors.toList());
@@ -1424,7 +1402,7 @@ public class HoodieMetadataTableValidator implements Serializable {
         return baseFileNameList.stream().flatMap(filename ->
                 new ParquetUtils().readRangeFromParquetMetadata(
                     metaClient.getHadoopConf(),
-                    new Path(FSUtils.getPartitionPath(metaClient.getBasePath(), partitionPath), filename),
+                    new Path(FSUtils.getPartitionPath(metaClient.getBasePathV2(), partitionPath), filename),
                     allColumnNameList).stream())
             .sorted(new HoodieColumnRangeMetadataComparator())
             .collect(Collectors.toList());
@@ -1460,7 +1438,7 @@ public class HoodieMetadataTableValidator implements Serializable {
         return schemaResolver.getTableAvroSchema().getFields().stream()
             .map(Schema.Field::name).collect(Collectors.toList());
       } catch (Exception e) {
-        throw new HoodieException("Failed to get all column names for " + metaClient.getBasePath());
+        throw new HoodieException("Failed to get all column names for " + metaClient.getBasePathV2());
       }
     }
 
@@ -1468,17 +1446,17 @@ public class HoodieMetadataTableValidator implements Serializable {
       Path path = new Path(FSUtils.getPartitionPath(metaClient.getBasePathV2(), partitionPath), filename);
       BloomFilter bloomFilter;
       HoodieConfig hoodieConfig = new HoodieConfig();
-      hoodieConfig.setValue(USE_NATIVE_HFILE_READER,
-          Boolean.toString(ConfigUtils.getBooleanWithAltKeys(props, USE_NATIVE_HFILE_READER)));
+      hoodieConfig.setValue(HoodieReaderConfig.USE_NATIVE_HFILE_READER,
+          Boolean.toString(ConfigUtils.getBooleanWithAltKeys(props, HoodieReaderConfig.USE_NATIVE_HFILE_READER)));
       try (HoodieFileReader fileReader = HoodieFileReaderFactory.getReaderFactory(HoodieRecordType.AVRO)
           .getFileReader(hoodieConfig, metaClient.getHadoopConf(), path)) {
         bloomFilter = fileReader.readBloomFilter();
         if (bloomFilter == null) {
-          LOG.error("Failed to read bloom filter for " + path);
+          LOG.error("Failed to read bloom filter for {}", path);
           return Option.empty();
         }
       } catch (IOException e) {
-        LOG.error("Failed to get file reader for " + path + " " + e.getMessage());
+        LOG.error("Failed to get file reader for {} {}", path, e.getMessage());
         return Option.empty();
       }
       return Option.of(BloomFilterData.builder()


(hudi) 11/28: [HUDI-7378] Fix Spark SQL DML with custom key generator (#10615)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 922e1eb87d012d626ea35de0f0bca49d17d0acb3
Author: Y Ethan Guo <et...@gmail.com>
AuthorDate: Fri Apr 12 22:51:03 2024 -0700

    [HUDI-7378] Fix Spark SQL DML with custom key generator (#10615)
---
 .../factory/HoodieSparkKeyGeneratorFactory.java    |   4 +
 .../org/apache/hudi/util/SparkKeyGenUtils.scala    |  16 +-
 .../scala/org/apache/hudi/HoodieWriterUtils.scala  |  20 +-
 .../spark/sql/hudi/ProvidesHoodieConfig.scala      |  60 ++-
 .../spark/sql/hudi/TestProvidesHoodieConfig.scala  |  79 +++
 .../hudi/command/MergeIntoHoodieTableCommand.scala |   5 +-
 .../TestSparkSqlWithCustomKeyGenerator.scala       | 571 +++++++++++++++++++++
 7 files changed, 742 insertions(+), 13 deletions(-)

diff --git a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/keygen/factory/HoodieSparkKeyGeneratorFactory.java b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/keygen/factory/HoodieSparkKeyGeneratorFactory.java
index 1ea5adcd6b4..dcc2eaec9eb 100644
--- a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/keygen/factory/HoodieSparkKeyGeneratorFactory.java
+++ b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/keygen/factory/HoodieSparkKeyGeneratorFactory.java
@@ -79,6 +79,10 @@ public class HoodieSparkKeyGeneratorFactory {
 
   public static KeyGenerator createKeyGenerator(TypedProperties props) throws IOException {
     String keyGeneratorClass = getKeyGeneratorClassName(props);
+    return createKeyGenerator(keyGeneratorClass, props);
+  }
+
+  public static KeyGenerator createKeyGenerator(String keyGeneratorClass, TypedProperties props) throws IOException {
     boolean autoRecordKeyGen = KeyGenUtils.isAutoGeneratedRecordKeysEnabled(props)
         //Need to prevent overwriting the keygen for spark sql merge into because we need to extract
         //the recordkey from the meta cols if it exists. Sql keygen will use pkless keygen if needed.
diff --git a/hudi-client/hudi-spark-client/src/main/scala/org/apache/hudi/util/SparkKeyGenUtils.scala b/hudi-client/hudi-spark-client/src/main/scala/org/apache/hudi/util/SparkKeyGenUtils.scala
index 7b91ae5a728..bd094464096 100644
--- a/hudi-client/hudi-spark-client/src/main/scala/org/apache/hudi/util/SparkKeyGenUtils.scala
+++ b/hudi-client/hudi-spark-client/src/main/scala/org/apache/hudi/util/SparkKeyGenUtils.scala
@@ -21,8 +21,8 @@ import org.apache.hudi.common.config.TypedProperties
 import org.apache.hudi.common.util.StringUtils
 import org.apache.hudi.common.util.ValidationUtils.checkArgument
 import org.apache.hudi.keygen.constant.KeyGeneratorOptions
-import org.apache.hudi.keygen.{AutoRecordKeyGeneratorWrapper, AutoRecordGenWrapperKeyGenerator, CustomAvroKeyGenerator, CustomKeyGenerator, GlobalAvroDeleteKeyGenerator, GlobalDeleteKeyGenerator, KeyGenerator, NonpartitionedAvroKeyGenerator, NonpartitionedKeyGenerator}
 import org.apache.hudi.keygen.factory.HoodieSparkKeyGeneratorFactory
+import org.apache.hudi.keygen.{AutoRecordKeyGeneratorWrapper, CustomAvroKeyGenerator, CustomKeyGenerator, GlobalAvroDeleteKeyGenerator, GlobalDeleteKeyGenerator, KeyGenerator, NonpartitionedAvroKeyGenerator, NonpartitionedKeyGenerator}
 
 object SparkKeyGenUtils {
 
@@ -35,6 +35,20 @@ object SparkKeyGenUtils {
     getPartitionColumns(keyGenerator, props)
   }
 
+  /**
+   * @param KeyGenClassNameOption key generator class name if present.
+   * @param props                 config properties.
+   * @return partition column names only, concatenated by ","
+   */
+  def getPartitionColumns(KeyGenClassNameOption: Option[String], props: TypedProperties): String = {
+    val keyGenerator = if (KeyGenClassNameOption.isEmpty) {
+      HoodieSparkKeyGeneratorFactory.createKeyGenerator(props)
+    } else {
+      HoodieSparkKeyGeneratorFactory.createKeyGenerator(KeyGenClassNameOption.get, props)
+    }
+    getPartitionColumns(keyGenerator, props)
+  }
+
   /**
    * @param keyGen key generator class name
    * @return partition columns
diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieWriterUtils.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieWriterUtils.scala
index 0a4ef7a3d63..fade5957210 100644
--- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieWriterUtils.scala
+++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieWriterUtils.scala
@@ -197,8 +197,26 @@ object HoodieWriterUtils {
           diffConfigs.append(s"KeyGenerator:\t$datasourceKeyGen\t$tableConfigKeyGen\n")
         }
 
+        // Please note that the validation of partition path fields needs the key generator class
+        // for the table, since the custom key generator expects a different format of
+        // the value of the write config "hoodie.datasource.write.partitionpath.field"
+        // e.g., "col:simple,ts:timestamp", whereas the table config "hoodie.table.partition.fields"
+        // in hoodie.properties stores "col,ts".
+        // The "params" here may only contain the write config of partition path field,
+        // so we need to pass in the validated key generator class name.
+        val validatedKeyGenClassName = if (tableConfigKeyGen != null) {
+          Option(tableConfigKeyGen)
+        } else if (datasourceKeyGen != null) {
+          Option(datasourceKeyGen)
+        } else {
+          None
+        }
         val datasourcePartitionFields = params.getOrElse(PARTITIONPATH_FIELD.key(), null)
-        val currentPartitionFields = if (datasourcePartitionFields == null) null else SparkKeyGenUtils.getPartitionColumns(TypedProperties.fromMap(params))
+        val currentPartitionFields = if (datasourcePartitionFields == null) {
+          null
+        } else {
+          SparkKeyGenUtils.getPartitionColumns(validatedKeyGenClassName, TypedProperties.fromMap(params))
+        }
         val tableConfigPartitionFields = tableConfig.getString(HoodieTableConfig.PARTITION_FIELDS)
         if (null != datasourcePartitionFields && null != tableConfigPartitionFields
           && currentPartitionFields != tableConfigPartitionFields) {
diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/ProvidesHoodieConfig.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/ProvidesHoodieConfig.scala
index 782c1a2bc06..85d613637e7 100644
--- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/ProvidesHoodieConfig.scala
+++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/ProvidesHoodieConfig.scala
@@ -18,34 +18,36 @@
 package org.apache.spark.sql.hudi
 
 import org.apache.hudi.AutoRecordKeyGenerationUtils.shouldAutoGenerateRecordKeys
-import org.apache.hudi.{DataSourceWriteOptions, HoodieFileIndex}
 import org.apache.hudi.DataSourceWriteOptions._
 import org.apache.hudi.HoodieConversionUtils.toProperties
 import org.apache.hudi.common.config.{DFSPropertiesConfiguration, TypedProperties}
 import org.apache.hudi.common.model.{DefaultHoodieRecordPayload, WriteOperationType}
 import org.apache.hudi.common.table.HoodieTableConfig
+import org.apache.hudi.common.util.{ReflectionUtils, StringUtils}
 import org.apache.hudi.config.HoodieWriteConfig.TBL_NAME
 import org.apache.hudi.config.{HoodieIndexConfig, HoodieInternalConfig, HoodieWriteConfig}
 import org.apache.hudi.hive.ddl.HiveSyncMode
 import org.apache.hudi.hive.{HiveSyncConfig, HiveSyncConfigHolder, MultiPartKeysValueExtractor}
-import org.apache.hudi.keygen.ComplexKeyGenerator
+import org.apache.hudi.keygen.{ComplexKeyGenerator, CustomAvroKeyGenerator, CustomKeyGenerator}
 import org.apache.hudi.sql.InsertMode
 import org.apache.hudi.sync.common.HoodieSyncConfig
+import org.apache.hudi.{DataSourceWriteOptions, HoodieFileIndex}
 import org.apache.spark.internal.Logging
-import org.apache.spark.sql.{SaveMode, SparkSession}
 import org.apache.spark.sql.catalyst.catalog.HoodieCatalogTable
 import org.apache.spark.sql.catalyst.expressions.{AttributeReference, EqualTo, Literal}
 import org.apache.spark.sql.execution.datasources.FileStatusCache
 import org.apache.spark.sql.hive.HiveExternalCatalog
 import org.apache.spark.sql.hudi.HoodieOptionConfig.mapSqlOptionsToDataSourceWriteConfigs
 import org.apache.spark.sql.hudi.HoodieSqlCommonUtils.{isHoodieConfigKey, isUsingHiveCatalog}
-import org.apache.spark.sql.hudi.ProvidesHoodieConfig.combineOptions
+import org.apache.spark.sql.hudi.ProvidesHoodieConfig.{combineOptions, getPartitionPathFieldWriteConfig}
 import org.apache.spark.sql.hudi.command.{SqlKeyGenerator, ValidateDuplicateKeyPayload}
 import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.internal.SQLConf.PARTITION_OVERWRITE_MODE
 import org.apache.spark.sql.types.StructType
-import java.util.Locale
+import org.apache.spark.sql.{SaveMode, SparkSession}
+import org.slf4j.LoggerFactory
 
+import java.util.Locale
 import scala.collection.JavaConverters._
 
 trait ProvidesHoodieConfig extends Logging {
@@ -82,7 +84,8 @@ trait ProvidesHoodieConfig extends Logging {
       PRECOMBINE_FIELD.key -> preCombineField,
       HIVE_STYLE_PARTITIONING.key -> tableConfig.getHiveStylePartitioningEnable,
       URL_ENCODE_PARTITIONING.key -> tableConfig.getUrlEncodePartitioning,
-      PARTITIONPATH_FIELD.key -> tableConfig.getPartitionFieldProp
+      PARTITIONPATH_FIELD.key -> getPartitionPathFieldWriteConfig(
+        tableConfig.getKeyGeneratorClassName, tableConfig.getPartitionFieldProp, hoodieCatalogTable)
     )
 
     combineOptions(hoodieCatalogTable, tableConfig, sparkSession.sqlContext.conf,
@@ -313,7 +316,8 @@ trait ProvidesHoodieConfig extends Logging {
       URL_ENCODE_PARTITIONING.key -> urlEncodePartitioning,
       RECORDKEY_FIELD.key -> recordKeyConfigValue,
       PRECOMBINE_FIELD.key -> preCombineField,
-      PARTITIONPATH_FIELD.key -> partitionFieldsStr
+      PARTITIONPATH_FIELD.key -> getPartitionPathFieldWriteConfig(
+        keyGeneratorClassName, partitionFieldsStr, hoodieCatalogTable)
     ) ++ overwriteTableOpts ++ getDropDupsConfig(useLegacyInsertModeFlow, combinedOpts) ++ staticOverwritePartitionPathOptions
 
     combineOptions(hoodieCatalogTable, tableConfig, sparkSession.sqlContext.conf,
@@ -405,7 +409,8 @@ trait ProvidesHoodieConfig extends Logging {
       PARTITIONS_TO_DELETE.key -> partitionsToDrop,
       RECORDKEY_FIELD.key -> hoodieCatalogTable.primaryKeys.mkString(","),
       PRECOMBINE_FIELD.key -> hoodieCatalogTable.preCombineKey.getOrElse(""),
-      PARTITIONPATH_FIELD.key -> partitionFields,
+      PARTITIONPATH_FIELD.key -> getPartitionPathFieldWriteConfig(
+        tableConfig.getKeyGeneratorClassName, partitionFields, hoodieCatalogTable),
       HoodieSyncConfig.META_SYNC_ENABLED.key -> hiveSyncConfig.getString(HoodieSyncConfig.META_SYNC_ENABLED.key),
       HiveSyncConfigHolder.HIVE_SYNC_ENABLED.key -> hiveSyncConfig.getString(HiveSyncConfigHolder.HIVE_SYNC_ENABLED.key),
       HiveSyncConfigHolder.HIVE_SYNC_MODE.key -> hiveSyncConfig.getStringOrDefault(HiveSyncConfigHolder.HIVE_SYNC_MODE, HiveSyncMode.HMS.name()),
@@ -451,7 +456,8 @@ trait ProvidesHoodieConfig extends Logging {
       HIVE_STYLE_PARTITIONING.key -> tableConfig.getHiveStylePartitioningEnable,
       URL_ENCODE_PARTITIONING.key -> tableConfig.getUrlEncodePartitioning,
       OPERATION.key -> DataSourceWriteOptions.DELETE_OPERATION_OPT_VAL,
-      PARTITIONPATH_FIELD.key -> tableConfig.getPartitionFieldProp
+      PARTITIONPATH_FIELD.key -> getPartitionPathFieldWriteConfig(
+        tableConfig.getKeyGeneratorClassName, tableConfig.getPartitionFieldProp, hoodieCatalogTable)
     )
 
     combineOptions(hoodieCatalogTable, tableConfig, sparkSession.sqlContext.conf,
@@ -496,6 +502,8 @@ trait ProvidesHoodieConfig extends Logging {
 
 object ProvidesHoodieConfig {
 
+  private val log = LoggerFactory.getLogger(getClass)
+
   // NOTE: PLEASE READ CAREFULLY BEFORE CHANGING
   //
   // Spark SQL operations configuration might be coming from a variety of diverse sources
@@ -530,6 +538,40 @@ object ProvidesHoodieConfig {
       filterNullValues(overridingOpts)
   }
 
+  /**
+   * @param tableConfigKeyGeneratorClassName     key generator class name in the table config.
+   * @param partitionFieldNamesWithoutKeyGenType partition field names without key generator types
+   *                                             from the table config.
+   * @param catalogTable                         HoodieCatalogTable instance to fetch table properties.
+   * @return the write config value to set for "hoodie.datasource.write.partitionpath.field".
+   */
+  def getPartitionPathFieldWriteConfig(tableConfigKeyGeneratorClassName: String,
+                                       partitionFieldNamesWithoutKeyGenType: String,
+                                       catalogTable: HoodieCatalogTable): String = {
+    if (StringUtils.isNullOrEmpty(tableConfigKeyGeneratorClassName)) {
+      partitionFieldNamesWithoutKeyGenType
+    } else {
+      val writeConfigPartitionField = catalogTable.catalogProperties.get(PARTITIONPATH_FIELD.key())
+      val keyGenClass = ReflectionUtils.getClass(tableConfigKeyGeneratorClassName)
+      if (classOf[CustomKeyGenerator].equals(keyGenClass)
+        || classOf[CustomAvroKeyGenerator].equals(keyGenClass)) {
+        // For custom key generator, we have to take the write config value from
+        // "hoodie.datasource.write.partitionpath.field" which contains the key generator
+        // type, whereas the table config only contains the prtition field names without
+        // key generator types.
+        if (writeConfigPartitionField.isDefined) {
+          writeConfigPartitionField.get
+        } else {
+          log.warn("Write config \"hoodie.datasource.write.partitionpath.field\" is not set for "
+            + "custom key generator. This may fail the write operation.")
+          partitionFieldNamesWithoutKeyGenType
+        }
+      } else {
+        partitionFieldNamesWithoutKeyGenType
+      }
+    }
+  }
+
   private def filterNullValues(opts: Map[String, String]): Map[String, String] =
     opts.filter { case (_, v) => v != null }
 
diff --git a/hudi-spark-datasource/hudi-spark-common/src/test/scala/org/apache/spark/sql/hudi/TestProvidesHoodieConfig.scala b/hudi-spark-datasource/hudi-spark-common/src/test/scala/org/apache/spark/sql/hudi/TestProvidesHoodieConfig.scala
new file mode 100644
index 00000000000..8414e41ca6c
--- /dev/null
+++ b/hudi-spark-datasource/hudi-spark-common/src/test/scala/org/apache/spark/sql/hudi/TestProvidesHoodieConfig.scala
@@ -0,0 +1,79 @@
+/*
+ * 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.spark.sql.hudi
+
+import org.apache.hudi.DataSourceWriteOptions.PARTITIONPATH_FIELD
+import org.apache.hudi.keygen.{ComplexKeyGenerator, CustomKeyGenerator}
+
+import org.apache.spark.sql.catalyst.catalog.HoodieCatalogTable
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Test
+import org.mockito.Mockito
+import org.mockito.Mockito.when
+
+/**
+ * Tests {@link ProvidesHoodieConfig}
+ */
+class TestProvidesHoodieConfig {
+  @Test
+  def testGetPartitionPathFieldWriteConfig(): Unit = {
+    val mockTable = Mockito.mock(classOf[HoodieCatalogTable])
+    val partitionFieldNames = "ts,segment"
+    val customKeyGenPartitionFieldWriteConfig = "ts:timestamp,segment:simple"
+
+    mockPartitionWriteConfigInCatalogProps(mockTable, None)
+    assertEquals(
+      partitionFieldNames,
+      ProvidesHoodieConfig.getPartitionPathFieldWriteConfig(
+        "", partitionFieldNames, mockTable))
+    assertEquals(
+      partitionFieldNames,
+      ProvidesHoodieConfig.getPartitionPathFieldWriteConfig(
+        classOf[ComplexKeyGenerator].getName, partitionFieldNames, mockTable))
+    assertEquals(
+      partitionFieldNames,
+      ProvidesHoodieConfig.getPartitionPathFieldWriteConfig(
+        classOf[CustomKeyGenerator].getName, partitionFieldNames, mockTable))
+
+    mockPartitionWriteConfigInCatalogProps(mockTable, Option(customKeyGenPartitionFieldWriteConfig))
+    assertEquals(
+      partitionFieldNames,
+      ProvidesHoodieConfig.getPartitionPathFieldWriteConfig(
+        "", partitionFieldNames, mockTable))
+    assertEquals(
+      partitionFieldNames,
+      ProvidesHoodieConfig.getPartitionPathFieldWriteConfig(
+        classOf[ComplexKeyGenerator].getName, partitionFieldNames, mockTable))
+    assertEquals(
+      customKeyGenPartitionFieldWriteConfig,
+      ProvidesHoodieConfig.getPartitionPathFieldWriteConfig(
+        classOf[CustomKeyGenerator].getName, partitionFieldNames, mockTable))
+  }
+
+  private def mockPartitionWriteConfigInCatalogProps(mockTable: HoodieCatalogTable,
+                                                     value: Option[String]): Unit = {
+    val props = if (value.isDefined) {
+      Map(PARTITIONPATH_FIELD.key() -> value.get)
+    } else {
+      Map[String, String]()
+    }
+    when(mockTable.catalogProperties).thenReturn(props)
+  }
+}
diff --git a/hudi-spark-datasource/hudi-spark/src/main/scala/org/apache/spark/sql/hudi/command/MergeIntoHoodieTableCommand.scala b/hudi-spark-datasource/hudi-spark/src/main/scala/org/apache/spark/sql/hudi/command/MergeIntoHoodieTableCommand.scala
index dd8e62ab53c..2449817458d 100644
--- a/hudi-spark-datasource/hudi-spark/src/main/scala/org/apache/spark/sql/hudi/command/MergeIntoHoodieTableCommand.scala
+++ b/hudi-spark-datasource/hudi-spark/src/main/scala/org/apache/spark/sql/hudi/command/MergeIntoHoodieTableCommand.scala
@@ -40,7 +40,7 @@ import org.apache.spark.sql.catalyst.plans.LeftOuter
 import org.apache.spark.sql.catalyst.plans.logical._
 import org.apache.spark.sql.hudi.HoodieSqlCommonUtils._
 import org.apache.spark.sql.hudi.ProvidesHoodieConfig
-import org.apache.spark.sql.hudi.ProvidesHoodieConfig.combineOptions
+import org.apache.spark.sql.hudi.ProvidesHoodieConfig.{combineOptions, getPartitionPathFieldWriteConfig}
 import org.apache.spark.sql.hudi.analysis.HoodieAnalysis.failAnalysis
 import org.apache.spark.sql.hudi.command.MergeIntoHoodieTableCommand.{CoercedAttributeReference, encodeAsBase64String, stripCasting, toStructType}
 import org.apache.spark.sql.hudi.command.PartialAssignmentMode.PartialAssignmentMode
@@ -631,7 +631,8 @@ case class MergeIntoHoodieTableCommand(mergeInto: MergeIntoTable) extends Hoodie
       RECORDKEY_FIELD.key -> tableConfig.getRawRecordKeyFieldProp,
       PRECOMBINE_FIELD.key -> preCombineField,
       TBL_NAME.key -> hoodieCatalogTable.tableName,
-      PARTITIONPATH_FIELD.key -> tableConfig.getPartitionFieldProp,
+      PARTITIONPATH_FIELD.key -> getPartitionPathFieldWriteConfig(
+        tableConfig.getKeyGeneratorClassName, tableConfig.getPartitionFieldProp, hoodieCatalogTable),
       HIVE_STYLE_PARTITIONING.key -> tableConfig.getHiveStylePartitioningEnable,
       URL_ENCODE_PARTITIONING.key -> tableConfig.getUrlEncodePartitioning,
       KEYGENERATOR_CLASS_NAME.key -> keyGeneratorClassName,
diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestSparkSqlWithCustomKeyGenerator.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestSparkSqlWithCustomKeyGenerator.scala
new file mode 100644
index 00000000000..c85eb40bca7
--- /dev/null
+++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestSparkSqlWithCustomKeyGenerator.scala
@@ -0,0 +1,571 @@
+/*
+ * 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.hudi.functional
+
+import org.apache.hudi.HoodieSparkUtils
+import org.apache.hudi.common.config.TypedProperties
+import org.apache.hudi.common.table.HoodieTableMetaClient
+import org.apache.hudi.common.util.StringUtils
+import org.apache.hudi.exception.HoodieException
+import org.apache.hudi.functional.TestSparkSqlWithCustomKeyGenerator._
+import org.apache.hudi.util.SparkKeyGenUtils
+import org.apache.spark.sql.SaveMode
+import org.apache.spark.sql.hudi.common.HoodieSparkSqlTestBase
+import org.joda.time.DateTime
+import org.joda.time.format.DateTimeFormat
+import org.junit.jupiter.api.Assertions.{assertEquals, assertFalse, assertTrue}
+import org.slf4j.LoggerFactory
+
+import java.io.IOException
+
+/**
+ * Tests Spark SQL DML with custom key generator and write configs.
+ */
+class TestSparkSqlWithCustomKeyGenerator extends HoodieSparkSqlTestBase {
+  private val LOG = LoggerFactory.getLogger(getClass)
+
+  test("Test Spark SQL DML with custom key generator") {
+    withTempDir { tmp =>
+      Seq(
+        Seq("COPY_ON_WRITE", "ts:timestamp,segment:simple",
+          "(ts=202401, segment='cat2')", "202401/cat2",
+          Seq("202312/cat2", "202312/cat4", "202401/cat1", "202401/cat3", "202402/cat1", "202402/cat3", "202402/cat5"),
+          TS_FORMATTER_FUNC,
+          (ts: Integer, segment: String) => TS_FORMATTER_FUNC.apply(ts) + "/" + segment),
+        Seq("MERGE_ON_READ", "segment:simple",
+          "(segment='cat3')", "cat3",
+          Seq("cat1", "cat2", "cat4", "cat5"),
+          TS_TO_STRING_FUNC,
+          (_: Integer, segment: String) => segment),
+        Seq("MERGE_ON_READ", "ts:timestamp",
+          "(ts=202312)", "202312",
+          Seq("202401", "202402"),
+          TS_FORMATTER_FUNC,
+          (ts: Integer, _: String) => TS_FORMATTER_FUNC.apply(ts)),
+        Seq("MERGE_ON_READ", "ts:timestamp,segment:simple",
+          "(ts=202401, segment='cat2')", "202401/cat2",
+          Seq("202312/cat2", "202312/cat4", "202401/cat1", "202401/cat3", "202402/cat1", "202402/cat3", "202402/cat5"),
+          TS_FORMATTER_FUNC,
+          (ts: Integer, segment: String) => TS_FORMATTER_FUNC.apply(ts) + "/" + segment)
+      ).foreach { testParams =>
+        withTable(generateTableName) { tableName =>
+          LOG.warn("Testing with parameters: " + testParams)
+          val tableType = testParams(0).asInstanceOf[String]
+          val writePartitionFields = testParams(1).asInstanceOf[String]
+          val dropPartitionStatement = testParams(2).asInstanceOf[String]
+          val droppedPartition = testParams(3).asInstanceOf[String]
+          val expectedPartitions = testParams(4).asInstanceOf[Seq[String]]
+          val tsGenFunc = testParams(5).asInstanceOf[Integer => String]
+          val partitionGenFunc = testParams(6).asInstanceOf[(Integer, String) => String]
+          val tablePath = tmp.getCanonicalPath + "/" + tableName
+          val timestampKeyGeneratorConfig = if (writePartitionFields.contains("timestamp")) {
+            TS_KEY_GEN_CONFIGS
+          } else {
+            Map[String, String]()
+          }
+          val timestampKeyGenProps = if (timestampKeyGeneratorConfig.nonEmpty) {
+            ", " + timestampKeyGeneratorConfig.map(e => e._1 + " = '" + e._2 + "'").mkString(", ")
+          } else {
+            ""
+          }
+
+          prepareTableWithKeyGenerator(
+            tableName, tablePath, tableType,
+            CUSTOM_KEY_GEN_CLASS_NAME, writePartitionFields, timestampKeyGeneratorConfig)
+
+          // SQL CTAS with table properties containing key generator write configs
+          createTableWithSql(tableName, tablePath,
+            s"hoodie.datasource.write.partitionpath.field = '$writePartitionFields'" + timestampKeyGenProps)
+
+          // Prepare source and test SQL INSERT INTO
+          val sourceTableName = tableName + "_source"
+          prepareParquetSource(sourceTableName, Seq(
+            "(7, 'a7', 1399.0, 1706800227, 'cat1')",
+            "(8, 'a8', 26.9, 1706800227, 'cat3')",
+            "(9, 'a9', 299.0, 1701443427, 'cat4')"))
+          spark.sql(
+            s"""
+               | INSERT INTO $tableName
+               | SELECT * from ${tableName}_source
+               | """.stripMargin)
+          validateResults(
+            tableName,
+            s"SELECT id, name, cast(price as string), cast(ts as string), segment from $tableName",
+            tsGenFunc,
+            partitionGenFunc,
+            Seq(),
+            Seq(1, "a1", "1.6", 1704121827, "cat1"),
+            Seq(2, "a2", "10.8", 1704121827, "cat1"),
+            Seq(3, "a3", "30.0", 1706800227, "cat1"),
+            Seq(4, "a4", "103.4", 1701443427, "cat2"),
+            Seq(5, "a5", "1999.0", 1704121827, "cat2"),
+            Seq(6, "a6", "80.0", 1704121827, "cat3"),
+            Seq(7, "a7", "1399.0", 1706800227, "cat1"),
+            Seq(8, "a8", "26.9", 1706800227, "cat3"),
+            Seq(9, "a9", "299.0", 1701443427, "cat4")
+          )
+
+          // Test SQL UPDATE
+          spark.sql(
+            s"""
+               | UPDATE $tableName
+               | SET price = price + 10.0
+               | WHERE id between 4 and 7
+               | """.stripMargin)
+          validateResults(
+            tableName,
+            s"SELECT id, name, cast(price as string), cast(ts as string), segment from $tableName",
+            tsGenFunc,
+            partitionGenFunc,
+            Seq(),
+            Seq(1, "a1", "1.6", 1704121827, "cat1"),
+            Seq(2, "a2", "10.8", 1704121827, "cat1"),
+            Seq(3, "a3", "30.0", 1706800227, "cat1"),
+            Seq(4, "a4", "113.4", 1701443427, "cat2"),
+            Seq(5, "a5", "2009.0", 1704121827, "cat2"),
+            Seq(6, "a6", "90.0", 1704121827, "cat3"),
+            Seq(7, "a7", "1409.0", 1706800227, "cat1"),
+            Seq(8, "a8", "26.9", 1706800227, "cat3"),
+            Seq(9, "a9", "299.0", 1701443427, "cat4")
+          )
+
+          // Test SQL MERGE INTO
+          spark.sql(
+            s"""
+               | MERGE INTO $tableName as target
+               | USING (
+               |   SELECT 1 as id, 'a1' as name, 1.6 as price, 1704121827 as ts, 'cat1' as segment, 'delete' as flag
+               |   UNION
+               |   SELECT 2 as id, 'a2' as name, 11.9 as price, 1704121827 as ts, 'cat1' as segment, '' as flag
+               |   UNION
+               |   SELECT 6 as id, 'a6' as name, 99.0 as price, 1704121827 as ts, 'cat3' as segment, '' as flag
+               |   UNION
+               |   SELECT 8 as id, 'a8' as name, 24.9 as price, 1706800227 as ts, 'cat3' as segment, '' as flag
+               |   UNION
+               |   SELECT 10 as id, 'a10' as name, 888.8 as price, 1706800227 as ts, 'cat5' as segment, '' as flag
+               | ) source
+               | on target.id = source.id
+               | WHEN MATCHED AND flag != 'delete' THEN UPDATE SET
+               |   id = source.id, name = source.name, price = source.price, ts = source.ts, segment = source.segment
+               | WHEN MATCHED AND flag = 'delete' THEN DELETE
+               | WHEN NOT MATCHED THEN INSERT (id, name, price, ts, segment)
+               |   values (source.id, source.name, source.price, source.ts, source.segment)
+               | """.stripMargin)
+          validateResults(
+            tableName,
+            s"SELECT id, name, cast(price as string), cast(ts as string), segment from $tableName",
+            tsGenFunc,
+            partitionGenFunc,
+            Seq(),
+            Seq(2, "a2", "11.9", 1704121827, "cat1"),
+            Seq(3, "a3", "30.0", 1706800227, "cat1"),
+            Seq(4, "a4", "113.4", 1701443427, "cat2"),
+            Seq(5, "a5", "2009.0", 1704121827, "cat2"),
+            Seq(6, "a6", "99.0", 1704121827, "cat3"),
+            Seq(7, "a7", "1409.0", 1706800227, "cat1"),
+            Seq(8, "a8", "24.9", 1706800227, "cat3"),
+            Seq(9, "a9", "299.0", 1701443427, "cat4"),
+            Seq(10, "a10", "888.8", 1706800227, "cat5")
+          )
+
+          // Test SQL DELETE
+          spark.sql(
+            s"""
+               | DELETE FROM $tableName
+               | WHERE id = 7
+               | """.stripMargin)
+          validateResults(
+            tableName,
+            s"SELECT id, name, cast(price as string), cast(ts as string), segment from $tableName",
+            tsGenFunc,
+            partitionGenFunc,
+            Seq(),
+            Seq(2, "a2", "11.9", 1704121827, "cat1"),
+            Seq(3, "a3", "30.0", 1706800227, "cat1"),
+            Seq(4, "a4", "113.4", 1701443427, "cat2"),
+            Seq(5, "a5", "2009.0", 1704121827, "cat2"),
+            Seq(6, "a6", "99.0", 1704121827, "cat3"),
+            Seq(8, "a8", "24.9", 1706800227, "cat3"),
+            Seq(9, "a9", "299.0", 1701443427, "cat4"),
+            Seq(10, "a10", "888.8", 1706800227, "cat5")
+          )
+
+          // Test DROP PARTITION
+          assertTrue(getSortedTablePartitions(tableName).contains(droppedPartition))
+          spark.sql(
+            s"""
+               | ALTER TABLE $tableName DROP PARTITION $dropPartitionStatement
+               |""".stripMargin)
+          validatePartitions(tableName, Seq(droppedPartition), expectedPartitions)
+
+          if (HoodieSparkUtils.isSpark3) {
+            // Test INSERT OVERWRITE, only supported in Spark 3.x
+            spark.sql(
+              s"""
+                 | INSERT OVERWRITE $tableName
+                 | SELECT 100 as id, 'a100' as name, 299.0 as price, 1706800227 as ts, 'cat10' as segment
+                 | """.stripMargin)
+            validateResults(
+              tableName,
+              s"SELECT id, name, cast(price as string), cast(ts as string), segment from $tableName",
+              tsGenFunc,
+              partitionGenFunc,
+              Seq(),
+              Seq(100, "a100", "299.0", 1706800227, "cat10")
+            )
+          }
+        }
+      }
+    }
+  }
+
+  test("Test table property isolation for partition path field config "
+    + "with custom key generator for Spark 3.1 and above") {
+    // Only testing Spark 3.1 and above as lower Spark versions do not support
+    // ALTER TABLE .. SET TBLPROPERTIES .. to store table-level properties in Hudi Catalog
+    if (HoodieSparkUtils.gteqSpark3_1) {
+      withTempDir { tmp => {
+        val tableNameNonPartitioned = generateTableName
+        val tableNameSimpleKey = generateTableName
+        val tableNameCustom1 = generateTableName
+        val tableNameCustom2 = generateTableName
+
+        val tablePathNonPartitioned = tmp.getCanonicalPath + "/" + tableNameNonPartitioned
+        val tablePathSimpleKey = tmp.getCanonicalPath + "/" + tableNameSimpleKey
+        val tablePathCustom1 = tmp.getCanonicalPath + "/" + tableNameCustom1
+        val tablePathCustom2 = tmp.getCanonicalPath + "/" + tableNameCustom2
+
+        val tableType = "MERGE_ON_READ"
+        val writePartitionFields1 = "segment:simple"
+        val writePartitionFields2 = "ts:timestamp,segment:simple"
+
+        prepareTableWithKeyGenerator(
+          tableNameNonPartitioned, tablePathNonPartitioned, tableType,
+          NONPARTITIONED_KEY_GEN_CLASS_NAME, "", Map())
+        prepareTableWithKeyGenerator(
+          tableNameSimpleKey, tablePathSimpleKey, tableType,
+          SIMPLE_KEY_GEN_CLASS_NAME, "segment", Map())
+        prepareTableWithKeyGenerator(
+          tableNameCustom1, tablePathCustom1, tableType,
+          CUSTOM_KEY_GEN_CLASS_NAME, writePartitionFields1, Map())
+        prepareTableWithKeyGenerator(
+          tableNameCustom2, tablePathCustom2, tableType,
+          CUSTOM_KEY_GEN_CLASS_NAME, writePartitionFields2, TS_KEY_GEN_CONFIGS)
+
+        // Non-partitioned table does not require additional partition path field write config
+        createTableWithSql(tableNameNonPartitioned, tablePathNonPartitioned, "")
+        // Partitioned table with simple key generator does not require additional partition path field write config
+        createTableWithSql(tableNameSimpleKey, tablePathSimpleKey, "")
+        // Partitioned table with custom key generator requires additional partition path field write config
+        // Without that, right now the SQL DML fails
+        createTableWithSql(tableNameCustom1, tablePathCustom1, "")
+        createTableWithSql(tableNameCustom2, tablePathCustom2,
+          s"hoodie.datasource.write.partitionpath.field = '$writePartitionFields2', "
+            + TS_KEY_GEN_CONFIGS.map(e => e._1 + " = '" + e._2 + "'").mkString(", "))
+
+        val segmentPartitionFunc = (_: Integer, segment: String) => segment
+        val customPartitionFunc = (ts: Integer, segment: String) => TS_FORMATTER_FUNC.apply(ts) + "/" + segment
+
+        testFirstRoundInserts(tableNameNonPartitioned, TS_TO_STRING_FUNC, (_, _) => "")
+        testFirstRoundInserts(tableNameSimpleKey, TS_TO_STRING_FUNC, segmentPartitionFunc)
+        // INSERT INTO should fail for tableNameCustom1
+        val sourceTableName = tableNameCustom1 + "_source"
+        prepareParquetSource(sourceTableName, Seq("(7, 'a7', 1399.0, 1706800227, 'cat1')"))
+        assertThrows[IOException] {
+          spark.sql(
+            s"""
+               | INSERT INTO $tableNameCustom1
+               | SELECT * from $sourceTableName
+               | """.stripMargin)
+        }
+        testFirstRoundInserts(tableNameCustom2, TS_FORMATTER_FUNC, customPartitionFunc)
+
+        // Now add the missing partition path field write config for tableNameCustom1
+        spark.sql(
+          s"""ALTER TABLE $tableNameCustom1
+             | SET TBLPROPERTIES (hoodie.datasource.write.partitionpath.field = '$writePartitionFields1')
+             | """.stripMargin)
+
+        // All tables should be able to do INSERT INTO without any problem,
+        // since the scope of the added write config is at the catalog table level
+        testSecondRoundInserts(tableNameNonPartitioned, TS_TO_STRING_FUNC, (_, _) => "")
+        testSecondRoundInserts(tableNameSimpleKey, TS_TO_STRING_FUNC, segmentPartitionFunc)
+        testFirstRoundInserts(tableNameCustom1, TS_TO_STRING_FUNC, segmentPartitionFunc)
+        testSecondRoundInserts(tableNameCustom2, TS_FORMATTER_FUNC, customPartitionFunc)
+      }
+      }
+    }
+  }
+
+  test("Test wrong partition path field write config with custom key generator") {
+    withTempDir { tmp => {
+      val tableName = generateTableName
+      val tablePath = tmp.getCanonicalPath + "/" + tableName
+      val tableType = "MERGE_ON_READ"
+      val writePartitionFields = "segment:simple,ts:timestamp"
+      val wrongWritePartitionFields = "segment:simple"
+      val customPartitionFunc = (ts: Integer, segment: String) => segment + "/" + TS_FORMATTER_FUNC.apply(ts)
+
+      prepareTableWithKeyGenerator(
+        tableName, tablePath, "MERGE_ON_READ",
+        CUSTOM_KEY_GEN_CLASS_NAME, writePartitionFields, TS_KEY_GEN_CONFIGS)
+
+      // CREATE TABLE should fail due to config conflict
+      assertThrows[HoodieException] {
+        createTableWithSql(tableName, tablePath,
+          s"hoodie.datasource.write.partitionpath.field = '$wrongWritePartitionFields', "
+            + TS_KEY_GEN_CONFIGS.map(e => e._1 + " = '" + e._2 + "'").mkString(", "))
+      }
+
+      createTableWithSql(tableName, tablePath,
+        s"hoodie.datasource.write.partitionpath.field = '$writePartitionFields', "
+          + TS_KEY_GEN_CONFIGS.map(e => e._1 + " = '" + e._2 + "'").mkString(", "))
+      // Set wrong write config
+      spark.sql(
+        s"""ALTER TABLE $tableName
+           | SET TBLPROPERTIES (hoodie.datasource.write.partitionpath.field = '$wrongWritePartitionFields')
+           | """.stripMargin)
+
+      // INSERT INTO should fail due to conflict between write and table config of partition path fields
+      val sourceTableName = tableName + "_source"
+      prepareParquetSource(sourceTableName, Seq("(7, 'a7', 1399.0, 1706800227, 'cat1')"))
+      assertThrows[HoodieException] {
+        spark.sql(
+          s"""
+             | INSERT INTO $tableName
+             | SELECT * from $sourceTableName
+             | """.stripMargin)
+      }
+
+      // Only testing Spark 3.1 and above as lower Spark versions do not support
+      // ALTER TABLE .. SET TBLPROPERTIES .. to store table-level properties in Hudi Catalog
+      if (HoodieSparkUtils.gteqSpark3_1) {
+        // Now fix the partition path field write config for tableName
+        spark.sql(
+          s"""ALTER TABLE $tableName
+             | SET TBLPROPERTIES (hoodie.datasource.write.partitionpath.field = '$writePartitionFields')
+             | """.stripMargin)
+
+        // INSERT INTO should succeed now
+        testFirstRoundInserts(tableName, TS_FORMATTER_FUNC, customPartitionFunc)
+      }
+    }
+    }
+  }
+
+  private def testFirstRoundInserts(tableName: String,
+                                    tsGenFunc: Integer => String,
+                                    partitionGenFunc: (Integer, String) => String): Unit = {
+    val sourceTableName = tableName + "_source1"
+    prepareParquetSource(sourceTableName, Seq("(7, 'a7', 1399.0, 1706800227, 'cat1')"))
+    spark.sql(
+      s"""
+         | INSERT INTO $tableName
+         | SELECT * from $sourceTableName
+         | """.stripMargin)
+    validateResults(
+      tableName,
+      s"SELECT id, name, cast(price as string), cast(ts as string), segment from $tableName",
+      tsGenFunc,
+      partitionGenFunc,
+      Seq(),
+      Seq(1, "a1", "1.6", 1704121827, "cat1"),
+      Seq(2, "a2", "10.8", 1704121827, "cat1"),
+      Seq(3, "a3", "30.0", 1706800227, "cat1"),
+      Seq(4, "a4", "103.4", 1701443427, "cat2"),
+      Seq(5, "a5", "1999.0", 1704121827, "cat2"),
+      Seq(6, "a6", "80.0", 1704121827, "cat3"),
+      Seq(7, "a7", "1399.0", 1706800227, "cat1")
+    )
+  }
+
+  private def testSecondRoundInserts(tableName: String,
+                                     tsGenFunc: Integer => String,
+                                     partitionGenFunc: (Integer, String) => String): Unit = {
+    val sourceTableName = tableName + "_source2"
+    prepareParquetSource(sourceTableName, Seq("(8, 'a8', 26.9, 1706800227, 'cat3')"))
+    spark.sql(
+      s"""
+         | INSERT INTO $tableName
+         | SELECT * from $sourceTableName
+         | """.stripMargin)
+    validateResults(
+      tableName,
+      s"SELECT id, name, cast(price as string), cast(ts as string), segment from $tableName",
+      tsGenFunc,
+      partitionGenFunc,
+      Seq(),
+      Seq(1, "a1", "1.6", 1704121827, "cat1"),
+      Seq(2, "a2", "10.8", 1704121827, "cat1"),
+      Seq(3, "a3", "30.0", 1706800227, "cat1"),
+      Seq(4, "a4", "103.4", 1701443427, "cat2"),
+      Seq(5, "a5", "1999.0", 1704121827, "cat2"),
+      Seq(6, "a6", "80.0", 1704121827, "cat3"),
+      Seq(7, "a7", "1399.0", 1706800227, "cat1"),
+      Seq(8, "a8", "26.9", 1706800227, "cat3")
+    )
+  }
+
+  private def prepareTableWithKeyGenerator(tableName: String,
+                                           tablePath: String,
+                                           tableType: String,
+                                           keyGenClassName: String,
+                                           writePartitionFields: String,
+                                           timestampKeyGeneratorConfig: Map[String, String]): Unit = {
+    val df = spark.sql(
+      s"""SELECT 1 as id, 'a1' as name, 1.6 as price, 1704121827 as ts, 'cat1' as segment
+         | UNION
+         | SELECT 2 as id, 'a2' as name, 10.8 as price, 1704121827 as ts, 'cat1' as segment
+         | UNION
+         | SELECT 3 as id, 'a3' as name, 30.0 as price, 1706800227 as ts, 'cat1' as segment
+         | UNION
+         | SELECT 4 as id, 'a4' as name, 103.4 as price, 1701443427 as ts, 'cat2' as segment
+         | UNION
+         | SELECT 5 as id, 'a5' as name, 1999.0 as price, 1704121827 as ts, 'cat2' as segment
+         | UNION
+         | SELECT 6 as id, 'a6' as name, 80.0 as price, 1704121827 as ts, 'cat3' as segment
+         |""".stripMargin)
+
+    df.write.format("hudi")
+      .option("hoodie.datasource.write.table.type", tableType)
+      .option("hoodie.datasource.write.keygenerator.class", keyGenClassName)
+      .option("hoodie.datasource.write.partitionpath.field", writePartitionFields)
+      .option("hoodie.datasource.write.recordkey.field", "id")
+      .option("hoodie.datasource.write.precombine.field", "name")
+      .option("hoodie.table.name", tableName)
+      .option("hoodie.insert.shuffle.parallelism", "1")
+      .option("hoodie.upsert.shuffle.parallelism", "1")
+      .option("hoodie.bulkinsert.shuffle.parallelism", "1")
+      .options(timestampKeyGeneratorConfig)
+      .mode(SaveMode.Overwrite)
+      .save(tablePath)
+
+    // Validate that the generated table has expected table configs of key generator and partition path fields
+    val metaClient = HoodieTableMetaClient.builder()
+      .setConf(spark.sparkContext.hadoopConfiguration)
+      .setBasePath(tablePath)
+      .build()
+    assertEquals(keyGenClassName, metaClient.getTableConfig.getKeyGeneratorClassName)
+    // Validate that that partition path fields in the table config should always
+    // contain the field names only (no key generator type like "segment:simple")
+    if (CUSTOM_KEY_GEN_CLASS_NAME.equals(keyGenClassName)) {
+      val props = new TypedProperties()
+      props.put("hoodie.datasource.write.partitionpath.field", writePartitionFields)
+      timestampKeyGeneratorConfig.foreach(e => {
+        props.put(e._1, e._2)
+      })
+      // For custom key generator, the "hoodie.datasource.write.partitionpath.field"
+      // contains the key generator type, like "ts:timestamp,segment:simple",
+      // whereas the partition path fields in table config is "ts,segment"
+      assertEquals(
+        SparkKeyGenUtils.getPartitionColumns(Option(CUSTOM_KEY_GEN_CLASS_NAME), props),
+        metaClient.getTableConfig.getPartitionFieldProp)
+    } else {
+      assertEquals(writePartitionFields, metaClient.getTableConfig.getPartitionFieldProp)
+    }
+  }
+
+  private def createTableWithSql(tableName: String,
+                                 tablePath: String,
+                                 tblProps: String): Unit = {
+    val tblPropsStatement = if (StringUtils.isNullOrEmpty(tblProps)) {
+      ""
+    } else {
+      "TBLPROPERTIES (\n" + tblProps + "\n)"
+    }
+    spark.sql(
+      s"""
+         | CREATE TABLE $tableName USING HUDI
+         | location '$tablePath'
+         | $tblPropsStatement
+         | """.stripMargin)
+  }
+
+  private def prepareParquetSource(sourceTableName: String,
+                                   rows: Seq[String]): Unit = {
+    spark.sql(
+      s"""CREATE TABLE $sourceTableName
+         | (id int, name string, price decimal(5, 1), ts int, segment string)
+         | USING PARQUET
+         |""".stripMargin)
+    spark.sql(
+      s"""
+         | INSERT INTO $sourceTableName values
+         | ${rows.mkString(", ")}
+         | """.stripMargin)
+  }
+
+  private def validateResults(tableName: String,
+                              sql: String,
+                              tsGenFunc: Integer => String,
+                              partitionGenFunc: (Integer, String) => String,
+                              droppedPartitions: Seq[String],
+                              expects: Seq[Any]*): Unit = {
+    checkAnswer(sql)(
+      expects.map(e => Seq(e(0), e(1), e(2), tsGenFunc.apply(e(3).asInstanceOf[Integer]), e(4))): _*
+    )
+    val expectedPartitions: Seq[String] = expects
+      .map(e => partitionGenFunc.apply(e(3).asInstanceOf[Integer], e(4).asInstanceOf[String]))
+      .distinct.sorted
+    validatePartitions(tableName, droppedPartitions, expectedPartitions)
+  }
+
+  private def getSortedTablePartitions(tableName: String): Seq[String] = {
+    spark.sql(s"SHOW PARTITIONS $tableName").collect()
+      .map(row => row.getString(0))
+      .sorted.toSeq
+  }
+
+  private def validatePartitions(tableName: String,
+                                 droppedPartitions: Seq[String],
+                                 expectedPartitions: Seq[String]): Unit = {
+    val actualPartitions: Seq[String] = getSortedTablePartitions(tableName)
+    if (expectedPartitions.size == 1 && expectedPartitions.head.isEmpty) {
+      assertTrue(actualPartitions.isEmpty)
+    } else {
+      assertEquals(expectedPartitions, actualPartitions)
+    }
+    droppedPartitions.foreach(dropped => assertFalse(actualPartitions.contains(dropped)))
+  }
+}
+
+object TestSparkSqlWithCustomKeyGenerator {
+  val SIMPLE_KEY_GEN_CLASS_NAME = "org.apache.hudi.keygen.SimpleKeyGenerator"
+  val NONPARTITIONED_KEY_GEN_CLASS_NAME = "org.apache.hudi.keygen.NonpartitionedKeyGenerator"
+  val CUSTOM_KEY_GEN_CLASS_NAME = "org.apache.hudi.keygen.CustomKeyGenerator"
+  val DATE_FORMAT_PATTERN = "yyyyMM"
+  val TS_KEY_GEN_CONFIGS = Map(
+    "hoodie.keygen.timebased.timestamp.type" -> "SCALAR",
+    "hoodie.keygen.timebased.output.dateformat" -> DATE_FORMAT_PATTERN,
+    "hoodie.keygen.timebased.timestamp.scalar.time.unit" -> "seconds"
+  )
+  val TS_TO_STRING_FUNC = (tsSeconds: Integer) => tsSeconds.toString
+  val TS_FORMATTER_FUNC = (tsSeconds: Integer) => {
+    new DateTime(tsSeconds * 1000L).toString(DateTimeFormat.forPattern(DATE_FORMAT_PATTERN))
+  }
+
+  def getTimestampKeyGenConfigs: Map[String, String] = {
+    Map(
+      "hoodie.keygen.timebased.timestamp.type" -> "SCALAR",
+      "hoodie.keygen.timebased.output.dateformat" -> DATE_FORMAT_PATTERN,
+      "hoodie.keygen.timebased.timestamp.scalar.time.unit" -> "seconds"
+    )
+  }
+}


(hudi) 22/28: [HUDI-7626] Propagate UserGroupInformation from the main thread to the new thread of timeline service threadpool (#11039)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 3cdb6faefcb56bef3e7dcf26a81eb822576aa8ed
Author: Jing Zhang <be...@gmail.com>
AuthorDate: Wed Apr 17 16:40:29 2024 +0800

    [HUDI-7626] Propagate UserGroupInformation from the main thread to the new thread of timeline service threadpool (#11039)
---
 .../hudi/timeline/service/RequestHandler.java      | 128 +++++++++++----------
 1 file changed, 70 insertions(+), 58 deletions(-)

diff --git a/hudi-timeline-service/src/main/java/org/apache/hudi/timeline/service/RequestHandler.java b/hudi-timeline-service/src/main/java/org/apache/hudi/timeline/service/RequestHandler.java
index 9385b4eca9e..12e11db403d 100644
--- a/hudi-timeline-service/src/main/java/org/apache/hudi/timeline/service/RequestHandler.java
+++ b/hudi-timeline-service/src/main/java/org/apache/hudi/timeline/service/RequestHandler.java
@@ -52,11 +52,13 @@ import io.javalin.http.Context;
 import io.javalin.http.Handler;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.security.UserGroupInformation;
 import org.jetbrains.annotations.NotNull;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import java.io.IOException;
+import java.security.PrivilegedExceptionAction;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
@@ -563,76 +565,86 @@ public class RequestHandler {
 
     private final Handler handler;
     private final boolean performRefreshCheck;
+    private final UserGroupInformation ugi;
 
     ViewHandler(Handler handler, boolean performRefreshCheck) {
       this.handler = handler;
       this.performRefreshCheck = performRefreshCheck;
+      try {
+        ugi = UserGroupInformation.getCurrentUser();
+      } catch (Exception e) {
+        LOG.warn("Fail to get ugi", e);
+        throw new HoodieException(e);
+      }
     }
 
     @Override
     public void handle(@NotNull Context context) throws Exception {
-      boolean success = true;
-      long beginTs = System.currentTimeMillis();
-      boolean synced = false;
-      boolean refreshCheck = performRefreshCheck && !isRefreshCheckDisabledInQuery(context);
-      long refreshCheckTimeTaken = 0;
-      long handleTimeTaken = 0;
-      long finalCheckTimeTaken = 0;
-      try {
-        if (refreshCheck) {
-          long beginRefreshCheck = System.currentTimeMillis();
-          synced = syncIfLocalViewBehind(context);
-          long endRefreshCheck = System.currentTimeMillis();
-          refreshCheckTimeTaken = endRefreshCheck - beginRefreshCheck;
-        }
+      ugi.doAs((PrivilegedExceptionAction<Void>) () -> {
+        boolean success = true;
+        long beginTs = System.currentTimeMillis();
+        boolean synced = false;
+        boolean refreshCheck = performRefreshCheck && !isRefreshCheckDisabledInQuery(context);
+        long refreshCheckTimeTaken = 0;
+        long handleTimeTaken = 0;
+        long finalCheckTimeTaken = 0;
+        try {
+          if (refreshCheck) {
+            long beginRefreshCheck = System.currentTimeMillis();
+            synced = syncIfLocalViewBehind(context);
+            long endRefreshCheck = System.currentTimeMillis();
+            refreshCheckTimeTaken = endRefreshCheck - beginRefreshCheck;
+          }
 
-        long handleBeginMs = System.currentTimeMillis();
-        handler.handle(context);
-        long handleEndMs = System.currentTimeMillis();
-        handleTimeTaken = handleEndMs - handleBeginMs;
-
-        if (refreshCheck) {
-          long beginFinalCheck = System.currentTimeMillis();
-          if (isLocalViewBehind(context)) {
-            String lastKnownInstantFromClient = context.queryParamAsClass(RemoteHoodieTableFileSystemView.LAST_INSTANT_TS, String.class).getOrDefault(HoodieTimeline.INVALID_INSTANT_TS);
-            String timelineHashFromClient = context.queryParamAsClass(RemoteHoodieTableFileSystemView.TIMELINE_HASH, String.class).getOrDefault("");
-            HoodieTimeline localTimeline =
-                viewManager.getFileSystemView(context.queryParam(RemoteHoodieTableFileSystemView.BASEPATH_PARAM)).getTimeline();
-            if (shouldThrowExceptionIfLocalViewBehind(localTimeline, timelineHashFromClient)) {
-              String errMsg =
-                  "Last known instant from client was "
-                      + lastKnownInstantFromClient
-                      + " but server has the following timeline "
-                      + localTimeline.getInstants();
-              throw new BadRequestResponse(errMsg);
+          long handleBeginMs = System.currentTimeMillis();
+          handler.handle(context);
+          long handleEndMs = System.currentTimeMillis();
+          handleTimeTaken = handleEndMs - handleBeginMs;
+
+          if (refreshCheck) {
+            long beginFinalCheck = System.currentTimeMillis();
+            if (isLocalViewBehind(context)) {
+              String lastKnownInstantFromClient = context.queryParamAsClass(RemoteHoodieTableFileSystemView.LAST_INSTANT_TS, String.class).getOrDefault(HoodieTimeline.INVALID_INSTANT_TS);
+              String timelineHashFromClient = context.queryParamAsClass(RemoteHoodieTableFileSystemView.TIMELINE_HASH, String.class).getOrDefault("");
+              HoodieTimeline localTimeline =
+                  viewManager.getFileSystemView(context.queryParam(RemoteHoodieTableFileSystemView.BASEPATH_PARAM)).getTimeline();
+              if (shouldThrowExceptionIfLocalViewBehind(localTimeline, timelineHashFromClient)) {
+                String errMsg =
+                    "Last known instant from client was "
+                        + lastKnownInstantFromClient
+                        + " but server has the following timeline "
+                        + localTimeline.getInstants();
+                throw new BadRequestResponse(errMsg);
+              }
             }
+            long endFinalCheck = System.currentTimeMillis();
+            finalCheckTimeTaken = endFinalCheck - beginFinalCheck;
           }
-          long endFinalCheck = System.currentTimeMillis();
-          finalCheckTimeTaken = endFinalCheck - beginFinalCheck;
-        }
-      } catch (RuntimeException re) {
-        success = false;
-        if (re instanceof BadRequestResponse) {
-          LOG.warn("Bad request response due to client view behind server view. " + re.getMessage());
-        } else {
-          LOG.error("Got runtime exception servicing request " + context.queryString(), re);
+        } catch (RuntimeException re) {
+          success = false;
+          if (re instanceof BadRequestResponse) {
+            LOG.warn("Bad request response due to client view behind server view. " + re.getMessage());
+          } else {
+            LOG.error("Got runtime exception servicing request " + context.queryString(), re);
+          }
+          throw re;
+        } finally {
+          long endTs = System.currentTimeMillis();
+          long timeTakenMillis = endTs - beginTs;
+          metricsRegistry.add("TOTAL_API_TIME", timeTakenMillis);
+          metricsRegistry.add("TOTAL_REFRESH_TIME", refreshCheckTimeTaken);
+          metricsRegistry.add("TOTAL_HANDLE_TIME", handleTimeTaken);
+          metricsRegistry.add("TOTAL_CHECK_TIME", finalCheckTimeTaken);
+          metricsRegistry.add("TOTAL_API_CALLS", 1);
+
+          LOG.debug(String.format(
+              "TimeTakenMillis[Total=%d, Refresh=%d, handle=%d, Check=%d], "
+                  + "Success=%s, Query=%s, Host=%s, synced=%s",
+              timeTakenMillis, refreshCheckTimeTaken, handleTimeTaken, finalCheckTimeTaken, success,
+              context.queryString(), context.host(), synced));
         }
-        throw re;
-      } finally {
-        long endTs = System.currentTimeMillis();
-        long timeTakenMillis = endTs - beginTs;
-        metricsRegistry.add("TOTAL_API_TIME", timeTakenMillis);
-        metricsRegistry.add("TOTAL_REFRESH_TIME", refreshCheckTimeTaken);
-        metricsRegistry.add("TOTAL_HANDLE_TIME", handleTimeTaken);
-        metricsRegistry.add("TOTAL_CHECK_TIME", finalCheckTimeTaken);
-        metricsRegistry.add("TOTAL_API_CALLS", 1);
-
-        LOG.debug(String.format(
-            "TimeTakenMillis[Total=%d, Refresh=%d, handle=%d, Check=%d], "
-                + "Success=%s, Query=%s, Host=%s, synced=%s",
-            timeTakenMillis, refreshCheckTimeTaken, handleTimeTaken, finalCheckTimeTaken, success,
-            context.queryString(), context.host(), synced));
-      }
+        return null;
+      });
     }
   }
 }


(hudi) 14/28: [HUDI-7615] Mark a few write configs with the correct sinceVersion (#11012)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 89ff73de17513d79c311db4ccb0e13dbe1a25b39
Author: FreeTao <ta...@gmail.com>
AuthorDate: Sun Apr 14 18:36:22 2024 -0700

    [HUDI-7615] Mark a few write configs with the correct sinceVersion (#11012)
---
 .../main/java/org/apache/hudi/keygen/constant/KeyGeneratorOptions.java   | 1 +
 1 file changed, 1 insertion(+)

diff --git a/hudi-common/src/main/java/org/apache/hudi/keygen/constant/KeyGeneratorOptions.java b/hudi-common/src/main/java/org/apache/hudi/keygen/constant/KeyGeneratorOptions.java
index db4a9162129..3273a4fc49b 100644
--- a/hudi-common/src/main/java/org/apache/hudi/keygen/constant/KeyGeneratorOptions.java
+++ b/hudi-common/src/main/java/org/apache/hudi/keygen/constant/KeyGeneratorOptions.java
@@ -63,6 +63,7 @@ public class KeyGeneratorOptions extends HoodieConfig {
   public static final ConfigProperty<String> KEYGENERATOR_CONSISTENT_LOGICAL_TIMESTAMP_ENABLED = ConfigProperty
       .key("hoodie.datasource.write.keygenerator.consistent.logical.timestamp.enabled")
       .defaultValue("false")
+      .sinceVersion("0.10.1")
       .markAdvanced()
       .withDocumentation("When set to true, consistent value will be generated for a logical timestamp type column, "
           + "like timestamp-millis and timestamp-micros, irrespective of whether row-writer is enabled. Disabled by default so "


(hudi) 12/28: [HUDI-7616] Avoid multiple cleaner plans and deprecate hoodie.clean.allow.multiple (#11013)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit f12cd043095c7a41f84a910bc588cb171a8bfa41
Author: Y Ethan Guo <et...@gmail.com>
AuthorDate: Sat Apr 13 19:04:44 2024 -0700

    [HUDI-7616] Avoid multiple cleaner plans and deprecate hoodie.clean.allow.multiple (#11013)
---
 .../src/main/java/org/apache/hudi/config/HoodieCleanConfig.java     | 4 +++-
 .../src/test/java/org/apache/hudi/table/TestCleaner.java            | 6 +++---
 2 files changed, 6 insertions(+), 4 deletions(-)

diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieCleanConfig.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieCleanConfig.java
index a4114152023..e023bee4274 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieCleanConfig.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieCleanConfig.java
@@ -167,11 +167,13 @@ public class HoodieCleanConfig extends HoodieConfig {
           + "execution is slow due to limited parallelism, you can increase this to tune the "
           + "performance..");
 
+  @Deprecated
   public static final ConfigProperty<Boolean> ALLOW_MULTIPLE_CLEANS = ConfigProperty
       .key("hoodie.clean.allow.multiple")
-      .defaultValue(true)
+      .defaultValue(false)
       .markAdvanced()
       .sinceVersion("0.11.0")
+      .deprecatedAfter("1.0.0")
       .withDocumentation("Allows scheduling/executing multiple cleans by enabling this config. If users prefer to strictly ensure clean requests should be mutually exclusive, "
           + ".i.e. a 2nd clean will not be scheduled if another clean is not yet completed to avoid repeat cleaning of same files, they might want to disable this config.");
 
diff --git a/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/table/TestCleaner.java b/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/table/TestCleaner.java
index b18238f3392..6a8ce948373 100644
--- a/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/table/TestCleaner.java
+++ b/hudi-client/hudi-spark-client/src/test/java/org/apache/hudi/table/TestCleaner.java
@@ -593,13 +593,13 @@ public class TestCleaner extends HoodieCleanerTestBase {
       timeline = metaClient.reloadActiveTimeline();
 
       assertEquals(0, cleanStats.size(), "Must not clean any files");
-      assertEquals(1, timeline.getTimelineOfActions(
+      assertEquals(0, timeline.getTimelineOfActions(
           CollectionUtils.createSet(HoodieTimeline.CLEAN_ACTION)).filterInflightsAndRequested().countInstants());
       assertEquals(0, timeline.getTimelineOfActions(
           CollectionUtils.createSet(HoodieTimeline.CLEAN_ACTION)).filterInflights().countInstants());
-      assertEquals(--cleanCount, timeline.getTimelineOfActions(
+      assertEquals(cleanCount, timeline.getTimelineOfActions(
           CollectionUtils.createSet(HoodieTimeline.CLEAN_ACTION)).filterCompletedInstants().countInstants());
-      assertTrue(timeline.getTimelineOfActions(
+      assertFalse(timeline.getTimelineOfActions(
           CollectionUtils.createSet(HoodieTimeline.CLEAN_ACTION)).filterInflightsAndRequested().containsInstant(makeNewCommitTime(--instantClean, "%09d")));
     }
   }


(hudi) 25/28: [MINOR] Remove redundant TestStringUtils in hudi-common (#11046)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit bfb83c8eb8c59f90a548a34561c7fdee833ebaee
Author: Y Ethan Guo <et...@gmail.com>
AuthorDate: Wed Apr 17 21:34:06 2024 -0700

    [MINOR] Remove redundant TestStringUtils in hudi-common (#11046)
---
 .../apache/hudi/common/util/TestStringUtils.java   | 124 ---------------------
 1 file changed, 124 deletions(-)

diff --git a/hudi-common/src/test/java/org/apache/hudi/common/util/TestStringUtils.java b/hudi-common/src/test/java/org/apache/hudi/common/util/TestStringUtils.java
deleted file mode 100644
index 54985056bf0..00000000000
--- a/hudi-common/src/test/java/org/apache/hudi/common/util/TestStringUtils.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * 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.hudi.common.util;
-
-import org.junit.jupiter.api.Test;
-
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-
-import static org.apache.hudi.common.util.StringUtils.getUTF8Bytes;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-/**
- * Tests {@link StringUtils}.
- */
-public class TestStringUtils {
-
-  private static final String[] STRINGS = {"This", "is", "a", "test"};
-
-  @Test
-  public void testStringJoinWithDelim() {
-    String joinedString = StringUtils.joinUsingDelim("-", STRINGS);
-    assertEquals(STRINGS.length, joinedString.split("-").length);
-  }
-
-  @Test
-  public void testStringJoin() {
-    assertNotEquals(null, StringUtils.join(""));
-    assertNotEquals(null, StringUtils.join(STRINGS));
-  }
-
-  @Test
-  public void testStringJoinWithJavaImpl() {
-    assertNull(StringUtils.join(",", null));
-    assertEquals("", String.join(",", Collections.singletonList("")));
-    assertEquals(",", String.join(",", Arrays.asList("", "")));
-    assertEquals("a,", String.join(",", Arrays.asList("a", "")));
-  }
-
-  @Test
-  public void testStringNullToEmpty() {
-    String str = "This is a test";
-    assertEquals(str, StringUtils.nullToEmpty(str));
-    assertEquals("", StringUtils.nullToEmpty(null));
-  }
-
-  @Test
-  public void testStringObjToString() {
-    assertNull(StringUtils.objToString(null));
-    assertEquals("Test String", StringUtils.objToString("Test String"));
-
-    // assert byte buffer
-    ByteBuffer byteBuffer1 = ByteBuffer.wrap(getUTF8Bytes("1234"));
-    ByteBuffer byteBuffer2 = ByteBuffer.wrap(getUTF8Bytes("5678"));
-    // assert equal because ByteBuffer has overwritten the toString to return a summary string
-    assertEquals(byteBuffer1.toString(), byteBuffer2.toString());
-    // assert not equal
-    assertNotEquals(StringUtils.objToString(byteBuffer1), StringUtils.objToString(byteBuffer2));
-  }
-
-  @Test
-  public void testStringEmptyToNull() {
-    assertNull(StringUtils.emptyToNull(""));
-    assertEquals("Test String", StringUtils.emptyToNull("Test String"));
-  }
-
-  @Test
-  public void testStringNullOrEmpty() {
-    assertTrue(StringUtils.isNullOrEmpty(null));
-    assertTrue(StringUtils.isNullOrEmpty(""));
-    assertNotEquals(null, StringUtils.isNullOrEmpty("this is not empty"));
-    assertTrue(StringUtils.isNullOrEmpty(""));
-  }
-
-  @Test
-  public void testSplit() {
-    assertEquals(new ArrayList<>(), StringUtils.split(null, ","));
-    assertEquals(new ArrayList<>(), StringUtils.split("", ","));
-    assertEquals(Arrays.asList("a", "b", "c"), StringUtils.split("a,b, c", ","));
-    assertEquals(Arrays.asList("a", "b", "c"), StringUtils.split("a,b,, c ", ","));
-  }
-
-  @Test
-  public void testHexString() {
-    String str = "abcd";
-    assertEquals(StringUtils.toHexString(getUTF8Bytes(str)), toHexString(getUTF8Bytes(str)));
-  }
-
-  private static String toHexString(byte[] bytes) {
-    StringBuilder sb = new StringBuilder(bytes.length * 2);
-    for (byte b : bytes) {
-      sb.append(String.format("%02x", b));
-    }
-    return sb.toString();
-  }
-
-  @Test
-  public void testTruncate() {
-    assertNull(StringUtils.truncate(null, 10, 10));
-    assertEquals("http://use...ons/latest", StringUtils.truncate("http://username:password@myregistry.com:5000/versions/latest", 10, 10));
-    assertEquals("http://abc.com", StringUtils.truncate("http://abc.com", 10, 10));
-  }
-}


(hudi) 16/28: [HUDI-7619] Removed code duplicates in HoodieTableMetadataUtil (#11022)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 59a1b28849f8412449f6fd2d3ed662524443e037
Author: Vova Kolmakov <wo...@gmail.com>
AuthorDate: Tue May 14 16:01:09 2024 -0700

    [HUDI-7619] Removed code duplicates in HoodieTableMetadataUtil (#11022)
    
    Co-authored-by: Vova Kolmakov <ko...@huawei-partners.com>
---
 .../hudi/metadata/HoodieTableMetadataUtil.java     | 92 +++++++++-------------
 1 file changed, 36 insertions(+), 56 deletions(-)

diff --git a/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieTableMetadataUtil.java b/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieTableMetadataUtil.java
index b25d6741b83..503e3351d8c 100644
--- a/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieTableMetadataUtil.java
+++ b/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieTableMetadataUtil.java
@@ -73,6 +73,7 @@ import org.apache.hudi.exception.HoodieMetadataException;
 import org.apache.hudi.hadoop.fs.HadoopFSUtils;
 import org.apache.hudi.io.storage.HoodieFileReader;
 import org.apache.hudi.io.storage.HoodieFileReaderFactory;
+import org.apache.hudi.storage.StoragePath;
 import org.apache.hudi.util.Lazy;
 
 import org.apache.avro.AvroTypeException;
@@ -1749,26 +1750,7 @@ public class HoodieTableMetadataUtil {
       final String instantTime = baseFile.getCommitTime();
       HoodieFileReader reader = HoodieFileReaderFactory.getReaderFactory(HoodieRecord.HoodieRecordType.AVRO)
           .getFileReader(config, configuration.get(), dataFilePath);
-      ClosableIterator<String> recordKeyIterator = reader.getRecordKeyIterator();
-
-      return new ClosableIterator<HoodieRecord>() {
-        @Override
-        public void close() {
-          recordKeyIterator.close();
-        }
-
-        @Override
-        public boolean hasNext() {
-          return recordKeyIterator.hasNext();
-        }
-
-        @Override
-        public HoodieRecord next() {
-          return forDelete
-              ? HoodieMetadataPayload.createRecordIndexDelete(recordKeyIterator.next())
-              : HoodieMetadataPayload.createRecordIndexUpdate(recordKeyIterator.next(), partition, fileId, instantTime, 0);
-        }
-      };
+      return getHoodieRecordIterator(reader.getRecordKeyIterator(), forDelete, partition, fileId, instantTime);
     });
   }
 
@@ -1816,24 +1798,7 @@ public class HoodieTableMetadataUtil {
             .withTableMetaClient(metaClient)
             .build();
         ClosableIterator<String> recordKeyIterator = ClosableIterator.wrap(mergedLogRecordScanner.getRecords().keySet().iterator());
-        return new ClosableIterator<HoodieRecord>() {
-          @Override
-          public void close() {
-            recordKeyIterator.close();
-          }
-
-          @Override
-          public boolean hasNext() {
-            return recordKeyIterator.hasNext();
-          }
-
-          @Override
-          public HoodieRecord next() {
-            return forDelete
-                ? HoodieMetadataPayload.createRecordIndexDelete(recordKeyIterator.next())
-                : HoodieMetadataPayload.createRecordIndexUpdate(recordKeyIterator.next(), partition, fileSlice.getFileId(), fileSlice.getBaseInstantTime(), 0);
-          }
-        };
+        return getHoodieRecordIterator(recordKeyIterator, forDelete, partition, fileSlice.getFileId(), fileSlice.getBaseInstantTime());
       }
       final HoodieBaseFile baseFile = fileSlice.getBaseFile().get();
       final String filename = baseFile.getFileName();
@@ -1844,26 +1809,41 @@ public class HoodieTableMetadataUtil {
       HoodieConfig hoodieConfig = getReaderConfigs(configuration.get());
       HoodieFileReader reader = HoodieFileReaderFactory.getReaderFactory(HoodieRecord.HoodieRecordType.AVRO)
           .getFileReader(hoodieConfig, configuration.get(), dataFilePath);
-      ClosableIterator<String> recordKeyIterator = reader.getRecordKeyIterator();
+      return getHoodieRecordIterator(reader.getRecordKeyIterator(), forDelete, partition, fileId, instantTime);
+    });
+  }
 
-      return new ClosableIterator<HoodieRecord>() {
-        @Override
-        public void close() {
-          recordKeyIterator.close();
-        }
+  private static Path filePath(String basePath, String partition, String filename) {
+    if (partition.isEmpty()) {
+      return new Path(basePath, filename);
+    } else {
+      return new Path(basePath, partition + StoragePath.SEPARATOR + filename);
+    }
+  }
 
-        @Override
-        public boolean hasNext() {
-          return recordKeyIterator.hasNext();
-        }
+  private static ClosableIterator<HoodieRecord> getHoodieRecordIterator(ClosableIterator<String> recordKeyIterator,
+                                                                        boolean forDelete,
+                                                                        String partition,
+                                                                        String fileId,
+                                                                        String instantTime
+  ) {
+    return new ClosableIterator<HoodieRecord>() {
+      @Override
+      public void close() {
+        recordKeyIterator.close();
+      }
 
-        @Override
-        public HoodieRecord next() {
-          return forDelete
-              ? HoodieMetadataPayload.createRecordIndexDelete(recordKeyIterator.next())
-              : HoodieMetadataPayload.createRecordIndexUpdate(recordKeyIterator.next(), partition, fileId, instantTime, 0);
-        }
-      };
-    });
+      @Override
+      public boolean hasNext() {
+        return recordKeyIterator.hasNext();
+      }
+
+      @Override
+      public HoodieRecord next() {
+        return forDelete
+                ? HoodieMetadataPayload.createRecordIndexDelete(recordKeyIterator.next())
+                : HoodieMetadataPayload.createRecordIndexUpdate(recordKeyIterator.next(), partition, fileId, instantTime, 0);
+      }
+    };
   }
 }


(hudi) 26/28: [HUDI-7636] Make StoragePath Serializable (#11049)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 9b0945c7817a552548c23c3cf3dd485caa38f8ec
Author: Y Ethan Guo <et...@gmail.com>
AuthorDate: Wed Apr 17 21:39:28 2024 -0700

    [HUDI-7636] Make StoragePath Serializable (#11049)
---
 .../java/org/apache/hudi/storage/StoragePath.java  | 14 +++++++++--
 .../apache/hudi/io/storage/TestStoragePath.java    | 28 +++++++++++++++++++++-
 2 files changed, 39 insertions(+), 3 deletions(-)

diff --git a/hudi-io/src/main/java/org/apache/hudi/storage/StoragePath.java b/hudi-io/src/main/java/org/apache/hudi/storage/StoragePath.java
index f3a88f7c89b..24bf77e76ad 100644
--- a/hudi-io/src/main/java/org/apache/hudi/storage/StoragePath.java
+++ b/hudi-io/src/main/java/org/apache/hudi/storage/StoragePath.java
@@ -23,6 +23,9 @@ import org.apache.hudi.ApiMaturityLevel;
 import org.apache.hudi.PublicAPIClass;
 import org.apache.hudi.PublicAPIMethod;
 
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
 import java.io.Serializable;
 import java.net.URI;
 import java.net.URISyntaxException;
@@ -33,12 +36,11 @@ import java.net.URISyntaxException;
  * The APIs are mainly based on {@code org.apache.hadoop.fs.Path} class.
  */
 @PublicAPIClass(maturity = ApiMaturityLevel.EVOLVING)
-// StoragePath
 public class StoragePath implements Comparable<StoragePath>, Serializable {
   public static final char SEPARATOR_CHAR = '/';
   public static final char COLON_CHAR = ':';
   public static final String SEPARATOR = "" + SEPARATOR_CHAR;
-  private final URI uri;
+  private URI uri;
   private transient volatile StoragePath cachedParent;
   private transient volatile String cachedName;
   private transient volatile String uriString;
@@ -306,4 +308,12 @@ public class StoragePath implements Comparable<StoragePath>, Serializable {
     }
     return path.substring(0, indexOfLastSlash);
   }
+
+  private void writeObject(ObjectOutputStream out) throws IOException {
+    out.writeObject(uri);
+  }
+
+  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
+    uri = (URI) in.readObject();
+  }
 }
diff --git a/hudi-io/src/test/java/org/apache/hudi/io/storage/TestStoragePath.java b/hudi-io/src/test/java/org/apache/hudi/io/storage/TestStoragePath.java
index 9195ebec9fd..e7ce6ecc838 100644
--- a/hudi-io/src/test/java/org/apache/hudi/io/storage/TestStoragePath.java
+++ b/hudi-io/src/test/java/org/apache/hudi/io/storage/TestStoragePath.java
@@ -22,7 +22,14 @@ package org.apache.hudi.io.storage;
 import org.apache.hudi.storage.StoragePath;
 
 import org.junit.jupiter.api.Test;
-
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.util.Arrays;
@@ -197,6 +204,25 @@ public class TestStoragePath {
         () -> new StoragePath("a").makeQualified(defaultUri));
   }
 
+  @ParameterizedTest
+  @ValueSource(strings = {
+      "/x/y/1.file#bar",
+      "s3://foo/bar/1%2F2%2F3",
+      "hdfs://host1/a/b/c"
+  })
+  public void testSerializability(String pathStr) throws IOException, ClassNotFoundException {
+    StoragePath path = new StoragePath(pathStr);
+    try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
+         ObjectOutputStream oos = new ObjectOutputStream(baos)) {
+      oos.writeObject(path);
+      try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+           ObjectInputStream ois = new ObjectInputStream(bais)) {
+        StoragePath deserialized = (StoragePath) ois.readObject();
+        assertEquals(path.toUri(), deserialized.toUri());
+      }
+    }
+  }
+
   @Test
   public void testEquals() {
     assertEquals(new StoragePath("/foo"), new StoragePath("/foo"));


(hudi) 27/28: [HUDI-7635] Add default block size and openSeekable APIs to HoodieStorage (#11048)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 6c152dbef8a0dd1bebdefbe08d22171214964c06
Author: Y Ethan Guo <et...@gmail.com>
AuthorDate: Tue May 14 17:02:25 2024 -0700

    [HUDI-7635] Add default block size and openSeekable APIs to HoodieStorage (#11048)
    
    This PR adds `getDefaultBlockSize` and `openSeekable` APIs to
    `HoodieStorage` and implements these APIs in `HoodieHadoopStorage`.
    The implementation follows the same logic of creating seekable input
    stream for log file reading, and `openSeekable` will be used by the log
    reading logic.
    
    A few util methods are moved from `FSUtils` and
    `HoodieLogFileReader` classes to `HadoopFSUtilsclass`.
---
 .../java/org/apache/hudi/common/fs/FSUtils.java    | 18 -----
 .../hudi/common/table/log/HoodieLogFileReader.java | 75 +-----------------
 .../org/apache/hudi/hadoop/fs/HadoopFSUtils.java   | 90 ++++++++++++++++++++++
 .../hudi/storage/hadoop/HoodieHadoopStorage.java   | 13 ++++
 .../org/apache/hudi/storage/HoodieStorage.java     | 30 ++++++++
 .../hudi/io/storage/TestHoodieStorageBase.java     | 43 +++++++++++
 6 files changed, 179 insertions(+), 90 deletions(-)

diff --git a/hudi-common/src/main/java/org/apache/hudi/common/fs/FSUtils.java b/hudi-common/src/main/java/org/apache/hudi/common/fs/FSUtils.java
index 292c2b41946..1b51fd78bfa 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/fs/FSUtils.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/fs/FSUtils.java
@@ -667,24 +667,6 @@ public class FSUtils {
     return fs.getUri() + fullPartitionPath.toUri().getRawPath();
   }
 
-  /**
-   * This is due to HUDI-140 GCS has a different behavior for detecting EOF during seek().
-   *
-   * @param fs fileSystem instance.
-   * @return true if the inputstream or the wrapped one is of type GoogleHadoopFSInputStream
-   */
-  public static boolean isGCSFileSystem(FileSystem fs) {
-    return fs.getScheme().equals(StorageSchemes.GCS.getScheme());
-  }
-
-  /**
-   * Chdfs will throw {@code IOException} instead of {@code EOFException}. It will cause error in isBlockCorrupted().
-   * Wrapped by {@code BoundedFsDataInputStream}, to check whether the desired offset is out of the file size in advance.
-   */
-  public static boolean isCHDFileSystem(FileSystem fs) {
-    return StorageSchemes.CHDFS.getScheme().equals(fs.getScheme());
-  }
-
   public static Configuration registerFileSystem(Path file, Configuration conf) {
     Configuration returnConf = new Configuration(conf);
     String scheme = HadoopFSUtils.getFs(file.toString(), conf).getScheme();
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFileReader.java b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFileReader.java
index c1daf5e32d1..062e3639073 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFileReader.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFileReader.java
@@ -37,20 +37,15 @@ import org.apache.hudi.common.util.Option;
 import org.apache.hudi.exception.CorruptedLogFileException;
 import org.apache.hudi.exception.HoodieIOException;
 import org.apache.hudi.exception.HoodieNotSupportedException;
-import org.apache.hudi.hadoop.fs.BoundedFsDataInputStream;
 import org.apache.hudi.hadoop.fs.HadoopSeekableDataInputStream;
-import org.apache.hudi.hadoop.fs.SchemeAwareFSDataInputStream;
-import org.apache.hudi.hadoop.fs.TimedFSDataInputStream;
 import org.apache.hudi.internal.schema.InternalSchema;
 import org.apache.hudi.io.SeekableDataInputStream;
 import org.apache.hudi.io.util.IOUtils;
+import org.apache.hudi.storage.StoragePath;
 import org.apache.hudi.storage.StorageSchemes;
 
 import org.apache.avro.Schema;
 import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.BufferedFSInputStream;
-import org.apache.hadoop.fs.FSDataInputStream;
-import org.apache.hadoop.fs.FSInputStream;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
 import org.slf4j.Logger;
@@ -67,6 +62,7 @@ import java.util.Objects;
 
 import static org.apache.hudi.common.util.ValidationUtils.checkArgument;
 import static org.apache.hudi.common.util.ValidationUtils.checkState;
+import static org.apache.hudi.hadoop.fs.HadoopFSUtils.getFSDataInputStream;
 
 /**
  * Scans a log file and provides block level iterator on the log file Loads the entire block contents in memory Can emit
@@ -479,71 +475,6 @@ public class HoodieLogFileReader implements HoodieLogFormat.Reader {
   private static SeekableDataInputStream getDataInputStream(FileSystem fs,
                                                             HoodieLogFile logFile,
                                                             int bufferSize) {
-    return new HadoopSeekableDataInputStream(getFSDataInputStream(fs, logFile, bufferSize));
-  }
-
-  /**
-   * Fetch the right {@link FSDataInputStream} to be used by wrapping with required input streams.
-   *
-   * @param fs         instance of {@link FileSystem} in use.
-   * @param bufferSize buffer size to be used.
-   * @return the right {@link FSDataInputStream} as required.
-   */
-  private static FSDataInputStream getFSDataInputStream(FileSystem fs,
-                                                        HoodieLogFile logFile,
-                                                        int bufferSize) {
-    FSDataInputStream fsDataInputStream = null;
-    try {
-      fsDataInputStream = fs.open(logFile.getPath(), bufferSize);
-    } catch (IOException e) {
-      throw new HoodieIOException("Exception creating input stream from file: " + logFile, e);
-    }
-
-    if (FSUtils.isGCSFileSystem(fs)) {
-      // in GCS FS, we might need to interceptor seek offsets as we might get EOF exception
-      return new SchemeAwareFSDataInputStream(getFSDataInputStreamForGCS(fsDataInputStream, logFile, bufferSize), true);
-    }
-
-    if (FSUtils.isCHDFileSystem(fs)) {
-      return new BoundedFsDataInputStream(fs, logFile.getPath(), fsDataInputStream);
-    }
-
-    if (fsDataInputStream.getWrappedStream() instanceof FSInputStream) {
-      return new TimedFSDataInputStream(logFile.getPath(), new FSDataInputStream(
-          new BufferedFSInputStream((FSInputStream) fsDataInputStream.getWrappedStream(), bufferSize)));
-    }
-
-    // fsDataInputStream.getWrappedStream() maybe a BufferedFSInputStream
-    // need to wrap in another BufferedFSInputStream the make bufferSize work?
-    return fsDataInputStream;
-  }
-
-  /**
-   * GCS FileSystem needs some special handling for seek and hence this method assists to fetch the right {@link FSDataInputStream} to be
-   * used by wrapping with required input streams.
-   * @param fsDataInputStream original instance of {@link FSDataInputStream}.
-   * @param bufferSize buffer size to be used.
-   * @return the right {@link FSDataInputStream} as required.
-   */
-  private static FSDataInputStream getFSDataInputStreamForGCS(FSDataInputStream fsDataInputStream,
-                                                              HoodieLogFile logFile,
-                                                              int bufferSize) {
-    // in case of GCS FS, there are two flows.
-    // a. fsDataInputStream.getWrappedStream() instanceof FSInputStream
-    // b. fsDataInputStream.getWrappedStream() not an instanceof FSInputStream, but an instance of FSDataInputStream.
-    // (a) is handled in the first if block and (b) is handled in the second if block. If not, we fallback to original fsDataInputStream
-    if (fsDataInputStream.getWrappedStream() instanceof FSInputStream) {
-      return new TimedFSDataInputStream(logFile.getPath(), new FSDataInputStream(
-          new BufferedFSInputStream((FSInputStream) fsDataInputStream.getWrappedStream(), bufferSize)));
-    }
-
-    if (fsDataInputStream.getWrappedStream() instanceof FSDataInputStream
-        && ((FSDataInputStream) fsDataInputStream.getWrappedStream()).getWrappedStream() instanceof FSInputStream) {
-      FSInputStream inputStream = (FSInputStream)((FSDataInputStream) fsDataInputStream.getWrappedStream()).getWrappedStream();
-      return new TimedFSDataInputStream(logFile.getPath(),
-          new FSDataInputStream(new BufferedFSInputStream(inputStream, bufferSize)));
-    }
-
-    return fsDataInputStream;
+    return new HadoopSeekableDataInputStream(getFSDataInputStream(fs, new StoragePath(logFile.getPath().toUri()), bufferSize));
   }
 }
diff --git a/hudi-hadoop-common/src/main/java/org/apache/hudi/hadoop/fs/HadoopFSUtils.java b/hudi-hadoop-common/src/main/java/org/apache/hudi/hadoop/fs/HadoopFSUtils.java
index d59bffc9217..8eaa9398082 100644
--- a/hudi-hadoop-common/src/main/java/org/apache/hudi/hadoop/fs/HadoopFSUtils.java
+++ b/hudi-hadoop-common/src/main/java/org/apache/hudi/hadoop/fs/HadoopFSUtils.java
@@ -24,9 +24,13 @@ import org.apache.hudi.exception.HoodieIOException;
 import org.apache.hudi.storage.StorageConfiguration;
 import org.apache.hudi.storage.StoragePath;
 import org.apache.hudi.storage.StoragePathInfo;
+import org.apache.hudi.storage.StorageSchemes;
 import org.apache.hudi.storage.hadoop.HadoopStorageConfiguration;
 
 import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.BufferedFSInputStream;
+import org.apache.hadoop.fs.FSDataInputStream;
+import org.apache.hadoop.fs.FSInputStream;
 import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
@@ -154,4 +158,90 @@ public class HadoopFSUtils {
         pathInfo.getModificationTime(),
         convertToHadoopPath(pathInfo.getPath()));
   }
+
+  /**
+   * Fetch the right {@link FSDataInputStream} to be used by wrapping with required input streams.
+   *
+   * @param fs         instance of {@link FileSystem} in use.
+   * @param filePath   path of the file.
+   * @param bufferSize buffer size to be used.
+   * @return the right {@link FSDataInputStream} as required.
+   */
+  public static FSDataInputStream getFSDataInputStream(FileSystem fs,
+                                                       StoragePath filePath,
+                                                       int bufferSize) {
+    FSDataInputStream fsDataInputStream = null;
+    try {
+      fsDataInputStream = fs.open(convertToHadoopPath(filePath), bufferSize);
+    } catch (IOException e) {
+      throw new HoodieIOException("Exception creating input stream from file: " + filePath, e);
+    }
+
+    if (isGCSFileSystem(fs)) {
+      // in GCS FS, we might need to interceptor seek offsets as we might get EOF exception
+      return new SchemeAwareFSDataInputStream(getFSDataInputStreamForGCS(fsDataInputStream, filePath, bufferSize), true);
+    }
+
+    if (isCHDFileSystem(fs)) {
+      return new BoundedFsDataInputStream(fs, convertToHadoopPath(filePath), fsDataInputStream);
+    }
+
+    if (fsDataInputStream.getWrappedStream() instanceof FSInputStream) {
+      return new TimedFSDataInputStream(convertToHadoopPath(filePath), new FSDataInputStream(
+          new BufferedFSInputStream((FSInputStream) fsDataInputStream.getWrappedStream(), bufferSize)));
+    }
+
+    // fsDataInputStream.getWrappedStream() maybe a BufferedFSInputStream
+    // need to wrap in another BufferedFSInputStream the make bufferSize work?
+    return fsDataInputStream;
+  }
+
+  /**
+   * GCS FileSystem needs some special handling for seek and hence this method assists to fetch the right {@link FSDataInputStream} to be
+   * used by wrapping with required input streams.
+   *
+   * @param fsDataInputStream original instance of {@link FSDataInputStream}.
+   * @param filePath          path of the file.
+   * @param bufferSize        buffer size to be used.
+   * @return the right {@link FSDataInputStream} as required.
+   */
+  private static FSDataInputStream getFSDataInputStreamForGCS(FSDataInputStream fsDataInputStream,
+                                                              StoragePath filePath,
+                                                              int bufferSize) {
+    // in case of GCS FS, there are two flows.
+    // a. fsDataInputStream.getWrappedStream() instanceof FSInputStream
+    // b. fsDataInputStream.getWrappedStream() not an instanceof FSInputStream, but an instance of FSDataInputStream.
+    // (a) is handled in the first if block and (b) is handled in the second if block. If not, we fallback to original fsDataInputStream
+    if (fsDataInputStream.getWrappedStream() instanceof FSInputStream) {
+      return new TimedFSDataInputStream(convertToHadoopPath(filePath), new FSDataInputStream(
+          new BufferedFSInputStream((FSInputStream) fsDataInputStream.getWrappedStream(), bufferSize)));
+    }
+
+    if (fsDataInputStream.getWrappedStream() instanceof FSDataInputStream
+        && ((FSDataInputStream) fsDataInputStream.getWrappedStream()).getWrappedStream() instanceof FSInputStream) {
+      FSInputStream inputStream = (FSInputStream) ((FSDataInputStream) fsDataInputStream.getWrappedStream()).getWrappedStream();
+      return new TimedFSDataInputStream(convertToHadoopPath(filePath),
+          new FSDataInputStream(new BufferedFSInputStream(inputStream, bufferSize)));
+    }
+
+    return fsDataInputStream;
+  }
+
+  /**
+   * This is due to HUDI-140 GCS has a different behavior for detecting EOF during seek().
+   *
+   * @param fs fileSystem instance.
+   * @return true if the inputstream or the wrapped one is of type GoogleHadoopFSInputStream
+   */
+  public static boolean isGCSFileSystem(FileSystem fs) {
+    return fs.getScheme().equals(StorageSchemes.GCS.getScheme());
+  }
+
+  /**
+   * Chdfs will throw {@code IOException} instead of {@code EOFException}. It will cause error in isBlockCorrupted().
+   * Wrapped by {@code BoundedFsDataInputStream}, to check whether the desired offset is out of the file size in advance.
+   */
+  public static boolean isCHDFileSystem(FileSystem fs) {
+    return StorageSchemes.CHDFS.getScheme().equals(fs.getScheme());
+  }
 }
diff --git a/hudi-hadoop-common/src/main/java/org/apache/hudi/storage/hadoop/HoodieHadoopStorage.java b/hudi-hadoop-common/src/main/java/org/apache/hudi/storage/hadoop/HoodieHadoopStorage.java
index 54c1712be35..9785f42989d 100644
--- a/hudi-hadoop-common/src/main/java/org/apache/hudi/storage/hadoop/HoodieHadoopStorage.java
+++ b/hudi-hadoop-common/src/main/java/org/apache/hudi/storage/hadoop/HoodieHadoopStorage.java
@@ -20,6 +20,8 @@
 package org.apache.hudi.storage.hadoop;
 
 import org.apache.hudi.hadoop.fs.HadoopFSUtils;
+import org.apache.hudi.hadoop.fs.HadoopSeekableDataInputStream;
+import org.apache.hudi.io.SeekableDataInputStream;
 import org.apache.hudi.storage.HoodieStorage;
 import org.apache.hudi.storage.StoragePath;
 import org.apache.hudi.storage.StoragePathFilter;
@@ -63,6 +65,11 @@ public class HoodieHadoopStorage extends HoodieStorage {
     return fs.getUri();
   }
 
+  @Override
+  public int getDefaultBlockSize(StoragePath path) {
+    return (int) fs.getDefaultBlockSize(convertToHadoopPath(path));
+  }
+
   @Override
   public OutputStream create(StoragePath path, boolean overwrite) throws IOException {
     return fs.create(convertToHadoopPath(path), overwrite);
@@ -73,6 +80,12 @@ public class HoodieHadoopStorage extends HoodieStorage {
     return fs.open(convertToHadoopPath(path));
   }
 
+  @Override
+  public SeekableDataInputStream openSeekable(StoragePath path, int bufferSize) throws IOException {
+    return new HadoopSeekableDataInputStream(
+        HadoopFSUtils.getFSDataInputStream(fs, path, bufferSize));
+  }
+
   @Override
   public OutputStream append(StoragePath path) throws IOException {
     return fs.append(convertToHadoopPath(path));
diff --git a/hudi-io/src/main/java/org/apache/hudi/storage/HoodieStorage.java b/hudi-io/src/main/java/org/apache/hudi/storage/HoodieStorage.java
index 9ab5e9f9e08..adf9371c243 100644
--- a/hudi-io/src/main/java/org/apache/hudi/storage/HoodieStorage.java
+++ b/hudi-io/src/main/java/org/apache/hudi/storage/HoodieStorage.java
@@ -24,6 +24,7 @@ import org.apache.hudi.PublicAPIClass;
 import org.apache.hudi.PublicAPIMethod;
 import org.apache.hudi.common.util.Option;
 import org.apache.hudi.exception.HoodieIOException;
+import org.apache.hudi.io.SeekableDataInputStream;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -52,6 +53,12 @@ public abstract class HoodieStorage implements Closeable {
   @PublicAPIMethod(maturity = ApiMaturityLevel.EVOLVING)
   public abstract String getScheme();
 
+  /**
+   * @return the default block size.
+   */
+  @PublicAPIMethod(maturity = ApiMaturityLevel.EVOLVING)
+  public abstract int getDefaultBlockSize(StoragePath path);
+
   /**
    * Returns a URI which identifies this HoodieStorage.
    *
@@ -82,6 +89,17 @@ public abstract class HoodieStorage implements Closeable {
   @PublicAPIMethod(maturity = ApiMaturityLevel.EVOLVING)
   public abstract InputStream open(StoragePath path) throws IOException;
 
+  /**
+   * Opens an SeekableDataInputStream at the indicated path with seeks supported.
+   *
+   * @param path       the file to open.
+   * @param bufferSize buffer size to use.
+   * @return the InputStream to read from.
+   * @throws IOException IO error.
+   */
+  @PublicAPIMethod(maturity = ApiMaturityLevel.EVOLVING)
+  public abstract SeekableDataInputStream openSeekable(StoragePath path, int bufferSize) throws IOException;
+
   /**
    * Appends to an existing file (optional operation).
    *
@@ -332,6 +350,18 @@ public abstract class HoodieStorage implements Closeable {
     }
   }
 
+  /**
+   * Opens an SeekableDataInputStream at the indicated path with seeks supported.
+   *
+   * @param path the file to open.
+   * @return the InputStream to read from.
+   * @throws IOException IO error.
+   */
+  @PublicAPIMethod(maturity = ApiMaturityLevel.EVOLVING)
+  public SeekableDataInputStream openSeekable(StoragePath path) throws IOException {
+    return openSeekable(path, getDefaultBlockSize(path));
+  }
+
   /**
    * Lists the file info of the direct files/directories in the given list of paths,
    * if the paths are directory.
diff --git a/hudi-io/src/test/java/org/apache/hudi/io/storage/TestHoodieStorageBase.java b/hudi-io/src/test/java/org/apache/hudi/io/storage/TestHoodieStorageBase.java
index 460c831e1c0..e044599b115 100644
--- a/hudi-io/src/test/java/org/apache/hudi/io/storage/TestHoodieStorageBase.java
+++ b/hudi-io/src/test/java/org/apache/hudi/io/storage/TestHoodieStorageBase.java
@@ -20,6 +20,7 @@
 package org.apache.hudi.io.storage;
 
 import org.apache.hudi.common.util.Option;
+import org.apache.hudi.io.SeekableDataInputStream;
 import org.apache.hudi.io.util.IOUtils;
 import org.apache.hudi.storage.HoodieStorage;
 import org.apache.hudi.storage.StoragePath;
@@ -36,6 +37,7 @@ import java.io.OutputStream;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.nio.file.Path;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Comparator;
 import java.util.List;
@@ -148,6 +150,47 @@ public abstract class TestHoodieStorageBase {
     assertTrue(storage.createDirectory(path4));
   }
 
+  @Test
+  public void testSeekable() throws IOException {
+    HoodieStorage storage = getHoodieStorage();
+    StoragePath path = new StoragePath(getTempDir(), "testSeekable/1.file");
+    assertFalse(storage.exists(path));
+    byte[] data = new byte[] {2, 42, 49, (byte) 158, (byte) 233, 66, 9, 34, 79};
+
+    // By default, create overwrites the file
+    try (OutputStream stream = storage.create(path)) {
+      stream.write(data);
+      stream.flush();
+    }
+
+    try (SeekableDataInputStream seekableStream = storage.openSeekable(path)) {
+      validateSeekableDataInputStream(seekableStream, data);
+    }
+
+    try (SeekableDataInputStream seekableStream = storage.openSeekable(path, 2)) {
+      validateSeekableDataInputStream(seekableStream, data);
+    }
+  }
+
+  private void validateSeekableDataInputStream(SeekableDataInputStream seekableStream,
+                                               byte[] expectedData) throws IOException {
+    List<Integer> positionList = new ArrayList<>();
+    // Adding these positions for testing non-contiguous and backward seeks
+    positionList.add(1);
+    positionList.add(expectedData.length / 2);
+    positionList.add(expectedData.length - 1);
+    for (int i = 0; i < expectedData.length; i++) {
+      positionList.add(i);
+    }
+
+    assertEquals(0, seekableStream.getPos());
+    for (Integer pos : positionList) {
+      seekableStream.seek(pos);
+      assertEquals(pos, (int) seekableStream.getPos());
+      assertEquals(expectedData[pos], seekableStream.readByte());
+    }
+  }
+
   @Test
   public void testListing() throws IOException {
     HoodieStorage storage = getHoodieStorage();


(hudi) 02/28: [HUDI-7583] Read log block header only for the schema and instant time (#10984)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit a9c7eebd0fc8ffccf8859ae56147f2873d0f9892
Author: Y Ethan Guo <et...@gmail.com>
AuthorDate: Tue May 14 16:07:09 2024 -0700

    [HUDI-7583] Read log block header only for the schema and instant time (#10984)
---
 .../hudi/common/table/TableSchemaResolver.java     |  5 +-
 .../common/functional/TestHoodieLogFormat.java     |  2 +-
 .../hudi/common/table/TestTableSchemaResolver.java | 56 ++++++++++++++++++++++
 .../utilities/HoodieMetadataTableValidator.java    |  2 +-
 4 files changed, 62 insertions(+), 3 deletions(-)

diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/TableSchemaResolver.java b/hudi-common/src/main/java/org/apache/hudi/common/table/TableSchemaResolver.java
index f37dd4e7540..0344331ab75 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/TableSchemaResolver.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/TableSchemaResolver.java
@@ -385,7 +385,10 @@ public class TableSchemaResolver {
    * @return
    */
   public static MessageType readSchemaFromLogFile(FileSystem fs, Path path) throws IOException {
-    try (Reader reader = HoodieLogFormat.newReader(fs, new HoodieLogFile(path), null)) {
+    // We only need to read the schema from the log block header,
+    // so we read the block lazily to avoid reading block content
+    // containing the records
+    try (Reader reader = HoodieLogFormat.newReader(fs, new HoodieLogFile(path), null, true, false)) {
       HoodieDataBlock lastBlock = null;
       while (reader.hasNext()) {
         HoodieLogBlock block = reader.next();
diff --git a/hudi-common/src/test/java/org/apache/hudi/common/functional/TestHoodieLogFormat.java b/hudi-common/src/test/java/org/apache/hudi/common/functional/TestHoodieLogFormat.java
index 0b3bcc812ae..d4cb5021afc 100755
--- a/hudi-common/src/test/java/org/apache/hudi/common/functional/TestHoodieLogFormat.java
+++ b/hudi-common/src/test/java/org/apache/hudi/common/functional/TestHoodieLogFormat.java
@@ -2804,7 +2804,7 @@ public class TestHoodieLogFormat extends HoodieCommonTestHarness {
     }
   }
 
-  private static HoodieDataBlock getDataBlock(HoodieLogBlockType dataBlockType, List<IndexedRecord> records,
+  public static HoodieDataBlock getDataBlock(HoodieLogBlockType dataBlockType, List<IndexedRecord> records,
                                               Map<HeaderMetadataType, String> header) {
     return getDataBlock(dataBlockType, records.stream().map(HoodieAvroIndexedRecord::new).collect(Collectors.toList()), header, new Path("dummy_path"));
   }
diff --git a/hudi-common/src/test/java/org/apache/hudi/common/table/TestTableSchemaResolver.java b/hudi-common/src/test/java/org/apache/hudi/common/table/TestTableSchemaResolver.java
index b7f0ba8eba7..d8d0d8c9f72 100644
--- a/hudi-common/src/test/java/org/apache/hudi/common/table/TestTableSchemaResolver.java
+++ b/hudi-common/src/test/java/org/apache/hudi/common/table/TestTableSchemaResolver.java
@@ -19,13 +19,33 @@
 package org.apache.hudi.common.table;
 
 import org.apache.hudi.avro.AvroSchemaUtils;
+import org.apache.hudi.common.model.HoodieLogFile;
+import org.apache.hudi.common.table.log.HoodieLogFormat;
+import org.apache.hudi.common.table.log.block.HoodieDataBlock;
+import org.apache.hudi.common.table.log.block.HoodieLogBlock;
 import org.apache.hudi.common.testutils.HoodieTestDataGenerator;
+import org.apache.hudi.common.testutils.SchemaTestUtil;
 import org.apache.hudi.common.util.Option;
 import org.apache.hudi.internal.schema.HoodieSchemaException;
 
 import org.apache.avro.Schema;
+import org.apache.avro.generic.IndexedRecord;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.parquet.avro.AvroSchemaConverter;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.apache.hudi.common.functional.TestHoodieLogFormat.getDataBlock;
+import static org.apache.hudi.common.table.log.block.HoodieLogBlock.HoodieLogBlockType.AVRO_DATA_BLOCK;
+import static org.apache.hudi.common.testutils.SchemaTestUtil.getSimpleSchema;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotEquals;
 import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -35,6 +55,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
  */
 public class TestTableSchemaResolver {
 
+  @TempDir
+  public java.nio.file.Path tempDir;
+
   @Test
   public void testRecreateSchemaWhenDropPartitionColumns() {
     Schema originSchema = new Schema.Parser().parse(HoodieTestDataGenerator.TRIP_EXAMPLE_SCHEMA);
@@ -65,4 +88,37 @@ public class TestTableSchemaResolver {
       assertTrue(e.getMessage().contains("Partial partition fields are still in the schema"));
     }
   }
+
+  @Test
+  public void testReadSchemaFromLogFile() throws IOException, URISyntaxException, InterruptedException {
+    String testDir = initTestDir("read_schema_from_log_file");
+    Path partitionPath = new Path(testDir, "partition1");
+    Schema expectedSchema = getSimpleSchema();
+    Path logFilePath = writeLogFile(partitionPath, expectedSchema);
+    assertEquals(
+        new AvroSchemaConverter().convert(expectedSchema),
+        TableSchemaResolver.readSchemaFromLogFile(
+            logFilePath.getFileSystem(new Configuration()), logFilePath));
+  }
+
+  private String initTestDir(String folderName) throws IOException {
+    java.nio.file.Path basePath = tempDir.resolve(folderName);
+    java.nio.file.Files.createDirectories(basePath);
+    return basePath.toString();
+  }
+
+  private Path writeLogFile(Path partitionPath, Schema schema) throws IOException, URISyntaxException, InterruptedException {
+    FileSystem fs = partitionPath.getFileSystem(new Configuration());
+    HoodieLogFormat.Writer writer =
+        HoodieLogFormat.newWriterBuilder().onParentPath(partitionPath).withFileExtension(HoodieLogFile.DELTA_EXTENSION)
+            .withFileId("test-fileid1").overBaseCommit("100").withFs(fs).build();
+    List<IndexedRecord> records = SchemaTestUtil.generateTestRecords(0, 100);
+    Map<HoodieLogBlock.HeaderMetadataType, String> header = new HashMap<>();
+    header.put(HoodieLogBlock.HeaderMetadataType.INSTANT_TIME, "100");
+    header.put(HoodieLogBlock.HeaderMetadataType.SCHEMA, schema.toString());
+    HoodieDataBlock dataBlock = getDataBlock(AVRO_DATA_BLOCK, records, header);
+    writer.appendBlock(dataBlock);
+    writer.close();
+    return writer.getLogFile().getPath();
+  }
 }
diff --git a/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieMetadataTableValidator.java b/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieMetadataTableValidator.java
index 0e6630967b3..9d91999bac5 100644
--- a/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieMetadataTableValidator.java
+++ b/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieMetadataTableValidator.java
@@ -1193,7 +1193,7 @@ public class HoodieMetadataTableValidator implements Serializable {
         }
         Schema readerSchema = converter.convert(messageType);
         reader =
-            HoodieLogFormat.newReader(fs, new HoodieLogFile(logFilePathStr), readerSchema);
+            HoodieLogFormat.newReader(fs, new HoodieLogFile(logFilePathStr), readerSchema, true, false);
         // read the avro blocks
         if (reader.hasNext()) {
           HoodieLogBlock block = reader.next();


(hudi) 17/28: [HUDI-6762] Removed usages of MetadataRecordsGenerationParams (#10962)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 566039010cf3725e751cb3c4ca8641f42ff5bdb6
Author: Vova Kolmakov <wo...@gmail.com>
AuthorDate: Tue May 14 16:10:59 2024 -0700

    [HUDI-6762] Removed usages of MetadataRecordsGenerationParams (#10962)
    
    Co-authored-by: Vova Kolmakov <ko...@huawei-partners.com>
---
 .../metadata/HoodieBackedTableMetadataWriter.java  | 118 +++++----
 .../hudi/metadata/HoodieTableMetadataUtil.java     | 266 ++++++++++++---------
 .../metadata/MetadataRecordsGenerationParams.java  |  89 -------
 3 files changed, 204 insertions(+), 269 deletions(-)

diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metadata/HoodieBackedTableMetadataWriter.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metadata/HoodieBackedTableMetadataWriter.java
index 329ff261f53..3537a6ddb40 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metadata/HoodieBackedTableMetadataWriter.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metadata/HoodieBackedTableMetadataWriter.java
@@ -329,12 +329,6 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
       LOG.warn("Metadata Table will need to be re-initialized as no instants were found");
       return true;
     }
-
-    final String latestMetadataInstantTimestamp = latestMetadataInstant.get().getTimestamp();
-    if (latestMetadataInstantTimestamp.startsWith(SOLO_COMMIT_TIMESTAMP)) { // the initialization timestamp is SOLO_COMMIT_TIMESTAMP + offset
-      return false;
-    }
-
     return false;
   }
 
@@ -394,8 +388,8 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
     for (MetadataPartitionType partitionType : partitionsToInit) {
       // Find the commit timestamp to use for this partition. Each initialization should use its own unique commit time.
       String commitTimeForPartition = generateUniqueCommitInstantTime(initializationTime);
-
-      LOG.info("Initializing MDT partition " + partitionType.name() + " at instant " + commitTimeForPartition);
+      String partitionTypeName = partitionType.name();
+      LOG.info("Initializing MDT partition {} at instant {}", partitionTypeName, commitTimeForPartition);
 
       Pair<Integer, HoodieData<HoodieRecord>> fileGroupCountAndRecordsPair;
       try {
@@ -413,24 +407,26 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
             fileGroupCountAndRecordsPair = initializeRecordIndexPartition();
             break;
           default:
-            throw new HoodieMetadataException("Unsupported MDT partition type: " + partitionType);
+            throw new HoodieMetadataException(String.format("Unsupported MDT partition type: %s", partitionType));
         }
       } catch (Exception e) {
         String metricKey = partitionType.getPartitionPath() + "_" + HoodieMetadataMetrics.BOOTSTRAP_ERR_STR;
         metrics.ifPresent(m -> m.setMetric(metricKey, 1));
-        LOG.error("Bootstrap on " + partitionType.getPartitionPath() + " partition failed for "
-            + metadataMetaClient.getBasePath(), e);
-        throw new HoodieMetadataException(partitionType.getPartitionPath()
-            + " bootstrap failed for " + metadataMetaClient.getBasePath(), e);
+        String errMsg = String.format("Bootstrap on %s partition failed for %s",
+            partitionType.getPartitionPath(), metadataMetaClient.getBasePathV2());
+        LOG.error(errMsg, e);
+        throw new HoodieMetadataException(errMsg, e);
       }
 
-      LOG.info(String.format("Initializing %s index with %d mappings and %d file groups.", partitionType.name(), fileGroupCountAndRecordsPair.getKey(),
-          fileGroupCountAndRecordsPair.getValue().count()));
+      if (LOG.isInfoEnabled()) {
+        LOG.info("Initializing {} index with {} mappings and {} file groups.", partitionTypeName, fileGroupCountAndRecordsPair.getKey(),
+            fileGroupCountAndRecordsPair.getValue().count());
+      }
       HoodieTimer partitionInitTimer = HoodieTimer.start();
 
       // Generate the file groups
       final int fileGroupCount = fileGroupCountAndRecordsPair.getKey();
-      ValidationUtils.checkArgument(fileGroupCount > 0, "FileGroup count for MDT partition " + partitionType.name() + " should be > 0");
+      ValidationUtils.checkArgument(fileGroupCount > 0, "FileGroup count for MDT partition " + partitionTypeName + " should be > 0");
       initializeFileGroups(dataMetaClient, partitionType, commitTimeForPartition, fileGroupCount);
 
       // Perform the commit using bulkCommit
@@ -441,7 +437,7 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
       // initialize the metadata reader again so the MDT partition can be read after initialization
       initMetadataReader();
       long totalInitTime = partitionInitTimer.endTimer();
-      LOG.info(String.format("Initializing %s index in metadata table took " + totalInitTime + " in ms", partitionType.name()));
+      LOG.info("Initializing {} index in metadata table took {} in ms", partitionTypeName, totalInitTime);
     }
 
     return true;
@@ -474,7 +470,8 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
 
   private Pair<Integer, HoodieData<HoodieRecord>> initializeColumnStatsPartition(Map<String, Map<String, Long>> partitionToFilesMap) {
     HoodieData<HoodieRecord> records = HoodieTableMetadataUtil.convertFilesToColumnStatsRecords(
-        engineContext, Collections.emptyMap(), partitionToFilesMap, getRecordsGenerationParams());
+        engineContext, Collections.emptyMap(), partitionToFilesMap, dataMetaClient, dataWriteConfig.isMetadataColumnStatsIndexEnabled(),
+            dataWriteConfig.getColumnStatsIndexParallelism(), dataWriteConfig.getColumnsEnabledForColumnStatsIndex());
 
     final int fileGroupCount = dataWriteConfig.getMetadataConfig().getColumnStatsIndexFileGroupCount();
     return Pair.of(fileGroupCount, records);
@@ -482,7 +479,8 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
 
   private Pair<Integer, HoodieData<HoodieRecord>> initializeBloomFiltersPartition(String createInstantTime, Map<String, Map<String, Long>> partitionToFilesMap) {
     HoodieData<HoodieRecord> records = HoodieTableMetadataUtil.convertFilesToBloomFilterRecords(
-        engineContext, Collections.emptyMap(), partitionToFilesMap, getRecordsGenerationParams(), createInstantTime);
+        engineContext, Collections.emptyMap(), partitionToFilesMap, createInstantTime, dataMetaClient,
+            dataWriteConfig.getBloomIndexParallelism(), dataWriteConfig.getBloomFilterType());
 
     final int fileGroupCount = dataWriteConfig.getMetadataConfig().getBloomFilterIndexFileGroupCount();
     return Pair.of(fileGroupCount, records);
@@ -501,8 +499,7 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
           .map(basefile -> Pair.of(partition, basefile)).collect(Collectors.toList()));
     }
 
-    LOG.info("Initializing record index from " + partitionBaseFilePairs.size() + " base files in "
-        + partitions.size() + " partitions");
+    LOG.info("Initializing record index from {} base files in {} partitions", partitionBaseFilePairs.size(), partitions.size());
 
     // Collect record keys from the files in parallel
     HoodieData<HoodieRecord> records = readRecordKeysFromBaseFiles(
@@ -523,7 +520,7 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
         dataWriteConfig.getRecordIndexMaxFileGroupCount(), dataWriteConfig.getRecordIndexGrowthFactor(),
         dataWriteConfig.getRecordIndexMaxFileGroupSizeBytes());
 
-    LOG.info(String.format("Initializing record index with %d mappings and %d file groups.", recordCount, fileGroupCount));
+    LOG.info("Initializing record index with {} mappings and {} file groups.", recordCount, fileGroupCount);
     return Pair.of(fileGroupCount, records);
   }
 
@@ -565,8 +562,8 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
 
     if (!pendingDataInstant.isEmpty()) {
       metrics.ifPresent(m -> m.updateMetrics(HoodieMetadataMetrics.BOOTSTRAP_ERR_STR, 1));
-      LOG.warn("Cannot initialize metadata table as operation(s) are in progress on the dataset: "
-          + Arrays.toString(pendingDataInstant.toArray()));
+      LOG.warn("Cannot initialize metadata table as operation(s) are in progress on the dataset: {}",
+          Arrays.toString(pendingDataInstant.toArray()));
       return true;
     }
     return false;
@@ -599,7 +596,7 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
     final int fileListingParallelism = metadataWriteConfig.getFileListingParallelism();
     SerializableConfiguration conf = new SerializableConfiguration(dataMetaClient.getHadoopConf());
     final String dirFilterRegex = dataWriteConfig.getMetadataConfig().getDirectoryFilterRegex();
-    final String datasetBasePath = dataMetaClient.getBasePath();
+    final String datasetBasePath = dataMetaClient.getBasePathV2().toString();
     SerializablePath serializableBasePath = new SerializablePath(new CachingPath(datasetBasePath));
 
     while (!pathsToList.isEmpty()) {
@@ -621,7 +618,7 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
         if (!dirFilterRegex.isEmpty()) {
           final String relativePath = dirInfo.getRelativePath();
           if (!relativePath.isEmpty() && relativePath.matches(dirFilterRegex)) {
-            LOG.info("Ignoring directory " + relativePath + " which matches the filter regex " + dirFilterRegex);
+            LOG.info("Ignoring directory {} which matches the filter regex {}", relativePath, dirFilterRegex);
             continue;
           }
         }
@@ -733,7 +730,7 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
       LOG.warn("Deleting Metadata Table partition: " + partitionPath);
       dataMetaClient.getFs().delete(new Path(metadataWriteConfig.getBasePath(), partitionPath), true);
       // delete corresponding pending indexing instant file in the timeline
-      LOG.warn("Deleting pending indexing instant from the timeline for partition: " + partitionPath);
+      LOG.warn("Deleting pending indexing instant from the timeline for partition: {}", partitionPath);
       deletePendingIndexingInstant(dataMetaClient, partitionPath);
     }
     closeInternal();
@@ -755,7 +752,7 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
               metaClient.getActiveTimeline().deleteInstantFileIfExists(getIndexInflightInstant(instant.getTimestamp()));
             }
           } catch (IOException e) {
-            LOG.error("Failed to delete the instant file corresponding to " + instant);
+            LOG.error("Failed to delete the instant file corresponding to {}", instant);
           }
         });
   }
@@ -775,18 +772,6 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
     }
   }
 
-  private MetadataRecordsGenerationParams getRecordsGenerationParams() {
-    return new MetadataRecordsGenerationParams(
-        dataMetaClient,
-        enabledPartitionTypes,
-        dataWriteConfig.getBloomFilterType(),
-        dataWriteConfig.getMetadataBloomFilterIndexParallelism(),
-        dataWriteConfig.isMetadataColumnStatsIndexEnabled(),
-        dataWriteConfig.getColumnStatsIndexParallelism(),
-        dataWriteConfig.getColumnsEnabledForColumnStatsIndex(),
-        dataWriteConfig.getColumnsEnabledForBloomFilterIndex());
-  }
-
   /**
    * Interface to assist in converting commit metadata to List of HoodieRecords to be written to metadata table.
    * Updates of different commit metadata uses the same method to convert to HoodieRecords and hence.
@@ -837,8 +822,8 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
     List<MetadataPartitionType> partitionTypes = new ArrayList<>();
     indexPartitionInfos.forEach(indexPartitionInfo -> {
       String relativePartitionPath = indexPartitionInfo.getMetadataPartitionPath();
-      LOG.info(String.format("Creating a new metadata index for partition '%s' under path %s upto instant %s",
-          relativePartitionPath, metadataWriteConfig.getBasePath(), indexUptoInstantTime));
+      LOG.info("Creating a new metadata index for partition '{}' under path {} upto instant {}",
+          relativePartitionPath, metadataWriteConfig.getBasePath(), indexUptoInstantTime);
 
       // return early and populate enabledPartitionTypes correctly (check in initialCommit)
       MetadataPartitionType partitionType = MetadataPartitionType.valueOf(relativePartitionPath.toUpperCase(Locale.ROOT));
@@ -866,7 +851,10 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
     processAndCommit(instantTime, () -> {
       Map<MetadataPartitionType, HoodieData<HoodieRecord>> partitionToRecordMap =
           HoodieTableMetadataUtil.convertMetadataToRecords(
-              engineContext, dataWriteConfig, commitMetadata, instantTime, getRecordsGenerationParams());
+              engineContext, dataWriteConfig, commitMetadata, instantTime, dataMetaClient,
+                  enabledPartitionTypes, dataWriteConfig.getBloomFilterType(),
+                  dataWriteConfig.getBloomIndexParallelism(), dataWriteConfig.isMetadataColumnStatsIndexEnabled(),
+                  dataWriteConfig.getColumnStatsIndexParallelism(), dataWriteConfig.getColumnsEnabledForColumnStatsIndex());
 
       // Updates for record index are created by parsing the WriteStatus which is a hudi-client object. Hence, we cannot yet move this code
       // to the HoodieTableMetadataUtil class in hudi-common.
@@ -883,7 +871,10 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
     processAndCommit(instantTime, () -> {
       Map<MetadataPartitionType, HoodieData<HoodieRecord>> partitionToRecordMap =
           HoodieTableMetadataUtil.convertMetadataToRecords(
-              engineContext, dataWriteConfig, commitMetadata, instantTime, getRecordsGenerationParams());
+              engineContext, dataWriteConfig, commitMetadata, instantTime, dataMetaClient,
+                  enabledPartitionTypes, dataWriteConfig.getBloomFilterType(),
+                  dataWriteConfig.getBloomIndexParallelism(), dataWriteConfig.isMetadataColumnStatsIndexEnabled(),
+                  dataWriteConfig.getColumnStatsIndexParallelism(), dataWriteConfig.getColumnsEnabledForColumnStatsIndex());
       HoodieData<HoodieRecord> additionalUpdates = getRecordIndexAdditionalUpserts(records, commitMetadata);
       partitionToRecordMap.put(MetadataPartitionType.RECORD_INDEX, records.union(additionalUpdates));
       return partitionToRecordMap;
@@ -900,7 +891,9 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
   @Override
   public void update(HoodieCleanMetadata cleanMetadata, String instantTime) {
     processAndCommit(instantTime, () -> HoodieTableMetadataUtil.convertMetadataToRecords(engineContext,
-        cleanMetadata, getRecordsGenerationParams(), instantTime));
+            cleanMetadata, instantTime, dataMetaClient, enabledPartitionTypes,
+            dataWriteConfig.getBloomIndexParallelism(), dataWriteConfig.isMetadataColumnStatsIndexEnabled(),
+            dataWriteConfig.getColumnStatsIndexParallelism(), dataWriteConfig.getColumnsEnabledForColumnStatsIndex()));
     closeInternal();
   }
 
@@ -915,22 +908,22 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
     dataMetaClient.reloadActiveTimeline();
 
     // Fetch the commit to restore to (savepointed commit time)
-    HoodieInstant restoreInstant = new HoodieInstant(HoodieInstant.State.REQUESTED, HoodieTimeline.RESTORE_ACTION, instantTime);
+    HoodieInstant restoreInstant = new HoodieInstant(REQUESTED, HoodieTimeline.RESTORE_ACTION, instantTime);
     HoodieInstant requested = HoodieTimeline.getRestoreRequestedInstant(restoreInstant);
     HoodieRestorePlan restorePlan = null;
     try {
       restorePlan = TimelineMetadataUtils.deserializeAvroMetadata(
           dataMetaClient.getActiveTimeline().readRestoreInfoAsBytes(requested).get(), HoodieRestorePlan.class);
     } catch (IOException e) {
-      throw new HoodieIOException("Deserialization of restore plan failed whose restore instant time is " + instantTime + " in data table", e);
+      throw new HoodieIOException(String.format("Deserialization of restore plan failed whose restore instant time is %s in data table", instantTime), e);
     }
     final String restoreToInstantTime = restorePlan.getSavepointToRestoreTimestamp();
-    LOG.info("Triggering restore to " + restoreToInstantTime + " in metadata table");
+    LOG.info("Triggering restore to {} in metadata table", restoreToInstantTime);
 
     // fetch the earliest commit to retain and ensure the base file prior to the time to restore is present
     List<HoodieFileGroup> filesGroups = metadata.getMetadataFileSystemView().getAllFileGroups(MetadataPartitionType.FILES.getPartitionPath()).collect(Collectors.toList());
 
-    boolean cannotRestore = filesGroups.stream().map(fileGroup -> fileGroup.getAllFileSlices().map(fileSlice -> fileSlice.getBaseInstantTime()).anyMatch(
+    boolean cannotRestore = filesGroups.stream().map(fileGroup -> fileGroup.getAllFileSlices().map(FileSlice::getBaseInstantTime).anyMatch(
         instantTime1 -> HoodieTimeline.compareTimestamps(instantTime1, LESSER_THAN_OR_EQUALS, restoreToInstantTime))).anyMatch(canRestore -> !canRestore);
     if (cannotRestore) {
       throw new HoodieMetadataException(String.format("Can't restore to %s since there is no base file in MDT lesser than the commit to restore to. "
@@ -1005,8 +998,8 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
           throw new HoodieMetadataException("Failed to rollback deltacommit at " + commitToRollbackInstantTime);
         }
       } else {
-        LOG.info(String.format("Ignoring rollback of instant %s at %s. The commit to rollback is not found in MDT",
-            commitToRollbackInstantTime, instantTime));
+        LOG.info("Ignoring rollback of instant {} at {}. The commit to rollback is not found in MDT",
+            commitToRollbackInstantTime, instantTime);
       }
       closeInternal();
     }
@@ -1069,7 +1062,7 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
 
     if (!metadataMetaClient.getActiveTimeline().getCommitsTimeline().containsInstant(instantTime)) {
       // if this is a new commit being applied to metadata for the first time
-      LOG.info("New commit at " + instantTime + " being applied to MDT.");
+      LOG.info("New commit at {} being applied to MDT.", instantTime);
     } else {
       // this code path refers to a re-attempted commit that:
       //   1. got committed to metadata table, but failed in datatable.
@@ -1081,12 +1074,12 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
       // already part of completed commit. So, we have to manually rollback the completed instant and proceed.
       Option<HoodieInstant> alreadyCompletedInstant = metadataMetaClient.getActiveTimeline().filterCompletedInstants().filter(entry -> entry.getTimestamp().equals(instantTime))
           .lastInstant();
-      LOG.info(String.format("%s completed commit at %s being applied to MDT.",
-          alreadyCompletedInstant.isPresent() ? "Already" : "Partially", instantTime));
+      LOG.info("{} completed commit at {} being applied to MDT.",
+          alreadyCompletedInstant.isPresent() ? "Already" : "Partially", instantTime);
 
       // Rollback the previous commit
       if (!writeClient.rollback(instantTime)) {
-        throw new HoodieMetadataException("Failed to rollback deltacommit at " + instantTime + " from MDT");
+        throw new HoodieMetadataException(String.format("Failed to rollback deltacommit at %s from MDT", instantTime));
       }
       metadataMetaClient.reloadActiveTimeline();
     }
@@ -1153,7 +1146,7 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
         fileSlices = HoodieTableMetadataUtil.getPartitionLatestFileSlicesIncludingInflight(metadataMetaClient, Option.ofNullable(fsView), partitionName);
       }
       final int fileGroupCount = fileSlices.size();
-      ValidationUtils.checkArgument(fileGroupCount > 0, "FileGroup count for MDT partition " + partitionName + " should be >0");
+      ValidationUtils.checkArgument(fileGroupCount > 0, String.format("FileGroup count for MDT partition %s should be >0", partitionName));
 
       List<FileSlice> finalFileSlices = fileSlices;
       HoodieData<HoodieRecord> rddSinglePartitionRecords = records.map(r -> {
@@ -1250,9 +1243,9 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
     // and again w/ C6, we will re-attempt compaction at which point latest delta commit is C4 in MDT.
     // and so we try compaction w/ instant C4001. So, we can avoid compaction if we already have compaction w/ same instant time.
     if (metadataMetaClient.getActiveTimeline().filterCompletedInstants().containsInstant(compactionInstantTime)) {
-      LOG.info(String.format("Compaction with same %s time is already present in the timeline.", compactionInstantTime));
+      LOG.info("Compaction with same {} time is already present in the timeline.", compactionInstantTime);
     } else if (writeClient.scheduleCompactionAtInstant(compactionInstantTime, Option.empty())) {
-      LOG.info("Compaction is scheduled for timestamp " + compactionInstantTime);
+      LOG.info("Compaction is scheduled for timestamp {}", compactionInstantTime);
       writeClient.compact(compactionInstantTime);
     } else if (metadataWriteConfig.isLogCompactionEnabled()) {
       // Schedule and execute log compaction with suffixes based on the same instant time. This ensures that any future
@@ -1260,9 +1253,9 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
       // metadata table.
       final String logCompactionInstantTime = HoodieTableMetadataUtil.createLogCompactionTimestamp(latestDeltacommitTime);
       if (metadataMetaClient.getActiveTimeline().filterCompletedInstants().containsInstant(logCompactionInstantTime)) {
-        LOG.info(String.format("Log compaction with same %s time is already present in the timeline.", logCompactionInstantTime));
+        LOG.info("Log compaction with same {} time is already present in the timeline.", logCompactionInstantTime);
       } else if (writeClient.scheduleLogCompactionAtInstant(logCompactionInstantTime, Option.empty())) {
-        LOG.info("Log compaction is scheduled for timestamp " + logCompactionInstantTime);
+        LOG.info("Log compaction is scheduled for timestamp {}", logCompactionInstantTime);
         writeClient.logCompact(logCompactionInstantTime);
       }
     }
@@ -1387,8 +1380,7 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
               // newLocation should have the same fileID as currentLocation. The instantTimes differ as newLocation's
               // instantTime refers to the current commit which was completed.
               if (!recordDelegate.getCurrentLocation().get().getFileId().equals(newLocation.get().getFileId())) {
-                final String msg = String.format("Detected update in location of record with key %s from %s "
-                        + " to %s. The fileID should not change.",
+                final String msg = String.format("Detected update in location of record with key %s from %s to %s. The fileID should not change.",
                     recordDelegate, recordDelegate.getCurrentLocation().get(), newLocation.get());
                 LOG.error(msg);
                 throw new HoodieMetadataException(msg);
@@ -1517,7 +1509,7 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
           // Regular HUDI data file (base file or log file)
           String dataFileCommitTime = FSUtils.getCommitTime(status.getPath().getName());
           // Limit the file listings to files which were created before the maxInstant time.
-          if (HoodieTimeline.compareTimestamps(dataFileCommitTime, HoodieTimeline.LESSER_THAN_OR_EQUALS, maxInstantTime)) {
+          if (HoodieTimeline.compareTimestamps(dataFileCommitTime, LESSER_THAN_OR_EQUALS, maxInstantTime)) {
             filenameToSizeMap.put(status.getPath().getName(), status.getLen());
           }
         }
diff --git a/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieTableMetadataUtil.java b/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieTableMetadataUtil.java
index 503e3351d8c..3321451541b 100644
--- a/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieTableMetadataUtil.java
+++ b/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieTableMetadataUtil.java
@@ -144,6 +144,9 @@ public class HoodieTableMetadataUtil {
   public static final String PARTITION_NAME_BLOOM_FILTERS = "bloom_filters";
   public static final String PARTITION_NAME_RECORD_INDEX = "record_index";
 
+  private HoodieTableMetadataUtil() {
+  }
+
   // Suffix to use for various operations on MDT
   private enum OperationSuffix {
     COMPACTION("001"),
@@ -174,7 +177,7 @@ public class HoodieTableMetadataUtil {
   // are reserved for future operations on the MDT.
   private static final int PARTITION_INITIALIZATION_TIME_SUFFIX = 10; // corresponds to "010";
   // we have max of 4 partitions (FILES, COL_STATS, BLOOM, RLI)
-  private static final List<String> VALID_PARTITION_INITIALIZATION_TIME_SUFFIXES = Arrays.asList("010","011","012","013");
+  private static final List<String> VALID_PARTITION_INITIALIZATION_TIME_SUFFIXES = Arrays.asList("010", "011", "012", "013");
 
   /**
    * Returns whether the files partition of metadata table is ready for read.
@@ -218,7 +221,7 @@ public class HoodieTableMetadataUtil {
       // For each column (field) we have to index update corresponding column stats
       // with the values from this record
       targetFields.forEach(field -> {
-        ColumnStats colStats = allColumnStats.computeIfAbsent(field.name(), (ignored) -> new ColumnStats());
+        ColumnStats colStats = allColumnStats.computeIfAbsent(field.name(), ignored -> new ColumnStats());
 
         GenericRecord genericRecord = (GenericRecord) record;
 
@@ -245,7 +248,7 @@ public class HoodieTableMetadataUtil {
     });
 
     Collector<HoodieColumnRangeMetadata<Comparable>, ?, Map<String, HoodieColumnRangeMetadata<Comparable>>> collector =
-        Collectors.toMap(colRangeMetadata -> colRangeMetadata.getColumnName(), Function.identity());
+        Collectors.toMap(HoodieColumnRangeMetadata::getColumnName, Function.identity());
 
     return (Map<String, HoodieColumnRangeMetadata<Comparable>>) targetFields.stream()
         .map(field -> {
@@ -326,28 +329,44 @@ public class HoodieTableMetadataUtil {
   /**
    * Convert commit action to metadata records for the enabled partition types.
    *
-   * @param commitMetadata          - Commit action metadata
-   * @param hoodieConfig            - Hudi configs
-   * @param instantTime             - Action instant time
-   * @param recordsGenerationParams - Parameters for the record generation
+   * @param context                          - Engine context to use
+   * @param hoodieConfig                     - Hudi configs
+   * @param commitMetadata                   - Commit action metadata
+   * @param instantTime                      - Action instant time
+   * @param dataMetaClient                   - HoodieTableMetaClient for data
+   * @param enabledPartitionTypes            - List of enabled MDT partitions
+   * @param bloomFilterType                  - Type of generated bloom filter records
+   * @param bloomIndexParallelism            - Parallelism for bloom filter record generation
+   * @param isColumnStatsIndexEnabled        - Is column stats index enabled
+   * @param columnStatsIndexParallelism      - Parallelism for column stats index records generation
+   * @param targetColumnsForColumnStatsIndex - List of columns for column stats index
    * @return Map of partition to metadata records for the commit action
    */
-  public static Map<MetadataPartitionType, HoodieData<HoodieRecord>> convertMetadataToRecords(
-      HoodieEngineContext context, HoodieConfig hoodieConfig, HoodieCommitMetadata commitMetadata,
-      String instantTime, MetadataRecordsGenerationParams recordsGenerationParams) {
+  public static Map<MetadataPartitionType, HoodieData<HoodieRecord>> convertMetadataToRecords(HoodieEngineContext context,
+                                                                                              HoodieConfig hoodieConfig,
+                                                                                              HoodieCommitMetadata commitMetadata,
+                                                                                              String instantTime,
+                                                                                              HoodieTableMetaClient dataMetaClient,
+                                                                                              List<MetadataPartitionType> enabledPartitionTypes,
+                                                                                              String bloomFilterType,
+                                                                                              int bloomIndexParallelism,
+                                                                                              boolean isColumnStatsIndexEnabled,
+                                                                                              int columnStatsIndexParallelism,
+                                                                                              List<String> targetColumnsForColumnStatsIndex) {
     final Map<MetadataPartitionType, HoodieData<HoodieRecord>> partitionToRecordsMap = new HashMap<>();
     final HoodieData<HoodieRecord> filesPartitionRecordsRDD = context.parallelize(
         convertMetadataToFilesPartitionRecords(commitMetadata, instantTime), 1);
     partitionToRecordsMap.put(MetadataPartitionType.FILES, filesPartitionRecordsRDD);
 
-    if (recordsGenerationParams.getEnabledPartitionTypes().contains(MetadataPartitionType.BLOOM_FILTERS)) {
+    if (enabledPartitionTypes.contains(MetadataPartitionType.BLOOM_FILTERS)) {
       final HoodieData<HoodieRecord> metadataBloomFilterRecords = convertMetadataToBloomFilterRecords(
-          context, hoodieConfig, commitMetadata, instantTime, recordsGenerationParams);
+          context, hoodieConfig, commitMetadata, instantTime, dataMetaClient, bloomFilterType, bloomIndexParallelism);
       partitionToRecordsMap.put(MetadataPartitionType.BLOOM_FILTERS, metadataBloomFilterRecords);
     }
 
-    if (recordsGenerationParams.getEnabledPartitionTypes().contains(MetadataPartitionType.COLUMN_STATS)) {
-      final HoodieData<HoodieRecord> metadataColumnStatsRDD = convertMetadataToColumnStatsRecords(commitMetadata, context, recordsGenerationParams);
+    if (enabledPartitionTypes.contains(MetadataPartitionType.COLUMN_STATS)) {
+      final HoodieData<HoodieRecord> metadataColumnStatsRDD = convertMetadataToColumnStatsRecords(commitMetadata, context,
+              dataMetaClient, isColumnStatsIndexEnabled, columnStatsIndexParallelism, targetColumnsForColumnStatsIndex);
       partitionToRecordsMap.put(MetadataPartitionType.COLUMN_STATS, metadataColumnStatsRDD);
     }
     return partitionToRecordsMap;
@@ -384,7 +403,7 @@ public class HoodieTableMetadataUtil {
                         String pathWithPartition = stat.getPath();
                         if (pathWithPartition == null) {
                           // Empty partition
-                          LOG.warn("Unable to find path in write stat to update metadata table " + stat);
+                          LOG.warn("Unable to find path in write stat to update metadata table {}", stat);
                           return map;
                         }
 
@@ -398,9 +417,7 @@ public class HoodieTableMetadataUtil {
 
                         Map<String, Long> cdcPathAndSizes = stat.getCdcStats();
                         if (cdcPathAndSizes != null && !cdcPathAndSizes.isEmpty()) {
-                          cdcPathAndSizes.entrySet().forEach(cdcEntry -> {
-                            map.put(FSUtils.getFileName(cdcEntry.getKey(), partitionStatName), cdcEntry.getValue());
-                          });
+                          cdcPathAndSizes.forEach((key, value) -> map.put(FSUtils.getFileName(key, partitionStatName), value));
                         }
                         return map;
                       },
@@ -414,8 +431,8 @@ public class HoodieTableMetadataUtil {
 
     records.addAll(updatedPartitionFilesRecords);
 
-    LOG.info(String.format("Updating at %s from Commit/%s. #partitions_updated=%d, #files_added=%d", instantTime, commitMetadata.getOperationType(),
-        records.size(), newFileCount.value()));
+    LOG.info("Updating at {} from Commit/{}. #partitions_updated={}, #files_added={}", instantTime, commitMetadata.getOperationType(),
+        records.size(), newFileCount.value());
 
     return records;
   }
@@ -444,21 +461,28 @@ public class HoodieTableMetadataUtil {
    * Convert commit action metadata to bloom filter records.
    *
    * @param context                 - Engine context to use
+   * @param hoodieConfig            - Hudi configs
    * @param commitMetadata          - Commit action metadata
    * @param instantTime             - Action instant time
-   * @param recordsGenerationParams - Parameters for bloom filter record generation
+   * @param dataMetaClient          - HoodieTableMetaClient for data
+   * @param bloomFilterType         - Type of generated bloom filter records
+   * @param bloomIndexParallelism   - Parallelism for bloom filter record generation
    * @return HoodieData of metadata table records
    */
-  public static HoodieData<HoodieRecord> convertMetadataToBloomFilterRecords(
-      HoodieEngineContext context, HoodieConfig hoodieConfig, HoodieCommitMetadata commitMetadata,
-      String instantTime, MetadataRecordsGenerationParams recordsGenerationParams) {
+  public static HoodieData<HoodieRecord> convertMetadataToBloomFilterRecords(HoodieEngineContext context,
+                                                                             HoodieConfig hoodieConfig,
+                                                                             HoodieCommitMetadata commitMetadata,
+                                                                             String instantTime,
+                                                                             HoodieTableMetaClient dataMetaClient,
+                                                                             String bloomFilterType,
+                                                                             int bloomIndexParallelism) {
     final List<HoodieWriteStat> allWriteStats = commitMetadata.getPartitionToWriteStats().values().stream()
-        .flatMap(entry -> entry.stream()).collect(Collectors.toList());
+        .flatMap(Collection::stream).collect(Collectors.toList());
     if (allWriteStats.isEmpty()) {
       return context.emptyHoodieData();
     }
 
-    final int parallelism = Math.max(Math.min(allWriteStats.size(), recordsGenerationParams.getBloomIndexParallelism()), 1);
+    final int parallelism = Math.max(Math.min(allWriteStats.size(), bloomIndexParallelism), 1);
     HoodieData<HoodieWriteStat> allWriteStatsRDD = context.parallelize(allWriteStats, parallelism);
     return allWriteStatsRDD.flatMap(hoodieWriteStat -> {
       final String partition = hoodieWriteStat.getPartitionPath();
@@ -471,7 +495,7 @@ public class HoodieTableMetadataUtil {
       String pathWithPartition = hoodieWriteStat.getPath();
       if (pathWithPartition == null) {
         // Empty partition
-        LOG.error("Failed to find path in write stat to update metadata table " + hoodieWriteStat);
+        LOG.error("Failed to find path in write stat to update metadata table {}", hoodieWriteStat);
         return Collections.emptyListIterator();
       }
 
@@ -480,28 +504,26 @@ public class HoodieTableMetadataUtil {
         return Collections.emptyListIterator();
       }
 
-      final Path writeFilePath = new Path(recordsGenerationParams.getDataMetaClient().getBasePath(), pathWithPartition);
+      final Path writeFilePath = new Path(dataMetaClient.getBasePathV2(), pathWithPartition);
       try (HoodieFileReader fileReader =
                HoodieFileReaderFactory.getReaderFactory(HoodieRecordType.AVRO).getFileReader(
-                   hoodieConfig, recordsGenerationParams.getDataMetaClient().getHadoopConf(), writeFilePath)) {
+                   hoodieConfig, dataMetaClient.getHadoopConf(), writeFilePath)) {
         try {
           final BloomFilter fileBloomFilter = fileReader.readBloomFilter();
           if (fileBloomFilter == null) {
-            LOG.error("Failed to read bloom filter for " + writeFilePath);
+            LOG.error("Failed to read bloom filter for {}", writeFilePath);
             return Collections.emptyListIterator();
           }
           ByteBuffer bloomByteBuffer = ByteBuffer.wrap(getUTF8Bytes(fileBloomFilter.serializeToString()));
           HoodieRecord record = HoodieMetadataPayload.createBloomFilterMetadataRecord(
-              partition, fileName, instantTime, recordsGenerationParams.getBloomFilterType(), bloomByteBuffer, false);
+              partition, fileName, instantTime, bloomFilterType, bloomByteBuffer, false);
           return Collections.singletonList(record).iterator();
         } catch (Exception e) {
-          LOG.error("Failed to read bloom filter for " + writeFilePath);
+          LOG.error("Failed to read bloom filter for {}", writeFilePath);
           return Collections.emptyListIterator();
-        } finally {
-          fileReader.close();
         }
       } catch (IOException e) {
-        LOG.error("Failed to get bloom filter for file: " + writeFilePath + ", write stat: " + hoodieWriteStat);
+        LOG.error("Failed to get bloom filter for file: {}, write stat: {}", writeFilePath, hoodieWriteStat);
       }
       return Collections.emptyListIterator();
     });
@@ -512,22 +534,28 @@ public class HoodieTableMetadataUtil {
    */
   public static Map<MetadataPartitionType, HoodieData<HoodieRecord>> convertMetadataToRecords(HoodieEngineContext engineContext,
                                                                                               HoodieCleanMetadata cleanMetadata,
-                                                                                              MetadataRecordsGenerationParams recordsGenerationParams,
-                                                                                              String instantTime) {
+                                                                                              String instantTime,
+                                                                                              HoodieTableMetaClient dataMetaClient,
+                                                                                              List<MetadataPartitionType> enabledPartitionTypes,
+                                                                                              int bloomIndexParallelism,
+                                                                                              boolean isColumnStatsIndexEnabled,
+                                                                                              int columnStatsIndexParallelism,
+                                                                                              List<String> targetColumnsForColumnStatsIndex) {
     final Map<MetadataPartitionType, HoodieData<HoodieRecord>> partitionToRecordsMap = new HashMap<>();
     final HoodieData<HoodieRecord> filesPartitionRecordsRDD = engineContext.parallelize(
         convertMetadataToFilesPartitionRecords(cleanMetadata, instantTime), 1);
     partitionToRecordsMap.put(MetadataPartitionType.FILES, filesPartitionRecordsRDD);
 
-    if (recordsGenerationParams.getEnabledPartitionTypes().contains(MetadataPartitionType.BLOOM_FILTERS)) {
+    if (enabledPartitionTypes.contains(MetadataPartitionType.BLOOM_FILTERS)) {
       final HoodieData<HoodieRecord> metadataBloomFilterRecordsRDD =
-          convertMetadataToBloomFilterRecords(cleanMetadata, engineContext, instantTime, recordsGenerationParams);
+          convertMetadataToBloomFilterRecords(cleanMetadata, engineContext, instantTime, bloomIndexParallelism);
       partitionToRecordsMap.put(MetadataPartitionType.BLOOM_FILTERS, metadataBloomFilterRecordsRDD);
     }
 
-    if (recordsGenerationParams.getEnabledPartitionTypes().contains(MetadataPartitionType.COLUMN_STATS)) {
+    if (enabledPartitionTypes.contains(MetadataPartitionType.COLUMN_STATS)) {
       final HoodieData<HoodieRecord> metadataColumnStatsRDD =
-          convertMetadataToColumnStatsRecords(cleanMetadata, engineContext, recordsGenerationParams);
+          convertMetadataToColumnStatsRecords(cleanMetadata, engineContext,
+                  dataMetaClient, isColumnStatsIndexEnabled, columnStatsIndexParallelism, targetColumnsForColumnStatsIndex);
       partitionToRecordsMap.put(MetadataPartitionType.COLUMN_STATS, metadataColumnStatsRDD);
     }
 
@@ -563,8 +591,8 @@ public class HoodieTableMetadataUtil {
       // if there are partitions to be deleted, add them to delete list
       records.add(HoodieMetadataPayload.createPartitionListRecord(deletedPartitions, true));
     }
-    LOG.info("Updating at " + instantTime + " from Clean. #partitions_updated=" + records.size()
-        + ", #files_deleted=" + fileDeleteCount[0] + ", #partitions_deleted=" + deletedPartitions.size());
+    LOG.info("Updating at {} from Clean. #partitions_updated={}, #files_deleted={}, #partitions_deleted={}",
+            instantTime, records.size(), fileDeleteCount[0], deletedPartitions.size());
     return records;
   }
 
@@ -597,8 +625,8 @@ public class HoodieTableMetadataUtil {
       records.add(HoodieMetadataPayload.createPartitionListRecord(deletedPartitions, true));
     }
 
-    LOG.info("Re-adding missing records at " + instantTime + " during Restore. #partitions_updated=" + records.size()
-        + ", #files_added=" + filesAddedCount[0] + ", #files_deleted=" + fileDeleteCount[0] + ", #partitions_deleted=" + deletedPartitions.size());
+    LOG.info("Re-adding missing records at {} during Restore. #partitions_updated={}, #files_added={}, #files_deleted={}, #partitions_deleted={}",
+            instantTime, records.size(), filesAddedCount[0], fileDeleteCount[0], deletedPartitions.size());
     return Collections.singletonMap(MetadataPartitionType.FILES, engineContext.parallelize(records, 1));
   }
 
@@ -608,13 +636,13 @@ public class HoodieTableMetadataUtil {
    * @param cleanMetadata           - Clean action metadata
    * @param engineContext           - Engine context
    * @param instantTime             - Clean action instant time
-   * @param recordsGenerationParams - Parameters for bloom filter record generation
+   * @param bloomIndexParallelism   - Parallelism for bloom filter record generation
    * @return List of bloom filter index records for the clean metadata
    */
   public static HoodieData<HoodieRecord> convertMetadataToBloomFilterRecords(HoodieCleanMetadata cleanMetadata,
                                                                              HoodieEngineContext engineContext,
                                                                              String instantTime,
-                                                                             MetadataRecordsGenerationParams recordsGenerationParams) {
+                                                                             int bloomIndexParallelism) {
     List<Pair<String, String>> deleteFileList = new ArrayList<>();
     cleanMetadata.getPartitionMetadata().forEach((partition, partitionMetadata) -> {
       // Files deleted from a partition
@@ -627,7 +655,7 @@ public class HoodieTableMetadataUtil {
       });
     });
 
-    final int parallelism = Math.max(Math.min(deleteFileList.size(), recordsGenerationParams.getBloomIndexParallelism()), 1);
+    final int parallelism = Math.max(Math.min(deleteFileList.size(), bloomIndexParallelism), 1);
     HoodieData<Pair<String, String>> deleteFileListRDD = engineContext.parallelize(deleteFileList, parallelism);
     return deleteFileListRDD.map(deleteFileInfoPair -> HoodieMetadataPayload.createBloomFilterMetadataRecord(
         deleteFileInfoPair.getLeft(), deleteFileInfoPair.getRight(), instantTime, StringUtils.EMPTY_STRING,
@@ -637,14 +665,20 @@ public class HoodieTableMetadataUtil {
   /**
    * Convert clean metadata to column stats index records.
    *
-   * @param cleanMetadata           - Clean action metadata
-   * @param engineContext           - Engine context
-   * @param recordsGenerationParams - Parameters for bloom filter record generation
+   * @param cleanMetadata                    - Clean action metadata
+   * @param engineContext                    - Engine context
+   * @param dataMetaClient                   - HoodieTableMetaClient for data
+   * @param isColumnStatsIndexEnabled        - Is column stats index enabled
+   * @param columnStatsIndexParallelism      - Parallelism for column stats index records generation
+   * @param targetColumnsForColumnStatsIndex - List of columns for column stats index
    * @return List of column stats index records for the clean metadata
    */
   public static HoodieData<HoodieRecord> convertMetadataToColumnStatsRecords(HoodieCleanMetadata cleanMetadata,
                                                                              HoodieEngineContext engineContext,
-                                                                             MetadataRecordsGenerationParams recordsGenerationParams) {
+                                                                             HoodieTableMetaClient dataMetaClient,
+                                                                             boolean isColumnStatsIndexEnabled,
+                                                                             int columnStatsIndexParallelism,
+                                                                             List<String> targetColumnsForColumnStatsIndex) {
     List<Pair<String, String>> deleteFileList = new ArrayList<>();
     cleanMetadata.getPartitionMetadata().forEach((partition, partitionMetadata) -> {
       // Files deleted from a partition
@@ -652,25 +686,23 @@ public class HoodieTableMetadataUtil {
       deletedFiles.forEach(entry -> deleteFileList.add(Pair.of(partition, entry)));
     });
 
-    HoodieTableMetaClient dataTableMetaClient = recordsGenerationParams.getDataMetaClient();
-
     List<String> columnsToIndex =
-        getColumnsToIndex(recordsGenerationParams,
-            Lazy.lazily(() -> tryResolveSchemaForTable(dataTableMetaClient)));
+        getColumnsToIndex(isColumnStatsIndexEnabled, targetColumnsForColumnStatsIndex,
+            Lazy.lazily(() -> tryResolveSchemaForTable(dataMetaClient)));
 
     if (columnsToIndex.isEmpty()) {
       // In case there are no columns to index, bail
       return engineContext.emptyHoodieData();
     }
 
-    int parallelism = Math.max(Math.min(deleteFileList.size(), recordsGenerationParams.getColumnStatsIndexParallelism()), 1);
+    int parallelism = Math.max(Math.min(deleteFileList.size(), columnStatsIndexParallelism), 1);
     return engineContext.parallelize(deleteFileList, parallelism)
         .flatMap(deleteFileInfoPair -> {
           String partitionPath = deleteFileInfoPair.getLeft();
           String filePath = deleteFileInfoPair.getRight();
 
           if (filePath.endsWith(HoodieFileFormat.PARQUET.getFileExtension()) || ExternalFilePathUtil.isExternallyCreatedFile(filePath)) {
-            return getColumnStatsRecords(partitionPath, filePath, dataTableMetaClient, columnsToIndex, true).iterator();
+            return getColumnStatsRecords(partitionPath, filePath, dataMetaClient, columnsToIndex, true).iterator();
           }
           return Collections.emptyListIterator();
         });
@@ -784,8 +816,8 @@ public class HoodieTableMetadataUtil {
       records.add(record);
     });
 
-    LOG.info("Found at " + instantTime + " from " + operation + ". #partitions_updated=" + records.size()
-        + ", #files_deleted=" + fileChangeCount[0] + ", #files_appended=" + fileChangeCount[1]);
+    LOG.info("Found at {} from {}. #partitions_updated={}, #files_deleted={}, #files_appended={}",
+            instantTime, operation, records.size(), fileChangeCount[0], fileChangeCount[1]);
 
     return records;
   }
@@ -815,19 +847,21 @@ public class HoodieTableMetadataUtil {
   public static HoodieData<HoodieRecord> convertFilesToBloomFilterRecords(HoodieEngineContext engineContext,
                                                                           Map<String, List<String>> partitionToDeletedFiles,
                                                                           Map<String, Map<String, Long>> partitionToAppendedFiles,
-                                                                          MetadataRecordsGenerationParams recordsGenerationParams,
-                                                                          String instantTime) {
+                                                                          String instantTime,
+                                                                          HoodieTableMetaClient dataMetaClient,
+                                                                          int bloomIndexParallelism,
+                                                                          String bloomFilterType) {
     // Create the tuple (partition, filename, isDeleted) to handle both deletes and appends
     final List<Tuple3<String, String, Boolean>> partitionFileFlagTupleList = fetchPartitionFileInfoTriplets(partitionToDeletedFiles, partitionToAppendedFiles);
 
     // Create records MDT
-    int parallelism = Math.max(Math.min(partitionFileFlagTupleList.size(), recordsGenerationParams.getBloomIndexParallelism()), 1);
+    int parallelism = Math.max(Math.min(partitionFileFlagTupleList.size(), bloomIndexParallelism), 1);
     return engineContext.parallelize(partitionFileFlagTupleList, parallelism).flatMap(partitionFileFlagTuple -> {
       final String partitionName = partitionFileFlagTuple.f0;
       final String filename = partitionFileFlagTuple.f1;
       final boolean isDeleted = partitionFileFlagTuple.f2;
       if (!FSUtils.isBaseFile(new Path(filename))) {
-        LOG.warn(String.format("Ignoring file %s as it is not a base file", filename));
+        LOG.warn("Ignoring file {} as it is not a base file", filename);
         return Stream.<HoodieRecord>empty().iterator();
       }
 
@@ -835,18 +869,18 @@ public class HoodieTableMetadataUtil {
       ByteBuffer bloomFilterBuffer = ByteBuffer.allocate(0);
       if (!isDeleted) {
         final String pathWithPartition = partitionName + "/" + filename;
-        final Path addedFilePath = new Path(recordsGenerationParams.getDataMetaClient().getBasePath(), pathWithPartition);
-        bloomFilterBuffer = readBloomFilter(recordsGenerationParams.getDataMetaClient().getHadoopConf(), addedFilePath);
+        final Path addedFilePath = new Path(dataMetaClient.getBasePathV2(), pathWithPartition);
+        bloomFilterBuffer = readBloomFilter(dataMetaClient.getHadoopConf(), addedFilePath);
 
         // If reading the bloom filter failed then do not add a record for this file
         if (bloomFilterBuffer == null) {
-          LOG.error("Failed to read bloom filter from " + addedFilePath);
+          LOG.error("Failed to read bloom filter from {}", addedFilePath);
           return Stream.<HoodieRecord>empty().iterator();
         }
       }
 
       return Stream.<HoodieRecord>of(HoodieMetadataPayload.createBloomFilterMetadataRecord(
-              partitionName, filename, instantTime, recordsGenerationParams.getBloomFilterType(), bloomFilterBuffer, partitionFileFlagTuple.f2))
+              partitionName, filename, instantTime, bloomFilterType, bloomFilterBuffer, partitionFileFlagTuple.f2))
           .iterator();
     });
   }
@@ -857,35 +891,37 @@ public class HoodieTableMetadataUtil {
   public static HoodieData<HoodieRecord> convertFilesToColumnStatsRecords(HoodieEngineContext engineContext,
                                                                           Map<String, List<String>> partitionToDeletedFiles,
                                                                           Map<String, Map<String, Long>> partitionToAppendedFiles,
-                                                                          MetadataRecordsGenerationParams recordsGenerationParams) {
+                                                                          HoodieTableMetaClient dataMetaClient,
+                                                                          boolean isColumnStatsIndexEnabled,
+                                                                          int columnStatsIndexParallelism,
+                                                                          List<String> targetColumnsForColumnStatsIndex) {
     // Find the columns to index
-    HoodieTableMetaClient dataTableMetaClient = recordsGenerationParams.getDataMetaClient();
     final List<String> columnsToIndex =
-        getColumnsToIndex(recordsGenerationParams,
-            Lazy.lazily(() -> tryResolveSchemaForTable(dataTableMetaClient)));
+        getColumnsToIndex(isColumnStatsIndexEnabled, targetColumnsForColumnStatsIndex,
+            Lazy.lazily(() -> tryResolveSchemaForTable(dataMetaClient)));
     if (columnsToIndex.isEmpty()) {
       // In case there are no columns to index, bail
       return engineContext.emptyHoodieData();
     }
 
-    LOG.info(String.format("Indexing %d columns for column stats index", columnsToIndex.size()));
+    LOG.info("Indexing {} columns for column stats index", columnsToIndex.size());
 
     // Create the tuple (partition, filename, isDeleted) to handle both deletes and appends
     final List<Tuple3<String, String, Boolean>> partitionFileFlagTupleList = fetchPartitionFileInfoTriplets(partitionToDeletedFiles, partitionToAppendedFiles);
 
     // Create records MDT
-    int parallelism = Math.max(Math.min(partitionFileFlagTupleList.size(), recordsGenerationParams.getColumnStatsIndexParallelism()), 1);
+    int parallelism = Math.max(Math.min(partitionFileFlagTupleList.size(), columnStatsIndexParallelism), 1);
     return engineContext.parallelize(partitionFileFlagTupleList, parallelism).flatMap(partitionFileFlagTuple -> {
       final String partitionName = partitionFileFlagTuple.f0;
       final String filename = partitionFileFlagTuple.f1;
       final boolean isDeleted = partitionFileFlagTuple.f2;
       if (!FSUtils.isBaseFile(new Path(filename)) || !filename.endsWith(HoodieFileFormat.PARQUET.getFileExtension())) {
-        LOG.warn(String.format("Ignoring file %s as it is not a PARQUET file", filename));
+        LOG.warn("Ignoring file {} as it is not a PARQUET file", filename);
         return Stream.<HoodieRecord>empty().iterator();
       }
 
       final String filePathWithPartition = partitionName + "/" + filename;
-      return getColumnStatsRecords(partitionName, filePathWithPartition, dataTableMetaClient, columnsToIndex, isDeleted).iterator();
+      return getColumnStatsRecords(partitionName, filePathWithPartition, dataMetaClient, columnsToIndex, isDeleted).iterator();
     });
   }
 
@@ -947,7 +983,7 @@ public class HoodieTableMetadataUtil {
    */
   public static List<FileSlice> getPartitionLatestMergedFileSlices(
       HoodieTableMetaClient metaClient, HoodieTableFileSystemView fsView, String partition) {
-    LOG.info("Loading latest merged file slices for metadata table partition " + partition);
+    LOG.info("Loading latest merged file slices for metadata table partition {}", partition);
     return getPartitionFileSlices(metaClient, Option.of(fsView), partition, true);
   }
 
@@ -962,7 +998,7 @@ public class HoodieTableMetadataUtil {
    */
   public static List<FileSlice> getPartitionLatestFileSlices(HoodieTableMetaClient metaClient,
                                                              Option<HoodieTableFileSystemView> fsView, String partition) {
-    LOG.info("Loading latest file slices for metadata table partition " + partition);
+    LOG.info("Loading latest file slices for metadata table partition {}", partition);
     return getPartitionFileSlices(metaClient, fsView, partition, false);
   }
 
@@ -1035,7 +1071,10 @@ public class HoodieTableMetadataUtil {
 
   public static HoodieData<HoodieRecord> convertMetadataToColumnStatsRecords(HoodieCommitMetadata commitMetadata,
                                                                              HoodieEngineContext engineContext,
-                                                                             MetadataRecordsGenerationParams recordsGenerationParams) {
+                                                                             HoodieTableMetaClient dataMetaClient,
+                                                                             boolean isColumnStatsIndexEnabled,
+                                                                             int columnStatsIndexParallelism,
+                                                                             List<String> targetColumnsForColumnStatsIndex) {
     List<HoodieWriteStat> allWriteStats = commitMetadata.getPartitionToWriteStats().values().stream()
         .flatMap(Collection::stream).collect(Collectors.toList());
 
@@ -1051,14 +1090,13 @@ public class HoodieTableMetadataUtil {
                       ? Option.empty()
                       : Option.of(new Schema.Parser().parse(writerSchemaStr)));
 
-      HoodieTableMetaClient dataTableMetaClient = recordsGenerationParams.getDataMetaClient();
-      HoodieTableConfig tableConfig = dataTableMetaClient.getTableConfig();
+      HoodieTableConfig tableConfig = dataMetaClient.getTableConfig();
 
       // NOTE: Writer schema added to commit metadata will not contain Hudi's metadata fields
       Option<Schema> tableSchema = writerSchema.map(schema ->
           tableConfig.populateMetaFields() ? addMetadataFields(schema) : schema);
 
-      List<String> columnsToIndex = getColumnsToIndex(recordsGenerationParams,
+      List<String> columnsToIndex = getColumnsToIndex(isColumnStatsIndexEnabled, targetColumnsForColumnStatsIndex,
           Lazy.eagerly(tableSchema));
 
       if (columnsToIndex.isEmpty()) {
@@ -1066,10 +1104,10 @@ public class HoodieTableMetadataUtil {
         return engineContext.emptyHoodieData();
       }
 
-      int parallelism = Math.max(Math.min(allWriteStats.size(), recordsGenerationParams.getColumnStatsIndexParallelism()), 1);
+      int parallelism = Math.max(Math.min(allWriteStats.size(), columnStatsIndexParallelism), 1);
       return engineContext.parallelize(allWriteStats, parallelism)
           .flatMap(writeStat ->
-              translateWriteStatToColumnStats(writeStat, dataTableMetaClient, columnsToIndex).iterator());
+              translateWriteStatToColumnStats(writeStat, dataMetaClient, columnsToIndex).iterator());
     } catch (Exception e) {
       throw new HoodieException("Failed to generate column stats records for metadata table", e);
     }
@@ -1078,13 +1116,13 @@ public class HoodieTableMetadataUtil {
   /**
    * Get the list of columns for the table for column stats indexing
    */
-  private static List<String> getColumnsToIndex(MetadataRecordsGenerationParams recordsGenParams,
+  private static List<String> getColumnsToIndex(boolean isColumnStatsIndexEnabled,
+                                                List<String> targetColumnsForColumnStatsIndex,
                                                 Lazy<Option<Schema>> lazyWriterSchemaOpt) {
-    checkState(recordsGenParams.isColumnStatsIndexEnabled());
+    checkState(isColumnStatsIndexEnabled);
 
-    List<String> targetColumns = recordsGenParams.getTargetColumnsForColumnStatsIndex();
-    if (!targetColumns.isEmpty()) {
-      return targetColumns;
+    if (!targetColumnsForColumnStatsIndex.isEmpty()) {
+      return targetColumnsForColumnStatsIndex;
     }
 
     Option<Schema> writerSchemaOpt = lazyWriterSchemaOpt.get();
@@ -1136,19 +1174,17 @@ public class HoodieTableMetadataUtil {
                                                                                          List<String> columnsToIndex) {
     try {
       if (filePath.endsWith(HoodieFileFormat.PARQUET.getFileExtension())) {
-        Path fullFilePath = new Path(datasetMetaClient.getBasePath(), filePath);
-        List<HoodieColumnRangeMetadata<Comparable>> columnRangeMetadataList =
+        Path fullFilePath = new Path(datasetMetaClient.getBasePathV2(), filePath);
+        return
             new ParquetUtils().readRangeFromParquetMetadata(datasetMetaClient.getHadoopConf(), fullFilePath, columnsToIndex);
-
-        return columnRangeMetadataList;
       }
 
-      LOG.warn("Column range index not supported for: " + filePath);
+      LOG.warn("Column range index not supported for: {}", filePath);
       return Collections.emptyList();
     } catch (Exception e) {
       // NOTE: In case reading column range metadata from individual file failed,
       //       we simply fall back, in lieu of failing the whole task
-      LOG.error("Failed to fetch column range metadata for: " + filePath);
+      LOG.error("Failed to fetch column range metadata for: {}", filePath);
       return Collections.emptyList();
     }
   }
@@ -1196,13 +1232,13 @@ public class HoodieTableMetadataUtil {
       TableSchemaResolver schemaResolver = new TableSchemaResolver(dataTableMetaClient);
       return Option.of(schemaResolver.getTableAvroSchema());
     } catch (Exception e) {
-      throw new HoodieException("Failed to get latest columns for " + dataTableMetaClient.getBasePath(), e);
+      throw new HoodieException("Failed to get latest columns for " + dataTableMetaClient.getBasePathV2(), e);
     }
   }
 
   /**
    * Given a schema, coerces provided value to instance of {@link Comparable<?>} such that
-   * it could subsequently used in column stats
+   * it could subsequently be used in column stats
    *
    * NOTE: This method has to stay compatible with the semantic of
    *      {@link ParquetUtils#readRangeFromParquetMetadata} as they are used in tandem
@@ -1302,10 +1338,8 @@ public class HoodieTableMetadataUtil {
     // instant which we have a log block for.
     final String earliestInstantTime = validInstantTimestamps.isEmpty() ? SOLO_COMMIT_TIMESTAMP : Collections.min(validInstantTimestamps);
     datasetTimeline.getRollbackAndRestoreTimeline().filterCompletedInstants().getInstantsAsStream()
-        .filter(instant -> HoodieTimeline.compareTimestamps(instant.getTimestamp(), HoodieTimeline.GREATER_THAN, earliestInstantTime))
-        .forEach(instant -> {
-          validInstantTimestamps.addAll(getRollbackedCommits(instant, datasetTimeline));
-        });
+            .filter(instant -> HoodieTimeline.compareTimestamps(instant.getTimestamp(), HoodieTimeline.GREATER_THAN, earliestInstantTime))
+            .forEach(instant -> validInstantTimestamps.addAll(getRollbackedCommits(instant, datasetTimeline)));
 
     // add restore and rollback instants from MDT.
     metadataMetaClient.getActiveTimeline().getRollbackAndRestoreTimeline().filterCompletedInstants()
@@ -1384,7 +1418,7 @@ public class HoodieTableMetadataUtil {
               timeline.readRollbackInfoAsBytes(new HoodieInstant(HoodieInstant.State.REQUESTED, HoodieTimeline.ROLLBACK_ACTION,
                   instant.getTimestamp())).get(), HoodieRollbackPlan.class);
           commitsToRollback = Collections.singletonList(rollbackPlan.getInstantToRollback().getCommitTime());
-          LOG.warn("Had to fetch rollback info from requested instant since completed file is empty " + instant.toString());
+          LOG.warn("Had to fetch rollback info from requested instant since completed file is empty {}", instant);
         }
         return commitsToRollback;
       }
@@ -1394,9 +1428,8 @@ public class HoodieTableMetadataUtil {
         // Restore is made up of several rollbacks
         HoodieRestoreMetadata restoreMetadata = TimelineMetadataUtils.deserializeHoodieRestoreMetadata(
             timeline.getInstantDetails(instant).get());
-        restoreMetadata.getHoodieRestoreMetadata().values().forEach(rms -> {
-          rms.forEach(rm -> rollbackedCommits.addAll(rm.getCommitsRollback()));
-        });
+        restoreMetadata.getHoodieRestoreMetadata().values()
+                .forEach(rms -> rms.forEach(rm -> rollbackedCommits.addAll(rm.getCommitsRollback())));
       }
       return rollbackedCommits;
     } catch (IOException e) {
@@ -1441,7 +1474,7 @@ public class HoodieTableMetadataUtil {
       }
     }
 
-    LOG.info("Deleting metadata table from " + metadataTablePath);
+    LOG.info("Deleting metadata table from {}", metadataTablePath);
     try {
       fs.delete(metadataTablePath, true);
     } catch (Exception e) {
@@ -1497,7 +1530,7 @@ public class HoodieTableMetadataUtil {
         LOG.error(String.format("Failed to backup MDT partition %s using rename", partitionType), e);
       }
     } else {
-      LOG.info("Deleting metadata table partition from " + metadataTablePartitionPath);
+      LOG.info("Deleting metadata table partition from {}", metadataTablePartitionPath);
       try {
         fs.delete(metadataTablePartitionPath, true);
       } catch (Exception e) {
@@ -1637,10 +1670,10 @@ public class HoodieTableMetadataUtil {
       }
     }
 
-    LOG.info(String.format("Estimated file group count for MDT partition %s is %d "
-            + "[recordCount=%d, avgRecordSize=%d, minFileGroupCount=%d, maxFileGroupCount=%d, growthFactor=%f, "
-            + "maxFileGroupSizeBytes=%d]", partitionType.name(), fileGroupCount, recordCount, averageRecordSize, minFileGroupCount,
-        maxFileGroupCount, growthFactor, maxFileGroupSizeBytes));
+    LOG.info("Estimated file group count for MDT partition {} is {} "
+            + "[recordCount={}, avgRecordSize={}, minFileGroupCount={}, maxFileGroupCount={}, growthFactor={}, "
+            + "maxFileGroupSizeBytes={}]", partitionType.name(), fileGroupCount, recordCount, averageRecordSize, minFileGroupCount,
+        maxFileGroupCount, growthFactor, maxFileGroupSizeBytes);
     return fileGroupCount;
   }
 
@@ -1664,10 +1697,7 @@ public class HoodieTableMetadataUtil {
     }
 
     // Does any enabled partition being enabled need to track the written records
-    if (config.enableRecordIndex()) {
-      return true;
-    }
-    return false;
+    return config.enableRecordIndex();
   }
 
   /**
@@ -1784,12 +1814,14 @@ public class HoodieTableMetadataUtil {
             .withReaderSchema(HoodieAvroUtils.getRecordKeySchema())
             .withLatestInstantTime(metaClient.getActiveTimeline().filterCompletedInstants().lastInstant().map(HoodieInstant::getTimestamp).orElse(""))
             .withReverseReader(false)
-            .withMaxMemorySizeInBytes(configuration.get().getLongBytes(MAX_MEMORY_FOR_COMPACTION.key(), DEFAULT_MAX_MEMORY_FOR_SPILLABLE_MAP_IN_BYTES))
+            .withMaxMemorySizeInBytes(configuration.get()
+                .getLongBytes(MAX_MEMORY_FOR_COMPACTION.key(), DEFAULT_MAX_MEMORY_FOR_SPILLABLE_MAP_IN_BYTES))
             .withSpillableMapBasePath(FileIOUtils.getDefaultSpillableMapBasePath())
             .withPartition(fileSlice.getPartitionPath())
             .withOptimizedLogBlocksScan(configuration.get().getBoolean("hoodie" + HoodieMetadataConfig.OPTIMIZED_LOG_BLOCKS_SCAN, false))
             .withDiskMapType(configuration.get().getEnum(SPILLABLE_DISK_MAP_TYPE.key(), SPILLABLE_DISK_MAP_TYPE.defaultValue()))
-            .withBitCaskDiskMapCompressionEnabled(configuration.get().getBoolean(DISK_MAP_BITCASK_COMPRESSION_ENABLED.key(), DISK_MAP_BITCASK_COMPRESSION_ENABLED.defaultValue()))
+            .withBitCaskDiskMapCompressionEnabled(configuration.get()
+                .getBoolean(DISK_MAP_BITCASK_COMPRESSION_ENABLED.key(), DISK_MAP_BITCASK_COMPRESSION_ENABLED.defaultValue()))
             .withRecordMerger(HoodieRecordUtils.createRecordMerger(
                 metaClient.getBasePathV2().toString(),
                 engineType,
diff --git a/hudi-common/src/main/java/org/apache/hudi/metadata/MetadataRecordsGenerationParams.java b/hudi-common/src/main/java/org/apache/hudi/metadata/MetadataRecordsGenerationParams.java
deleted file mode 100644
index 72a8bf4cd26..00000000000
--- a/hudi-common/src/main/java/org/apache/hudi/metadata/MetadataRecordsGenerationParams.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * 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.hudi.metadata;
-
-import org.apache.hudi.common.table.HoodieTableMetaClient;
-
-import java.io.Serializable;
-import java.util.List;
-
-/**
- * Encapsulates all parameters required to generate metadata index for enabled index types.
- *
- * @deprecated this component currently duplicates configuration coming from the {@code HoodieWriteConfig}
- *             which is problematic; instead we should break this component down and use source of truth
- *             for each respective data-point directly ({@code HoodieWriteConfig}, {@code HoodieTableMetaClient}, etc)
- */
-@Deprecated
-public class MetadataRecordsGenerationParams implements Serializable {
-
-  private final HoodieTableMetaClient dataMetaClient;
-  private final List<MetadataPartitionType> enabledPartitionTypes;
-  private final String bloomFilterType;
-  private final int bloomIndexParallelism;
-  private final boolean isColumnStatsIndexEnabled;
-  private final int columnStatsIndexParallelism;
-  private final List<String> targetColumnsForColumnStatsIndex;
-  private final List<String> targetColumnsForBloomFilterIndex;
-
-  MetadataRecordsGenerationParams(HoodieTableMetaClient dataMetaClient, List<MetadataPartitionType> enabledPartitionTypes, String bloomFilterType, int bloomIndexParallelism,
-                                  boolean isColumnStatsIndexEnabled, int columnStatsIndexParallelism, List<String> targetColumnsForColumnStatsIndex, List<String> targetColumnsForBloomFilterIndex) {
-    this.dataMetaClient = dataMetaClient;
-    this.enabledPartitionTypes = enabledPartitionTypes;
-    this.bloomFilterType = bloomFilterType;
-    this.bloomIndexParallelism = bloomIndexParallelism;
-    this.isColumnStatsIndexEnabled = isColumnStatsIndexEnabled;
-    this.columnStatsIndexParallelism = columnStatsIndexParallelism;
-    this.targetColumnsForColumnStatsIndex = targetColumnsForColumnStatsIndex;
-    this.targetColumnsForBloomFilterIndex = targetColumnsForBloomFilterIndex;
-  }
-
-  public HoodieTableMetaClient getDataMetaClient() {
-    return dataMetaClient;
-  }
-
-  public List<MetadataPartitionType> getEnabledPartitionTypes() {
-    return enabledPartitionTypes;
-  }
-
-  public String getBloomFilterType() {
-    return bloomFilterType;
-  }
-
-  public boolean isColumnStatsIndexEnabled() {
-    return isColumnStatsIndexEnabled;
-  }
-
-  public int getBloomIndexParallelism() {
-    return bloomIndexParallelism;
-  }
-
-  public int getColumnStatsIndexParallelism() {
-    return columnStatsIndexParallelism;
-  }
-
-  public List<String> getTargetColumnsForColumnStatsIndex() {
-    return targetColumnsForColumnStatsIndex;
-  }
-
-  public List<String> getSecondaryKeysForBloomFilterIndex() {
-    return targetColumnsForBloomFilterIndex;
-  }
-}


(hudi) 19/28: [MINOR] Rename location to path in `makeQualified` (#11037)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 51f7557070da4b3b218e0f17bbc6f7a18baae218
Author: Y Ethan Guo <et...@gmail.com>
AuthorDate: Tue Apr 16 18:30:11 2024 -0700

    [MINOR] Rename location to path in `makeQualified` (#11037)
---
 .../src/main/java/org/apache/hudi/common/fs/FSUtils.java     | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/hudi-common/src/main/java/org/apache/hudi/common/fs/FSUtils.java b/hudi-common/src/main/java/org/apache/hudi/common/fs/FSUtils.java
index 68cc5c131db..292c2b41946 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/fs/FSUtils.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/fs/FSUtils.java
@@ -123,14 +123,14 @@ public class FSUtils {
   }
 
   /**
-   * Makes location qualified with {@link HoodieStorage}'s URI.
+   * Makes path qualified with {@link HoodieStorage}'s URI.
    *
-   * @param storage  instance of {@link HoodieStorage}.
-   * @param location to be qualified.
-   * @return qualified location, prefixed with the URI of the target HoodieStorage object provided.
+   * @param storage instance of {@link HoodieStorage}.
+   * @param path    to be qualified.
+   * @return qualified path, prefixed with the URI of the target HoodieStorage object provided.
    */
-  public static StoragePath makeQualified(HoodieStorage storage, StoragePath location) {
-    return location.makeQualified(storage.getUri());
+  public static StoragePath makeQualified(HoodieStorage storage, StoragePath path) {
+    return path.makeQualified(storage.getUri());
   }
 
   /**


(hudi) 24/28: [HUDI-7633] Use try with resources for AutoCloseable (#11045)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit d20f8175b95db94d30f937b8e696d57c3993b8dd
Author: Y Ethan Guo <et...@gmail.com>
AuthorDate: Wed Apr 17 21:31:44 2024 -0700

    [HUDI-7633] Use try with resources for AutoCloseable (#11045)
---
 .../hudi/cli/commands/ArchivedCommitsCommand.java  | 104 ++++++++--------
 .../apache/hudi/cli/commands/ExportCommand.java    |  93 +++++++-------
 .../hudi/cli/commands/HoodieLogFileCommand.java    | 104 ++++++++--------
 .../org/apache/hudi/cli/commands/TableCommand.java |   6 +-
 .../metadata/HoodieBackedTableMetadataWriter.java  |   8 +-
 .../hudi/common/model/HoodiePartitionMetadata.java |   8 +-
 .../hudi/common/table/log/LogReaderUtils.java      |  22 ++--
 .../table/log/block/HoodieAvroDataBlock.java       | 135 ++++++++++-----------
 .../hudi/common/util/SerializationUtils.java       |   6 +-
 .../hudi/metadata/HoodieBackedTableMetadata.java   |  24 ++--
 .../java/HoodieJavaWriteClientExample.java         |  70 +++++------
 .../examples/spark/HoodieWriteClientExample.java   |  90 +++++++-------
 .../org/apache/hudi/common/util/FileIOUtils.java   |  14 +--
 .../hudi/utilities/HoodieCompactionAdminTool.java  |   9 +-
 .../utilities/streamer/SchedulerConfGenerator.java |   6 +-
 15 files changed, 344 insertions(+), 355 deletions(-)

diff --git a/hudi-cli/src/main/java/org/apache/hudi/cli/commands/ArchivedCommitsCommand.java b/hudi-cli/src/main/java/org/apache/hudi/cli/commands/ArchivedCommitsCommand.java
index 075a57d541c..5c57c8f5288 100644
--- a/hudi-cli/src/main/java/org/apache/hudi/cli/commands/ArchivedCommitsCommand.java
+++ b/hudi-cli/src/main/java/org/apache/hudi/cli/commands/ArchivedCommitsCommand.java
@@ -114,47 +114,46 @@ public class ArchivedCommitsCommand {
     List<Comparable[]> allStats = new ArrayList<>();
     for (FileStatus fs : fsStatuses) {
       // read the archived file
-      Reader reader = HoodieLogFormat.newReader(HadoopFSUtils.getFs(basePath, HoodieCLI.conf),
-          new HoodieLogFile(fs.getPath()), HoodieArchivedMetaEntry.getClassSchema());
-
-      List<IndexedRecord> readRecords = new ArrayList<>();
-      // read the avro blocks
-      while (reader.hasNext()) {
-        HoodieAvroDataBlock blk = (HoodieAvroDataBlock) reader.next();
-        blk.getRecordIterator(HoodieRecordType.AVRO).forEachRemaining(r -> readRecords.add((IndexedRecord) r.getData()));
+      try (Reader reader = HoodieLogFormat.newReader(HadoopFSUtils.getFs(basePath, HoodieCLI.conf),
+          new HoodieLogFile(fs.getPath()), HoodieArchivedMetaEntry.getClassSchema())) {
+        List<IndexedRecord> readRecords = new ArrayList<>();
+        // read the avro blocks
+        while (reader.hasNext()) {
+          HoodieAvroDataBlock blk = (HoodieAvroDataBlock) reader.next();
+          blk.getRecordIterator(HoodieRecordType.AVRO).forEachRemaining(r -> readRecords.add((IndexedRecord) r.getData()));
+        }
+        List<Comparable[]> readCommits = readRecords.stream().map(r -> (GenericRecord) r)
+            .filter(r -> r.get("actionType").toString().equals(HoodieTimeline.COMMIT_ACTION)
+                || r.get("actionType").toString().equals(HoodieTimeline.DELTA_COMMIT_ACTION))
+            .flatMap(r -> {
+              HoodieCommitMetadata metadata = (HoodieCommitMetadata) SpecificData.get()
+                  .deepCopy(HoodieCommitMetadata.SCHEMA$, r.get("hoodieCommitMetadata"));
+              final String instantTime = r.get("commitTime").toString();
+              final String action = r.get("actionType").toString();
+              return metadata.getPartitionToWriteStats().values().stream().flatMap(hoodieWriteStats -> hoodieWriteStats.stream().map(hoodieWriteStat -> {
+                List<Comparable> row = new ArrayList<>();
+                row.add(action);
+                row.add(instantTime);
+                row.add(hoodieWriteStat.getPartitionPath());
+                row.add(hoodieWriteStat.getFileId());
+                row.add(hoodieWriteStat.getPrevCommit());
+                row.add(hoodieWriteStat.getNumWrites());
+                row.add(hoodieWriteStat.getNumInserts());
+                row.add(hoodieWriteStat.getNumDeletes());
+                row.add(hoodieWriteStat.getNumUpdateWrites());
+                row.add(hoodieWriteStat.getTotalLogFiles());
+                row.add(hoodieWriteStat.getTotalLogBlocks());
+                row.add(hoodieWriteStat.getTotalCorruptLogBlock());
+                row.add(hoodieWriteStat.getTotalRollbackBlocks());
+                row.add(hoodieWriteStat.getTotalLogRecords());
+                row.add(hoodieWriteStat.getTotalUpdatedRecordsCompacted());
+                row.add(hoodieWriteStat.getTotalWriteBytes());
+                row.add(hoodieWriteStat.getTotalWriteErrors());
+                return row;
+              })).map(rowList -> rowList.toArray(new Comparable[0]));
+            }).collect(Collectors.toList());
+        allStats.addAll(readCommits);
       }
-      List<Comparable[]> readCommits = readRecords.stream().map(r -> (GenericRecord) r)
-          .filter(r -> r.get("actionType").toString().equals(HoodieTimeline.COMMIT_ACTION)
-              || r.get("actionType").toString().equals(HoodieTimeline.DELTA_COMMIT_ACTION))
-          .flatMap(r -> {
-            HoodieCommitMetadata metadata = (HoodieCommitMetadata) SpecificData.get()
-                .deepCopy(HoodieCommitMetadata.SCHEMA$, r.get("hoodieCommitMetadata"));
-            final String instantTime = r.get("commitTime").toString();
-            final String action = r.get("actionType").toString();
-            return metadata.getPartitionToWriteStats().values().stream().flatMap(hoodieWriteStats -> hoodieWriteStats.stream().map(hoodieWriteStat -> {
-              List<Comparable> row = new ArrayList<>();
-              row.add(action);
-              row.add(instantTime);
-              row.add(hoodieWriteStat.getPartitionPath());
-              row.add(hoodieWriteStat.getFileId());
-              row.add(hoodieWriteStat.getPrevCommit());
-              row.add(hoodieWriteStat.getNumWrites());
-              row.add(hoodieWriteStat.getNumInserts());
-              row.add(hoodieWriteStat.getNumDeletes());
-              row.add(hoodieWriteStat.getNumUpdateWrites());
-              row.add(hoodieWriteStat.getTotalLogFiles());
-              row.add(hoodieWriteStat.getTotalLogBlocks());
-              row.add(hoodieWriteStat.getTotalCorruptLogBlock());
-              row.add(hoodieWriteStat.getTotalRollbackBlocks());
-              row.add(hoodieWriteStat.getTotalLogRecords());
-              row.add(hoodieWriteStat.getTotalUpdatedRecordsCompacted());
-              row.add(hoodieWriteStat.getTotalWriteBytes());
-              row.add(hoodieWriteStat.getTotalWriteErrors());
-              return row;
-            })).map(rowList -> rowList.toArray(new Comparable[0]));
-          }).collect(Collectors.toList());
-      allStats.addAll(readCommits);
-      reader.close();
     }
     TableHeader header = new TableHeader().addTableHeaderField("action").addTableHeaderField("instant")
         .addTableHeaderField("partition").addTableHeaderField("file_id").addTableHeaderField("prev_instant")
@@ -188,21 +187,20 @@ public class ArchivedCommitsCommand {
     List<Comparable[]> allCommits = new ArrayList<>();
     for (FileStatus fs : fsStatuses) {
       // read the archived file
-      HoodieLogFormat.Reader reader = HoodieLogFormat.newReader(HadoopFSUtils.getFs(basePath, HoodieCLI.conf),
-          new HoodieLogFile(fs.getPath()), HoodieArchivedMetaEntry.getClassSchema());
-
-      List<IndexedRecord> readRecords = new ArrayList<>();
-      // read the avro blocks
-      while (reader.hasNext()) {
-        HoodieAvroDataBlock blk = (HoodieAvroDataBlock) reader.next();
-        try (ClosableIterator<HoodieRecord<IndexedRecord>> recordItr = blk.getRecordIterator(HoodieRecordType.AVRO)) {
-          recordItr.forEachRemaining(r -> readRecords.add(r.getData()));
+      try (HoodieLogFormat.Reader reader = HoodieLogFormat.newReader(HadoopFSUtils.getFs(basePath, HoodieCLI.conf),
+          new HoodieLogFile(fs.getPath()), HoodieArchivedMetaEntry.getClassSchema())) {
+        List<IndexedRecord> readRecords = new ArrayList<>();
+        // read the avro blocks
+        while (reader.hasNext()) {
+          HoodieAvroDataBlock blk = (HoodieAvroDataBlock) reader.next();
+          try (ClosableIterator<HoodieRecord<IndexedRecord>> recordItr = blk.getRecordIterator(HoodieRecordType.AVRO)) {
+            recordItr.forEachRemaining(r -> readRecords.add(r.getData()));
+          }
         }
+        List<Comparable[]> readCommits = readRecords.stream().map(r -> (GenericRecord) r)
+            .map(r -> readCommit(r, skipMetadata)).collect(Collectors.toList());
+        allCommits.addAll(readCommits);
       }
-      List<Comparable[]> readCommits = readRecords.stream().map(r -> (GenericRecord) r)
-          .map(r -> readCommit(r, skipMetadata)).collect(Collectors.toList());
-      allCommits.addAll(readCommits);
-      reader.close();
     }
 
     TableHeader header = new TableHeader().addTableHeaderField("CommitTime").addTableHeaderField("CommitType");
diff --git a/hudi-cli/src/main/java/org/apache/hudi/cli/commands/ExportCommand.java b/hudi-cli/src/main/java/org/apache/hudi/cli/commands/ExportCommand.java
index effa096bfa9..eda0d0de219 100644
--- a/hudi-cli/src/main/java/org/apache/hudi/cli/commands/ExportCommand.java
+++ b/hudi-cli/src/main/java/org/apache/hudi/cli/commands/ExportCommand.java
@@ -125,57 +125,56 @@ public class ExportCommand {
 
     for (FileStatus fs : statuses) {
       // read the archived file
-      Reader reader = HoodieLogFormat.newReader(fileSystem, new HoodieLogFile(fs.getPath()), HoodieArchivedMetaEntry.getClassSchema());
-
-      // read the avro blocks
-      while (reader.hasNext() && copyCount++ < limit) {
-        HoodieAvroDataBlock blk = (HoodieAvroDataBlock) reader.next();
-        try (ClosableIterator<HoodieRecord<IndexedRecord>> recordItr = blk.getRecordIterator(HoodieRecordType.AVRO)) {
-          while (recordItr.hasNext()) {
-            IndexedRecord ir = recordItr.next().getData();
-            // Archived instants are saved as arvo encoded HoodieArchivedMetaEntry records. We need to get the
-            // metadata record from the entry and convert it to json.
-            HoodieArchivedMetaEntry archiveEntryRecord = (HoodieArchivedMetaEntry) SpecificData.get()
-                .deepCopy(HoodieArchivedMetaEntry.SCHEMA$, ir);
-            final String action = archiveEntryRecord.get("actionType").toString();
-            if (!actionSet.contains(action)) {
-              continue;
+      try (Reader reader = HoodieLogFormat.newReader(fileSystem, new HoodieLogFile(fs.getPath()), HoodieArchivedMetaEntry.getClassSchema())) {
+
+        // read the avro blocks
+        while (reader.hasNext() && copyCount++ < limit) {
+          HoodieAvroDataBlock blk = (HoodieAvroDataBlock) reader.next();
+          try (ClosableIterator<HoodieRecord<IndexedRecord>> recordItr = blk.getRecordIterator(HoodieRecordType.AVRO)) {
+            while (recordItr.hasNext()) {
+              IndexedRecord ir = recordItr.next().getData();
+              // Archived instants are saved as arvo encoded HoodieArchivedMetaEntry records. We need to get the
+              // metadata record from the entry and convert it to json.
+              HoodieArchivedMetaEntry archiveEntryRecord = (HoodieArchivedMetaEntry) SpecificData.get()
+                  .deepCopy(HoodieArchivedMetaEntry.SCHEMA$, ir);
+              final String action = archiveEntryRecord.get("actionType").toString();
+              if (!actionSet.contains(action)) {
+                continue;
+              }
+
+              GenericRecord metadata = null;
+              switch (action) {
+                case HoodieTimeline.CLEAN_ACTION:
+                  metadata = archiveEntryRecord.getHoodieCleanMetadata();
+                  break;
+                case HoodieTimeline.COMMIT_ACTION:
+                case HoodieTimeline.DELTA_COMMIT_ACTION:
+                  metadata = archiveEntryRecord.getHoodieCommitMetadata();
+                  break;
+                case HoodieTimeline.ROLLBACK_ACTION:
+                  metadata = archiveEntryRecord.getHoodieRollbackMetadata();
+                  break;
+                case HoodieTimeline.SAVEPOINT_ACTION:
+                  metadata = archiveEntryRecord.getHoodieSavePointMetadata();
+                  break;
+                case HoodieTimeline.COMPACTION_ACTION:
+                  metadata = archiveEntryRecord.getHoodieCompactionMetadata();
+                  break;
+                default:
+                  throw new HoodieException("Unknown type of action " + action);
+              }
+
+              final String instantTime = archiveEntryRecord.get("commitTime").toString();
+              if (metadata == null) {
+                LOG.error("Could not load metadata for action " + action + " at instant time " + instantTime);
+                continue;
+              }
+              final String outPath = localFolder + StoragePath.SEPARATOR + instantTime + "." + action;
+              writeToFile(outPath, HoodieAvroUtils.avroToJson(metadata, true));
             }
-
-            GenericRecord metadata = null;
-            switch (action) {
-              case HoodieTimeline.CLEAN_ACTION:
-                metadata = archiveEntryRecord.getHoodieCleanMetadata();
-                break;
-              case HoodieTimeline.COMMIT_ACTION:
-              case HoodieTimeline.DELTA_COMMIT_ACTION:
-                metadata = archiveEntryRecord.getHoodieCommitMetadata();
-                break;
-              case HoodieTimeline.ROLLBACK_ACTION:
-                metadata = archiveEntryRecord.getHoodieRollbackMetadata();
-                break;
-              case HoodieTimeline.SAVEPOINT_ACTION:
-                metadata = archiveEntryRecord.getHoodieSavePointMetadata();
-                break;
-              case HoodieTimeline.COMPACTION_ACTION:
-                metadata = archiveEntryRecord.getHoodieCompactionMetadata();
-                break;
-              default:
-                throw new HoodieException("Unknown type of action " + action);
-            }
-
-            final String instantTime = archiveEntryRecord.get("commitTime").toString();
-            if (metadata == null) {
-              LOG.error("Could not load metadata for action " + action + " at instant time " + instantTime);
-              continue;
-            }
-            final String outPath = localFolder + StoragePath.SEPARATOR + instantTime + "." + action;
-            writeToFile(outPath, HoodieAvroUtils.avroToJson(metadata, true));
           }
         }
       }
-
-      reader.close();
     }
 
     return copyCount;
diff --git a/hudi-cli/src/main/java/org/apache/hudi/cli/commands/HoodieLogFileCommand.java b/hudi-cli/src/main/java/org/apache/hudi/cli/commands/HoodieLogFileCommand.java
index 77d9392fcd0..feb07fbe489 100644
--- a/hudi-cli/src/main/java/org/apache/hudi/cli/commands/HoodieLogFileCommand.java
+++ b/hudi-cli/src/main/java/org/apache/hudi/cli/commands/HoodieLogFileCommand.java
@@ -114,52 +114,52 @@ public class HoodieLogFileCommand {
       MessageType schema = TableSchemaResolver.readSchemaFromLogFile(fs, path);
       Schema writerSchema = schema != null
           ? new AvroSchemaConverter().convert(Objects.requireNonNull(schema)) : null;
-      Reader reader = HoodieLogFormat.newReader(fs, new HoodieLogFile(fsStatus[0].getPath()), writerSchema);
+      try (Reader reader = HoodieLogFormat.newReader(fs, new HoodieLogFile(fsStatus[0].getPath()), writerSchema)) {
 
-      // read the avro blocks
-      while (reader.hasNext()) {
-        HoodieLogBlock n = reader.next();
-        String instantTime;
-        AtomicInteger recordCount = new AtomicInteger(0);
-        if (n instanceof HoodieCorruptBlock) {
-          try {
+        // read the avro blocks
+        while (reader.hasNext()) {
+          HoodieLogBlock n = reader.next();
+          String instantTime;
+          AtomicInteger recordCount = new AtomicInteger(0);
+          if (n instanceof HoodieCorruptBlock) {
+            try {
+              instantTime = n.getLogBlockHeader().get(HeaderMetadataType.INSTANT_TIME);
+              if (instantTime == null) {
+                throw new Exception("Invalid instant time " + instantTime);
+              }
+            } catch (Exception e) {
+              numCorruptBlocks++;
+              instantTime = "corrupt_block_" + numCorruptBlocks;
+              // could not read metadata for corrupt block
+            }
+          } else {
             instantTime = n.getLogBlockHeader().get(HeaderMetadataType.INSTANT_TIME);
             if (instantTime == null) {
-              throw new Exception("Invalid instant time " + instantTime);
+              // This can happen when reading archived commit files since they were written without any instant time
+              dummyInstantTimeCount++;
+              instantTime = "dummy_instant_time_" + dummyInstantTimeCount;
             }
-          } catch (Exception e) {
-            numCorruptBlocks++;
-            instantTime = "corrupt_block_" + numCorruptBlocks;
-            // could not read metadata for corrupt block
-          }
-        } else {
-          instantTime = n.getLogBlockHeader().get(HeaderMetadataType.INSTANT_TIME);
-          if (instantTime == null) {
-            // This can happen when reading archived commit files since they were written without any instant time
-            dummyInstantTimeCount++;
-            instantTime = "dummy_instant_time_" + dummyInstantTimeCount;
-          }
-          if (n instanceof HoodieDataBlock) {
-            try (ClosableIterator<HoodieRecord<IndexedRecord>> recordItr = ((HoodieDataBlock) n).getRecordIterator(HoodieRecordType.AVRO)) {
-              recordItr.forEachRemaining(r -> recordCount.incrementAndGet());
+            if (n instanceof HoodieDataBlock) {
+              try (ClosableIterator<HoodieRecord<IndexedRecord>> recordItr = ((HoodieDataBlock) n).getRecordIterator(HoodieRecordType.AVRO)) {
+                recordItr.forEachRemaining(r -> recordCount.incrementAndGet());
+              }
             }
           }
-        }
-        if (commitCountAndMetadata.containsKey(instantTime)) {
-          commitCountAndMetadata.get(instantTime).add(
-              new Tuple3<>(new Tuple2<>(fileName, n.getBlockType()),
-                  new Tuple2<>(n.getLogBlockHeader(), n.getLogBlockFooter()), recordCount.get()));
-        } else {
-          List<Tuple3<Tuple2<String, HoodieLogBlockType>, Tuple2<Map<HeaderMetadataType, String>,
-              Map<HeaderMetadataType, String>>, Integer>> list =
-              new ArrayList<>();
-          list.add(
-              new Tuple3<>(new Tuple2<>(fileName, n.getBlockType()),
-                  new Tuple2<>(n.getLogBlockHeader(), n.getLogBlockFooter()), recordCount.get()));
-          commitCountAndMetadata.put(instantTime, list);
+          if (commitCountAndMetadata.containsKey(instantTime)) {
+            commitCountAndMetadata.get(instantTime).add(
+                new Tuple3<>(new Tuple2<>(fileName, n.getBlockType()),
+                    new Tuple2<>(n.getLogBlockHeader(), n.getLogBlockFooter()), recordCount.get()));
+          } else {
+            List<Tuple3<Tuple2<String, HoodieLogBlockType>, Tuple2<Map<HeaderMetadataType, String>,
+                Map<HeaderMetadataType, String>>, Integer>> list =
+                new ArrayList<>();
+            list.add(
+                new Tuple3<>(new Tuple2<>(fileName, n.getBlockType()),
+                    new Tuple2<>(n.getLogBlockHeader(), n.getLogBlockFooter()), recordCount.get()));
+            commitCountAndMetadata.put(instantTime, list);
+          }
         }
       }
-      reader.close();
     }
     List<Comparable[]> rows = new ArrayList<>();
     ObjectMapper objectMapper = new ObjectMapper();
@@ -260,23 +260,23 @@ public class HoodieLogFileCommand {
         MessageType schema = TableSchemaResolver.readSchemaFromLogFile(client.getFs(), new CachingPath(logFile));
         Schema writerSchema = schema != null
             ? new AvroSchemaConverter().convert(Objects.requireNonNull(schema)) : null;
-        HoodieLogFormat.Reader reader =
-            HoodieLogFormat.newReader(fs, new HoodieLogFile(new CachingPath(logFile)), writerSchema);
-        // read the avro blocks
-        while (reader.hasNext()) {
-          HoodieLogBlock n = reader.next();
-          if (n instanceof HoodieDataBlock) {
-            HoodieDataBlock blk = (HoodieDataBlock) n;
-            try (ClosableIterator<HoodieRecord<IndexedRecord>> recordItr = blk.getRecordIterator(HoodieRecordType.AVRO)) {
-              recordItr.forEachRemaining(record -> {
-                if (allRecords.size() < limit) {
-                  allRecords.add(record.getData());
-                }
-              });
+        try (HoodieLogFormat.Reader reader =
+                 HoodieLogFormat.newReader(fs, new HoodieLogFile(new CachingPath(logFile)), writerSchema)) {
+          // read the avro blocks
+          while (reader.hasNext()) {
+            HoodieLogBlock n = reader.next();
+            if (n instanceof HoodieDataBlock) {
+              HoodieDataBlock blk = (HoodieDataBlock) n;
+              try (ClosableIterator<HoodieRecord<IndexedRecord>> recordItr = blk.getRecordIterator(HoodieRecordType.AVRO)) {
+                recordItr.forEachRemaining(record -> {
+                  if (allRecords.size() < limit) {
+                    allRecords.add(record.getData());
+                  }
+                });
+              }
             }
           }
         }
-        reader.close();
         if (allRecords.size() >= limit) {
           break;
         }
diff --git a/hudi-cli/src/main/java/org/apache/hudi/cli/commands/TableCommand.java b/hudi-cli/src/main/java/org/apache/hudi/cli/commands/TableCommand.java
index f0b653ec1e9..00185725830 100644
--- a/hudi-cli/src/main/java/org/apache/hudi/cli/commands/TableCommand.java
+++ b/hudi-cli/src/main/java/org/apache/hudi/cli/commands/TableCommand.java
@@ -259,12 +259,8 @@ public class TableCommand {
     if (outFile.exists()) {
       outFile.delete();
     }
-    OutputStream os = null;
-    try {
-      os = new FileOutputStream(outFile);
+    try (OutputStream os = new FileOutputStream(outFile)) {
       os.write(getUTF8Bytes(data), 0, data.length());
-    } finally {
-      os.close();
     }
   }
 }
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metadata/HoodieBackedTableMetadataWriter.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metadata/HoodieBackedTableMetadataWriter.java
index 3537a6ddb40..2735282f793 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metadata/HoodieBackedTableMetadataWriter.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/metadata/HoodieBackedTableMetadataWriter.java
@@ -703,7 +703,7 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
         final Map<HeaderMetadataType, String> blockHeader = Collections.singletonMap(HeaderMetadataType.INSTANT_TIME, instantTime);
         final HoodieDeleteBlock block = new HoodieDeleteBlock(new DeleteRecord[0], blockHeader);
 
-        HoodieLogFormat.Writer writer = HoodieLogFormat.newWriterBuilder()
+        try (HoodieLogFormat.Writer writer = HoodieLogFormat.newWriterBuilder()
             .onParentPath(FSUtils.getPartitionPath(metadataWriteConfig.getBasePath(), metadataPartition.getPartitionPath()))
             .withFileId(fileGroupFileId)
             .overBaseCommit(instantTime)
@@ -713,9 +713,9 @@ public abstract class HoodieBackedTableMetadataWriter<I> implements HoodieTableM
             .withFs(dataMetaClient.getFs())
             .withRolloverLogWriteToken(HoodieLogFormat.DEFAULT_WRITE_TOKEN)
             .withLogWriteToken(HoodieLogFormat.DEFAULT_WRITE_TOKEN)
-            .withFileExtension(HoodieLogFile.DELTA_EXTENSION).build();
-        writer.appendBlock(block);
-        writer.close();
+            .withFileExtension(HoodieLogFile.DELTA_EXTENSION).build()) {
+          writer.appendBlock(block);
+        }
       } catch (InterruptedException e) {
         throw new HoodieException("Failed to created fileGroup " + fileGroupFileId + " for partition " + metadataPartition.getPartitionPath(), e);
       }
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/model/HoodiePartitionMetadata.java b/hudi-common/src/main/java/org/apache/hudi/common/model/HoodiePartitionMetadata.java
index bbf505c8670..d84a529a084 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/model/HoodiePartitionMetadata.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/model/HoodiePartitionMetadata.java
@@ -141,10 +141,10 @@ public class HoodiePartitionMetadata {
       BaseFileUtils.getInstance(format.get()).writeMetaFile(fs, filePath, props);
     } else {
       // Backwards compatible properties file format
-      OutputStream os = fs.create(filePath, true);
-      props.store(os, "partition metadata");
-      os.flush();
-      os.close();
+      try (OutputStream os = fs.create(filePath, true)) {
+        props.store(os, "partition metadata");
+        os.flush();
+      }
     }
   }
 
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/log/LogReaderUtils.java b/hudi-common/src/main/java/org/apache/hudi/common/table/log/LogReaderUtils.java
index 93383df332f..5e1f14c086b 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/log/LogReaderUtils.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/log/LogReaderUtils.java
@@ -52,21 +52,21 @@ public class LogReaderUtils {
   private static Schema readSchemaFromLogFileInReverse(FileSystem fs, HoodieActiveTimeline activeTimeline, HoodieLogFile hoodieLogFile)
       throws IOException {
     // set length for the HoodieLogFile as it will be leveraged by HoodieLogFormat.Reader with reverseReading enabled
-    Reader reader = HoodieLogFormat.newReader(fs, hoodieLogFile, null, true);
     Schema writerSchema = null;
-    HoodieTimeline completedTimeline = activeTimeline.getCommitsTimeline().filterCompletedInstants();
-    while (reader.hasPrev()) {
-      HoodieLogBlock block = reader.prev();
-      if (block instanceof HoodieDataBlock) {
-        HoodieDataBlock lastBlock = (HoodieDataBlock) block;
-        if (completedTimeline
-            .containsOrBeforeTimelineStarts(lastBlock.getLogBlockHeader().get(HeaderMetadataType.INSTANT_TIME))) {
-          writerSchema = new Schema.Parser().parse(lastBlock.getLogBlockHeader().get(HeaderMetadataType.SCHEMA));
-          break;
+    try (Reader reader = HoodieLogFormat.newReader(fs, hoodieLogFile, null, true)) {
+      HoodieTimeline completedTimeline = activeTimeline.getCommitsTimeline().filterCompletedInstants();
+      while (reader.hasPrev()) {
+        HoodieLogBlock block = reader.prev();
+        if (block instanceof HoodieDataBlock) {
+          HoodieDataBlock lastBlock = (HoodieDataBlock) block;
+          if (completedTimeline
+              .containsOrBeforeTimelineStarts(lastBlock.getLogBlockHeader().get(HeaderMetadataType.INSTANT_TIME))) {
+            writerSchema = new Schema.Parser().parse(lastBlock.getLogBlockHeader().get(HeaderMetadataType.SCHEMA));
+            break;
+          }
         }
       }
     }
-    reader.close();
     return writerSchema;
   }
 
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/log/block/HoodieAvroDataBlock.java b/hudi-common/src/main/java/org/apache/hudi/common/table/log/block/HoodieAvroDataBlock.java
index 620e123059b..4153dd4c545 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/log/block/HoodieAvroDataBlock.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/log/block/HoodieAvroDataBlock.java
@@ -102,38 +102,37 @@ public class HoodieAvroDataBlock extends HoodieDataBlock {
     Schema schema = new Schema.Parser().parse(super.getLogBlockHeader().get(HeaderMetadataType.SCHEMA));
     GenericDatumWriter<IndexedRecord> writer = new GenericDatumWriter<>(schema);
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
-    DataOutputStream output = new DataOutputStream(baos);
-
-    // 1. Write out the log block version
-    output.writeInt(HoodieLogBlock.version);
-
-    // 2. Write total number of records
-    output.writeInt(records.size());
-
-    // 3. Write the records
-    for (HoodieRecord<?> s : records) {
-      ByteArrayOutputStream temp = new ByteArrayOutputStream();
-      BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(temp, encoderCache.get());
-      encoderCache.set(encoder);
-      try {
-        // Encode the record into bytes
-        // Spark Record not support write avro log
-        IndexedRecord data = s.toIndexedRecord(schema, new Properties()).get().getData();
-        writer.write(data, encoder);
-        encoder.flush();
-
-        // Get the size of the bytes
-        int size = temp.toByteArray().length;
-        // Write the record size
-        output.writeInt(size);
-        // Write the content
-        output.write(temp.toByteArray());
-      } catch (IOException e) {
-        throw new HoodieIOException("IOException converting HoodieAvroDataBlock to bytes", e);
+    try (DataOutputStream output = new DataOutputStream(baos)) {
+      // 1. Write out the log block version
+      output.writeInt(HoodieLogBlock.version);
+
+      // 2. Write total number of records
+      output.writeInt(records.size());
+
+      // 3. Write the records
+      for (HoodieRecord<?> s : records) {
+        ByteArrayOutputStream temp = new ByteArrayOutputStream();
+        BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(temp, encoderCache.get());
+        encoderCache.set(encoder);
+        try {
+          // Encode the record into bytes
+          // Spark Record not support write avro log
+          IndexedRecord data = s.toIndexedRecord(schema, new Properties()).get().getData();
+          writer.write(data, encoder);
+          encoder.flush();
+
+          // Get the size of the bytes
+          int size = temp.toByteArray().length;
+          // Write the record size
+          output.writeInt(size);
+          // Write the content
+          output.write(temp.toByteArray());
+        } catch (IOException e) {
+          throw new HoodieIOException("IOException converting HoodieAvroDataBlock to bytes", e);
+        }
       }
+      encoderCache.remove();
     }
-    encoderCache.remove();
-    output.close();
     return baos.toByteArray();
   }
 
@@ -278,9 +277,9 @@ public class HoodieAvroDataBlock extends HoodieDataBlock {
   private static byte[] compress(String text) {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     try {
-      OutputStream out = new DeflaterOutputStream(baos);
-      out.write(getUTF8Bytes(text));
-      out.close();
+      try (OutputStream out = new DeflaterOutputStream(baos)) {
+        out.write(getUTF8Bytes(text));
+      }
     } catch (IOException e) {
       throw new HoodieIOException("IOException while compressing text " + text, e);
     }
@@ -307,45 +306,43 @@ public class HoodieAvroDataBlock extends HoodieDataBlock {
 
     GenericDatumWriter<IndexedRecord> writer = new GenericDatumWriter<>(schema);
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
-    DataOutputStream output = new DataOutputStream(baos);
-
-    // 1. Compress and Write schema out
-    byte[] schemaContent = compress(schema.toString());
-    output.writeInt(schemaContent.length);
-    output.write(schemaContent);
-
-    List<HoodieRecord<?>> records = new ArrayList<>();
-    try (ClosableIterator<HoodieRecord<Object>> recordItr = getRecordIterator(HoodieRecordType.AVRO)) {
-      recordItr.forEachRemaining(records::add);
-    }
-
-    // 2. Write total number of records
-    output.writeInt(records.size());
+    try (DataOutputStream output = new DataOutputStream(baos)) {
+      // 1. Compress and Write schema out
+      byte[] schemaContent = compress(schema.toString());
+      output.writeInt(schemaContent.length);
+      output.write(schemaContent);
+
+      List<HoodieRecord<?>> records = new ArrayList<>();
+      try (ClosableIterator<HoodieRecord<Object>> recordItr = getRecordIterator(HoodieRecordType.AVRO)) {
+        recordItr.forEachRemaining(records::add);
+      }
 
-    // 3. Write the records
-    Iterator<HoodieRecord<?>> itr = records.iterator();
-    while (itr.hasNext()) {
-      IndexedRecord s = itr.next().toIndexedRecord(schema, new Properties()).get().getData();
-      ByteArrayOutputStream temp = new ByteArrayOutputStream();
-      Encoder encoder = EncoderFactory.get().binaryEncoder(temp, null);
-      try {
-        // Encode the record into bytes
-        writer.write(s, encoder);
-        encoder.flush();
-
-        // Get the size of the bytes
-        int size = temp.toByteArray().length;
-        // Write the record size
-        output.writeInt(size);
-        // Write the content
-        output.write(temp.toByteArray());
-        itr.remove();
-      } catch (IOException e) {
-        throw new HoodieIOException("IOException converting HoodieAvroDataBlock to bytes", e);
+      // 2. Write total number of records
+      output.writeInt(records.size());
+
+      // 3. Write the records
+      Iterator<HoodieRecord<?>> itr = records.iterator();
+      while (itr.hasNext()) {
+        IndexedRecord s = itr.next().toIndexedRecord(schema, new Properties()).get().getData();
+        ByteArrayOutputStream temp = new ByteArrayOutputStream();
+        Encoder encoder = EncoderFactory.get().binaryEncoder(temp, null);
+        try {
+          // Encode the record into bytes
+          writer.write(s, encoder);
+          encoder.flush();
+
+          // Get the size of the bytes
+          int size = temp.toByteArray().length;
+          // Write the record size
+          output.writeInt(size);
+          // Write the content
+          output.write(temp.toByteArray());
+          itr.remove();
+        } catch (IOException e) {
+          throw new HoodieIOException("IOException converting HoodieAvroDataBlock to bytes", e);
+        }
       }
     }
-
-    output.close();
     return baos.toByteArray();
   }
 }
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/util/SerializationUtils.java b/hudi-common/src/main/java/org/apache/hudi/common/util/SerializationUtils.java
index 6b1069847f3..de5df5c73b7 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/util/SerializationUtils.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/util/SerializationUtils.java
@@ -92,9 +92,9 @@ public class SerializationUtils {
     byte[] serialize(Object obj) {
       kryo.reset();
       baos.reset();
-      Output output = new Output(baos);
-      this.kryo.writeClassAndObject(output, obj);
-      output.close();
+      try (Output output = new Output(baos)) {
+        this.kryo.writeClassAndObject(output, obj);
+      }
       return baos.toByteArray();
     }
 
diff --git a/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieBackedTableMetadata.java b/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieBackedTableMetadata.java
index 86406b5963e..3e5c155e9ec 100644
--- a/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieBackedTableMetadata.java
+++ b/hudi-common/src/main/java/org/apache/hudi/metadata/HoodieBackedTableMetadata.java
@@ -372,19 +372,19 @@ public class HoodieBackedTableMetadata extends BaseTableMetadata {
                                                                                       List<String> sortedKeys,
                                                                                       boolean fullKeys,
                                                                                       String partitionName) throws IOException {
-    ClosableIterator<HoodieRecord<?>> records = fullKeys
+    Map<String, HoodieRecord<HoodieMetadataPayload>> result;
+    try (ClosableIterator<HoodieRecord<?>> records = fullKeys
         ? reader.getRecordsByKeysIterator(sortedKeys)
-        : reader.getRecordsByKeyPrefixIterator(sortedKeys);
-
-    Map<String, HoodieRecord<HoodieMetadataPayload>> result = toStream(records)
-        .map(record -> {
-          GenericRecord data = (GenericRecord) record.getData();
-          return Pair.of(
-              (String) (data).get(HoodieMetadataPayload.KEY_FIELD_NAME),
-              composeRecord(data, partitionName));
-        })
-        .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
-    records.close();
+        : reader.getRecordsByKeyPrefixIterator(sortedKeys)) {
+      result = toStream(records)
+          .map(record -> {
+            GenericRecord data = (GenericRecord) record.getData();
+            return Pair.of(
+                (String) (data).get(HoodieMetadataPayload.KEY_FIELD_NAME),
+                composeRecord(data, partitionName));
+          })
+          .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
+    }
     return result;
   }
 
diff --git a/hudi-examples/hudi-examples-java/src/main/java/org/apache/hudi/examples/java/HoodieJavaWriteClientExample.java b/hudi-examples/hudi-examples-java/src/main/java/org/apache/hudi/examples/java/HoodieJavaWriteClientExample.java
index fe6dd497b2f..352444faa34 100644
--- a/hudi-examples/hudi-examples-java/src/main/java/org/apache/hudi/examples/java/HoodieJavaWriteClientExample.java
+++ b/hudi-examples/hudi-examples-java/src/main/java/org/apache/hudi/examples/java/HoodieJavaWriteClientExample.java
@@ -75,8 +75,8 @@ public class HoodieJavaWriteClientExample {
       HoodieTableMetaClient.withPropertyBuilder()
         .setTableType(tableType)
         .setTableName(tableName)
-        .setPayloadClassName(HoodieAvroPayload.class.getName())
-        .initTable(hadoopConf, tablePath);
+          .setPayloadClassName(HoodieAvroPayload.class.getName())
+          .initTable(hadoopConf, tablePath);
     }
 
     // Create the write client to write some records in
@@ -85,38 +85,38 @@ public class HoodieJavaWriteClientExample {
         .withDeleteParallelism(2).forTable(tableName)
         .withIndexConfig(HoodieIndexConfig.newBuilder().withIndexType(HoodieIndex.IndexType.INMEMORY).build())
         .withArchivalConfig(HoodieArchivalConfig.newBuilder().archiveCommitsWith(20, 30).build()).build();
-    HoodieJavaWriteClient<HoodieAvroPayload> client =
-        new HoodieJavaWriteClient<>(new HoodieJavaEngineContext(hadoopConf), cfg);
-
-    // inserts
-    String newCommitTime = client.startCommit();
-    LOG.info("Starting commit " + newCommitTime);
-
-    List<HoodieRecord<HoodieAvroPayload>> records = dataGen.generateInserts(newCommitTime, 10);
-    List<HoodieRecord<HoodieAvroPayload>> recordsSoFar = new ArrayList<>(records);
-    List<HoodieRecord<HoodieAvroPayload>> writeRecords =
-        recordsSoFar.stream().map(r -> new HoodieAvroRecord<HoodieAvroPayload>(r)).collect(Collectors.toList());
-    client.insert(writeRecords, newCommitTime);
-
-    // updates
-    newCommitTime = client.startCommit();
-    LOG.info("Starting commit " + newCommitTime);
-    List<HoodieRecord<HoodieAvroPayload>> toBeUpdated = dataGen.generateUpdates(newCommitTime, 2);
-    records.addAll(toBeUpdated);
-    recordsSoFar.addAll(toBeUpdated);
-    writeRecords =
-        recordsSoFar.stream().map(r -> new HoodieAvroRecord<HoodieAvroPayload>(r)).collect(Collectors.toList());
-    client.upsert(writeRecords, newCommitTime);
-
-    // Delete
-    newCommitTime = client.startCommit();
-    LOG.info("Starting commit " + newCommitTime);
-    // just delete half of the records
-    int numToDelete = recordsSoFar.size() / 2;
-    List<HoodieKey> toBeDeleted =
-        recordsSoFar.stream().map(HoodieRecord::getKey).limit(numToDelete).collect(Collectors.toList());
-    client.delete(toBeDeleted, newCommitTime);
-
-    client.close();
+
+    try (HoodieJavaWriteClient<HoodieAvroPayload> client =
+             new HoodieJavaWriteClient<>(new HoodieJavaEngineContext(hadoopConf), cfg)) {
+
+      // inserts
+      String newCommitTime = client.startCommit();
+      LOG.info("Starting commit " + newCommitTime);
+
+      List<HoodieRecord<HoodieAvroPayload>> records = dataGen.generateInserts(newCommitTime, 10);
+      List<HoodieRecord<HoodieAvroPayload>> recordsSoFar = new ArrayList<>(records);
+      List<HoodieRecord<HoodieAvroPayload>> writeRecords =
+          recordsSoFar.stream().map(r -> new HoodieAvroRecord<HoodieAvroPayload>(r)).collect(Collectors.toList());
+      client.insert(writeRecords, newCommitTime);
+
+      // updates
+      newCommitTime = client.startCommit();
+      LOG.info("Starting commit " + newCommitTime);
+      List<HoodieRecord<HoodieAvroPayload>> toBeUpdated = dataGen.generateUpdates(newCommitTime, 2);
+      records.addAll(toBeUpdated);
+      recordsSoFar.addAll(toBeUpdated);
+      writeRecords =
+          recordsSoFar.stream().map(r -> new HoodieAvroRecord<HoodieAvroPayload>(r)).collect(Collectors.toList());
+      client.upsert(writeRecords, newCommitTime);
+
+      // Delete
+      newCommitTime = client.startCommit();
+      LOG.info("Starting commit " + newCommitTime);
+      // just delete half of the records
+      int numToDelete = recordsSoFar.size() / 2;
+      List<HoodieKey> toBeDeleted =
+          recordsSoFar.stream().map(HoodieRecord::getKey).limit(numToDelete).collect(Collectors.toList());
+      client.delete(toBeDeleted, newCommitTime);
+    }
   }
 }
diff --git a/hudi-examples/hudi-examples-spark/src/main/java/org/apache/hudi/examples/spark/HoodieWriteClientExample.java b/hudi-examples/hudi-examples-spark/src/main/java/org/apache/hudi/examples/spark/HoodieWriteClientExample.java
index cbe505b7012..b57ce25671c 100644
--- a/hudi-examples/hudi-examples-spark/src/main/java/org/apache/hudi/examples/spark/HoodieWriteClientExample.java
+++ b/hudi-examples/hudi-examples-spark/src/main/java/org/apache/hudi/examples/spark/HoodieWriteClientExample.java
@@ -99,52 +99,52 @@ public class HoodieWriteClientExample {
               .withDeleteParallelism(2).forTable(tableName)
               .withIndexConfig(HoodieIndexConfig.newBuilder().withIndexType(HoodieIndex.IndexType.BLOOM).build())
               .withArchivalConfig(HoodieArchivalConfig.newBuilder().archiveCommitsWith(20, 30).build()).build();
-      SparkRDDWriteClient<HoodieAvroPayload> client = new SparkRDDWriteClient<>(new HoodieSparkEngineContext(jsc), cfg);
-
-      // inserts
-      String newCommitTime = client.startCommit();
-      LOG.info("Starting commit " + newCommitTime);
-
-      List<HoodieRecord<HoodieAvroPayload>> records = dataGen.generateInserts(newCommitTime, 10);
-      List<HoodieRecord<HoodieAvroPayload>> recordsSoFar = new ArrayList<>(records);
-      JavaRDD<HoodieRecord<HoodieAvroPayload>> writeRecords = jsc.parallelize(records, 1);
-      client.insert(writeRecords, newCommitTime);
-
-      // updates
-      newCommitTime = client.startCommit();
-      LOG.info("Starting commit " + newCommitTime);
-      List<HoodieRecord<HoodieAvroPayload>> toBeUpdated = dataGen.generateUpdates(newCommitTime, 2);
-      records.addAll(toBeUpdated);
-      recordsSoFar.addAll(toBeUpdated);
-      writeRecords = jsc.parallelize(records, 1);
-      client.upsert(writeRecords, newCommitTime);
-
-      // Delete
-      newCommitTime = client.startCommit();
-      LOG.info("Starting commit " + newCommitTime);
-      // just delete half of the records
-      int numToDelete = recordsSoFar.size() / 2;
-      List<HoodieKey> toBeDeleted = recordsSoFar.stream().map(HoodieRecord::getKey).limit(numToDelete).collect(Collectors.toList());
-      JavaRDD<HoodieKey> deleteRecords = jsc.parallelize(toBeDeleted, 1);
-      client.delete(deleteRecords, newCommitTime);
-
-      // Delete by partition
-      newCommitTime = client.startCommit();
-      client.startCommitWithTime(newCommitTime, HoodieTimeline.REPLACE_COMMIT_ACTION);
-      LOG.info("Starting commit " + newCommitTime);
-      // The partition where the data needs to be deleted
-      List<String> partitionList = toBeDeleted.stream().map(s -> s.getPartitionPath()).distinct().collect(Collectors.toList());
-      List<String> deleteList = recordsSoFar.stream().filter(f -> !partitionList.contains(f.getPartitionPath()))
-          .map(m -> m.getKey().getPartitionPath()).distinct().collect(Collectors.toList());
-      client.deletePartitions(deleteList, newCommitTime);
-
-      // compaction
-      if (HoodieTableType.valueOf(tableType) == HoodieTableType.MERGE_ON_READ) {
-        Option<String> instant = client.scheduleCompaction(Option.empty());
-        HoodieWriteMetadata<JavaRDD<WriteStatus>> compactionMetadata = client.compact(instant.get());
-        client.commitCompaction(instant.get(), compactionMetadata.getCommitMetadata().get(), Option.empty());
+      try (SparkRDDWriteClient<HoodieAvroPayload> client = new SparkRDDWriteClient<>(new HoodieSparkEngineContext(jsc), cfg)) {
+
+        // inserts
+        String newCommitTime = client.startCommit();
+        LOG.info("Starting commit " + newCommitTime);
+
+        List<HoodieRecord<HoodieAvroPayload>> records = dataGen.generateInserts(newCommitTime, 10);
+        List<HoodieRecord<HoodieAvroPayload>> recordsSoFar = new ArrayList<>(records);
+        JavaRDD<HoodieRecord<HoodieAvroPayload>> writeRecords = jsc.parallelize(records, 1);
+        client.insert(writeRecords, newCommitTime);
+
+        // updates
+        newCommitTime = client.startCommit();
+        LOG.info("Starting commit " + newCommitTime);
+        List<HoodieRecord<HoodieAvroPayload>> toBeUpdated = dataGen.generateUpdates(newCommitTime, 2);
+        records.addAll(toBeUpdated);
+        recordsSoFar.addAll(toBeUpdated);
+        writeRecords = jsc.parallelize(records, 1);
+        client.upsert(writeRecords, newCommitTime);
+
+        // Delete
+        newCommitTime = client.startCommit();
+        LOG.info("Starting commit " + newCommitTime);
+        // just delete half of the records
+        int numToDelete = recordsSoFar.size() / 2;
+        List<HoodieKey> toBeDeleted = recordsSoFar.stream().map(HoodieRecord::getKey).limit(numToDelete).collect(Collectors.toList());
+        JavaRDD<HoodieKey> deleteRecords = jsc.parallelize(toBeDeleted, 1);
+        client.delete(deleteRecords, newCommitTime);
+
+        // Delete by partition
+        newCommitTime = client.startCommit();
+        client.startCommitWithTime(newCommitTime, HoodieTimeline.REPLACE_COMMIT_ACTION);
+        LOG.info("Starting commit " + newCommitTime);
+        // The partition where the data needs to be deleted
+        List<String> partitionList = toBeDeleted.stream().map(s -> s.getPartitionPath()).distinct().collect(Collectors.toList());
+        List<String> deleteList = recordsSoFar.stream().filter(f -> !partitionList.contains(f.getPartitionPath()))
+            .map(m -> m.getKey().getPartitionPath()).distinct().collect(Collectors.toList());
+        client.deletePartitions(deleteList, newCommitTime);
+
+        // compaction
+        if (HoodieTableType.valueOf(tableType) == HoodieTableType.MERGE_ON_READ) {
+          Option<String> instant = client.scheduleCompaction(Option.empty());
+          HoodieWriteMetadata<JavaRDD<WriteStatus>> compactionMetadata = client.compact(instant.get());
+          client.commitCompaction(instant.get(), compactionMetadata.getCommitMetadata().get(), Option.empty());
+        }
       }
-      client.close();
     }
   }
 
diff --git a/hudi-io/src/main/java/org/apache/hudi/common/util/FileIOUtils.java b/hudi-io/src/main/java/org/apache/hudi/common/util/FileIOUtils.java
index 37c573a173c..5bc91ebed14 100644
--- a/hudi-io/src/main/java/org/apache/hudi/common/util/FileIOUtils.java
+++ b/hudi-io/src/main/java/org/apache/hudi/common/util/FileIOUtils.java
@@ -140,10 +140,10 @@ public class FileIOUtils {
   }
 
   public static void writeStringToFile(String str, String filePath) throws IOException {
-    PrintStream out = new PrintStream(new FileOutputStream(filePath));
-    out.println(str);
-    out.flush();
-    out.close();
+    try (PrintStream out = new PrintStream(new FileOutputStream(filePath))) {
+      out.println(str);
+      out.flush();
+    }
   }
 
   /**
@@ -174,9 +174,9 @@ public class FileIOUtils {
       }
 
       if (content.isPresent()) {
-        OutputStream out = fileSystem.create(fullPath, true);
-        out.write(content.get());
-        out.close();
+        try (OutputStream out = fileSystem.create(fullPath, true)) {
+          out.write(content.get());
+        }
       }
     } catch (IOException e) {
       LOG.warn("Failed to create file " + fullPath, e);
diff --git a/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieCompactionAdminTool.java b/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieCompactionAdminTool.java
index 8806ce46ea3..4194547894d 100644
--- a/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieCompactionAdminTool.java
+++ b/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieCompactionAdminTool.java
@@ -107,11 +107,10 @@ public class HoodieCompactionAdminTool {
   private <T> void serializeOperationResult(FileSystem fs, T result) throws Exception {
     if ((cfg.outputPath != null) && (result != null)) {
       Path outputPath = new Path(cfg.outputPath);
-      OutputStream stream = fs.create(outputPath, true);
-      ObjectOutputStream out = new ObjectOutputStream(stream);
-      out.writeObject(result);
-      out.close();
-      stream.close();
+      try (OutputStream stream = fs.create(outputPath, true);
+           ObjectOutputStream out = new ObjectOutputStream(stream)) {
+        out.writeObject(result);
+      }
     }
   }
 
diff --git a/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/SchedulerConfGenerator.java b/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/SchedulerConfGenerator.java
index 66b4382d784..669af8dca9f 100644
--- a/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/SchedulerConfGenerator.java
+++ b/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/SchedulerConfGenerator.java
@@ -131,9 +131,9 @@ public class SchedulerConfGenerator {
   private static String generateAndStoreConfig(Integer deltaSyncWeight, Integer compactionWeight,
       Integer deltaSyncMinShare, Integer compactionMinShare, Integer clusteringWeight, Integer clusteringMinShare) throws IOException {
     File tempConfigFile = File.createTempFile(UUID.randomUUID().toString(), ".xml");
-    BufferedWriter bw = new BufferedWriter(new FileWriter(tempConfigFile));
-    bw.write(generateConfig(deltaSyncWeight, compactionWeight, deltaSyncMinShare, compactionMinShare, clusteringWeight, clusteringMinShare));
-    bw.close();
+    try (BufferedWriter bw = new BufferedWriter(new FileWriter(tempConfigFile))) {
+      bw.write(generateConfig(deltaSyncWeight, compactionWeight, deltaSyncMinShare, compactionMinShare, clusteringWeight, clusteringMinShare));
+    }
     // SPARK-35083 introduces remote scheduler pool files, so the file must include scheme since Spark 3.2
     String path = HoodieSparkUtils.gteqSpark3_2() ? tempConfigFile.toURI().toString() : tempConfigFile.getAbsolutePath();
     LOG.info("Configs written to file " + path);


(hudi) 07/28: [HUDI-6441] Passing custom Headers with Hudi Callback URL (#10970)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit db53c7af20c228d750b5273beb678240d114ce64
Author: Vova Kolmakov <wo...@gmail.com>
AuthorDate: Thu Apr 11 21:16:14 2024 +0700

    [HUDI-6441] Passing custom Headers with Hudi Callback URL (#10970)
---
 .../http/HoodieWriteCommitHttpCallbackClient.java  |  46 ++++-
 .../config/HoodieWriteCommitCallbackConfig.java    |  15 ++
 .../client/http/TestCallbackHttpClient.java        | 202 +++++++++++++++++++++
 .../hudi/callback/http/TestCallbackHttpClient.java | 143 ---------------
 4 files changed, 260 insertions(+), 146 deletions(-)

diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/callback/client/http/HoodieWriteCommitHttpCallbackClient.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/callback/client/http/HoodieWriteCommitHttpCallbackClient.java
index d9248ed20f1..037e84b3d00 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/callback/client/http/HoodieWriteCommitHttpCallbackClient.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/callback/client/http/HoodieWriteCommitHttpCallbackClient.java
@@ -18,6 +18,8 @@
 
 package org.apache.hudi.callback.client.http;
 
+import org.apache.hudi.common.util.StringUtils;
+import org.apache.hudi.common.util.VisibleForTesting;
 import org.apache.hudi.config.HoodieWriteCommitCallbackConfig;
 import org.apache.hudi.config.HoodieWriteConfig;
 
@@ -34,6 +36,9 @@ import org.slf4j.LoggerFactory;
 
 import java.io.Closeable;
 import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.StringTokenizer;
 
 /**
  * Write commit callback http client.
@@ -43,36 +48,42 @@ public class HoodieWriteCommitHttpCallbackClient implements Closeable {
   private static final Logger LOG = LoggerFactory.getLogger(HoodieWriteCommitHttpCallbackClient.class);
 
   public static final String HEADER_KEY_API_KEY = "HUDI-CALLBACK-KEY";
+  static final String HEADERS_DELIMITER = ";";
+  static final String HEADERS_KV_DELIMITER = ":";
 
   private final String apiKey;
   private final String url;
   private final CloseableHttpClient client;
   private HoodieWriteConfig writeConfig;
+  private final Map<String, String> customHeaders;
 
   public HoodieWriteCommitHttpCallbackClient(HoodieWriteConfig config) {
     this.writeConfig = config;
     this.apiKey = getApiKey();
     this.url = getUrl();
     this.client = getClient();
+    this.customHeaders = parseCustomHeaders();
   }
 
-  public HoodieWriteCommitHttpCallbackClient(String apiKey, String url, CloseableHttpClient client) {
+  public HoodieWriteCommitHttpCallbackClient(String apiKey, String url, CloseableHttpClient client, Map<String, String> customHeaders) {
     this.apiKey = apiKey;
     this.url = url;
     this.client = client;
+    this.customHeaders = customHeaders != null ? customHeaders : new HashMap<>();
   }
 
   public void send(String callbackMsg) {
     HttpPost request = new HttpPost(url);
     request.setHeader(HEADER_KEY_API_KEY, apiKey);
     request.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
+    customHeaders.forEach(request::setHeader);
     request.setEntity(new StringEntity(callbackMsg, ContentType.APPLICATION_JSON));
     try (CloseableHttpResponse response = client.execute(request)) {
       int statusCode = response.getStatusLine().getStatusCode();
       if (statusCode >= 300) {
-        LOG.warn(String.format("Failed to send callback message. Response was %s", response));
+        LOG.warn("Failed to send callback message. Response was {}", response);
       } else {
-        LOG.info(String.format("Sent Callback data to %s successfully !", url));
+        LOG.info("Sent Callback data with {} custom headers to {} successfully !", customHeaders.size(), url);
       }
     } catch (IOException e) {
       LOG.warn("Failed to send callback.", e);
@@ -101,8 +112,37 @@ public class HoodieWriteCommitHttpCallbackClient implements Closeable {
     return writeConfig.getInt(HoodieWriteCommitCallbackConfig.CALLBACK_HTTP_TIMEOUT_IN_SECONDS);
   }
 
+  private Map<String, String> parseCustomHeaders() {
+    Map<String, String> headers = new HashMap<>();
+    String headersString = writeConfig.getString(HoodieWriteCommitCallbackConfig.CALLBACK_HTTP_CUSTOM_HEADERS);
+    if (!StringUtils.isNullOrEmpty(headersString)) {
+      StringTokenizer tokenizer = new StringTokenizer(headersString, HEADERS_DELIMITER);
+      while (tokenizer.hasMoreTokens()) {
+        String token = tokenizer.nextToken();
+        if (!StringUtils.isNullOrEmpty(token)) {
+          String[] keyValue = token.split(HEADERS_KV_DELIMITER);
+          if (keyValue.length == 2) {
+            String trimKey = keyValue[0].trim();
+            String trimValue = keyValue[1].trim();
+            if (trimKey.length() > 0 && trimValue.length() > 0) {
+              headers.put(trimKey, trimValue);
+            }
+          } else {
+            LOG.warn("Unable to parse some custom headers. Supported format is: Header_name1:Header value1;Header_name2:Header value2");
+          }
+        }
+      }
+    }
+    return headers;
+  }
+
   @Override
   public void close() throws IOException {
     client.close();
   }
+
+  @VisibleForTesting
+  String getCustomHeaders() {
+    return customHeaders.toString();
+  }
 }
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieWriteCommitCallbackConfig.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieWriteCommitCallbackConfig.java
index 4ca52e48318..26f8aeb53ac 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieWriteCommitCallbackConfig.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieWriteCommitCallbackConfig.java
@@ -21,6 +21,7 @@ import org.apache.hudi.common.config.ConfigClassProperty;
 import org.apache.hudi.common.config.ConfigGroups;
 import org.apache.hudi.common.config.ConfigProperty;
 import org.apache.hudi.common.config.HoodieConfig;
+import org.apache.hudi.common.util.StringUtils;
 
 import java.io.File;
 import java.io.FileReader;
@@ -76,6 +77,13 @@ public class HoodieWriteCommitCallbackConfig extends HoodieConfig {
       .sinceVersion("0.6.0")
       .withDocumentation("Callback timeout in seconds.");
 
+  public static final ConfigProperty<String> CALLBACK_HTTP_CUSTOM_HEADERS = ConfigProperty
+      .key(CALLBACK_PREFIX + "http.custom.headers")
+      .noDefaultValue()
+      .markAdvanced()
+      .sinceVersion("0.15.0")
+      .withDocumentation("Http callback custom headers. Format: HeaderName1:HeaderValue1;HeaderName2:HeaderValue2");
+
   /**
    * @deprecated Use {@link #TURN_CALLBACK_ON} and its methods instead
    */
@@ -171,6 +179,13 @@ public class HoodieWriteCommitCallbackConfig extends HoodieConfig {
       return this;
     }
 
+    public Builder withCustomHeaders(String customHeaders) {
+      if (!StringUtils.isNullOrEmpty(customHeaders)) {
+        writeCommitCallbackConfig.setValue(CALLBACK_HTTP_CUSTOM_HEADERS, customHeaders);
+      }
+      return this;
+    }
+
     public HoodieWriteCommitCallbackConfig build() {
       writeCommitCallbackConfig.setDefaults(HoodieWriteCommitCallbackConfig.class.getName());
       return writeCommitCallbackConfig;
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/callback/client/http/TestCallbackHttpClient.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/callback/client/http/TestCallbackHttpClient.java
new file mode 100644
index 00000000000..2de4ed08524
--- /dev/null
+++ b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/callback/client/http/TestCallbackHttpClient.java
@@ -0,0 +1,202 @@
+/*
+ * 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.hudi.callback.client.http;
+
+import org.apache.hudi.config.HoodieWriteCommitCallbackConfig;
+import org.apache.hudi.config.HoodieWriteConfig;
+
+import org.apache.http.StatusLine;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.core.Appender;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.Logger;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Unit test for {@link HoodieWriteCommitHttpCallbackClient}.
+ */
+@ExtendWith(MockitoExtension.class)
+class TestCallbackHttpClient {
+
+  public static final String FAKE_API_KEY = "fake_api_key";
+  public static final String FAKE_URL = "fake_url";
+  public static final String CALLBACK_MSG = "{}";
+  public static final String RESPONSE_UNAUTHORIZED = "unauthorized";
+  @Mock
+  Appender appender;
+
+  @Captor
+  ArgumentCaptor<LogEvent> logCaptor;
+
+  @Mock
+  CloseableHttpClient httpClient;
+
+  @Mock
+  CloseableHttpResponse httpResponse;
+
+  @Mock
+  StatusLine statusLine;
+
+  private Level initialLogLevel;
+
+  @BeforeEach
+  void prepareAppender() {
+    when(appender.getName()).thenReturn("MockAppender-" + UUID.randomUUID());
+    when(appender.isStarted()).thenReturn(true);
+    when(appender.isStopped()).thenReturn(false);
+    Logger logger = (Logger) LogManager.getLogger(HoodieWriteCommitHttpCallbackClient.class);
+    initialLogLevel = logger.getLevel();
+    logger.setLevel(Level.DEBUG);
+    logger.addAppender(appender);
+  }
+
+  @AfterEach
+  void resetMocks() {
+    Logger logger = (Logger) LogManager.getLogger(HoodieWriteCommitHttpCallbackClient.class);
+    logger.setLevel(initialLogLevel);
+    logger.removeAppender(appender);
+    reset(appender, httpClient, httpResponse, statusLine);
+  }
+
+  private void mockResponse(int statusCode) {
+    when(statusLine.getStatusCode()).thenReturn(statusCode);
+    when(httpResponse.getStatusLine()).thenReturn(statusLine);
+    try {
+      when(httpClient.execute(any())).thenReturn(httpResponse);
+    } catch (IOException e) {
+      fail(e.getMessage(), e);
+    }
+  }
+
+  @Test
+  void sendPayloadShouldLogWhenRequestFailed() throws IOException {
+    when(httpClient.execute(any())).thenThrow(IOException.class);
+
+    HoodieWriteCommitHttpCallbackClient hoodieWriteCommitCallBackHttpClient =
+        new HoodieWriteCommitHttpCallbackClient(FAKE_API_KEY, FAKE_URL, httpClient, null);
+    hoodieWriteCommitCallBackHttpClient.send(CALLBACK_MSG);
+
+    verify(appender).append(logCaptor.capture());
+    assertEquals("Failed to send callback.", logCaptor.getValue().getMessage().getFormattedMessage());
+    assertEquals(Level.WARN, logCaptor.getValue().getLevel());
+  }
+
+  @Test
+  void sendPayloadShouldLogUnsuccessfulSending() {
+    mockResponse(401);
+    when(httpResponse.toString()).thenReturn(RESPONSE_UNAUTHORIZED);
+
+    HoodieWriteCommitHttpCallbackClient hoodieWriteCommitCallBackHttpClient =
+        new HoodieWriteCommitHttpCallbackClient(FAKE_API_KEY, FAKE_URL, httpClient, null);
+    hoodieWriteCommitCallBackHttpClient.send(CALLBACK_MSG);
+
+    verify(appender).append(logCaptor.capture());
+    assertEquals("Failed to send callback message. Response was " + RESPONSE_UNAUTHORIZED, logCaptor.getValue().getMessage().getFormattedMessage());
+    assertEquals(Level.WARN, logCaptor.getValue().getLevel());
+  }
+
+  @Test
+  void sendPayloadShouldLogSuccessfulSending() {
+    mockResponse(202);
+
+    Map<String, String> customHeaders = new HashMap<>();
+    customHeaders.put("key1", "val1");
+    customHeaders.put("key2", "val2");
+    HoodieWriteCommitHttpCallbackClient hoodieWriteCommitCallBackHttpClient =
+        new HoodieWriteCommitHttpCallbackClient(FAKE_API_KEY, FAKE_URL, httpClient, customHeaders);
+    hoodieWriteCommitCallBackHttpClient.send(CALLBACK_MSG);
+
+    verify(appender).append(logCaptor.capture());
+    assertTrue(logCaptor.getValue().getMessage().getFormattedMessage().startsWith("Sent Callback data with 2 custom headers"));
+    assertEquals(Level.INFO, logCaptor.getValue().getLevel());
+  }
+
+  @Test
+  void testParsingCustomHeaders() {
+    String customHeaders = "Authorization " + HoodieWriteCommitHttpCallbackClient.HEADERS_KV_DELIMITER + "Basic 12345678";
+    HoodieWriteCommitHttpCallbackClient client = makeClient(customHeaders);
+    assertEquals("{Authorization=Basic 12345678}", client.getCustomHeaders());
+    customHeaders = "Authorization " + HoodieWriteCommitHttpCallbackClient.HEADERS_KV_DELIMITER + "Basic 12345678" + HoodieWriteCommitHttpCallbackClient.HEADERS_DELIMITER
+        + " another_header_key " + HoodieWriteCommitHttpCallbackClient.HEADERS_KV_DELIMITER + " another_header_value ";
+    client = makeClient(customHeaders);
+    assertEquals("{Authorization=Basic 12345678, another_header_key=another_header_value}", client.getCustomHeaders());
+    customHeaders = "Authorization" + HoodieWriteCommitHttpCallbackClient.HEADERS_KV_DELIMITER + "Basic 12345678" + HoodieWriteCommitHttpCallbackClient.HEADERS_DELIMITER;
+    client = makeClient(customHeaders);
+    assertEquals("{Authorization=Basic 12345678}", client.getCustomHeaders());
+    customHeaders = "Authorization" + HoodieWriteCommitHttpCallbackClient.HEADERS_KV_DELIMITER + "Basic 12345678"  + HoodieWriteCommitHttpCallbackClient.HEADERS_DELIMITER + "uu";
+    client = makeClient(customHeaders);
+    assertEquals("{Authorization=Basic 12345678}", client.getCustomHeaders());
+    customHeaders = "Authorization" + HoodieWriteCommitHttpCallbackClient.HEADERS_KV_DELIMITER;
+    client = makeClient(customHeaders);
+    assertEquals("{}", client.getCustomHeaders());
+    customHeaders = HoodieWriteCommitHttpCallbackClient.HEADERS_KV_DELIMITER + "Authorization";
+    client = makeClient(customHeaders);
+    assertEquals("{}", client.getCustomHeaders());
+    customHeaders = "Authorization" + HoodieWriteCommitHttpCallbackClient.HEADERS_KV_DELIMITER + "Basic 12345678" + HoodieWriteCommitHttpCallbackClient.HEADERS_KV_DELIMITER
+        + "Second header" + HoodieWriteCommitHttpCallbackClient.HEADERS_KV_DELIMITER + "val";
+    client = makeClient(customHeaders);
+    assertEquals("{}", client.getCustomHeaders());
+    customHeaders = null;
+    client = makeClient(customHeaders);
+    assertEquals("{}", client.getCustomHeaders());
+    customHeaders = "";
+    client = makeClient(customHeaders);
+    assertEquals("{}", client.getCustomHeaders());
+    customHeaders = "  ";
+    client = makeClient(customHeaders);
+    assertEquals("{}", client.getCustomHeaders());
+    customHeaders = "  " + HoodieWriteCommitHttpCallbackClient.HEADERS_KV_DELIMITER + " ";
+    client = makeClient(customHeaders);
+    assertEquals("{}", client.getCustomHeaders());
+  }
+
+  private HoodieWriteCommitHttpCallbackClient makeClient(String customHeaders) {
+    HoodieWriteConfig config = HoodieWriteConfig.newBuilder().withPath("path")
+        .withCallbackConfig(HoodieWriteCommitCallbackConfig.newBuilder()
+            .withCallbackHttpApiKey(FAKE_API_KEY)
+            .withCallbackHttpUrl(FAKE_URL)
+            .withCustomHeaders(customHeaders)
+            .build())
+        .build();
+    return new HoodieWriteCommitHttpCallbackClient(config);
+  }
+}
diff --git a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/callback/http/TestCallbackHttpClient.java b/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/callback/http/TestCallbackHttpClient.java
deleted file mode 100644
index 49b948dd8c0..00000000000
--- a/hudi-client/hudi-client-common/src/test/java/org/apache/hudi/callback/http/TestCallbackHttpClient.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * 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.hudi.callback.http;
-
-import org.apache.hudi.callback.client.http.HoodieWriteCommitHttpCallbackClient;
-
-import org.apache.http.StatusLine;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.logging.log4j.Level;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.core.Appender;
-import org.apache.logging.log4j.core.LogEvent;
-import org.apache.logging.log4j.core.Logger;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Captor;
-import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
-
-import java.io.IOException;
-import java.util.UUID;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-/**
- * Unit test for {@link HoodieWriteCommitHttpCallbackClient}.
- */
-@ExtendWith(MockitoExtension.class)
-public class TestCallbackHttpClient {
-
-  @Mock
-  Appender appender;
-
-  @Captor
-  ArgumentCaptor<LogEvent> logCaptor;
-
-  @Mock
-  CloseableHttpClient httpClient;
-
-  @Mock
-  CloseableHttpResponse httpResponse;
-
-  @Mock
-  StatusLine statusLine;
-
-  private Level initialLogLevel;
-
-  @BeforeEach
-  void prepareAppender() {
-    when(appender.getName()).thenReturn("MockAppender-" + UUID.randomUUID());
-    when(appender.isStarted()).thenReturn(true);
-    when(appender.isStopped()).thenReturn(false);
-    Logger logger = (Logger) LogManager.getLogger(HoodieWriteCommitHttpCallbackClient.class);
-    initialLogLevel = logger.getLevel();
-    logger.setLevel(Level.DEBUG);
-    logger.addAppender(appender);
-  }
-
-  @AfterEach
-  void resetMocks() {
-    Logger logger = (Logger) LogManager.getLogger(HoodieWriteCommitHttpCallbackClient.class);
-    logger.setLevel(initialLogLevel);
-    logger.removeAppender(appender);
-    reset(appender, httpClient, httpResponse, statusLine);
-  }
-
-  private void mockResponse(int statusCode) {
-    when(statusLine.getStatusCode()).thenReturn(statusCode);
-    when(httpResponse.getStatusLine()).thenReturn(statusLine);
-    try {
-      when(httpClient.execute(any())).thenReturn(httpResponse);
-    } catch (IOException e) {
-      fail(e.getMessage(), e);
-    }
-  }
-
-  @Test
-  public void sendPayloadShouldLogWhenRequestFailed() throws IOException {
-    when(httpClient.execute(any())).thenThrow(IOException.class);
-
-    HoodieWriteCommitHttpCallbackClient hoodieWriteCommitCallBackHttpClient =
-        new HoodieWriteCommitHttpCallbackClient("fake_api_key", "fake_url", httpClient);
-    hoodieWriteCommitCallBackHttpClient.send("{}");
-
-    verify(appender).append(logCaptor.capture());
-    assertEquals("Failed to send callback.", logCaptor.getValue().getMessage().getFormattedMessage());
-    assertEquals(Level.WARN, logCaptor.getValue().getLevel());
-  }
-
-  @Test
-  public void sendPayloadShouldLogUnsuccessfulSending() {
-    mockResponse(401);
-    when(httpResponse.toString()).thenReturn("unauthorized");
-
-    HoodieWriteCommitHttpCallbackClient hoodieWriteCommitCallBackHttpClient =
-        new HoodieWriteCommitHttpCallbackClient("fake_api_key", "fake_url", httpClient);
-    hoodieWriteCommitCallBackHttpClient.send("{}");
-
-    verify(appender).append(logCaptor.capture());
-    assertEquals("Failed to send callback message. Response was unauthorized", logCaptor.getValue().getMessage().getFormattedMessage());
-    assertEquals(Level.WARN, logCaptor.getValue().getLevel());
-  }
-
-  @Test
-  public void sendPayloadShouldLogSuccessfulSending() {
-    mockResponse(202);
-
-    HoodieWriteCommitHttpCallbackClient hoodieWriteCommitCallBackHttpClient =
-        new HoodieWriteCommitHttpCallbackClient("fake_api_key", "fake_url", httpClient);
-    hoodieWriteCommitCallBackHttpClient.send("{}");
-
-    verify(appender).append(logCaptor.capture());
-    assertTrue(logCaptor.getValue().getMessage().getFormattedMessage().startsWith("Sent Callback data"));
-    assertEquals(Level.INFO, logCaptor.getValue().getLevel());
-  }
-
-}


(hudi) 01/28: [HUDI-7556] Fixing false positive validation with MDT validator (#10986)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 86968a6b9e4655ae111d599ea7c55e9f16f16625
Author: Sivabalan Narayanan <n....@gmail.com>
AuthorDate: Tue May 14 17:24:06 2024 -0700

    [HUDI-7556] Fixing false positive validation with MDT validator (#10986)
---
 .../utilities/HoodieMetadataTableValidator.java    |  96 +++++++++-------
 .../TestHoodieMetadataTableValidator.java          | 125 ++++++++++++++++++++-
 2 files changed, 181 insertions(+), 40 deletions(-)

diff --git a/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieMetadataTableValidator.java b/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieMetadataTableValidator.java
index bbe8610abe3..0e6630967b3 100644
--- a/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieMetadataTableValidator.java
+++ b/hudi-utilities/src/main/java/org/apache/hudi/utilities/HoodieMetadataTableValidator.java
@@ -52,6 +52,7 @@ import org.apache.hudi.common.util.ConfigUtils;
 import org.apache.hudi.common.util.FileIOUtils;
 import org.apache.hudi.common.util.Option;
 import org.apache.hudi.common.util.ParquetUtils;
+import org.apache.hudi.common.util.VisibleForTesting;
 import org.apache.hudi.common.util.collection.Pair;
 import org.apache.hudi.exception.HoodieException;
 import org.apache.hudi.exception.HoodieIOException;
@@ -514,7 +515,9 @@ public class HoodieMetadataTableValidator implements Serializable {
     }
 
     HoodieSparkEngineContext engineContext = new HoodieSparkEngineContext(jsc);
-    List<String> allPartitions = validatePartitions(engineContext, basePath);
+    // compare partitions
+
+    List<String> allPartitions = validatePartitions(engineContext, basePath, metaClient);
 
     if (allPartitions.isEmpty()) {
       LOG.warn("The result of getting all partitions is null or empty, skip current validation. {}", taskLabels);
@@ -612,39 +615,14 @@ public class HoodieMetadataTableValidator implements Serializable {
   /**
    * Compare the listing partitions result between metadata table and fileSystem.
    */
-  private List<String> validatePartitions(HoodieSparkEngineContext engineContext, String basePath) {
+  @VisibleForTesting
+  List<String> validatePartitions(HoodieSparkEngineContext engineContext, String basePath, HoodieTableMetaClient metaClient) {
     // compare partitions
-    List<String> allPartitionPathsFromFS = FSUtils.getAllPartitionPaths(engineContext, basePath, false, cfg.assumeDatePartitioning);
     HoodieTimeline completedTimeline = metaClient.getCommitsTimeline().filterCompletedInstants();
+    List<String> allPartitionPathsFromFS = getPartitionsFromFileSystem(engineContext, basePath, metaClient.getFs(),
+        completedTimeline);
 
-    // ignore partitions created by uncommitted ingestion.
-    allPartitionPathsFromFS = allPartitionPathsFromFS.stream().parallel().filter(part -> {
-      HoodiePartitionMetadata hoodiePartitionMetadata =
-          new HoodiePartitionMetadata(metaClient.getFs(), FSUtils.getPartitionPath(basePath, part));
-
-      Option<String> instantOption = hoodiePartitionMetadata.readPartitionCreatedCommitTime();
-      if (instantOption.isPresent()) {
-        String instantTime = instantOption.get();
-        // There are two cases where the created commit time is written to the partition metadata:
-        // (1) Commit C1 creates the partition and C1 succeeds, the partition metadata has C1 as
-        // the created commit time.
-        // (2) Commit C1 creates the partition, the partition metadata is written, and C1 fails
-        // during writing data files.  Next time, C2 adds new data to the same partition after C1
-        // is rolled back. In this case, the partition metadata still has C1 as the created commit
-        // time, since Hudi does not rewrite the partition metadata in C2.
-        if (!completedTimeline.containsOrBeforeTimelineStarts(instantTime)) {
-          Option<HoodieInstant> lastInstant = completedTimeline.lastInstant();
-          return lastInstant.isPresent()
-              && HoodieTimeline.compareTimestamps(
-              instantTime, LESSER_THAN_OR_EQUALS, lastInstant.get().getTimestamp());
-        }
-        return true;
-      } else {
-        return false;
-      }
-    }).collect(Collectors.toList());
-
-    List<String> allPartitionPathsMeta = FSUtils.getAllPartitionPaths(engineContext, basePath, true, cfg.assumeDatePartitioning);
+    List<String> allPartitionPathsMeta = getPartitionsFromMDT(engineContext, basePath);
 
     Collections.sort(allPartitionPathsFromFS);
     Collections.sort(allPartitionPathsMeta);
@@ -652,26 +630,23 @@ public class HoodieMetadataTableValidator implements Serializable {
     if (allPartitionPathsFromFS.size() != allPartitionPathsMeta.size()
         || !allPartitionPathsFromFS.equals(allPartitionPathsMeta)) {
       List<String> additionalFromFS = new ArrayList<>(allPartitionPathsFromFS);
-      additionalFromFS.remove(allPartitionPathsMeta);
+      additionalFromFS.removeAll(allPartitionPathsMeta);
       List<String> additionalFromMDT = new ArrayList<>(allPartitionPathsMeta);
-      additionalFromMDT.remove(allPartitionPathsFromFS);
+      additionalFromMDT.removeAll(allPartitionPathsFromFS);
       boolean misMatch = true;
       List<String> actualAdditionalPartitionsInMDT = new ArrayList<>(additionalFromMDT);
       if (additionalFromFS.isEmpty() && !additionalFromMDT.isEmpty()) {
         // there is a chance that when we polled MDT there could have been a new completed commit which was not complete when we polled FS based
         // listing. let's rule that out.
         additionalFromMDT.forEach(partitionFromDMT -> {
-
-          HoodiePartitionMetadata hoodiePartitionMetadata =
-              new HoodiePartitionMetadata(metaClient.getFs(), FSUtils.getPartitionPath(basePath, partitionFromDMT));
-          Option<String> partitionCreationTimeOpt = hoodiePartitionMetadata.readPartitionCreatedCommitTime();
+          Option<String> partitionCreationTimeOpt = getPartitionCreationInstant(metaClient.getFs(), basePath, partitionFromDMT);
           // if creation time is greater than last completed instant in active timeline, we can ignore the additional partition from MDT.
           if (partitionCreationTimeOpt.isPresent() && !completedTimeline.containsInstant(partitionCreationTimeOpt.get())) {
             Option<HoodieInstant> lastInstant = completedTimeline.lastInstant();
             if (lastInstant.isPresent()
                 && HoodieTimeline.compareTimestamps(partitionCreationTimeOpt.get(), GREATER_THAN, lastInstant.get().getTimestamp())) {
               LOG.warn("Ignoring additional partition " + partitionFromDMT + ", as it was deduced to be part of a "
-                  + "latest completed commit which was inflighht when FS based listing was polled.");
+                  + "latest completed commit which was inflight when FS based listing was polled.");
               actualAdditionalPartitionsInMDT.remove(partitionFromDMT);
             }
           }
@@ -689,10 +664,53 @@ public class HoodieMetadataTableValidator implements Serializable {
         throw new HoodieValidationException(message);
       }
     }
-
     return allPartitionPathsMeta;
   }
 
+  @VisibleForTesting
+  Option<String> getPartitionCreationInstant(FileSystem fs, String basePath, String partition) {
+    HoodiePartitionMetadata hoodiePartitionMetadata =
+        new HoodiePartitionMetadata(fs, FSUtils.getPartitionPath(basePath, partition));
+    return hoodiePartitionMetadata.readPartitionCreatedCommitTime();
+  }
+
+  @VisibleForTesting
+   List<String> getPartitionsFromMDT(HoodieEngineContext engineContext, String basePath) {
+    return FSUtils.getAllPartitionPaths(engineContext, basePath, true, false);
+  }
+
+  @VisibleForTesting
+  List<String> getPartitionsFromFileSystem(HoodieEngineContext engineContext, String basePath,
+                                           FileSystem fs, HoodieTimeline completedTimeline) {
+    List<String> allPartitionPathsFromFS = FSUtils.getAllPartitionPaths(engineContext, basePath, false, false);
+
+    // ignore partitions created by uncommitted ingestion.
+    return allPartitionPathsFromFS.stream().parallel().filter(part -> {
+      HoodiePartitionMetadata hoodiePartitionMetadata =
+          new HoodiePartitionMetadata(fs, FSUtils.getPartitionPath(basePath, part));
+      Option<String> instantOption = hoodiePartitionMetadata.readPartitionCreatedCommitTime();
+      if (instantOption.isPresent()) {
+        String instantTime = instantOption.get();
+        // There are two cases where the created commit time is written to the partition metadata:
+        // (1) Commit C1 creates the partition and C1 succeeds, the partition metadata has C1 as
+        // the created commit time.
+        // (2) Commit C1 creates the partition, the partition metadata is written, and C1 fails
+        // during writing data files.  Next time, C2 adds new data to the same partition after C1
+        // is rolled back. In this case, the partition metadata still has C1 as the created commit
+        // time, since Hudi does not rewrite the partition metadata in C2.
+        if (!completedTimeline.containsOrBeforeTimelineStarts(instantTime)) {
+          Option<HoodieInstant> lastInstant = completedTimeline.lastInstant();
+          return lastInstant.isPresent()
+              && HoodieTimeline.compareTimestamps(
+              instantTime, LESSER_THAN_OR_EQUALS, lastInstant.get().getTimestamp());
+        }
+        return true;
+      } else {
+        return false;
+      }
+    }).collect(Collectors.toList());
+  }
+
   /**
    * Compare the file listing and index data between metadata table and fileSystem.
    * For now, validate five kinds of apis:
diff --git a/hudi-utilities/src/test/java/org/apache/hudi/utilities/TestHoodieMetadataTableValidator.java b/hudi-utilities/src/test/java/org/apache/hudi/utilities/TestHoodieMetadataTableValidator.java
index e87f6257c54..2dd0168b22a 100644
--- a/hudi-utilities/src/test/java/org/apache/hudi/utilities/TestHoodieMetadataTableValidator.java
+++ b/hudi-utilities/src/test/java/org/apache/hudi/utilities/TestHoodieMetadataTableValidator.java
@@ -19,31 +19,48 @@
 package org.apache.hudi.utilities;
 
 import org.apache.hudi.DataSourceWriteOptions;
+import org.apache.hudi.client.common.HoodieSparkEngineContext;
+import org.apache.hudi.common.engine.HoodieEngineContext;
 import org.apache.hudi.common.model.WriteOperationType;
+import org.apache.hudi.common.table.HoodieTableMetaClient;
+import org.apache.hudi.common.table.timeline.HoodieActiveTimeline;
+import org.apache.hudi.common.table.timeline.HoodieInstant;
+import org.apache.hudi.common.table.timeline.HoodieTimeline;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.exception.HoodieValidationException;
 import org.apache.hudi.testutils.HoodieSparkClientTestBase;
 
+import org.apache.hadoop.fs.FileSystem;
 import org.apache.spark.api.java.JavaRDD;
+import org.apache.spark.api.java.JavaSparkContext;
 import org.apache.spark.sql.Dataset;
 import org.apache.spark.sql.Row;
 import org.apache.spark.sql.SaveMode;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
 
 import java.io.IOException;
+import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.stream.Collectors;
 
 import static org.apache.hudi.common.testutils.RawTripTestPayload.recordToString;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 
 public class TestHoodieMetadataTableValidator extends HoodieSparkClientTestBase {
 
   @Test
   public void testMetadataTableValidation() {
 
-    Map<String,String> writeOptions = new HashMap<>();
+    Map<String, String> writeOptions = new HashMap<>();
     writeOptions.put(DataSourceWriteOptions.TABLE_NAME().key(), "test_table");
     writeOptions.put("hoodie.table.name", "test_table");
     writeOptions.put(DataSourceWriteOptions.TABLE_TYPE().key(), "MERGE_ON_READ");
@@ -73,6 +90,112 @@ public class TestHoodieMetadataTableValidator extends HoodieSparkClientTestBase
     assertTrue(validator.getThrowables().isEmpty());
   }
 
+  @ParameterizedTest
+  @ValueSource(booleans = {true, false})
+  public void testAdditionalPartitionsinMDT(boolean testFailureCase) throws InterruptedException {
+    Map<String, String> writeOptions = new HashMap<>();
+    writeOptions.put(DataSourceWriteOptions.TABLE_NAME().key(), "test_table");
+    writeOptions.put("hoodie.table.name", "test_table");
+    writeOptions.put(DataSourceWriteOptions.TABLE_TYPE().key(), "MERGE_ON_READ");
+    writeOptions.put(DataSourceWriteOptions.RECORDKEY_FIELD().key(), "_row_key");
+    writeOptions.put(DataSourceWriteOptions.PRECOMBINE_FIELD().key(), "timestamp");
+    writeOptions.put(DataSourceWriteOptions.PARTITIONPATH_FIELD().key(), "partition_path");
+
+    // constructor of HoodieMetadataValidator instantiates HoodieTableMetaClient. hence creating an actual table. but rest of tests is mocked.
+    Dataset<Row> inserts = makeInsertDf("000", 5).cache();
+    inserts.write().format("hudi").options(writeOptions)
+        .option(DataSourceWriteOptions.OPERATION().key(), WriteOperationType.BULK_INSERT.value())
+        .mode(SaveMode.Overwrite)
+        .save(basePath);
+
+    HoodieMetadataTableValidator.Config config = new HoodieMetadataTableValidator.Config();
+    config.basePath = basePath;
+    config.validateLatestFileSlices = true;
+    config.validateAllFileGroups = true;
+    MockHoodieMetadataTableValidator validator = new MockHoodieMetadataTableValidator(jsc, config);
+    HoodieSparkEngineContext engineContext = new HoodieSparkEngineContext(jsc);
+    HoodieTableMetaClient metaClient = mock(HoodieTableMetaClient.class);
+
+    String partition1 = "PARTITION1";
+    String partition2 = "PARTITION2";
+    String partition3 = "PARTITION3";
+
+    // mock list of partitions to return from MDT to have 1 additional partition compared to FS based listing.
+    List<String> mdtPartitions = Arrays.asList(partition1, partition2, partition3);
+    validator.setMetadataPartitionsToReturn(mdtPartitions);
+    List<String> fsPartitions = Arrays.asList(partition1, partition2);
+    validator.setFsPartitionsToReturn(fsPartitions);
+
+    // mock completed timeline.
+    HoodieTimeline commitsTimeline = mock(HoodieTimeline.class);
+    HoodieTimeline completedTimeline = mock(HoodieTimeline.class);
+    when(metaClient.getCommitsTimeline()).thenReturn(commitsTimeline);
+    when(commitsTimeline.filterCompletedInstants()).thenReturn(completedTimeline);
+
+    if (testFailureCase) {
+      // 3rd partition which is additional in MDT should have creation time before last instant in timeline.
+
+      String partition3CreationTime = HoodieActiveTimeline.createNewInstantTime(true);
+      Thread.sleep(100);
+      String lastIntantCreationTime = HoodieActiveTimeline.createNewInstantTime(true);
+
+      HoodieInstant lastInstant = new HoodieInstant(HoodieInstant.State.COMPLETED, HoodieTimeline.COMMIT_ACTION, lastIntantCreationTime);
+      when(completedTimeline.lastInstant()).thenReturn(Option.of(lastInstant));
+      validator.setPartitionCreationTime(Option.of(partition3CreationTime));
+      // validate that exception is thrown since MDT has one additional partition.
+      assertThrows(HoodieValidationException.class, () -> {
+        validator.validatePartitions(engineContext, basePath, metaClient);
+      });
+    } else {
+      // 3rd partition creation time is > last completed instant
+      HoodieInstant lastInstant = new HoodieInstant(HoodieInstant.State.COMPLETED, HoodieTimeline.COMMIT_ACTION, HoodieActiveTimeline.createNewInstantTime(true, timeGenerator));
+      when(completedTimeline.lastInstant()).thenReturn(Option.of(lastInstant));
+      Thread.sleep(100);
+      validator.setPartitionCreationTime(Option.of(HoodieActiveTimeline.createNewInstantTime(true, timeGenerator)));
+
+      // validate that all 3 partitions are returned
+      assertEquals(mdtPartitions, validator.validatePartitions(engineContext, basePath, metaClient));
+    }
+  }
+
+  class MockHoodieMetadataTableValidator extends HoodieMetadataTableValidator {
+
+    private List<String> metadataPartitionsToReturn;
+    private List<String> fsPartitionsToReturn;
+    private Option<String> partitionCreationTime;
+
+    public MockHoodieMetadataTableValidator(JavaSparkContext jsc, Config cfg) {
+      super(jsc, cfg);
+    }
+
+    void setMetadataPartitionsToReturn(List<String> metadataPartitionsToReturn) {
+      this.metadataPartitionsToReturn = metadataPartitionsToReturn;
+    }
+
+    void setFsPartitionsToReturn(List<String> fsPartitionsToReturn) {
+      this.fsPartitionsToReturn = fsPartitionsToReturn;
+    }
+
+    void setPartitionCreationTime(Option<String> partitionCreationTime) {
+      this.partitionCreationTime = partitionCreationTime;
+    }
+
+    @Override
+    List<String> getPartitionsFromFileSystem(HoodieEngineContext engineContext, String basePath, FileSystem fs, HoodieTimeline completedTimeline) {
+      return fsPartitionsToReturn;
+    }
+
+    @Override
+    List<String> getPartitionsFromMDT(HoodieEngineContext engineContext, String basePath) {
+      return metadataPartitionsToReturn;
+    }
+
+    @Override
+    Option<String> getPartitionCreationInstant(FileSystem fs, String basePath, String partition) {
+      return this.partitionCreationTime;
+    }
+  }
+
   protected Dataset<Row> makeInsertDf(String instantTime, Integer n) {
     List<String> records = dataGen.generateInserts(instantTime, n).stream()
         .map(r -> recordToString(r).get()).collect(Collectors.toList());


(hudi) 03/28: [HUDI-7597] Add logs of Kafka offsets when the checkpoint is out of bound (#10987)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit ef96676f39e44bc1a5e8133a28512967bcc337f9
Author: Y Ethan Guo <et...@gmail.com>
AuthorDate: Wed Apr 10 03:03:45 2024 -0700

    [HUDI-7597] Add logs of Kafka offsets when the checkpoint is out of bound (#10987)
    
    * [HUDI-7597] Add logs of Kafka offsets when the checkpoint is out of bound
    
    * Adjust test
---
 .../utilities/sources/helpers/KafkaOffsetGen.java  | 29 +++++++++++++++-------
 .../utilities/sources/BaseTestKafkaSource.java     | 16 ++++++------
 2 files changed, 27 insertions(+), 18 deletions(-)

diff --git a/hudi-utilities/src/main/java/org/apache/hudi/utilities/sources/helpers/KafkaOffsetGen.java b/hudi-utilities/src/main/java/org/apache/hudi/utilities/sources/helpers/KafkaOffsetGen.java
index 442046cd948..71fe7a7629a 100644
--- a/hudi-utilities/src/main/java/org/apache/hudi/utilities/sources/helpers/KafkaOffsetGen.java
+++ b/hudi-utilities/src/main/java/org/apache/hudi/utilities/sources/helpers/KafkaOffsetGen.java
@@ -331,24 +331,35 @@ public class KafkaOffsetGen {
 
   /**
    * Fetch checkpoint offsets for each partition.
-   * @param consumer instance of {@link KafkaConsumer} to fetch offsets from.
+   *
+   * @param consumer          instance of {@link KafkaConsumer} to fetch offsets from.
    * @param lastCheckpointStr last checkpoint string.
-   * @param topicPartitions set of topic partitions.
+   * @param topicPartitions   set of topic partitions.
    * @return a map of Topic partitions to offsets.
    */
   private Map<TopicPartition, Long> fetchValidOffsets(KafkaConsumer consumer,
-                                                        Option<String> lastCheckpointStr, Set<TopicPartition> topicPartitions) {
+                                                      Option<String> lastCheckpointStr, Set<TopicPartition> topicPartitions) {
     Map<TopicPartition, Long> earliestOffsets = consumer.beginningOffsets(topicPartitions);
     Map<TopicPartition, Long> checkpointOffsets = CheckpointUtils.strToOffsets(lastCheckpointStr.get());
-    boolean isCheckpointOutOfBounds = checkpointOffsets.entrySet().stream()
-        .anyMatch(offset -> offset.getValue() < earliestOffsets.get(offset.getKey()));
+    List<TopicPartition> outOfBoundPartitionList = checkpointOffsets.entrySet().stream()
+        .filter(offset -> offset.getValue() < earliestOffsets.get(offset.getKey()))
+        .map(Map.Entry::getKey)
+        .collect(Collectors.toList());
+    boolean isCheckpointOutOfBounds = !outOfBoundPartitionList.isEmpty();
+
     if (isCheckpointOutOfBounds) {
+      String outOfBoundOffsets = outOfBoundPartitionList.stream()
+          .map(p -> p.toString() + ":{checkpoint=" + checkpointOffsets.get(p)
+              + ",earliestOffset=" + earliestOffsets.get(p) + "}")
+          .collect(Collectors.joining(","));
+      String message = "Some data may have been lost because they are not available in Kafka any more;"
+          + " either the data was aged out by Kafka or the topic may have been deleted before all the data in the topic was processed. "
+          + "Kafka partitions that have out-of-bound checkpoints: " + outOfBoundOffsets + " .";
+
       if (getBooleanWithAltKeys(this.props, KafkaSourceConfig.ENABLE_FAIL_ON_DATA_LOSS)) {
-        throw new HoodieStreamerException("Some data may have been lost because they are not available in Kafka any more;"
-            + " either the data was aged out by Kafka or the topic may have been deleted before all the data in the topic was processed.");
+        throw new HoodieStreamerException(message);
       } else {
-        LOG.warn("Some data may have been lost because they are not available in Kafka any more;"
-            + " either the data was aged out by Kafka or the topic may have been deleted before all the data in the topic was processed."
+        LOG.warn(message
             + " If you want Hudi Streamer to fail on such cases, set \"" + KafkaSourceConfig.ENABLE_FAIL_ON_DATA_LOSS.key() + "\" to \"true\".");
       }
     }
diff --git a/hudi-utilities/src/test/java/org/apache/hudi/utilities/sources/BaseTestKafkaSource.java b/hudi-utilities/src/test/java/org/apache/hudi/utilities/sources/BaseTestKafkaSource.java
index c5fc7bfaafa..e45d10e7a61 100644
--- a/hudi-utilities/src/test/java/org/apache/hudi/utilities/sources/BaseTestKafkaSource.java
+++ b/hudi-utilities/src/test/java/org/apache/hudi/utilities/sources/BaseTestKafkaSource.java
@@ -53,6 +53,7 @@ import static org.apache.hudi.utilities.config.KafkaSourceConfig.ENABLE_KAFKA_CO
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -254,7 +255,7 @@ abstract class BaseTestKafkaSource extends SparkClientFunctionalTestHarness {
     final String topic = TEST_TOPIC_PREFIX + "testFailOnDataLoss";
     Properties topicConfig = new Properties();
     topicConfig.setProperty("retention.ms", "8000");
-    testUtils.createTopic(topic, 1, topicConfig);
+    testUtils.createTopic(topic, 2, topicConfig);
 
     TypedProperties failOnDataLossProps = createPropsForKafkaSource(topic, null, "earliest");
     failOnDataLossProps.setProperty(KafkaSourceConfig.ENABLE_FAIL_ON_DATA_LOSS.key(), Boolean.toString(true));
@@ -269,17 +270,14 @@ abstract class BaseTestKafkaSource extends SparkClientFunctionalTestHarness {
     Throwable t = assertThrows(HoodieStreamerException.class, () -> {
       kafkaSource.fetchNewDataInAvroFormat(Option.of(fetch1.getCheckpointForNextBatch()), Long.MAX_VALUE);
     });
-    assertEquals(
-        "Some data may have been lost because they are not available in Kafka any more;"
-            + " either the data was aged out by Kafka or the topic may have been deleted before all the data in the topic was processed.",
-        t.getMessage());
+    String errorMessagePrefix = "Some data may have been lost because they are not available in Kafka any more;"
+        + " either the data was aged out by Kafka or the topic may have been deleted before all the data in the topic was processed. "
+        + "Kafka partitions that have out-of-bound checkpoints:";
+    assertTrue(t.getMessage().startsWith(errorMessagePrefix));
     t = assertThrows(HoodieStreamerException.class, () -> {
       kafkaSource.fetchNewDataInRowFormat(Option.of(fetch1.getCheckpointForNextBatch()), Long.MAX_VALUE);
     });
-    assertEquals(
-        "Some data may have been lost because they are not available in Kafka any more;"
-            + " either the data was aged out by Kafka or the topic may have been deleted before all the data in the topic was processed.",
-        t.getMessage());
+    assertTrue(t.getMessage().startsWith(errorMessagePrefix));
   }
 
   @Test


(hudi) 23/28: [HUDI-4228] Clean up literal usage in Hudi CLI argument check (#11042)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 6fc3ad4060e29562ccba00561edcf75170219ac1
Author: Vova Kolmakov <wo...@gmail.com>
AuthorDate: Thu Apr 18 09:14:32 2024 +0700

    [HUDI-4228] Clean up literal usage in Hudi CLI argument check (#11042)
---
 .../org/apache/hudi/cli/commands/SparkMain.java    | 201 +++++++--------------
 .../org/apache/hudi/cli/ArchiveExecutorUtils.java  |   2 +-
 2 files changed, 69 insertions(+), 134 deletions(-)

diff --git a/hudi-cli/src/main/java/org/apache/hudi/cli/commands/SparkMain.java b/hudi-cli/src/main/java/org/apache/hudi/cli/commands/SparkMain.java
index 742540d0ff5..c312deaf6c3 100644
--- a/hudi-cli/src/main/java/org/apache/hudi/cli/commands/SparkMain.java
+++ b/hudi-cli/src/main/java/org/apache/hudi/cli/commands/SparkMain.java
@@ -19,14 +19,13 @@
 package org.apache.hudi.cli.commands;
 
 import org.apache.hudi.DataSourceWriteOptions;
+import org.apache.hudi.cli.ArchiveExecutorUtils;
 import org.apache.hudi.cli.utils.SparkUtil;
 import org.apache.hudi.client.HoodieTimelineArchiver;
 import org.apache.hudi.client.SparkRDDWriteClient;
 import org.apache.hudi.client.common.HoodieSparkEngineContext;
-import org.apache.hudi.common.config.HoodieMetadataConfig;
 import org.apache.hudi.common.config.TypedProperties;
 import org.apache.hudi.common.engine.HoodieEngineContext;
-import org.apache.hudi.common.model.HoodieAvroPayload;
 import org.apache.hudi.common.model.HoodieFailedWritesCleaningPolicy;
 import org.apache.hudi.common.model.HoodieRecord;
 import org.apache.hudi.common.model.WriteOperationType;
@@ -37,7 +36,6 @@ import org.apache.hudi.common.util.Option;
 import org.apache.hudi.common.util.PartitionPathEncodeUtils;
 import org.apache.hudi.common.util.StringUtils;
 import org.apache.hudi.common.util.ValidationUtils;
-import org.apache.hudi.config.HoodieArchivalConfig;
 import org.apache.hudi.config.HoodieBootstrapConfig;
 import org.apache.hudi.config.HoodieCleanConfig;
 import org.apache.hudi.config.HoodieIndexConfig;
@@ -99,16 +97,45 @@ public class SparkMain {
    * Commands.
    */
   enum SparkCommand {
-    BOOTSTRAP, ROLLBACK, DEDUPLICATE, ROLLBACK_TO_SAVEPOINT, SAVEPOINT, IMPORT, UPSERT, COMPACT_SCHEDULE, COMPACT_RUN, COMPACT_SCHEDULE_AND_EXECUTE,
-    COMPACT_UNSCHEDULE_PLAN, COMPACT_UNSCHEDULE_FILE, COMPACT_VALIDATE, COMPACT_REPAIR, CLUSTERING_SCHEDULE,
-    CLUSTERING_RUN, CLUSTERING_SCHEDULE_AND_EXECUTE, CLEAN, DELETE_MARKER, DELETE_SAVEPOINT, UPGRADE, DOWNGRADE,
-    REPAIR_DEPRECATED_PARTITION, RENAME_PARTITION, ARCHIVE
+    BOOTSTRAP(18), ROLLBACK(6), DEDUPLICATE(8), ROLLBACK_TO_SAVEPOINT(6), SAVEPOINT(7),
+    IMPORT(13), UPSERT(13), COMPACT_SCHEDULE(7), COMPACT_RUN(10), COMPACT_SCHEDULE_AND_EXECUTE(9),
+    COMPACT_UNSCHEDULE_PLAN(9), COMPACT_UNSCHEDULE_FILE(10), COMPACT_VALIDATE(7), COMPACT_REPAIR(8),
+    CLUSTERING_SCHEDULE(7), CLUSTERING_RUN(9), CLUSTERING_SCHEDULE_AND_EXECUTE(8), CLEAN(5),
+    DELETE_MARKER(5), DELETE_SAVEPOINT(5), UPGRADE(5), DOWNGRADE(5),
+    REPAIR_DEPRECATED_PARTITION(4), RENAME_PARTITION(6), ARCHIVE(8);
+
+    private final int minArgsCount;
+
+    SparkCommand(int minArgsCount) {
+      this.minArgsCount = minArgsCount;
+    }
+
+    void assertEq(int factArgsCount) {
+      ValidationUtils.checkArgument(factArgsCount == minArgsCount);
+    }
+
+    void assertGtEq(int factArgsCount) {
+      ValidationUtils.checkArgument(factArgsCount >= minArgsCount);
+    }
+
+    List<String> makeConfigs(String[] args) {
+      List<String> configs = new ArrayList<>();
+      if (args.length > minArgsCount) {
+        configs.addAll(Arrays.asList(args).subList(minArgsCount, args.length));
+      }
+      return configs;
+    }
+
+    String getPropsFilePath(String[] args) {
+      return (args.length >= minArgsCount && !StringUtils.isNullOrEmpty(args[minArgsCount - 1]))
+          ? args[minArgsCount - 1] : null;
+    }
   }
 
-  public static void main(String[] args) throws Exception {
+  public static void main(String[] args) {
     ValidationUtils.checkArgument(args.length >= 4);
     final String commandString = args[0];
-    LOG.info("Invoking SparkMain: " + commandString);
+    LOG.info("Invoking SparkMain: {}", commandString);
     final SparkCommand cmd = SparkCommand.valueOf(commandString);
 
     JavaSparkContext jsc = SparkUtil.initJavaSparkContext("hoodie-cli-" + commandString,
@@ -116,193 +143,112 @@ public class SparkMain {
 
     int returnCode = 0;
     try {
+      cmd.assertGtEq(args.length);
+      List<String> configs = cmd.makeConfigs(args);
+      String propsFilePath = cmd.getPropsFilePath(args);
       switch (cmd) {
         case ROLLBACK:
-          assert (args.length == 6);
+          cmd.assertEq(args.length);
           returnCode = rollback(jsc, args[3], args[4], Boolean.parseBoolean(args[5]));
           break;
         case DEDUPLICATE:
-          assert (args.length == 8);
+          cmd.assertEq(args.length);
           returnCode = deduplicatePartitionPath(jsc, args[3], args[4], args[5], Boolean.parseBoolean(args[6]), args[7]);
           break;
         case ROLLBACK_TO_SAVEPOINT:
-          assert (args.length == 6);
+          cmd.assertEq(args.length);
           returnCode = rollbackToSavepoint(jsc, args[3], args[4], Boolean.parseBoolean(args[5]));
           break;
         case IMPORT:
         case UPSERT:
-          assert (args.length >= 13);
-          String propsFilePath = null;
-          if (!StringUtils.isNullOrEmpty(args[12])) {
-            propsFilePath = args[12];
-          }
-          List<String> configs = new ArrayList<>();
-          if (args.length > 13) {
-            configs.addAll(Arrays.asList(args).subList(13, args.length));
-          }
           returnCode = dataLoad(jsc, commandString, args[3], args[4], args[5], args[6], args[7], args[8],
               Integer.parseInt(args[9]), args[10], Integer.parseInt(args[11]), propsFilePath, configs);
           break;
         case COMPACT_RUN:
-          assert (args.length >= 10);
-          propsFilePath = null;
-          if (!StringUtils.isNullOrEmpty(args[9])) {
-            propsFilePath = args[9];
-          }
-          configs = new ArrayList<>();
-          if (args.length > 10) {
-            configs.addAll(Arrays.asList(args).subList(10, args.length));
-          }
           returnCode = compact(jsc, args[3], args[4], args[5], Integer.parseInt(args[6]), args[7],
               Integer.parseInt(args[8]), HoodieCompactor.EXECUTE, propsFilePath, configs);
           break;
         case COMPACT_SCHEDULE_AND_EXECUTE:
-          assert (args.length >= 9);
-          propsFilePath = null;
-          if (!StringUtils.isNullOrEmpty(args[8])) {
-            propsFilePath = args[8];
-          }
-          configs = new ArrayList<>();
-          if (args.length > 9) {
-            configs.addAll(Arrays.asList(args).subList(9, args.length));
-          }
-
           returnCode = compact(jsc, args[3], args[4], null, Integer.parseInt(args[5]), args[6],
               Integer.parseInt(args[7]), HoodieCompactor.SCHEDULE_AND_EXECUTE, propsFilePath, configs);
           break;
         case COMPACT_SCHEDULE:
-          assert (args.length >= 7);
-          propsFilePath = null;
-          if (!StringUtils.isNullOrEmpty(args[6])) {
-            propsFilePath = args[6];
-          }
-          configs = new ArrayList<>();
-          if (args.length > 7) {
-            configs.addAll(Arrays.asList(args).subList(7, args.length));
-          }
           returnCode = compact(jsc, args[3], args[4], args[5], 1, "", 0, HoodieCompactor.SCHEDULE, propsFilePath, configs);
           break;
         case COMPACT_VALIDATE:
-          assert (args.length == 7);
+          cmd.assertEq(args.length);
           doCompactValidate(jsc, args[3], args[4], args[5], Integer.parseInt(args[6]));
           returnCode = 0;
           break;
         case COMPACT_REPAIR:
-          assert (args.length == 8);
-          doCompactRepair(jsc, args[3], args[4], args[5], Integer.parseInt(args[6]),
-              Boolean.parseBoolean(args[7]));
+          cmd.assertEq(args.length);
+          doCompactRepair(jsc, args[3], args[4], args[5], Integer.parseInt(args[6]), Boolean.parseBoolean(args[7]));
           returnCode = 0;
           break;
         case COMPACT_UNSCHEDULE_FILE:
-          assert (args.length == 10);
+          cmd.assertEq(args.length);
           doCompactUnscheduleFile(jsc, args[3], args[4], args[5], args[6], Integer.parseInt(args[7]),
               Boolean.parseBoolean(args[8]), Boolean.parseBoolean(args[9]));
           returnCode = 0;
           break;
         case COMPACT_UNSCHEDULE_PLAN:
-          assert (args.length == 9);
+          cmd.assertEq(args.length);
           doCompactUnschedule(jsc, args[3], args[4], args[5], Integer.parseInt(args[6]),
               Boolean.parseBoolean(args[7]), Boolean.parseBoolean(args[8]));
           returnCode = 0;
           break;
         case CLUSTERING_RUN:
-          assert (args.length >= 9);
-          propsFilePath = null;
-          if (!StringUtils.isNullOrEmpty(args[8])) {
-            propsFilePath = args[8];
-          }
-          configs = new ArrayList<>();
-          if (args.length > 9) {
-            configs.addAll(Arrays.asList(args).subList(9, args.length));
-          }
           returnCode = cluster(jsc, args[3], args[4], args[5], Integer.parseInt(args[6]), args[2],
               Integer.parseInt(args[7]), EXECUTE, propsFilePath, configs);
           break;
         case CLUSTERING_SCHEDULE_AND_EXECUTE:
-          assert (args.length >= 8);
-          propsFilePath = null;
-          if (!StringUtils.isNullOrEmpty(args[7])) {
-            propsFilePath = args[7];
-          }
-          configs = new ArrayList<>();
-          if (args.length > 8) {
-            configs.addAll(Arrays.asList(args).subList(8, args.length));
-          }
           returnCode = cluster(jsc, args[3], args[4], null, Integer.parseInt(args[5]), args[2],
               Integer.parseInt(args[6]), SCHEDULE_AND_EXECUTE, propsFilePath, configs);
           break;
         case CLUSTERING_SCHEDULE:
-          assert (args.length >= 7);
-          propsFilePath = null;
-          if (!StringUtils.isNullOrEmpty(args[6])) {
-            propsFilePath = args[6];
-          }
-          configs = new ArrayList<>();
-          if (args.length > 7) {
-            configs.addAll(Arrays.asList(args).subList(7, args.length));
-          }
-          returnCode = cluster(jsc, args[3], args[4], args[5], 1, args[2],
-              0, SCHEDULE, propsFilePath, configs);
+          returnCode = cluster(jsc, args[3], args[4], args[5], 1, args[2], 0, SCHEDULE, propsFilePath, configs);
           break;
         case CLEAN:
-          assert (args.length >= 5);
-          propsFilePath = null;
-          if (!StringUtils.isNullOrEmpty(args[4])) {
-            propsFilePath = args[4];
-          }
-          configs = new ArrayList<>();
-          if (args.length > 5) {
-            configs.addAll(Arrays.asList(args).subList(5, args.length));
-          }
           clean(jsc, args[3], propsFilePath, configs);
           break;
         case SAVEPOINT:
-          assert (args.length == 7);
+          cmd.assertEq(args.length);
           returnCode = createSavepoint(jsc, args[3], args[4], args[5], args[6]);
           break;
         case DELETE_MARKER:
-          assert (args.length == 5);
+          cmd.assertEq(args.length);
           returnCode = deleteMarker(jsc, args[3], args[4]);
           break;
         case DELETE_SAVEPOINT:
-          assert (args.length == 5);
+          cmd.assertEq(args.length);
           returnCode = deleteSavepoint(jsc, args[3], args[4]);
           break;
         case BOOTSTRAP:
-          assert (args.length >= 18);
-          propsFilePath = null;
-          if (!StringUtils.isNullOrEmpty(args[17])) {
-            propsFilePath = args[17];
-          }
-          configs = new ArrayList<>();
-          if (args.length > 18) {
-            configs.addAll(Arrays.asList(args).subList(18, args.length));
-          }
           returnCode = doBootstrap(jsc, args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10],
               args[11], args[12], args[13], args[14], args[15], args[16], propsFilePath, configs);
           break;
         case UPGRADE:
         case DOWNGRADE:
-          assert (args.length == 5);
+          cmd.assertEq(args.length);
           returnCode = upgradeOrDowngradeTable(jsc, args[3], args[4]);
           break;
         case REPAIR_DEPRECATED_PARTITION:
-          assert (args.length == 4);
+          cmd.assertEq(args.length);
           returnCode = repairDeprecatedPartition(jsc, args[3]);
           break;
         case RENAME_PARTITION:
-          assert (args.length == 6);
+          cmd.assertEq(args.length);
           returnCode = renamePartition(jsc, args[3], args[4], args[5]);
           break;
         case ARCHIVE:
-          assert (args.length == 8);
+          cmd.assertEq(args.length);
           returnCode = archive(jsc, Integer.parseInt(args[3]), Integer.parseInt(args[4]), Integer.parseInt(args[5]), Boolean.parseBoolean(args[6]), args[7]);
           break;
         default:
           break;
       }
-    } catch (Throwable throwable) {
-      LOG.error("Fail to execute commandString", throwable);
+    } catch (Exception exception) {
+      LOG.error("Fail to execute commandString", exception);
       returnCode = -1;
     } finally {
       jsc.stop();
@@ -473,7 +419,7 @@ public class SparkMain {
       try {
         fs.delete(new Path(basePath, oldPartition), true);
       } catch (IOException e) {
-        LOG.warn("Failed to delete older partition " + basePath);
+        LOG.warn("Failed to delete older partition {}", basePath);
       }
     }
     return 0;
@@ -563,10 +509,10 @@ public class SparkMain {
   private static int rollback(JavaSparkContext jsc, String instantTime, String basePath, Boolean rollbackUsingMarkers) throws Exception {
     SparkRDDWriteClient client = createHoodieClient(jsc, basePath, rollbackUsingMarkers, false);
     if (client.rollback(instantTime)) {
-      LOG.info(String.format("The commit \"%s\" rolled back.", instantTime));
+      LOG.info("The commit \"{}\" rolled back.", instantTime);
       return 0;
     } else {
-      LOG.warn(String.format("The commit \"%s\" failed to roll back.", instantTime));
+      LOG.warn("The commit \"{}\" failed to roll back.", instantTime);
       return -1;
     }
   }
@@ -575,10 +521,10 @@ public class SparkMain {
                                      String comments, String basePath) throws Exception {
     try (SparkRDDWriteClient client = createHoodieClient(jsc, basePath, false)) {
       client.savepoint(commitTime, user, comments);
-      LOG.info(String.format("The commit \"%s\" has been savepointed.", commitTime));
+      LOG.info("The commit \"{}\" has been savepointed.", commitTime);
       return 0;
     } catch (HoodieSavepointException se) {
-      LOG.warn(String.format("Failed: Could not create savepoint \"%s\".", commitTime));
+      LOG.warn("Failed: Could not create savepoint \"{}\".", commitTime);
       return -1;
     }
   }
@@ -586,7 +532,7 @@ public class SparkMain {
   private static int rollbackToSavepoint(JavaSparkContext jsc, String savepointTime, String basePath, boolean lazyCleanPolicy) throws Exception {
     try (SparkRDDWriteClient client = createHoodieClient(jsc, basePath, lazyCleanPolicy)) {
       client.restoreToSavepoint(savepointTime);
-      LOG.info(String.format("The commit \"%s\" rolled back.", savepointTime));
+      LOG.info("The commit \"{}\" rolled back.", savepointTime);
       return 0;
     } catch (Exception e) {
       LOG.warn(String.format("The commit \"%s\" failed to roll back.", savepointTime), e);
@@ -597,7 +543,7 @@ public class SparkMain {
   private static int deleteSavepoint(JavaSparkContext jsc, String savepointTime, String basePath) throws Exception {
     try (SparkRDDWriteClient client = createHoodieClient(jsc, basePath, false)) {
       client.deleteSavepoint(savepointTime);
-      LOG.info(String.format("Savepoint \"%s\" deleted.", savepointTime));
+      LOG.info("Savepoint \"{}\" deleted.", savepointTime);
       return 0;
     } catch (Exception e) {
       LOG.warn(String.format("Failed: Could not delete savepoint \"%s\".", savepointTime), e);
@@ -627,7 +573,7 @@ public class SparkMain {
     try {
       new UpgradeDowngrade(metaClient, updatedConfig, new HoodieSparkEngineContext(jsc), SparkUpgradeDowngradeHelper.getInstance())
           .run(HoodieTableVersion.valueOf(toVersion), null);
-      LOG.info(String.format("Table at \"%s\" upgraded / downgraded to version \"%s\".", basePath, toVersion));
+      LOG.info("Table at \"{}\" upgraded / downgraded to version \"{}\".", basePath, toVersion);
       return 0;
     } catch (Exception e) {
       LOG.warn(String.format("Failed: Could not upgrade/downgrade table at \"%s\" to version \"%s\".", basePath, toVersion), e);
@@ -653,21 +599,10 @@ public class SparkMain {
   }
 
   private static int archive(JavaSparkContext jsc, int minCommits, int maxCommits, int commitsRetained, boolean enableMetadata, String basePath) {
-    HoodieWriteConfig config = HoodieWriteConfig.newBuilder().withPath(basePath)
-        .withArchivalConfig(HoodieArchivalConfig.newBuilder().archiveCommitsWith(minCommits,maxCommits).build())
-        .withCleanConfig(HoodieCleanConfig.newBuilder().retainCommits(commitsRetained).build())
-        .withEmbeddedTimelineServerEnabled(false)
-        .withMetadataConfig(HoodieMetadataConfig.newBuilder().enable(enableMetadata).build())
-        .build();
-    HoodieEngineContext context = new HoodieSparkEngineContext(jsc);
-    HoodieSparkTable<HoodieAvroPayload> table = HoodieSparkTable.create(config, context);
     try {
-      HoodieTimelineArchiver archiver = new HoodieTimelineArchiver(config, table);
-      archiver.archiveIfRequired(context,true);
-    } catch (IOException ioe) {
-      LOG.error("Failed to archive with IOException: " + ioe);
-      return  -1;
+      return ArchiveExecutorUtils.archive(jsc, minCommits, maxCommits, commitsRetained, enableMetadata, basePath);
+    } catch (IOException ex) {
+      return -1;
     }
-    return 0;
   }
 }
diff --git a/hudi-spark-datasource/hudi-spark/src/main/java/org/apache/hudi/cli/ArchiveExecutorUtils.java b/hudi-spark-datasource/hudi-spark/src/main/java/org/apache/hudi/cli/ArchiveExecutorUtils.java
index 5a8545ed66a..a3bd9f5673f 100644
--- a/hudi-spark-datasource/hudi-spark/src/main/java/org/apache/hudi/cli/ArchiveExecutorUtils.java
+++ b/hudi-spark-datasource/hudi-spark/src/main/java/org/apache/hudi/cli/ArchiveExecutorUtils.java
@@ -61,7 +61,7 @@ public final class ArchiveExecutorUtils {
       HoodieTimelineArchiver archiver = new HoodieTimelineArchiver(config, table);
       archiver.archiveIfRequired(context, true);
     } catch (IOException ioe) {
-      LOG.error("Failed to archive with IOException: " + ioe);
+      LOG.error("Failed to archive with IOException: {}", ioe.getMessage());
       throw ioe;
     }
     return 0;


(hudi) 13/28: [HUDI-7606] Unpersist RDDs after table services, mainly compaction and clustering (#11000)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 7e5871a4634fc7b0d195a4148bb02dcf3f57d8e1
Author: Rajesh Mahindra <76...@users.noreply.github.com>
AuthorDate: Sun Apr 14 14:38:55 2024 -0700

    [HUDI-7606] Unpersist RDDs after table services, mainly compaction and clustering (#11000)
    
    ---------
    
    Co-authored-by: rmahindra123 <rm...@Rajeshs-MacBook-Pro.local>
---
 .../hudi/client/BaseHoodieTableServiceClient.java  | 12 ++++
 .../apache/hudi/client/BaseHoodieWriteClient.java  |  2 +-
 .../hudi/client/SparkRDDTableServiceClient.java    |  6 ++
 .../apache/hudi/client/SparkRDDWriteClient.java    | 21 +------
 .../hudi/client/utils/SparkReleaseResources.java   | 64 ++++++++++++++++++++++
 5 files changed, 85 insertions(+), 20 deletions(-)

diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieTableServiceClient.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieTableServiceClient.java
index e408dc7a779..d6ec07b89d0 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieTableServiceClient.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieTableServiceClient.java
@@ -331,6 +331,7 @@ public abstract class BaseHoodieTableServiceClient<I, T, O> extends BaseHoodieCl
       CompactHelpers.getInstance().completeInflightCompaction(table, compactionCommitTime, metadata);
     } finally {
       this.txnManager.endTransaction(Option.of(compactionInstant));
+      releaseResources(compactionCommitTime);
     }
     WriteMarkersFactory.get(config.getMarkersType(), table, compactionCommitTime)
         .quietDeleteMarkerDir(context, config.getMarkersDeleteParallelism());
@@ -391,6 +392,7 @@ public abstract class BaseHoodieTableServiceClient<I, T, O> extends BaseHoodieCl
       CompactHelpers.getInstance().completeInflightLogCompaction(table, logCompactionCommitTime, metadata);
     } finally {
       this.txnManager.endTransaction(Option.of(logCompactionInstant));
+      releaseResources(logCompactionCommitTime);
     }
     WriteMarkersFactory.get(config.getMarkersType(), table, logCompactionCommitTime)
         .quietDeleteMarkerDir(context, config.getMarkersDeleteParallelism());
@@ -520,6 +522,7 @@ public abstract class BaseHoodieTableServiceClient<I, T, O> extends BaseHoodieCl
       throw new HoodieClusteringException("unable to transition clustering inflight to complete: " + clusteringCommitTime, e);
     } finally {
       this.txnManager.endTransaction(Option.of(clusteringInstant));
+      releaseResources(clusteringCommitTime);
     }
     WriteMarkersFactory.get(config.getMarkersType(), table, clusteringCommitTime)
         .quietDeleteMarkerDir(context, config.getMarkersDeleteParallelism());
@@ -759,6 +762,7 @@ public abstract class BaseHoodieTableServiceClient<I, T, O> extends BaseHoodieCl
           + " Earliest Retained Instant :" + metadata.getEarliestCommitToRetain()
           + " cleanerElapsedMs" + durationMs);
     }
+    releaseResources(cleanInstantTime);
     return metadata;
   }
 
@@ -1133,4 +1137,12 @@ public abstract class BaseHoodieTableServiceClient<I, T, O> extends BaseHoodieCl
       }
     }
   }
+
+  /**
+   * Called after each commit of a compaction or clustering table service,
+   * to release any resources used.
+   */
+  protected void releaseResources(String instantTime) {
+    // do nothing here
+  }
 }
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieWriteClient.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieWriteClient.java
index d5d74e94673..fdc9eeca90d 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieWriteClient.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/BaseHoodieWriteClient.java
@@ -237,11 +237,11 @@ public abstract class BaseHoodieWriteClient<T, I, K, O> extends BaseHoodieClient
       commit(table, commitActionType, instantTime, metadata, stats, writeStatuses);
       postCommit(table, metadata, instantTime, extraMetadata);
       LOG.info("Committed " + instantTime);
-      releaseResources(instantTime);
     } catch (IOException e) {
       throw new HoodieCommitException("Failed to complete commit " + config.getBasePath() + " at time " + instantTime, e);
     } finally {
       this.txnManager.endTransaction(Option.of(inflightInstant));
+      releaseResources(instantTime);
     }
 
     // trigger clean and archival.
diff --git a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/SparkRDDTableServiceClient.java b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/SparkRDDTableServiceClient.java
index 54d91fae3cf..98914be7496 100644
--- a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/SparkRDDTableServiceClient.java
+++ b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/SparkRDDTableServiceClient.java
@@ -21,6 +21,7 @@ package org.apache.hudi.client;
 import org.apache.hudi.avro.model.HoodieClusteringGroup;
 import org.apache.hudi.avro.model.HoodieClusteringPlan;
 import org.apache.hudi.client.embedded.EmbeddedTimelineService;
+import org.apache.hudi.client.utils.SparkReleaseResources;
 import org.apache.hudi.common.data.HoodieData;
 import org.apache.hudi.common.engine.HoodieEngineContext;
 import org.apache.hudi.common.model.HoodieRecord;
@@ -73,4 +74,9 @@ public class SparkRDDTableServiceClient<T> extends BaseHoodieTableServiceClient<
   protected HoodieTable<?, HoodieData<HoodieRecord<T>>, ?, HoodieData<WriteStatus>> createTable(HoodieWriteConfig config, Configuration hadoopConf) {
     return HoodieSparkTable.create(config, context);
   }
+
+  @Override
+  protected void releaseResources(String instantTime) {
+    SparkReleaseResources.releaseCachedData(context, config, basePath, instantTime);
+  }
 }
diff --git a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/SparkRDDWriteClient.java b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/SparkRDDWriteClient.java
index 4ec886e1edb..0302c573db6 100644
--- a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/SparkRDDWriteClient.java
+++ b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/SparkRDDWriteClient.java
@@ -21,8 +21,8 @@ package org.apache.hudi.client;
 import org.apache.hudi.client.common.HoodieSparkEngineContext;
 import org.apache.hudi.client.embedded.EmbeddedTimelineService;
 import org.apache.hudi.client.utils.CommitMetadataUtils;
+import org.apache.hudi.client.utils.SparkReleaseResources;
 import org.apache.hudi.common.data.HoodieData;
-import org.apache.hudi.common.data.HoodieData.HoodieDataCacheKey;
 import org.apache.hudi.common.engine.HoodieEngineContext;
 import org.apache.hudi.common.metrics.Registry;
 import org.apache.hudi.common.model.HoodieCommitMetadata;
@@ -40,7 +40,6 @@ import org.apache.hudi.exception.HoodieException;
 import org.apache.hudi.hadoop.fs.HoodieWrapperFileSystem;
 import org.apache.hudi.index.HoodieIndex;
 import org.apache.hudi.index.SparkHoodieIndexFactory;
-import org.apache.hudi.metadata.HoodieTableMetadata;
 import org.apache.hudi.metadata.HoodieTableMetadataWriter;
 import org.apache.hudi.metadata.SparkHoodieBackedTableMetadataWriter;
 import org.apache.hudi.metrics.DistributedRegistry;
@@ -58,7 +57,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import java.io.IOException;
-import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.function.BiConsumer;
@@ -334,21 +332,6 @@ public class SparkRDDWriteClient<T> extends
 
   @Override
   protected void releaseResources(String instantTime) {
-    // If we do not explicitly release the resource, spark will automatically manage the resource and clean it up automatically
-    // see: https://spark.apache.org/docs/latest/rdd-programming-guide.html#removing-data
-    if (config.areReleaseResourceEnabled()) {
-      HoodieSparkEngineContext sparkEngineContext = (HoodieSparkEngineContext) context;
-      Map<Integer, JavaRDD<?>> allCachedRdds = sparkEngineContext.getJavaSparkContext().getPersistentRDDs();
-      List<Integer> allDataIds = new ArrayList<>(sparkEngineContext.removeCachedDataIds(HoodieDataCacheKey.of(basePath, instantTime)));
-      if (config.isMetadataTableEnabled()) {
-        String metadataTableBasePath = HoodieTableMetadata.getMetadataTableBasePath(basePath);
-        allDataIds.addAll(sparkEngineContext.removeCachedDataIds(HoodieDataCacheKey.of(metadataTableBasePath, instantTime)));
-      }
-      for (int id : allDataIds) {
-        if (allCachedRdds.containsKey(id)) {
-          allCachedRdds.get(id).unpersist();
-        }
-      }
-    }
+    SparkReleaseResources.releaseCachedData(context, config, basePath, instantTime);
   }
 }
diff --git a/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/utils/SparkReleaseResources.java b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/utils/SparkReleaseResources.java
new file mode 100644
index 00000000000..a151a33cee9
--- /dev/null
+++ b/hudi-client/hudi-spark-client/src/main/java/org/apache/hudi/client/utils/SparkReleaseResources.java
@@ -0,0 +1,64 @@
+/*
+ * 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.hudi.client.utils;
+
+import org.apache.hudi.client.common.HoodieSparkEngineContext;
+import org.apache.hudi.common.data.HoodieData;
+import org.apache.hudi.common.engine.HoodieEngineContext;
+import org.apache.hudi.config.HoodieWriteConfig;
+import org.apache.hudi.metadata.HoodieTableMetadata;
+
+import org.apache.spark.api.java.JavaRDD;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+public class SparkReleaseResources {
+
+  /**
+   * Called after each write commit, compaction commit and clustering commit
+   * to unpersist all RDDs persisted or cached per table.
+   * @param context the relevant {@link HoodieEngineContext}
+   * @param config writer configs {@link HoodieWriteConfig}
+   * @param basePath table base path
+   * @param instantTime instant time for which the RDDs need to be unpersisted.
+   */
+  public static void releaseCachedData(HoodieEngineContext context,
+                                      HoodieWriteConfig config,
+                                      String basePath,
+                                      String instantTime) {
+    // If we do not explicitly release the resource, spark will automatically manage the resource and clean it up automatically
+    // see: https://spark.apache.org/docs/latest/rdd-programming-guide.html#removing-data
+    if (config.areReleaseResourceEnabled()) {
+      HoodieSparkEngineContext sparkEngineContext = (HoodieSparkEngineContext) context;
+      Map<Integer, JavaRDD<?>> allCachedRdds = sparkEngineContext.getJavaSparkContext().getPersistentRDDs();
+      List<Integer> allDataIds = new ArrayList<>(sparkEngineContext.removeCachedDataIds(HoodieData.HoodieDataCacheKey.of(basePath, instantTime)));
+      if (config.isMetadataTableEnabled()) {
+        String metadataTableBasePath = HoodieTableMetadata.getMetadataTableBasePath(basePath);
+        allDataIds.addAll(sparkEngineContext.removeCachedDataIds(HoodieData.HoodieDataCacheKey.of(metadataTableBasePath, instantTime)));
+      }
+      for (int id : allDataIds) {
+        if (allCachedRdds.containsKey(id)) {
+          allCachedRdds.get(id).unpersist();
+        }
+      }
+    }
+  }
+}


(hudi) 20/28: [HUDI-7578] Avoid unnecessary rewriting to improve performance (#11028)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit ce9ff1cb21a2289a8c563b1c97f9c5943167b3f0
Author: Danny Chan <yu...@gmail.com>
AuthorDate: Wed Apr 17 11:31:17 2024 +0800

    [HUDI-7578] Avoid unnecessary rewriting to improve performance (#11028)
---
 .../src/main/java/org/apache/hudi/io/HoodieMergeHandle.java | 13 +++++--------
 .../org/apache/hudi/io/HoodieMergeHandleWithChangeLog.java  |  2 +-
 .../java/org/apache/hudi/io/HoodieSortedMergeHandle.java    |  4 ++--
 .../hudi/io/FlinkMergeAndReplaceHandleWithChangeLog.java    |  2 +-
 .../org/apache/hudi/io/FlinkMergeHandleWithChangeLog.java   |  2 +-
 .../src/main/java/org/apache/hudi/avro/HoodieAvroUtils.java |  4 ++++
 6 files changed, 14 insertions(+), 13 deletions(-)

diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergeHandle.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergeHandle.java
index e40a5585067..749b08c3e7e 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergeHandle.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergeHandle.java
@@ -103,7 +103,7 @@ public class HoodieMergeHandle<T, I, K, O> extends HoodieWriteHandle<T, I, K, O>
   protected Map<String, HoodieRecord<T>> keyToNewRecords;
   protected Set<String> writtenRecordKeys;
   protected HoodieFileWriter fileWriter;
-  private boolean preserveMetadata = false;
+  protected boolean preserveMetadata = false;
 
   protected Path newFilePath;
   protected Path oldFilePath;
@@ -111,7 +111,6 @@ public class HoodieMergeHandle<T, I, K, O> extends HoodieWriteHandle<T, I, K, O>
   protected long recordsDeleted = 0;
   protected long updatedRecordsWritten = 0;
   protected long insertRecordsWritten = 0;
-  protected boolean useWriterSchemaForCompaction;
   protected Option<BaseKeyGenerator> keyGeneratorOpt;
   private HoodieBaseFile baseFileToMerge;
 
@@ -142,7 +141,6 @@ public class HoodieMergeHandle<T, I, K, O> extends HoodieWriteHandle<T, I, K, O>
                            HoodieBaseFile dataFileToBeMerged, TaskContextSupplier taskContextSupplier, Option<BaseKeyGenerator> keyGeneratorOpt) {
     super(config, instantTime, partitionPath, fileId, hoodieTable, taskContextSupplier);
     this.keyToNewRecords = keyToNewRecords;
-    this.useWriterSchemaForCompaction = true;
     this.preserveMetadata = true;
     init(fileId, this.partitionPath, dataFileToBeMerged);
     validateAndSetAndKeyGenProps(keyGeneratorOpt, config.populateMetaFields());
@@ -279,7 +277,7 @@ public class HoodieMergeHandle<T, I, K, O> extends HoodieWriteHandle<T, I, K, O>
   }
 
   protected void writeInsertRecord(HoodieRecord<T> newRecord) throws IOException {
-    Schema schema = useWriterSchemaForCompaction ? writeSchemaWithMetaFields : writeSchema;
+    Schema schema = preserveMetadata ? writeSchemaWithMetaFields : writeSchema;
     // just skip the ignored record
     if (newRecord.shouldIgnore(schema, config.getProps())) {
       return;
@@ -308,7 +306,7 @@ public class HoodieMergeHandle<T, I, K, O> extends HoodieWriteHandle<T, I, K, O>
     }
     try {
       if (combineRecord.isPresent() && !combineRecord.get().isDelete(schema, config.getProps()) && !isDelete) {
-        writeToFile(newRecord.getKey(), combineRecord.get(), schema, prop, preserveMetadata && useWriterSchemaForCompaction);
+        writeToFile(newRecord.getKey(), combineRecord.get(), schema, prop, preserveMetadata);
         recordsWritten++;
       } else {
         recordsDeleted++;
@@ -335,7 +333,7 @@ public class HoodieMergeHandle<T, I, K, O> extends HoodieWriteHandle<T, I, K, O>
    */
   public void write(HoodieRecord<T> oldRecord) {
     Schema oldSchema = config.populateMetaFields() ? writeSchemaWithMetaFields : writeSchema;
-    Schema newSchema = useWriterSchemaForCompaction ? writeSchemaWithMetaFields : writeSchema;
+    Schema newSchema = preserveMetadata ? writeSchemaWithMetaFields : writeSchema;
     boolean copyOldRecord = true;
     String key = oldRecord.getRecordKey(oldSchema, keyGeneratorOpt);
     TypedProperties props = config.getPayloadConfig().getProps();
@@ -384,8 +382,7 @@ public class HoodieMergeHandle<T, I, K, O> extends HoodieWriteHandle<T, I, K, O>
     // NOTE: `FILENAME_METADATA_FIELD` has to be rewritten to correctly point to the
     //       file holding this record even in cases when overall metadata is preserved
     MetadataValues metadataValues = new MetadataValues().setFileName(newFilePath.getName());
-    HoodieRecord populatedRecord =
-        record.prependMetaFields(schema, writeSchemaWithMetaFields, metadataValues, prop);
+    HoodieRecord populatedRecord = record.prependMetaFields(schema, writeSchemaWithMetaFields, metadataValues, prop);
 
     if (shouldPreserveRecordMetadata) {
       fileWriter.write(key.getRecordKey(), populatedRecord, writeSchemaWithMetaFields);
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergeHandleWithChangeLog.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergeHandleWithChangeLog.java
index f8669416f0c..fba72310513 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergeHandleWithChangeLog.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieMergeHandleWithChangeLog.java
@@ -99,7 +99,7 @@ public class HoodieMergeHandleWithChangeLog<T, I, K, O> extends HoodieMergeHandl
   }
 
   protected void writeInsertRecord(HoodieRecord<T> newRecord) throws IOException {
-    Schema schema = useWriterSchemaForCompaction ? writeSchemaWithMetaFields : writeSchema;
+    Schema schema = preserveMetadata ? writeSchemaWithMetaFields : writeSchema;
     // TODO Remove these unnecessary newInstance invocations
     HoodieRecord<T> savedRecord = newRecord.newInstance();
     super.writeInsertRecord(newRecord);
diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieSortedMergeHandle.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieSortedMergeHandle.java
index 3d3a7308bb3..ee0ee914e19 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieSortedMergeHandle.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/io/HoodieSortedMergeHandle.java
@@ -74,7 +74,7 @@ public class HoodieSortedMergeHandle<T, I, K, O> extends HoodieMergeHandle<T, I,
   @Override
   public void write(HoodieRecord oldRecord) {
     Schema oldSchema = config.populateMetaFields() ? writeSchemaWithMetaFields : writeSchema;
-    Schema newSchema = useWriterSchemaForCompaction ? writeSchemaWithMetaFields : writeSchema;
+    Schema newSchema = preserveMetadata ? writeSchemaWithMetaFields : writeSchema;
     String key = oldRecord.getRecordKey(oldSchema, keyGeneratorOpt);
 
     // To maintain overall sorted order across updates and inserts, write any new inserts whose keys are less than
@@ -111,7 +111,7 @@ public class HoodieSortedMergeHandle<T, I, K, O> extends HoodieMergeHandle<T, I,
         String key = newRecordKeysSorted.poll();
         HoodieRecord<T> hoodieRecord = keyToNewRecords.get(key);
         if (!writtenRecordKeys.contains(hoodieRecord.getRecordKey())) {
-          if (useWriterSchemaForCompaction) {
+          if (preserveMetadata) {
             writeRecord(hoodieRecord, Option.of(hoodieRecord), writeSchemaWithMetaFields, config.getProps());
           } else {
             writeRecord(hoodieRecord, Option.of(hoodieRecord), writeSchema, config.getProps());
diff --git a/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/FlinkMergeAndReplaceHandleWithChangeLog.java b/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/FlinkMergeAndReplaceHandleWithChangeLog.java
index 666c0a8f3fd..85fb5a43504 100644
--- a/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/FlinkMergeAndReplaceHandleWithChangeLog.java
+++ b/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/FlinkMergeAndReplaceHandleWithChangeLog.java
@@ -83,7 +83,7 @@ public class FlinkMergeAndReplaceHandleWithChangeLog<T, I, K, O>
   }
 
   protected void writeInsertRecord(HoodieRecord<T> newRecord) throws IOException {
-    Schema schema = useWriterSchemaForCompaction ? writeSchemaWithMetaFields : writeSchema;
+    Schema schema = preserveMetadata ? writeSchemaWithMetaFields : writeSchema;
     // TODO Remove these unnecessary newInstance invocations
     HoodieRecord<T> savedRecord = newRecord.newInstance();
     super.writeInsertRecord(newRecord);
diff --git a/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/FlinkMergeHandleWithChangeLog.java b/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/FlinkMergeHandleWithChangeLog.java
index 7d19f454a92..92335d0965d 100644
--- a/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/FlinkMergeHandleWithChangeLog.java
+++ b/hudi-client/hudi-flink-client/src/main/java/org/apache/hudi/io/FlinkMergeHandleWithChangeLog.java
@@ -81,7 +81,7 @@ public class FlinkMergeHandleWithChangeLog<T, I, K, O>
   }
 
   protected void writeInsertRecord(HoodieRecord<T> newRecord) throws IOException {
-    Schema schema = useWriterSchemaForCompaction ? writeSchemaWithMetaFields : writeSchema;
+    Schema schema = preserveMetadata ? writeSchemaWithMetaFields : writeSchema;
     // TODO Remove these unnecessary newInstance invocations
     HoodieRecord<T> savedRecord = newRecord.newInstance();
     super.writeInsertRecord(newRecord);
diff --git a/hudi-common/src/main/java/org/apache/hudi/avro/HoodieAvroUtils.java b/hudi-common/src/main/java/org/apache/hudi/avro/HoodieAvroUtils.java
index 189c988dbc3..70ec37639d8 100644
--- a/hudi-common/src/main/java/org/apache/hudi/avro/HoodieAvroUtils.java
+++ b/hudi-common/src/main/java/org/apache/hudi/avro/HoodieAvroUtils.java
@@ -934,6 +934,10 @@ public class HoodieAvroUtils {
     if (oldRecord == null) {
       return null;
     }
+    if (oldAvroSchema.equals(newSchema)) {
+      // there is no need to rewrite if the schema equals.
+      return oldRecord;
+    }
     // try to get real schema for union type
     Schema oldSchema = getActualSchemaFromUnion(oldAvroSchema, oldRecord);
     Object newRecord = rewriteRecordWithNewSchemaInternal(oldRecord, oldSchema, newSchema, renameCols, fieldNames);


(hudi) 08/28: [HUDI-7605] Allow merger strategy to be set in spark sql writer (#10999)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit e9cd05376a337a806cdfc1a6a1f0d78fa78ac0ec
Author: Jon Vexler <jb...@gmail.com>
AuthorDate: Thu Apr 11 21:20:07 2024 -0400

    [HUDI-7605] Allow merger strategy to be set in spark sql writer (#10999)
---
 .../scala/org/apache/hudi/HoodieSparkSqlWriter.scala |  1 +
 .../apache/hudi/functional/TestMORDataSource.scala   | 20 ++++++++++++++++++++
 2 files changed, 21 insertions(+)

diff --git a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieSparkSqlWriter.scala b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieSparkSqlWriter.scala
index 7020781faf0..ad19ec48c7a 100644
--- a/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieSparkSqlWriter.scala
+++ b/hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/hudi/HoodieSparkSqlWriter.scala
@@ -302,6 +302,7 @@ class HoodieSparkSqlWriterInternal {
           .setPartitionMetafileUseBaseFormat(useBaseFormatMetaFile)
           .setShouldDropPartitionColumns(hoodieConfig.getBooleanOrDefault(HoodieTableConfig.DROP_PARTITION_COLUMNS))
           .setCommitTimezone(timelineTimeZone)
+          .setRecordMergerStrategy(hoodieConfig.getStringOrDefault(DataSourceWriteOptions.RECORD_MERGER_STRATEGY))
           .initTable(sparkContext.hadoopConfiguration, path)
       }
       val instantTime = HoodieActiveTimeline.createNewInstantTime()
diff --git a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestMORDataSource.scala b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestMORDataSource.scala
index 45bd3c645d4..b878eb76c40 100644
--- a/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestMORDataSource.scala
+++ b/hudi-spark-datasource/hudi-spark/src/test/scala/org/apache/hudi/functional/TestMORDataSource.scala
@@ -1403,4 +1403,24 @@ class TestMORDataSource extends HoodieSparkClientTestBase with SparkDatasetMixin
       basePath
     }
   }
+
+  @Test
+  def testMergerStrategySet(): Unit = {
+    val (writeOpts, _) = getWriterReaderOpts()
+    val input = recordsToStrings(dataGen.generateInserts("000", 1)).asScala
+    val inputDf= spark.read.json(spark.sparkContext.parallelize(input, 1))
+    val mergerStrategyName = "example_merger_strategy"
+    inputDf.write.format("hudi")
+      .options(writeOpts)
+      .option(DataSourceWriteOptions.TABLE_TYPE.key, "MERGE_ON_READ")
+      .option(DataSourceWriteOptions.OPERATION.key, DataSourceWriteOptions.INSERT_OPERATION_OPT_VAL)
+      .option(DataSourceWriteOptions.RECORD_MERGER_STRATEGY.key(), mergerStrategyName)
+      .mode(SaveMode.Overwrite)
+      .save(basePath)
+    metaClient = HoodieTableMetaClient.builder()
+      .setBasePath(basePath)
+      .setConf(spark.sessionState.newHadoopConf)
+      .build()
+    assertEquals(metaClient.getTableConfig.getRecordMergerStrategy, mergerStrategyName)
+  }
 }


(hudi) 05/28: [HUDI-7600] Shutdown ExecutorService when HiveMetastoreBasedLockProvider is closed (#10993)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 86f6bdf991e57a8ac3606beab08e0aa2cf7b3bf5
Author: Zouxxyy <zo...@alibaba-inc.com>
AuthorDate: Thu Apr 11 13:03:14 2024 +0800

    [HUDI-7600] Shutdown ExecutorService when HiveMetastoreBasedLockProvider is closed (#10993)
---
 .../hudi/hive/transaction/lock/HiveMetastoreBasedLockProvider.java       | 1 +
 1 file changed, 1 insertion(+)

diff --git a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/transaction/lock/HiveMetastoreBasedLockProvider.java b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/transaction/lock/HiveMetastoreBasedLockProvider.java
index df848957492..0280621bb53 100644
--- a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/transaction/lock/HiveMetastoreBasedLockProvider.java
+++ b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/transaction/lock/HiveMetastoreBasedLockProvider.java
@@ -154,6 +154,7 @@ public class HiveMetastoreBasedLockProvider implements LockProvider<LockResponse
         lock = null;
       }
       Hive.closeCurrent();
+      executor.shutdown();
     } catch (Exception e) {
       LOG.error(generateLogStatement(org.apache.hudi.common.lock.LockState.FAILED_TO_RELEASE, generateLogSuffixString()));
     }


(hudi) 10/28: [HUDI-7601] Add heartbeat mechanism to refresh lock (#10994)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 4aa23beec97032471eb522b7f5ae99ea57e358f5
Author: Yann Byron <bi...@gmail.com>
AuthorDate: Fri Apr 12 14:12:04 2024 +0800

    [HUDI-7601] Add heartbeat mechanism to refresh lock (#10994)
    
    * [HUDI-7601] Add heartbeat mechanism to refresh lock
---
 .../org/apache/hudi/config/HoodieLockConfig.java   | 13 +++++++
 .../hudi/common/config/LockConfiguration.java      |  3 ++
 .../hudi/hive/transaction/lock/Heartbeat.java      | 42 ++++++++++++++++++++++
 .../lock/HiveMetastoreBasedLockProvider.java       | 23 ++++++++++--
 4 files changed, 79 insertions(+), 2 deletions(-)

diff --git a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieLockConfig.java b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieLockConfig.java
index b24aecf46c1..4fbae5326f3 100644
--- a/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieLockConfig.java
+++ b/hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodieLockConfig.java
@@ -36,6 +36,7 @@ import java.util.Properties;
 
 import static org.apache.hudi.common.config.LockConfiguration.DEFAULT_LOCK_ACQUIRE_NUM_RETRIES;
 import static org.apache.hudi.common.config.LockConfiguration.DEFAULT_LOCK_ACQUIRE_RETRY_WAIT_TIME_IN_MILLIS;
+import static org.apache.hudi.common.config.LockConfiguration.DEFAULT_LOCK_HEARTBEAT_INTERVAL_MS;
 import static org.apache.hudi.common.config.LockConfiguration.DEFAULT_ZK_CONNECTION_TIMEOUT_MS;
 import static org.apache.hudi.common.config.LockConfiguration.DEFAULT_ZK_SESSION_TIMEOUT_MS;
 import static org.apache.hudi.common.config.LockConfiguration.FILESYSTEM_LOCK_EXPIRE_PROP_KEY;
@@ -49,6 +50,7 @@ import static org.apache.hudi.common.config.LockConfiguration.LOCK_ACQUIRE_NUM_R
 import static org.apache.hudi.common.config.LockConfiguration.LOCK_ACQUIRE_RETRY_MAX_WAIT_TIME_IN_MILLIS_PROP_KEY;
 import static org.apache.hudi.common.config.LockConfiguration.LOCK_ACQUIRE_RETRY_WAIT_TIME_IN_MILLIS_PROP_KEY;
 import static org.apache.hudi.common.config.LockConfiguration.LOCK_ACQUIRE_WAIT_TIMEOUT_MS_PROP_KEY;
+import static org.apache.hudi.common.config.LockConfiguration.LOCK_HEARTBEAT_INTERVAL_MS_KEY;
 import static org.apache.hudi.common.config.LockConfiguration.LOCK_PREFIX;
 import static org.apache.hudi.common.config.LockConfiguration.ZK_BASE_PATH_PROP_KEY;
 import static org.apache.hudi.common.config.LockConfiguration.ZK_CONNECTION_TIMEOUT_MS_PROP_KEY;
@@ -111,6 +113,12 @@ public class HoodieLockConfig extends HoodieConfig {
       .sinceVersion("0.8.0")
       .withDocumentation("Timeout in ms, to wait on an individual lock acquire() call, at the lock provider.");
 
+  public static final ConfigProperty<Integer> LOCK_HEARTBEAT_INTERVAL_MS = ConfigProperty
+      .key(LOCK_HEARTBEAT_INTERVAL_MS_KEY)
+      .defaultValue(DEFAULT_LOCK_HEARTBEAT_INTERVAL_MS)
+      .sinceVersion("1.0.0")
+      .withDocumentation("Heartbeat interval in ms, to send a heartbeat to indicate that hive client holding locks.");
+
   public static final ConfigProperty<String> FILESYSTEM_LOCK_PATH = ConfigProperty
       .key(FILESYSTEM_LOCK_PATH_PROP_KEY)
       .noDefaultValue()
@@ -342,6 +350,11 @@ public class HoodieLockConfig extends HoodieConfig {
       return this;
     }
 
+    public HoodieLockConfig.Builder withHeartbeatIntervalInMillis(Long intervalInMillis) {
+      lockConfig.setValue(LOCK_HEARTBEAT_INTERVAL_MS, String.valueOf(intervalInMillis));
+      return this;
+    }
+
     public HoodieLockConfig.Builder withConflictResolutionStrategy(ConflictResolutionStrategy conflictResolutionStrategy) {
       lockConfig.setValue(WRITE_CONFLICT_RESOLUTION_STRATEGY_CLASS_NAME, conflictResolutionStrategy.getClass().getName());
       return this;
diff --git a/hudi-common/src/main/java/org/apache/hudi/common/config/LockConfiguration.java b/hudi-common/src/main/java/org/apache/hudi/common/config/LockConfiguration.java
index c6ebc54e95d..1788122ffe4 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/config/LockConfiguration.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/config/LockConfiguration.java
@@ -43,6 +43,9 @@ public class LockConfiguration implements Serializable {
 
   public static final String LOCK_ACQUIRE_WAIT_TIMEOUT_MS_PROP_KEY = LOCK_PREFIX + "wait_time_ms";
 
+  public static final String LOCK_HEARTBEAT_INTERVAL_MS_KEY = LOCK_PREFIX + "heartbeat_interval_ms";
+  public static final int DEFAULT_LOCK_HEARTBEAT_INTERVAL_MS = 60 * 1000;
+
   // configs for file system based locks. NOTE: This only works for DFS with atomic create/delete operation
   public static final String FILESYSTEM_BASED_LOCK_PROPERTY_PREFIX = LOCK_PREFIX + "filesystem.";
 
diff --git a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/transaction/lock/Heartbeat.java b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/transaction/lock/Heartbeat.java
new file mode 100644
index 00000000000..14398af2c74
--- /dev/null
+++ b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/transaction/lock/Heartbeat.java
@@ -0,0 +1,42 @@
+/*
+ * 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.hudi.hive.transaction.lock;
+
+import org.apache.hadoop.hive.metastore.IMetaStoreClient;
+import org.apache.hudi.exception.HoodieLockException;
+
+class Heartbeat implements Runnable {
+  private final IMetaStoreClient client;
+  private final long lockId;
+
+  Heartbeat(IMetaStoreClient client, long lockId) {
+    this.client = client;
+    this.lockId = lockId;
+  }
+
+  @Override
+  public void run() {
+    try {
+      client.heartbeat(0, lockId);
+    } catch (Exception e) {
+      throw new HoodieLockException(String.format("Failed to heartbeat for lock: %d", lockId));
+    }
+  }
+}
diff --git a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/transaction/lock/HiveMetastoreBasedLockProvider.java b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/transaction/lock/HiveMetastoreBasedLockProvider.java
index 0280621bb53..4c5aa5cb4f7 100644
--- a/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/transaction/lock/HiveMetastoreBasedLockProvider.java
+++ b/hudi-sync/hudi-hive-sync/src/main/java/org/apache/hudi/hive/transaction/lock/HiveMetastoreBasedLockProvider.java
@@ -44,16 +44,19 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 
+import static org.apache.hudi.common.config.LockConfiguration.DEFAULT_LOCK_HEARTBEAT_INTERVAL_MS;
 import static org.apache.hudi.common.config.LockConfiguration.HIVE_DATABASE_NAME_PROP_KEY;
 import static org.apache.hudi.common.config.LockConfiguration.HIVE_METASTORE_URI_PROP_KEY;
 import static org.apache.hudi.common.config.LockConfiguration.HIVE_TABLE_NAME_PROP_KEY;
 import static org.apache.hudi.common.config.LockConfiguration.LOCK_ACQUIRE_NUM_RETRIES_PROP_KEY;
 import static org.apache.hudi.common.config.LockConfiguration.LOCK_ACQUIRE_RETRY_WAIT_TIME_IN_MILLIS_PROP_KEY;
+import static org.apache.hudi.common.config.LockConfiguration.LOCK_HEARTBEAT_INTERVAL_MS_KEY;
 import static org.apache.hudi.common.config.LockConfiguration.ZK_CONNECT_URL_PROP_KEY;
 import static org.apache.hudi.common.config.LockConfiguration.ZK_PORT_PROP_KEY;
 import static org.apache.hudi.common.config.LockConfiguration.ZK_SESSION_TIMEOUT_MS_PROP_KEY;
@@ -81,7 +84,8 @@ public class HiveMetastoreBasedLockProvider implements LockProvider<LockResponse
   private IMetaStoreClient hiveClient;
   private volatile LockResponse lock = null;
   protected LockConfiguration lockConfiguration;
-  ExecutorService executor = Executors.newSingleThreadExecutor();
+  private ScheduledFuture<?> future = null;
+  private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
 
   public HiveMetastoreBasedLockProvider(final LockConfiguration lockConfiguration, final Configuration conf) {
     this(lockConfiguration);
@@ -128,6 +132,9 @@ public class HiveMetastoreBasedLockProvider implements LockProvider<LockResponse
         return;
       }
       lock = null;
+      if (future != null) {
+        future.cancel(false);
+      }
       hiveClient.unlock(lockResponseLocal.getLockid());
       LOG.info(generateLogStatement(RELEASED, generateLogSuffixString()));
     } catch (TException e) {
@@ -153,6 +160,9 @@ public class HiveMetastoreBasedLockProvider implements LockProvider<LockResponse
         hiveClient.unlock(lock.getLockid());
         lock = null;
       }
+      if (future != null) {
+        future.cancel(false);
+      }
       Hive.closeCurrent();
       executor.shutdown();
     } catch (Exception e) {
@@ -188,6 +198,12 @@ public class HiveMetastoreBasedLockProvider implements LockProvider<LockResponse
       final LockRequest lockRequestFinal = lockRequest;
       this.lock = executor.submit(() -> hiveClient.lock(lockRequestFinal))
           .get(time, unit);
+
+      // refresh lock in case that certain commit takes a long time.
+      Heartbeat heartbeat = new Heartbeat(hiveClient, lock.getLockid());
+      long heartbeatIntervalMs = lockConfiguration.getConfig()
+          .getLong(LOCK_HEARTBEAT_INTERVAL_MS_KEY, DEFAULT_LOCK_HEARTBEAT_INTERVAL_MS);
+      future = executor.scheduleAtFixedRate(heartbeat, heartbeatIntervalMs / 2, heartbeatIntervalMs, TimeUnit.MILLISECONDS);
     } catch (InterruptedException | TimeoutException e) {
       if (this.lock == null || this.lock.getState() != LockState.ACQUIRED) {
         LockResponse lockResponse = this.hiveClient.checkLock(lockRequest.getTxnid());
@@ -202,6 +218,9 @@ public class HiveMetastoreBasedLockProvider implements LockProvider<LockResponse
       if (this.lock != null && this.lock.getState() != LockState.ACQUIRED) {
         hiveClient.unlock(this.lock.getLockid());
         lock = null;
+        if (future != null) {
+          future.cancel(false);
+        }
       }
     }
   }


(hudi) 18/28: [MINOR] Remove redundant lines in StreamSync and TestStreamSyncUnitTests (#11027)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit f0cf58d8c998018414b27ade424d72350131806e
Author: Y Ethan Guo <et...@gmail.com>
AuthorDate: Mon Apr 15 21:41:41 2024 -0700

    [MINOR] Remove redundant lines in StreamSync and TestStreamSyncUnitTests (#11027)
---
 .../apache/hudi/utilities/streamer/StreamSync.java   |  4 ----
 .../utilities/streamer/TestStreamSyncUnitTests.java  | 20 --------------------
 2 files changed, 24 deletions(-)

diff --git a/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/StreamSync.java b/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/StreamSync.java
index 2b0d94da74a..7e0b97ef570 100644
--- a/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/StreamSync.java
+++ b/hudi-utilities/src/main/java/org/apache/hudi/utilities/streamer/StreamSync.java
@@ -278,7 +278,6 @@ public class StreamSync implements Serializable, Closeable {
     this.formatAdapter = formatAdapter;
     this.transformer = transformer;
     this.useRowWriter = useRowWriter;
-
   }
 
   @Deprecated
@@ -500,7 +499,6 @@ public class StreamSync implements Serializable, Closeable {
    * @return Pair<InputBatch and Boolean> Input data read from upstream source, and boolean is true if empty.
    * @throws Exception in case of any Exception
    */
-
   public InputBatch readFromSource(String instantTime, HoodieTableMetaClient metaClient) throws IOException {
     // Retrieve the previous round checkpoints, if any
     Option<String> resumeCheckpointStr = Option.empty();
@@ -563,7 +561,6 @@ public class StreamSync implements Serializable, Closeable {
     // handle empty batch with change in checkpoint
     hoodieSparkContext.setJobStatus(this.getClass().getSimpleName(), "Checking if input is empty: " + cfg.targetTableName);
 
-
     if (useRowWriter) { // no additional processing required for row writer.
       return inputBatch;
     } else {
@@ -1297,5 +1294,4 @@ public class StreamSync implements Serializable, Closeable {
       return writeStatusRDD;
     }
   }
-
 }
diff --git a/hudi-utilities/src/test/java/org/apache/hudi/utilities/streamer/TestStreamSyncUnitTests.java b/hudi-utilities/src/test/java/org/apache/hudi/utilities/streamer/TestStreamSyncUnitTests.java
index 99148eb4b07..c0169ae64b8 100644
--- a/hudi-utilities/src/test/java/org/apache/hudi/utilities/streamer/TestStreamSyncUnitTests.java
+++ b/hudi-utilities/src/test/java/org/apache/hudi/utilities/streamer/TestStreamSyncUnitTests.java
@@ -17,25 +17,6 @@
  * under the License.
  */
 
-/*
- * 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.hudi.utilities.streamer;
 
 import org.apache.hudi.DataSourceWriteOptions;
@@ -75,7 +56,6 @@ import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 public class TestStreamSyncUnitTests {
-
   @ParameterizedTest
   @MethodSource("testCasesFetchNextBatchFromSource")
   void testFetchNextBatchFromSource(Boolean useRowWriter, Boolean hasTransformer, Boolean hasSchemaProvider,


(hudi) 28/28: [HUDI-7637] Make StoragePathInfo Comparable (#11050)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 31d24d7600bbfacc5959b12de97c84ea79fb6fa0
Author: Y Ethan Guo <et...@gmail.com>
AuthorDate: Thu Apr 18 05:51:23 2024 -0700

    [HUDI-7637] Make StoragePathInfo Comparable (#11050)
---
 .../main/java/org/apache/hudi/storage/StoragePathInfo.java  |  7 ++++++-
 .../org/apache/hudi/io/storage/TestStoragePathInfo.java     | 13 +++++++++++++
 2 files changed, 19 insertions(+), 1 deletion(-)

diff --git a/hudi-io/src/main/java/org/apache/hudi/storage/StoragePathInfo.java b/hudi-io/src/main/java/org/apache/hudi/storage/StoragePathInfo.java
index e4711bf72dd..1c1ebc32a2f 100644
--- a/hudi-io/src/main/java/org/apache/hudi/storage/StoragePathInfo.java
+++ b/hudi-io/src/main/java/org/apache/hudi/storage/StoragePathInfo.java
@@ -31,7 +31,7 @@ import java.io.Serializable;
  * with simplification based on what Hudi needs.
  */
 @PublicAPIClass(maturity = ApiMaturityLevel.EVOLVING)
-public class StoragePathInfo implements Serializable {
+public class StoragePathInfo implements Serializable, Comparable<StoragePathInfo> {
   private final StoragePath path;
   private final long length;
   private final boolean isDirectory;
@@ -109,6 +109,11 @@ public class StoragePathInfo implements Serializable {
     return modificationTime;
   }
 
+  @Override
+  public int compareTo(StoragePathInfo o) {
+    return this.getPath().compareTo(o.getPath());
+  }
+
   @Override
   public boolean equals(Object o) {
     if (this == o) {
diff --git a/hudi-io/src/test/java/org/apache/hudi/io/storage/TestStoragePathInfo.java b/hudi-io/src/test/java/org/apache/hudi/io/storage/TestStoragePathInfo.java
index 72640c5e3df..95cf4d798a4 100644
--- a/hudi-io/src/test/java/org/apache/hudi/io/storage/TestStoragePathInfo.java
+++ b/hudi-io/src/test/java/org/apache/hudi/io/storage/TestStoragePathInfo.java
@@ -71,6 +71,19 @@ public class TestStoragePathInfo {
     }
   }
 
+  @Test
+  public void testCompareTo() {
+    StoragePathInfo pathInfo1 = new StoragePathInfo(
+        new StoragePath(PATH1), LENGTH, false, BLOCK_REPLICATION, BLOCK_SIZE, MODIFICATION_TIME);
+    StoragePathInfo pathInfo2 = new StoragePathInfo(
+        new StoragePath(PATH1), LENGTH + 2, false, BLOCK_REPLICATION, BLOCK_SIZE, MODIFICATION_TIME + 2L);
+    StoragePathInfo pathInfo3 = new StoragePathInfo(
+        new StoragePath(PATH2), LENGTH, false, BLOCK_REPLICATION, BLOCK_SIZE, MODIFICATION_TIME);
+
+    assertEquals(0, pathInfo1.compareTo(pathInfo2));
+    assertEquals(-1, pathInfo1.compareTo(pathInfo3));
+  }
+
   @Test
   public void testEquals() {
     StoragePathInfo pathInfo1 = new StoragePathInfo(


(hudi) 04/28: [MINOR] Fix BUG: HoodieLogFormatWriter: unable to close output stream for log file HoodieLogFile{xxx} (#10989)

Posted by yi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch branch-0.x
in repository https://gitbox.apache.org/repos/asf/hudi.git

commit 705e5f59f28f72703a647487f9acbab65155f45b
Author: Silly Carbon <cr...@outlook.com>
AuthorDate: Wed Apr 10 18:21:57 2024 +0800

    [MINOR] Fix BUG: HoodieLogFormatWriter: unable to close output stream for log file HoodieLogFile{xxx} (#10989)
    
    * due to java.lang.IllegalStateException: Shutdown in progress, cause:
        when `org.apache.hudi.common.table.log.HoodieLogFormatWriter.close` tries to `removeShutdownHook`, hooks were already removed by JVM when triggered (hooks == null)
---
 .../java/org/apache/hudi/common/table/log/HoodieLogFormatWriter.java    | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFormatWriter.java b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFormatWriter.java
index 0b16d2ee2a6..d021cd2c499 100644
--- a/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFormatWriter.java
+++ b/hudi-common/src/main/java/org/apache/hudi/common/table/log/HoodieLogFormatWriter.java
@@ -294,7 +294,7 @@ public class HoodieLogFormatWriter implements HoodieLogFormat.Writer {
         try {
           LOG.warn("running logformatwriter hook");
           if (output != null) {
-            close();
+            closeStream();
           }
         } catch (Exception e) {
           LOG.warn("unable to close output stream for log file " + logFile, e);