shangxinli commented on code in PR #18068:
URL: https://github.com/apache/hudi/pull/18068#discussion_r2880669413


##########
hudi-common/src/main/java/org/apache/hudi/common/util/CheckpointUtils.java:
##########
@@ -0,0 +1,238 @@
+/*
+ * 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 java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Utility methods for parsing and working with streaming checkpoints.
+ * Supports multiple checkpoint formats used by different engines and sources.
+ *
+ * Checkpoint formats:
+ * - DELTASTREAMER_KAFKA: "topic,partition:offset,partition:offset,..."
+ *   Example: "events,0:1000,1:2000,2:1500"
+ *   Used by: DeltaStreamer (Spark)
+ *
+ * - FLINK_KAFKA: Base64-encoded serialized Map (TopicPartition → Long)
+ *   Example: "eyJ0b3BpY..." (base64)
+ *   Used by: Flink streaming connector
+ *   Note: Actual implementation requires Flink checkpoint deserialization 
(Phase 2)
+ *
+ * - PULSAR: "partition:ledgerId:entryId,partition:ledgerId:entryId,..."
+ *   Example: "0:123:45,1:234:56"
+ *   Used by: Pulsar sources
+ *   Note: To be implemented in Phase 4
+ *
+ * - KINESIS: "shardId:sequenceNumber,shardId:sequenceNumber,..."
+ *   Example: 
"shardId-000000000000:49590338271490256608559692538361571095921575989136588898"
+ *   Used by: Kinesis sources
+ *   Note: To be implemented in Phase 4
+ */
+public class CheckpointUtils {
+
+  /**
+   * Supported checkpoint formats across engines and sources.
+   */
+  public enum CheckpointFormat {
+    /** DeltaStreamer (Spark) Kafka format: "topic,0:1000,1:2000" */
+    DELTASTREAMER_KAFKA,
+
+    /** Flink Kafka format: base64-encoded Map<TopicPartition, Long> */
+    FLINK_KAFKA,
+
+    /** Pulsar format: "0:123:45,1:234:56" (ledgerId:entryId) */
+    PULSAR,
+
+    /** Kinesis format: "shard-0:12345,shard-1:67890" */
+    KINESIS,
+
+    /** Custom user-defined format */
+    CUSTOM
+  }
+
+  /**
+   * Parse checkpoint string into partition → offset mapping.
+   *
+   * @param format Checkpoint format
+   * @param checkpointStr Checkpoint string
+   * @return Map from partition number to offset/sequence number
+   * @throws IllegalArgumentException if format is invalid
+   */
+  public static Map<Integer, Long> parseCheckpoint(CheckpointFormat format, 
String checkpointStr) {
+    switch (format) {
+      case DELTASTREAMER_KAFKA:
+        return parseDeltaStreamerKafkaCheckpoint(checkpointStr);
+      case FLINK_KAFKA:
+        throw new UnsupportedOperationException(
+            "Flink Kafka checkpoint parsing not yet implemented. "
+                + "This will be added in Phase 2 with Flink checkpoint 
deserialization support.");
+      case PULSAR:
+        throw new UnsupportedOperationException(
+            "Pulsar checkpoint parsing not yet implemented. Planned for Phase 
4.");
+      case KINESIS:
+        throw new UnsupportedOperationException(
+            "Kinesis checkpoint parsing not yet implemented. Planned for Phase 
4.");
+      default:
+        throw new IllegalArgumentException("Unsupported checkpoint format: " + 
format);
+    }
+  }
+
+  /**
+   * Calculate offset difference between two checkpoints.
+   * Handles partition additions, removals, and resets.
+   *
+   * Algorithm:
+   * 1. For each partition in current checkpoint:
+   *    - If partition exists in previous: diff = current - previous
+   *    - If partition is new: diff = current (count from 0)
+   *    - If diff is negative (reset): use current offset
+   * 2. Sum all partition diffs
+   *
+   * @param format Checkpoint format
+   * @param previousCheckpoint Previous checkpoint string
+   * @param currentCheckpoint Current checkpoint string
+   * @return Total offset difference across all partitions
+   */
+  public static long calculateOffsetDifference(CheckpointFormat format,
+                                                String previousCheckpoint,
+                                                String currentCheckpoint) {
+    Map<Integer, Long> previousOffsets = parseCheckpoint(format, 
previousCheckpoint);
+    Map<Integer, Long> currentOffsets = parseCheckpoint(format, 
currentCheckpoint);
+
+    long totalDiff = 0;
+
+    for (Map.Entry<Integer, Long> entry : currentOffsets.entrySet()) {
+      int partition = entry.getKey();
+      long currentOffset = entry.getValue();
+      Long previousOffset = previousOffsets.get(partition);
+
+      if (previousOffset != null) {
+        // Partition exists in both checkpoints
+        long diff = currentOffset - previousOffset;
+
+        // Handle offset reset (negative diff) - topic/partition recreated
+        if (diff < 0) {
+          // Use current offset as diff (count from 0 to current)
+          totalDiff += currentOffset;
+        } else {
+          totalDiff += diff;
+        }
+      } else {
+        // New partition - count from 0 to current
+        totalDiff += currentOffset;
+      }
+    }
+
+    return totalDiff;
+  }
+
+  /**
+   * Validate checkpoint format.
+   *
+   * @param format Expected checkpoint format
+   * @param checkpointStr Checkpoint string to validate
+   * @return true if valid format
+   */
+  public static boolean isValidCheckpointFormat(CheckpointFormat format, 
String checkpointStr) {
+    if (checkpointStr == null || checkpointStr.trim().isEmpty()) {
+      return false;
+    }
+
+    try {
+      parseCheckpoint(format, checkpointStr);
+      return true;
+    } catch (Exception e) {
+      return false;
+    }
+  }
+
+  /**
+   * Extract topic name from DeltaStreamer Kafka checkpoint.
+   * Format: "topic,partition:offset,..."
+   *
+   * @param checkpointStr DeltaStreamer Kafka checkpoint
+   * @return Topic name
+   * @throws IllegalArgumentException if invalid format
+   */
+  public static String extractTopicName(String checkpointStr) {

Review Comment:
   Done — see reply on the comment above for the full breakdown.



##########
hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodiePreCommitValidatorConfig.java:
##########
@@ -64,6 +64,25 @@ public class HoodiePreCommitValidatorConfig extends 
HoodieConfig {
           + "Expected result is included as part of query separated by '#'. 
Example query: 'query1#result1:query2#result2'"
           + "Note \\<TABLE_NAME\\> variable is expected to be present in 
query.");
 
+  public static final ConfigProperty<String> 
STREAMING_OFFSET_TOLERANCE_PERCENTAGE = ConfigProperty
+      .key("hoodie.precommit.validators.streaming.offset.tolerance.percentage")
+      .defaultValue("0.0")
+      .markAdvanced()
+      .withDocumentation("Tolerance percentage for streaming offset 
validation. "

Review Comment:
   Added `org.apache.hudi.client.validator.StreamingOffsetValidator` to the 
config documentation. Done.



##########
hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/HoodiePreCommitValidatorConfig.java:
##########
@@ -64,6 +64,25 @@ public class HoodiePreCommitValidatorConfig extends 
HoodieConfig {
           + "Expected result is included as part of query separated by '#'. 
Example query: 'query1#result1:query2#result2'"
           + "Note \\<TABLE_NAME\\> variable is expected to be present in 
query.");
 
+  public static final ConfigProperty<String> 
STREAMING_OFFSET_TOLERANCE_PERCENTAGE = ConfigProperty
+      .key("hoodie.precommit.validators.streaming.offset.tolerance.percentage")
+      .defaultValue("0.0")
+      .markAdvanced()
+      .withDocumentation("Tolerance percentage for streaming offset 
validation. "
+          + "The validator compares the offset difference (expected records 
from source) "
+          + "with actual records written. If the deviation exceeds this 
percentage, "
+          + "the commit is rejected (or warned, depending on warn-only mode). "
+          + "For upsert workloads with deduplication, set a higher tolerance. "
+          + "Default is 0.0 (strict mode, exact match required).");
+
+  public static final ConfigProperty<String> WARN_ONLY_MODE = ConfigProperty
+      .key("hoodie.precommit.validators.warn.only")

Review Comment:
   Good suggestion. Replaced the boolean 
`hoodie.precommit.validators.warn.only` with 
`hoodie.precommit.validators.failure.policy` backed by a 
`ValidationFailurePolicy` enum with values `FAIL` (default) and `WARN_LOG`. 
This makes it extensible for future policies (e.g., `SKIP`, `QUARANTINE`).



##########
hudi-common/src/main/java/org/apache/hudi/client/validator/StreamingOffsetValidator.java:
##########
@@ -0,0 +1,209 @@
+/*
+ * 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.validator;
+
+import org.apache.hudi.common.config.TypedProperties;
+import org.apache.hudi.common.util.CheckpointUtils;
+import org.apache.hudi.common.util.CheckpointUtils.CheckpointFormat;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.exception.HoodieValidationException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Abstract base class for streaming offset validators.
+ * Handles common offset validation logic across all streaming sources (Kafka, 
Pulsar, Kinesis).
+ *
+ * This validator compares source offset differences with actual record counts 
written to detect data loss.
+ *
+ * <p><b>Note:</b> This validator is primarily intended for append-only 
ingestion scenarios.
+ * For upsert workloads with deduplication or event-time ordering, the 
deviation between
+ * source offsets and records written can be legitimately large (e.g., 
duplicate keys are
+ * deduplicated, late-arriving events are dropped). In such cases, configure 
an appropriate
+ * tolerance percentage or use warn-only mode.</p>
+ *
+ * Algorithm:
+ * 1. Extract current and previous checkpoints from commit metadata
+ * 2. Calculate offset difference using source-specific format
+ * 3. Get actual record count from write statistics
+ * 4. Calculate deviation percentage: |offsetDiff - recordCount| / offsetDiff 
* 100
+ * 5. If deviation &gt; tolerance: fail (or warn if warn-only mode)
+ *
+ * Subclasses specify:
+ * - Checkpoint format (DELTASTREAMER_KAFKA, FLINK_KAFKA, etc.)
+ * - Checkpoint metadata key
+ * - Source-specific parsing logic (if needed)
+ *
+ * Configuration:
+ * - hoodie.precommit.validators.streaming.offset.tolerance.percentage 
(default: 0.0)
+ * - hoodie.precommit.validators.warn.only (default: false)
+ */
+public abstract class StreamingOffsetValidator extends BasePreCommitValidator {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(StreamingOffsetValidator.class);
+
+  // Configuration keys - these mirror the ConfigProperty definitions in
+  // HoodiePreCommitValidatorConfig (hudi-client-common) for documentation 
surfacing.
+  protected static final String TOLERANCE_PERCENTAGE_KEY = 
"hoodie.precommit.validators.streaming.offset.tolerance.percentage";

Review Comment:
   Done — moved `StreamingOffsetValidator` (and its test) from `hudi-common` to 
`hudi-client/hudi-client-common`. It now directly references 
`HoodiePreCommitValidatorConfig.STREAMING_OFFSET_TOLERANCE_PERCENTAGE` and 
`HoodiePreCommitValidatorConfig.VALIDATION_FAILURE_POLICY` instead of 
duplicating string constants.



##########
hudi-common/src/main/java/org/apache/hudi/client/validator/StreamingOffsetValidator.java:
##########
@@ -0,0 +1,209 @@
+/*
+ * 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.validator;
+
+import org.apache.hudi.common.config.TypedProperties;
+import org.apache.hudi.common.util.CheckpointUtils;
+import org.apache.hudi.common.util.CheckpointUtils.CheckpointFormat;
+import org.apache.hudi.common.util.Option;
+import org.apache.hudi.exception.HoodieValidationException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Abstract base class for streaming offset validators.
+ * Handles common offset validation logic across all streaming sources (Kafka, 
Pulsar, Kinesis).
+ *
+ * This validator compares source offset differences with actual record counts 
written to detect data loss.
+ *
+ * <p><b>Note:</b> This validator is primarily intended for append-only 
ingestion scenarios.
+ * For upsert workloads with deduplication or event-time ordering, the 
deviation between
+ * source offsets and records written can be legitimately large (e.g., 
duplicate keys are
+ * deduplicated, late-arriving events are dropped). In such cases, configure 
an appropriate
+ * tolerance percentage or use warn-only mode.</p>
+ *
+ * Algorithm:
+ * 1. Extract current and previous checkpoints from commit metadata
+ * 2. Calculate offset difference using source-specific format
+ * 3. Get actual record count from write statistics
+ * 4. Calculate deviation percentage: |offsetDiff - recordCount| / offsetDiff 
* 100
+ * 5. If deviation &gt; tolerance: fail (or warn if warn-only mode)
+ *
+ * Subclasses specify:
+ * - Checkpoint format (DELTASTREAMER_KAFKA, FLINK_KAFKA, etc.)
+ * - Checkpoint metadata key
+ * - Source-specific parsing logic (if needed)
+ *
+ * Configuration:
+ * - hoodie.precommit.validators.streaming.offset.tolerance.percentage 
(default: 0.0)
+ * - hoodie.precommit.validators.warn.only (default: false)
+ */
+public abstract class StreamingOffsetValidator extends BasePreCommitValidator {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(StreamingOffsetValidator.class);
+
+  // Configuration keys - these mirror the ConfigProperty definitions in
+  // HoodiePreCommitValidatorConfig (hudi-client-common) for documentation 
surfacing.
+  protected static final String TOLERANCE_PERCENTAGE_KEY = 
"hoodie.precommit.validators.streaming.offset.tolerance.percentage";
+  protected static final String WARN_ONLY_MODE_KEY = 
"hoodie.precommit.validators.warn.only";
+
+  // Default values
+  protected static final double DEFAULT_TOLERANCE_PERCENTAGE = 0.0;
+  protected static final boolean DEFAULT_WARN_ONLY_MODE = false;
+
+  protected final String checkpointKey;
+  protected final double tolerancePercentage;
+  protected final boolean warnOnlyMode;
+  protected final CheckpointFormat checkpointFormat;
+
+  /**
+   * Create a streaming offset validator.
+   *
+   * @param config Validator configuration
+   * @param checkpointKey Key to extract checkpoint from extraMetadata
+   * @param checkpointFormat Format of the checkpoint string
+   */
+  protected StreamingOffsetValidator(TypedProperties config,
+                                      String checkpointKey,
+                                      CheckpointFormat checkpointFormat) {
+    super(config);
+    this.checkpointKey = checkpointKey;
+    this.checkpointFormat = checkpointFormat;
+    this.tolerancePercentage = config.getDouble(TOLERANCE_PERCENTAGE_KEY, 
DEFAULT_TOLERANCE_PERCENTAGE);
+    this.warnOnlyMode = config.getBoolean(WARN_ONLY_MODE_KEY, 
DEFAULT_WARN_ONLY_MODE);
+  }
+
+  @Override
+  protected void validateWithMetadata(ValidationContext context) throws 
HoodieValidationException {
+    // Skip validation for first commit (no previous checkpoint)
+    if (context.isFirstCommit()) {
+      LOG.info("Skipping offset validation for first commit");
+      return;
+    }
+
+    // Extract current checkpoint
+    Option<String> currentCheckpointOpt = 
context.getExtraMetadata(checkpointKey);
+    if (!currentCheckpointOpt.isPresent()) {
+      LOG.warn("Current checkpoint not found with key: {}. Skipping 
validation.", checkpointKey);
+      return;
+    }
+    String currentCheckpoint = currentCheckpointOpt.get();
+
+    // Validate current checkpoint format
+    if (!CheckpointUtils.isValidCheckpointFormat(checkpointFormat, 
currentCheckpoint)) {
+      LOG.warn("Current checkpoint has invalid format: {}. Skipping 
validation.", currentCheckpoint);
+      return;
+    }
+
+    // Extract previous checkpoint
+    Option<String> previousCheckpointOpt = context.getPreviousCommitMetadata()
+        .flatMap(metadata -> 
Option.ofNullable(metadata.getMetadata(checkpointKey)));
+
+    if (!previousCheckpointOpt.isPresent()) {
+      LOG.info("Previous checkpoint not found. May be first streaming commit. 
Skipping validation.");
+      return;
+    }
+    String previousCheckpoint = previousCheckpointOpt.get();
+
+    // Validate previous checkpoint format
+    if (!CheckpointUtils.isValidCheckpointFormat(checkpointFormat, 
previousCheckpoint)) {
+      LOG.warn("Previous checkpoint has invalid format: {}. Skipping 
validation.", previousCheckpoint);
+      return;
+    }
+
+    // Calculate offset difference using format-specific logic
+    long offsetDifference = CheckpointUtils.calculateOffsetDifference(
+        checkpointFormat, previousCheckpoint, currentCheckpoint);
+
+    // Handle negative offset (source reset)
+    if (offsetDifference < 0) {
+      LOG.warn("Negative offset difference detected ({}). May indicate source 
reset. Skipping validation.",

Review Comment:
   You are right — we cannot end up here. `calculateOffsetDifference` handles 
negative per-partition diffs internally (offset resets use the current offset 
as the diff), so the returned total is always >= 0. Removed this unreachable 
dead code and added a comment explaining why the check is unnecessary.



-- 
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