danny0405 commented on code in PR #20735:
URL: https://github.com/apache/hudi/pull/20735#discussion_r4624063346


##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/metrics/FlinkStreamReadLagMetrics.java:
##########
@@ -0,0 +1,210 @@
+/*
+ * 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.metrics;
+
+import org.apache.hudi.common.table.timeline.HoodieInstantTimeGenerator;
+import org.apache.hudi.common.util.VisibleForTesting;
+import org.apache.hudi.source.split.HoodieSourceSplitLagInfo;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.flink.metrics.MetricGroup;
+
+import java.text.ParseException;
+import java.time.Clock;
+import java.time.Duration;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+/**
+ * Metrics of how far the streaming read lags behind the commits of the table, 
tracked by the split
+ * enumerator.
+ *
+ * <p>A commit is pending until every split that reads it is finished: either 
it is not discovered yet,
+ * or some of its splits are queued or being read. The lag is computed when 
the gauge is read, so it keeps growing while the readers stall. The methods are
+ * called from the coordinator thread and the gauges are read by the metric 
reporter thread.
+ *
+ * <p>Splits that the readers restore from their own state are not known to 
the enumerator, so they are
+ * not counted until they are added back.
+ */
+@Slf4j
+public class FlinkStreamReadLagMetrics extends HoodieFlinkMetrics {
+
+  private final Clock clock;
+
+  /**
+   * Lag info of the discovered splits that are not finished yet, keyed by 
split id.
+   */
+  private final Map<String, HoodieSourceSplitLagInfo> pendingSplits = new 
HashMap<>();
+
+  /**
+   * Number of pending splits that read each commit, keyed by instant time.
+   */
+  private final Map<String, Integer> inFlightCommits = new HashMap<>();
+
+  /**
+   * Number of pending splits by the completion time of the oldest commit they 
read.
+   */
+  private final TreeMap<String, Integer> oldestCompletionTimes = new 
TreeMap<>();
+
+  private int undiscoveredCommits;
+
+  /**
+   * Completion time of the oldest undiscovered commit, null if there is none.
+   */
+  private String oldestUndiscoveredCompletionTime;
+
+  private long pendingRecords;
+
+  private long pendingBytes;
+
+  public FlinkStreamReadLagMetrics(MetricGroup metricGroup, String tableName) {
+    this(metricGroup, tableName, Clock.systemUTC());
+  }
+
+  @VisibleForTesting
+  FlinkStreamReadLagMetrics(MetricGroup metricGroup, String tableName, Clock 
clock) {
+    super(metricGroup.addGroup("table", tableName));
+    this.clock = clock;
+  }
+
+  @Override
+  public void registerMetrics() {
+    metricGroup.gauge("readLagSeconds", this::getReadLagSeconds);
+    metricGroup.gauge("pendingCommits", this::getPendingCommits);
+    metricGroup.gauge("undiscoveredCommits", this::getUndiscoveredCommits);
+    metricGroup.gauge("inFlightCommits", this::getInFlightCommits);
+    metricGroup.gauge("pendingSplits", this::getPendingSplits);
+    metricGroup.gauge("pendingRecords", this::getPendingRecords);
+    metricGroup.gauge("pendingBytes", this::getPendingBytes);
+  }
+
+  /**
+   * Starts tracking the splits that were discovered, restored or added back, 
keyed by split id. Splits
+   * that are already tracked are ignored.
+   */
+  public synchronized void addSplits(Map<String, HoodieSourceSplitLagInfo> 
lagInfos) {
+    lagInfos.forEach((splitId, lagInfo) -> {
+      if (pendingSplits.putIfAbsent(splitId, lagInfo) == null) {
+        add(lagInfo);
+      }
+    });
+  }
+
+  /**
+   * Replaces the lag info of the splits that are still tracked, keyed by 
split id.
+   */
+  public synchronized void updateSplits(Map<String, HoodieSourceSplitLagInfo> 
lagInfos) {
+    lagInfos.forEach((splitId, lagInfo) -> {
+      HoodieSourceSplitLagInfo previous = pendingSplits.get(splitId);
+      if (previous != null) {
+        remove(previous);
+        pendingSplits.put(splitId, lagInfo);
+        add(lagInfo);
+      }
+    });
+  }
+
+  /**
+   * Stops tracking the splits whose records were all emitted. Splits that are 
not tracked are ignored.
+   */
+  public synchronized void finishSplits(Collection<String> splitIds) {
+    for (String splitId : splitIds) {
+      HoodieSourceSplitLagInfo lagInfo = pendingSplits.remove(splitId);
+      if (lagInfo != null) {
+        remove(lagInfo);
+      }
+    }
+  }
+
+  /**
+   * Sets the completion times of the completed commits that are not 
discovered yet, in ascending order.
+   */
+  public synchronized void setUndiscoveredCommits(List<String> 
completionTimes) {
+    this.undiscoveredCommits = completionTimes.size();
+    this.oldestUndiscoveredCompletionTime = completionTimes.isEmpty() ? null : 
completionTimes.get(0);
+  }
+
+  /**
+   * Returns the seconds since the oldest pending commit completed, 0 if no 
commit is pending.
+   */
+  private synchronized long getReadLagSeconds() {
+    String oldest = oldestUndiscoveredCompletionTime;
+    if (!oldestCompletionTimes.isEmpty() && (oldest == null || 
oldestCompletionTimes.firstKey().compareTo(oldest) < 0)) {
+      oldest = oldestCompletionTimes.firstKey();
+    }
+    if (oldest == null) {
+      return 0L;
+    }
+    try {
+      return 
Duration.between(HoodieInstantTimeGenerator.parseDateFromInstantTime(oldest).toInstant(),
 clock.instant()).getSeconds();

Review Comment:
   [P2] Could we parse the completion time using the table's configured 
timeline timezone? `HoodieInstantTimeGenerator.parseDateFromInstantTime` uses 
`ZoneId.systemDefault()`, so for a UTC table with the JobManager in 
Asia/Shanghai a freshly completed commit appears roughly eight hours old; other 
timezone combinations can produce negative lag. `Clock.systemUTC()` does not 
change how the completion timestamp is parsed. Please add a test with a UTC 
table and a different JVM timezone, using an independently constructed expected 
instant—the current tests construct the clock with the same parser and 
therefore mask the mismatch.



##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/source/enumerator/HoodieContinuousSplitEnumerator.java:
##########
@@ -90,22 +132,80 @@ public HoodieSplitEnumeratorState snapshotState(long 
checkpointId) throws Except
     return new HoodieSplitEnumeratorState(splitProvider.state(), 
position.get().getIssuedInstant(), position.get().getIssuedOffset());
   }
 
-  private HoodieContinuousSplitBatch discoverSplits() {
+  @Override
+  void onSplitsFinished(Collection<String> finishedSplitIds) {
+    if (lagMetrics != null) {
+      lagMetrics.finishSplits(finishedSplitIds);
+    }
+  }
+
+  @Override
+  void onSplitsAddedBack(List<HoodieSourceSplit> splits) {
+    if (lagMetrics != null) {
+      lagMetrics.addSplits(getSplitLagInfo(splits));
+    }
+  }
+
+  /**
+   * Returns the discovered splits, with their lag info and the completion 
times of the commits left to
+   * discover, which are null when the metrics are disabled or failed to be 
resolved.
+   */
+  private DiscoveryResult discoverSplits() {
+    String issuedOffset = position.get().getIssuedOffset().orElse(null);
     int pendingSplitNumber = splitProvider.pendingSplitCount();
     if (pendingSplitNumber > scanContext.getMaxPendingSplits()) {
       log.info(
           "Pause split discovery as the assigner already has too many pending 
splits: {}",
           pendingSplitNumber);
-      return HoodieContinuousSplitBatch.EMPTY;
+      return new DiscoveryResult(HoodieContinuousSplitBatch.EMPTY, 
Collections.emptyMap(), getUndiscoveredCommits(issuedOffset, true));
+    }
+    HoodieContinuousSplitBatch batch = 
splitDiscover.discoverSplits(issuedOffset);
+    String nextOffset = StringUtils.isNullOrEmpty(batch.getOffset()) ? 
issuedOffset : batch.getOffset();
+    return new DiscoveryResult(batch, resolveLagInfo(batch.getSplits()), 
getUndiscoveredCommits(nextOffset, false));
+  }
+
+  @Nullable
+  private Map<String, HoodieSourceSplitLagInfo> 
resolveLagInfo(Collection<HoodieSourceSplit> splits) {
+    if (lagMetrics == null || splits.isEmpty()) {
+      return null;
+    }
+    try {
+      return splitDiscover.getLagInfo(splits);
+    } catch (Exception e) {
+      log.warn("Failed to resolve the lag info of {} discovered splits", 
splits.size(), e);
+      return null;
+    }
+  }
+
+  @Nullable
+  private List<String> getUndiscoveredCommits(String offset, boolean 
reloadTimeline) {
+    if (lagMetrics == null) {
+      return null;
     }
-    return 
splitDiscover.discoverSplits(position.get().getIssuedOffset().isPresent() ? 
position.get().getIssuedOffset().get() : null);
+    try {
+      return splitDiscover.getUndiscoveredCommits(offset, reloadTimeline);
+    } catch (Exception e) {
+      log.warn("Failed to get the undiscovered commits after {}", offset, e);
+      return null;
+    }
+  }
+
+  private static Map<String, HoodieSourceSplitLagInfo> 
getSplitLagInfo(Collection<HoodieSourceSplit> splits) {
+    return 
splits.stream().collect(Collectors.toMap(HoodieSourceSplit::splitId, 
HoodieSourceSplitLagInfo::of, (first, second) -> first));

Review Comment:
   Minor simplification: this fallback map construction duplicates the default 
implementation of `HoodieContinuousSplitDiscover.getLagInfo`, including its 
duplicate-key policy. Could we extract a shared collection-to-fallback-info 
helper, for example on `HoodieSourceSplitLagInfo`, and use it in both places?



##########
hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/source/split/DefaultHoodieSplitDiscover.java:
##########
@@ -65,6 +86,141 @@ public HoodieContinuousSplitBatch discoverSplits(String 
lastInstant) {
     return incrementalInputSplits.inputHoodieSourceSplits(metaClient, 
lastInstant, scanContext.isCdcEnabled());
   }
 
+  @Override
+  public List<String> getUndiscoveredCommits(@Nullable String offset, boolean 
reloadTimeline) {
+    if (metaClient == null || offset == null) {
+      return Collections.emptyList();
+    }
+    if (reloadTimeline) {
+      metaClient.reloadActiveTimeline();
+    }
+    HoodieTimeline timeline = 
IncrementalQueryAnalyzer.filterInstantsAsPerUserConfigs(
+        metaClient,
+        metaClient.getCommitsAndCompactionTimeline().filterCompletedInstants(),
+        scanContext.isSkipCompaction(),
+        scanContext.isSkipClustering(),
+        scanContext.isSkipInsertOverwrite());
+    return timeline.getInstantsAsStream()
+        .map(HoodieInstant::getCompletionTime)
+        .filter(completionTime -> completionTime != null && 
completionTime.compareTo(offset) > 0)

Review Comment:
   [P2] Could we also apply the configured `read.end-commit` bound here, with 
the same semantics as discovery? `IncrementalInputSplits.inputSplits` passes 
`READ_END_COMMIT` to the query analyzer, but this calculation counts every 
completion after the issued offset. If the reader has consumed through its 
configured end and the table receives later commits, those commits remain 
permanently 'undiscovered': `pendingCommits` stays nonzero and `readLagSeconds` 
keeps growing even though all eligible data has been consumed. A test with an 
end bound and a later completed commit would cover this.



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

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to