You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by "gguptp (via GitHub)" <gi...@apache.org> on 2025/03/25 06:48:17 UTC

[PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

gguptp opened a new pull request, #193:
URL: https://github.com/apache/flink-connector-aws/pull/193

   
   <!--
   *Thank you for contributing to Apache Flink AWS Connectors - we are happy that you want to help us improve our Flink connectors. To help the community review your contribution in the best possible way, please go through the checklist below, which will get the contribution into a shape in which it can be best reviewed.*
   
   ## Contribution Checklist
   
   - The name of the pull request should correspond to a [JIRA issue](https://issues.apache.org/jira/projects/FLINK/issues). Exceptions are made for typos in JavaDoc or documentation files, which need no JIRA issue.
   - Commits should be in the form of "[FLINK-XXXX][component] Title of the pull request", where [FLINK-XXXX] should be replaced by the actual issue number. 
       Generally, [component] should be the connector you are working on.
       For example: "[FLINK-XXXX][Connectors/Kinesis] XXXX" if you are working on the Kinesis connector or "[FLINK-XXXX][Connectors/AWS] XXXX" if you are working on components shared among all the connectors.
   - Each pull request should only have one JIRA issue.
   - Once all items of the checklist are addressed, remove the above text and this checklist, leaving only the filled out template below.
   -->
   
   ## Purpose of the change
   
   Theres a race condition in the connector which can lead to data loss:
   
   - A checkpoint started
   - Enumerator took a checkpoint (shard was assigned here)
   - Enumerator sent checkpoint event to reader
   - Before taking reader checkpoint, a SplitFinishedEvent came up in reader
   - Reader took checkpoint
   - Now, just after checkpoint complete, job restarted
   
   This can lead to a shard lineage getting lost. 
   This PR fixes the behaviour by also checkpointing the finished splits events received in between two checkpoints and on restore, those events again getting replayed.
   
   ## Verifying this change
   
   Please make sure both new and modified tests in this PR follows the conventions defined in our code quality guide: https://flink.apache.org/contributing/code-style-and-quality-common.html#testing
   
   *(Please pick either of the following options)*
   
   This change is a trivial rework / code cleanup without any test coverage.
   
   *(or)*
   
   This change is already covered by existing tests, such as *(please describe tests)*.
   
   *(or)*
   
   This change added tests and can be verified as follows:
   
   *(example:)*
   - *Added integration tests for end-to-end deployment*
   - *Added unit tests*
   - *Manually verified by running the Kinesis connector on a local Flink cluster.*
   
   I manually verified this by running the connector in a local flink cluster which was getting restarted every 10 minutes. I see there is no checkpoint discrepancy and there is no issue in the clusster
   
   I also added UTs for the change
   
   ## Significant changes
   *(Please check any boxes [x] if the answer is "yes". You can first publish the PR and check them afterwards, for convenience.)*
   - [ ] Dependencies have been added or upgraded
   - [ ] Public API has been changed (Public API is any class annotated with `@Public(Evolving)`)
   - [ x ] Serializers have been changed
   - [ x ] New feature has been introduced
     - If yes, how is this documented? (not applicable / docs / JavaDocs / not documented)
   


-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014079810


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/split/DynamoDbStreamsShardSplit.java:
##########
@@ -40,12 +40,22 @@ public final class DynamoDbStreamsShardSplit implements SourceSplit {
     private final String shardId;
     private final StartingPosition startingPosition;
     private final String parentShardId;
+    private final long finishedAfterCheckpoint;

Review Comment:
   actuallly i would rather say the issue exists due to following:
   - Enumerator checkpointed its state
   - It asked reader to checkpoint
   - Just before reader started checkpointing a SplitFinished event came
   - Reader checkpointed its state
   
   Now there is a gap between enumerator and reader in terms of enumerator checkpointed first and reader checkpointed later
   
   I guess from enumerator POV, this variable might be named as finishedAfterCheckpoint, from reader POV it can be named as finishedBeforeCheckpoint, so i'm in a dilemma what should be its name 😂 



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "leekeiabstraction (via GitHub)" <gi...@apache.org>.
leekeiabstraction commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014041555


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/enumerator/DynamoDbStreamsSourceEnumerator.java:
##########
@@ -138,14 +138,26 @@ public void handleSourceEvent(int subtaskId, SourceEvent sourceEvent) {
 
     /** When we mark a split as finished, we will only assign its child splits to the subtasks. */
     private void handleFinishedSplits(int subtaskId, SplitsFinishedEvent splitsFinishedEvent) {
+        Set<DynamoDbStreamsShardSplit> splitsAssignment = splitAssignment.get(subtaskId);

Review Comment:
   Nit: Place line after `splitTracker.markAsFinished(splitsFinishedEvent.getFinishedSplitIds());` instead, moving `splitAssignment` declaration closer to where it's used.



##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/enumerator/tracker/SplitTracker.java:
##########
@@ -333,7 +333,13 @@ private boolean verifyParentIsEitherFinishedOrCleanedUp(DynamoDbStreamsShardSpli
                 || isFinished(split.getParentShardId());
     }
 
-    private boolean isFinished(String splitId) {
+    /**
+     * Provides information whether a split is finished or not.
+     *
+     * @param splitId
+     * @return

Review Comment:
   Incomplete java doc. Suggest something like the below.
   
   ```
   * @return      boolean value indicating if split is finished
   ```



##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +115,54 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.isFinished()) {
+                // Restore finished splits state
+                splitFinishedEvents
+                        .computeIfAbsent(split.getFinishedAfterCheckpoint(), k -> new HashSet<>())
+                        .add(split);
+                // Replay the finished split event
+                context.sendSourceEventToCoordinator(
+                        new SplitsFinishedEvent(Collections.singleton(split.splitId())));
+            } else {
+                dynamoDbStreamsShardSplits.add(split);
+            }
+        }
+        dynamoDbStreamsShardSplits.forEach(this::registerShardMetricGroup);
+        super.addSplits(dynamoDbStreamsShardSplits);
+    }
+
+    /**
+     * At snapshot, we also store the pending finished split ids in the current checkpoint so that
+     * in case we have to restore the reader from state, we also send the finished split ids
+     * otherwise we run a risk of data loss during restarts of the source because of the
+     * SplitsFinishedEvent going missing.
+     *
+     * @param checkpointId
+     * @return
+     */
+    @Override
+    public List<DynamoDbStreamsShardSplit> snapshotState(long checkpointId) {
+        this.currentCheckpointId = checkpointId;
+        List<DynamoDbStreamsShardSplit> splits = super.snapshotState(checkpointId);
+
+        if (!splitFinishedEvents.isEmpty()) {
+            // Add all finished splits to the snapshot
+            splitFinishedEvents.values().forEach(splits::addAll);
+        }
+        return splits;
+    }
+
+    /**
+     * During notifyCheckpointComplete, we should clean up the state of finished splits that are
+     * older than the checkpoint id.
+     *
+     * @param checkpointId
+     */
+    @Override
+    public void notifyCheckpointComplete(long checkpointId) {
+        splitFinishedEvents.headMap(checkpointId, true).clear();

Review Comment:
   Java doc says we are cleaning up state of finished splits that are older (interpreting as exclusive) than checkpoint id, however we are providing `true` as inclusive arg in headMap. Which one is the intended behaviour?



##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/split/DynamoDbStreamsShardSplit.java:
##########
@@ -40,12 +40,22 @@ public final class DynamoDbStreamsShardSplit implements SourceSplit {
     private final String shardId;
     private final StartingPosition startingPosition;
     private final String parentShardId;
+    private final long finishedAfterCheckpoint;

Review Comment:
   Perhaps more of a question than comment. Would `finishedDuringCheckpoint` be more accurate? If I understand correctly, checkpointing is still in progress and the issue occurs when split happens before reader completed checkpoint.



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014045507


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +115,54 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.isFinished()) {
+                // Restore finished splits state
+                splitFinishedEvents
+                        .computeIfAbsent(split.getFinishedAfterCheckpoint(), k -> new HashSet<>())
+                        .add(split);
+                // Replay the finished split event
+                context.sendSourceEventToCoordinator(
+                        new SplitsFinishedEvent(Collections.singleton(split.splitId())));
+            } else {
+                dynamoDbStreamsShardSplits.add(split);
+            }
+        }
+        dynamoDbStreamsShardSplits.forEach(this::registerShardMetricGroup);
+        super.addSplits(dynamoDbStreamsShardSplits);
+    }
+
+    /**
+     * At snapshot, we also store the pending finished split ids in the current checkpoint so that
+     * in case we have to restore the reader from state, we also send the finished split ids
+     * otherwise we run a risk of data loss during restarts of the source because of the
+     * SplitsFinishedEvent going missing.
+     *
+     * @param checkpointId
+     * @return
+     */
+    @Override
+    public List<DynamoDbStreamsShardSplit> snapshotState(long checkpointId) {
+        this.currentCheckpointId = checkpointId;
+        List<DynamoDbStreamsShardSplit> splits = super.snapshotState(checkpointId);
+
+        if (!splitFinishedEvents.isEmpty()) {
+            // Add all finished splits to the snapshot
+            splitFinishedEvents.values().forEach(splits::addAll);
+        }
+        return splits;
+    }
+
+    /**
+     * During notifyCheckpointComplete, we should clean up the state of finished splits that are
+     * older than the checkpoint id.
+     *
+     * @param checkpointId
+     */
+    @Override
+    public void notifyCheckpointComplete(long checkpointId) {
+        splitFinishedEvents.headMap(checkpointId, true).clear();

Review Comment:
   good point, any splits which are <= this checkpoint will be cleared. I will update the javadoc



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014341394


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/enumerator/DynamoDbStreamsSourceEnumerator.java:
##########
@@ -139,13 +139,25 @@ public void handleSourceEvent(int subtaskId, SourceEvent sourceEvent) {
     /** When we mark a split as finished, we will only assign its child splits to the subtasks. */
     private void handleFinishedSplits(int subtaskId, SplitsFinishedEvent splitsFinishedEvent) {
         splitTracker.markAsFinished(splitsFinishedEvent.getFinishedSplitIds());
-        splitAssignment
-                .get(subtaskId)
-                .removeIf(
-                        split ->
-                                splitsFinishedEvent
-                                        .getFinishedSplitIds()
-                                        .contains(split.splitId()));
+
+        Set<DynamoDbStreamsShardSplit> splitsAssignment = splitAssignment.get(subtaskId);
+        // during recovery, splitAssignment may return null since there might be no split assigned
+        // to the subtask, but there might be SplitsFinishedEvent from that subtask.
+        // We will not do child shard assignment if that is the case since that might lead to child
+        // shards trying to get assigned before there being any readers.
+        if (splitsAssignment == null) {

Review Comment:
   Good spot Arvid..!



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014088060


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/split/DynamoDbStreamsShardSplit.java:
##########
@@ -40,12 +40,22 @@ public final class DynamoDbStreamsShardSplit implements SourceSplit {
     private final String shardId;
     private final StartingPosition startingPosition;
     private final String parentShardId;
+    private final long finishedAfterCheckpoint;

Review Comment:
   Agreed that from the Job POV, this is during checkpoint, hence naming the variable as `finishedDuringCheckpoint`



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014319333


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -58,10 +65,38 @@ public DynamoDbStreamsSourceReader(
             Map<String, DynamoDbStreamsShardMetrics> shardMetricGroupMap) {
         super(splitFetcherManager, recordEmitter, config, context);
         this.shardMetricGroupMap = shardMetricGroupMap;
+        this.splitFinishedEvents = new TreeMap<>();
+        this.currentCheckpointId = Long.MIN_VALUE;
     }
 
+    /**
+     * We store the finished splits in a map keyed by the checkpoint id.
+     *
+     * @param finishedSplitIds
+     */
     @Override
     protected void onSplitFinished(Map<String, DynamoDbStreamsShardSplitState> finishedSplitIds) {
+        if (finishedSplitIds.isEmpty()) {
+            return;
+        }
+
+        finishedSplitIds.values().stream()
+                .map(
+                        finishedSplit ->
+                                new DynamoDbStreamsShardSplit(
+                                        finishedSplit.getStreamArn(),
+                                        finishedSplit.getShardId(),
+                                        finishedSplit.getNextStartingPosition(),
+                                        finishedSplit
+                                                .getDynamoDbStreamsShardSplit()
+                                                .getParentShardId(),
+                                        true))
+                .forEach(
+                        split ->
+                                splitFinishedEvents
+                                        .computeIfAbsent(currentCheckpointId, k -> new HashSet<>())

Review Comment:
   good point



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2011546662


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +105,65 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.getShardId().equals(DYNAMODB_STREAMS_COMPLETED_SHARD_ID)) {
+                // Restore finished splits state
+                splitFinishedEvents.putAll(split.getFinishedSplitsMap());
+
+                // Replay all stored finished events
+                splitFinishedEvents.values().stream()
+                        .flatMap(Set::stream)
+                        .collect(Collectors.toSet())
+                        .forEach(
+                                splitId ->
+                                        context.sendSourceEventToCoordinator(
+                                                new SplitsFinishedEvent(
+                                                        Collections.singleton(splitId))));
+            } else {
+                dynamoDbStreamsShardSplits.add(split);
+            }
+        }
+        dynamoDbStreamsShardSplits.forEach(this::registerShardMetricGroup);
+        super.addSplits(dynamoDbStreamsShardSplits);
+    }
+
+    /**
+     * At snapshot, we also store the pending finished split ids in the current checkpoint so that
+     * in case we have to restore the reader from state, we also send the finished split ids
+     * otherwise we run a risk of data loss during restarts of the source because of the
+     * SplitsFinishedEvent going missing.
+     *
+     * @param checkpointId
+     * @return
+     */
+    @Override
+    public List<DynamoDbStreamsShardSplit> snapshotState(long checkpointId) {
+        this.currentCheckpointId = checkpointId;
+        List<DynamoDbStreamsShardSplit> splits = super.snapshotState(checkpointId);
+
+        if (!splitFinishedEvents.isEmpty()) {
+            // Always add a dedicated split for finished state
+            splits.add(
+                    new DynamoDbStreamsShardSplit(
+                            "",
+                            DYNAMODB_STREAMS_COMPLETED_SHARD_ID,
+                            StartingPosition.fromStart(),
+                            null,
+                            splitFinishedEvents));
+        }
+        return splits;

Review Comment:
   The only problem here is that we dont have access to the split state directly from the SourceReaderBase class and given the number of shards which DDB has, the `notifyCheckpointCompleted` function might become O(n) operation as compared to today where it is O(log(n)) operation and might hit performance, hence i wanted to avoid using a list for this. 
   
   I guess i might be missing something here so correct me if i'm wrong here



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014326029


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +115,55 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.isFinished()) {
+                // Replay the finished split event.
+                // We don't need to reload the split finished events in buffer back
+                // since if the next checkpoint completes, these would just be removed from the
+                // buffer. If the next checkpoint doesn't complete,
+                // we would go back to the previous checkpointed
+                // state which will again replay these split finished events.
+                context.sendSourceEventToCoordinator(
+                        new SplitsFinishedEvent(Collections.singleton(split.splitId())));
+            } else {
+                dynamoDbStreamsShardSplits.add(split);
+            }
+        }
+        dynamoDbStreamsShardSplits.forEach(this::registerShardMetricGroup);
+        super.addSplits(dynamoDbStreamsShardSplits);
+    }
+
+    /**
+     * At snapshot, we also store the pending finished split ids in the current checkpoint so that
+     * in case we have to restore the reader from state, we also send the finished split ids
+     * otherwise we run a risk of data loss during restarts of the source because of the
+     * SplitsFinishedEvent going missing.
+     *
+     * @param checkpointId
+     * @return
+     */
+    @Override
+    public List<DynamoDbStreamsShardSplit> snapshotState(long checkpointId) {
+        this.currentCheckpointId = checkpointId;
+        List<DynamoDbStreamsShardSplit> splits = super.snapshotState(checkpointId);
+
+        if (!splitFinishedEvents.isEmpty()) {
+            // Add all finished splits to the snapshot
+            splitFinishedEvents.values().forEach(splits::addAll);

Review Comment:
   agree, made the list returned by snapshotstate



##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +115,55 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.isFinished()) {
+                // Replay the finished split event.
+                // We don't need to reload the split finished events in buffer back
+                // since if the next checkpoint completes, these would just be removed from the
+                // buffer. If the next checkpoint doesn't complete,
+                // we would go back to the previous checkpointed
+                // state which will again replay these split finished events.
+                context.sendSourceEventToCoordinator(
+                        new SplitsFinishedEvent(Collections.singleton(split.splitId())));
+            } else {
+                dynamoDbStreamsShardSplits.add(split);
+            }
+        }
+        dynamoDbStreamsShardSplits.forEach(this::registerShardMetricGroup);
+        super.addSplits(dynamoDbStreamsShardSplits);
+    }
+
+    /**
+     * At snapshot, we also store the pending finished split ids in the current checkpoint so that
+     * in case we have to restore the reader from state, we also send the finished split ids
+     * otherwise we run a risk of data loss during restarts of the source because of the
+     * SplitsFinishedEvent going missing.
+     *
+     * @param checkpointId
+     * @return
+     */
+    @Override
+    public List<DynamoDbStreamsShardSplit> snapshotState(long checkpointId) {
+        this.currentCheckpointId = checkpointId;
+        List<DynamoDbStreamsShardSplit> splits = super.snapshotState(checkpointId);
+
+        if (!splitFinishedEvents.isEmpty()) {
+            // Add all finished splits to the snapshot
+            splitFinishedEvents.values().forEach(splits::addAll);

Review Comment:
   agree, made the list returned by snapshotstate as an arraylist



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014398236


##########
flink-connector-aws/flink-connector-dynamodb/src/test/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReaderTest.java:
##########
@@ -158,4 +163,128 @@ void testAddSplitsRegistersAndUpdatesShardMetricGroup() throws Exception {
         TestUtil.assertMillisBehindLatest(
                 split, TestUtil.MILLIS_BEHIND_LATEST_TEST_VALUE, metricListener);
     }
+
+    @Test
+    void testSnapshotStateWithFinishedSplits() throws Exception {
+        // Create and add a split
+        DynamoDbStreamsShardSplit split = getTestSplit();
+        List<DynamoDbStreamsShardSplit> splits = Collections.singletonList(split);
+        sourceReader.addSplits(splits);
+
+        // Set checkpoint ID by taking initial snapshot
+        List<DynamoDbStreamsShardSplit> initialSnapshot = sourceReader.snapshotState(1L);
+        assertThat(initialSnapshot).hasSize(1).containsExactly(split);
+
+        // Simulate split finishing
+        Map<String, DynamoDbStreamsShardSplitState> finishedSplits = new HashMap<>();
+        finishedSplits.put(split.splitId(), new DynamoDbStreamsShardSplitState(split));
+        sourceReader.onSplitFinished(finishedSplits);
+
+        // Take another snapshot
+        List<DynamoDbStreamsShardSplit> snapshotSplits = sourceReader.snapshotState(2L);
+        List<DynamoDbStreamsShardSplit> snapshotFinishedSplits =
+                snapshotSplits.stream()
+                        .filter(DynamoDbStreamsShardSplit::isFinished)
+                        .collect(Collectors.toList());
+        // Verify we have 2 splits - the original split and the finished split
+        assertThat(snapshotFinishedSplits)
+                .hasSize(1)
+                .allSatisfy(
+                        s -> {
+                            assertThat(s.splitId()).isEqualTo(split.splitId());
+                        });
+    }
+
+    @Test
+    void testAddSplitsWithStateRestoration() throws Exception {
+        // Create finished split with checkpoint id 1

Review Comment:
   lol, good catch, fixed this



##########
flink-connector-aws/flink-connector-dynamodb/src/test/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReaderTest.java:
##########
@@ -158,4 +163,128 @@ void testAddSplitsRegistersAndUpdatesShardMetricGroup() throws Exception {
         TestUtil.assertMillisBehindLatest(
                 split, TestUtil.MILLIS_BEHIND_LATEST_TEST_VALUE, metricListener);
     }
+
+    @Test
+    void testSnapshotStateWithFinishedSplits() throws Exception {
+        // Create and add a split
+        DynamoDbStreamsShardSplit split = getTestSplit();
+        List<DynamoDbStreamsShardSplit> splits = Collections.singletonList(split);
+        sourceReader.addSplits(splits);
+
+        // Set checkpoint ID by taking initial snapshot
+        List<DynamoDbStreamsShardSplit> initialSnapshot = sourceReader.snapshotState(1L);
+        assertThat(initialSnapshot).hasSize(1).containsExactly(split);
+
+        // Simulate split finishing
+        Map<String, DynamoDbStreamsShardSplitState> finishedSplits = new HashMap<>();
+        finishedSplits.put(split.splitId(), new DynamoDbStreamsShardSplitState(split));
+        sourceReader.onSplitFinished(finishedSplits);
+
+        // Take another snapshot
+        List<DynamoDbStreamsShardSplit> snapshotSplits = sourceReader.snapshotState(2L);
+        List<DynamoDbStreamsShardSplit> snapshotFinishedSplits =
+                snapshotSplits.stream()
+                        .filter(DynamoDbStreamsShardSplit::isFinished)
+                        .collect(Collectors.toList());
+        // Verify we have 2 splits - the original split and the finished split
+        assertThat(snapshotFinishedSplits)

Review Comment:
   fixed 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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2011604775


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +105,65 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.getShardId().equals(DYNAMODB_STREAMS_COMPLETED_SHARD_ID)) {
+                // Restore finished splits state
+                splitFinishedEvents.putAll(split.getFinishedSplitsMap());
+
+                // Replay all stored finished events
+                splitFinishedEvents.values().stream()
+                        .flatMap(Set::stream)
+                        .collect(Collectors.toSet())
+                        .forEach(
+                                splitId ->
+                                        context.sendSourceEventToCoordinator(
+                                                new SplitsFinishedEvent(
+                                                        Collections.singleton(splitId))));
+            } else {
+                dynamoDbStreamsShardSplits.add(split);
+            }
+        }
+        dynamoDbStreamsShardSplits.forEach(this::registerShardMetricGroup);
+        super.addSplits(dynamoDbStreamsShardSplits);
+    }
+
+    /**
+     * At snapshot, we also store the pending finished split ids in the current checkpoint so that
+     * in case we have to restore the reader from state, we also send the finished split ids
+     * otherwise we run a risk of data loss during restarts of the source because of the
+     * SplitsFinishedEvent going missing.
+     *
+     * @param checkpointId
+     * @return
+     */
+    @Override
+    public List<DynamoDbStreamsShardSplit> snapshotState(long checkpointId) {
+        this.currentCheckpointId = checkpointId;
+        List<DynamoDbStreamsShardSplit> splits = super.snapshotState(checkpointId);
+
+        if (!splitFinishedEvents.isEmpty()) {
+            // Always add a dedicated split for finished state
+            splits.add(
+                    new DynamoDbStreamsShardSplit(
+                            "",
+                            DYNAMODB_STREAMS_COMPLETED_SHARD_ID,
+                            StartingPosition.fromStart(),
+                            null,
+                            splitFinishedEvents));
+        }
+        return splits;

Review Comment:
   i see your point, i think this approach sounds much neater



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014178783


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +115,54 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.isFinished()) {
+                // Restore finished splits state
+                splitFinishedEvents
+                        .computeIfAbsent(split.getFinishedDuringCheckpoint(), k -> new HashSet<>())
+                        .add(split);

Review Comment:
   updated the PR



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014227005


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/enumerator/DynamoDbStreamsSourceEnumerator.java:
##########
@@ -139,13 +139,25 @@ public void handleSourceEvent(int subtaskId, SourceEvent sourceEvent) {
     /** When we mark a split as finished, we will only assign its child splits to the subtasks. */
     private void handleFinishedSplits(int subtaskId, SplitsFinishedEvent splitsFinishedEvent) {
         splitTracker.markAsFinished(splitsFinishedEvent.getFinishedSplitIds());
-        splitAssignment
-                .get(subtaskId)
-                .removeIf(
-                        split ->
-                                splitsFinishedEvent
-                                        .getFinishedSplitIds()
-                                        .contains(split.splitId()));
+
+        Set<DynamoDbStreamsShardSplit> splitsAssignment = splitAssignment.get(subtaskId);
+        // during recovery, splitAssignment may return null since there might be no split assigned
+        // to the subtask, but there might be SplitsFinishedEvent from that subtask.
+        // We will not do child shard assignment if that is the case since that might lead to child
+        // shards trying to get assigned before there being any readers.
+        if (splitsAssignment == null) {

Review Comment:
   Why don't we make this a generic warn if we don't find the finished split in the assigned splits? (Instead of if no split is assigned to subtask)



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "AHeise (via GitHub)" <gi...@apache.org>.
AHeise commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014306328


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/enumerator/DynamoDbStreamsSourceEnumerator.java:
##########
@@ -139,13 +139,25 @@ public void handleSourceEvent(int subtaskId, SourceEvent sourceEvent) {
     /** When we mark a split as finished, we will only assign its child splits to the subtasks. */
     private void handleFinishedSplits(int subtaskId, SplitsFinishedEvent splitsFinishedEvent) {
         splitTracker.markAsFinished(splitsFinishedEvent.getFinishedSplitIds());
-        splitAssignment
-                .get(subtaskId)
-                .removeIf(
-                        split ->
-                                splitsFinishedEvent
-                                        .getFinishedSplitIds()
-                                        .contains(split.splitId()));
+
+        Set<DynamoDbStreamsShardSplit> splitsAssignment = splitAssignment.get(subtaskId);
+        // during recovery, splitAssignment may return null since there might be no split assigned
+        // to the subtask, but there might be SplitsFinishedEvent from that subtask.
+        // We will not do child shard assignment if that is the case since that might lead to child
+        // shards trying to get assigned before there being any readers.
+        if (splitsAssignment == null) {

Review Comment:
   I'd not weaken consistency checks here for all events. I'd mark the events as recovered and then allow some leniency (not even WARN because this is expected).



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2011547100


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/split/DynamoDbStreamsShardSplit.java:
##########
@@ -40,6 +43,7 @@ public final class DynamoDbStreamsShardSplit implements SourceSplit {
     private final String shardId;
     private final StartingPosition startingPosition;
     private final String parentShardId;
+    private final NavigableMap<Long, Set<String>> finishedSplitsMap;

Review Comment:
   agree, i can just use a Set<String> here



##########
flink-connector-aws/flink-connector-dynamodb/src/test/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReaderTest.java:
##########
@@ -158,4 +165,148 @@ void testAddSplitsRegistersAndUpdatesShardMetricGroup() throws Exception {
         TestUtil.assertMillisBehindLatest(
                 split, TestUtil.MILLIS_BEHIND_LATEST_TEST_VALUE, metricListener);
     }
+
+    @Test
+    void testSnapshotStateWithFinishedSplits() throws Exception {
+        // Create and add a split
+        DynamoDbStreamsShardSplit split = getTestSplit();
+        List<DynamoDbStreamsShardSplit> splits = Collections.singletonList(split);
+        sourceReader.addSplits(splits);
+
+        // Set checkpoint ID by taking initial snapshot
+        List<DynamoDbStreamsShardSplit> initialSnapshot = sourceReader.snapshotState(1L);
+        assertThat(initialSnapshot).hasSize(1).containsExactly(split);
+
+        // Simulate split finishing
+        Map<String, DynamoDbStreamsShardSplitState> finishedSplits = new HashMap<>();
+        finishedSplits.put(split.splitId(), new DynamoDbStreamsShardSplitState(split));
+        sourceReader.onSplitFinished(finishedSplits);
+
+        // Take another snapshot
+        List<DynamoDbStreamsShardSplit> snapshotSplits = sourceReader.snapshotState(1L);
+
+        // Verify we have 2 splits - the original split and the state split
+        assertThat(snapshotSplits).hasSize(2);
+
+        // Find and verify the state split
+        Optional<DynamoDbStreamsShardSplit> stateSplitOptional =
+                snapshotSplits.stream()
+                        .filter(s -> s.getShardId().equals("finished-splits-state"))
+                        .findFirst();
+
+        assertThat(stateSplitOptional)
+                .isPresent()
+                .hasValueSatisfying(
+                        stateSplit -> {
+                            NavigableMap<Long, Set<String>> finishedSplitsMap =
+                                    stateSplit.getFinishedSplitsMap();
+                            assertThat(finishedSplitsMap).hasSize(1).containsKey(1L);
+                            assertThat(finishedSplitsMap.get(1L)).contains(split.splitId());
+                        });
+
+        // Find and verify the original split
+        Optional<DynamoDbStreamsShardSplit> originalSplitOptional =
+                snapshotSplits.stream()
+                        .filter(s -> s.getShardId().equals(split.getShardId()))
+                        .findFirst();
+
+        assertThat(originalSplitOptional)
+                .isPresent()
+                .hasValueSatisfying(
+                        originalSplit ->
+                                assertThat(originalSplit)
+                                        .usingRecursiveComparison()
+                                        .isEqualTo(split));

Review Comment:
   agree



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014150600


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +115,54 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.isFinished()) {
+                // Restore finished splits state
+                splitFinishedEvents
+                        .computeIfAbsent(split.getFinishedDuringCheckpoint(), k -> new HashSet<>())
+                        .add(split);

Review Comment:
   sounds reasonable



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2011546662


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +105,65 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.getShardId().equals(DYNAMODB_STREAMS_COMPLETED_SHARD_ID)) {
+                // Restore finished splits state
+                splitFinishedEvents.putAll(split.getFinishedSplitsMap());
+
+                // Replay all stored finished events
+                splitFinishedEvents.values().stream()
+                        .flatMap(Set::stream)
+                        .collect(Collectors.toSet())
+                        .forEach(
+                                splitId ->
+                                        context.sendSourceEventToCoordinator(
+                                                new SplitsFinishedEvent(
+                                                        Collections.singleton(splitId))));
+            } else {
+                dynamoDbStreamsShardSplits.add(split);
+            }
+        }
+        dynamoDbStreamsShardSplits.forEach(this::registerShardMetricGroup);
+        super.addSplits(dynamoDbStreamsShardSplits);
+    }
+
+    /**
+     * At snapshot, we also store the pending finished split ids in the current checkpoint so that
+     * in case we have to restore the reader from state, we also send the finished split ids
+     * otherwise we run a risk of data loss during restarts of the source because of the
+     * SplitsFinishedEvent going missing.
+     *
+     * @param checkpointId
+     * @return
+     */
+    @Override
+    public List<DynamoDbStreamsShardSplit> snapshotState(long checkpointId) {
+        this.currentCheckpointId = checkpointId;
+        List<DynamoDbStreamsShardSplit> splits = super.snapshotState(checkpointId);
+
+        if (!splitFinishedEvents.isEmpty()) {
+            // Always add a dedicated split for finished state
+            splits.add(
+                    new DynamoDbStreamsShardSplit(
+                            "",
+                            DYNAMODB_STREAMS_COMPLETED_SHARD_ID,
+                            StartingPosition.fromStart(),
+                            null,
+                            splitFinishedEvents));
+        }
+        return splits;

Review Comment:
   The only problem here is that we dont have access to the split state directly from the SourceReaderBase class and given the number of shards which DDB has, the `notifyCheckpointCompleted` function might become O(n) operation as compared to today where it is O(log(n)) operation and might hit performance, hence i wanted to avoid using a list for 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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014047414


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/split/DynamoDbStreamsShardSplit.java:
##########
@@ -40,12 +40,22 @@ public final class DynamoDbStreamsShardSplit implements SourceSplit {
     private final String shardId;
     private final StartingPosition startingPosition;
     private final String parentShardId;
+    private final long finishedAfterCheckpoint;

Review Comment:
   i would think finishedAfterCheckpoint is more accurate since the issue occurs when we restarted the job just after checkpoint and the reader state is up-to-date but enumerator's is not



##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/split/DynamoDbStreamsShardSplit.java:
##########
@@ -40,12 +40,22 @@ public final class DynamoDbStreamsShardSplit implements SourceSplit {
     private final String shardId;
     private final StartingPosition startingPosition;
     private final String parentShardId;
+    private final long finishedAfterCheckpoint;

Review Comment:
   i would say finishedAfterCheckpoint is more accurate since the issue occurs when we restarted the job just after checkpoint and the reader state is up-to-date but enumerator's is not



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2011546662


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +105,65 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.getShardId().equals(DYNAMODB_STREAMS_COMPLETED_SHARD_ID)) {
+                // Restore finished splits state
+                splitFinishedEvents.putAll(split.getFinishedSplitsMap());
+
+                // Replay all stored finished events
+                splitFinishedEvents.values().stream()
+                        .flatMap(Set::stream)
+                        .collect(Collectors.toSet())
+                        .forEach(
+                                splitId ->
+                                        context.sendSourceEventToCoordinator(
+                                                new SplitsFinishedEvent(
+                                                        Collections.singleton(splitId))));
+            } else {
+                dynamoDbStreamsShardSplits.add(split);
+            }
+        }
+        dynamoDbStreamsShardSplits.forEach(this::registerShardMetricGroup);
+        super.addSplits(dynamoDbStreamsShardSplits);
+    }
+
+    /**
+     * At snapshot, we also store the pending finished split ids in the current checkpoint so that
+     * in case we have to restore the reader from state, we also send the finished split ids
+     * otherwise we run a risk of data loss during restarts of the source because of the
+     * SplitsFinishedEvent going missing.
+     *
+     * @param checkpointId
+     * @return
+     */
+    @Override
+    public List<DynamoDbStreamsShardSplit> snapshotState(long checkpointId) {
+        this.currentCheckpointId = checkpointId;
+        List<DynamoDbStreamsShardSplit> splits = super.snapshotState(checkpointId);
+
+        if (!splitFinishedEvents.isEmpty()) {
+            // Always add a dedicated split for finished state
+            splits.add(
+                    new DynamoDbStreamsShardSplit(
+                            "",
+                            DYNAMODB_STREAMS_COMPLETED_SHARD_ID,
+                            StartingPosition.fromStart(),
+                            null,
+                            splitFinishedEvents));
+        }
+        return splits;

Review Comment:
   The only problem here is that we dont have access to the split state directly from the SourceReaderBase class and given the number of shards which DDB has, the `notifyCheckpointCompleted` function might become O(n) operation as compared to today where it is O(log(n)) operation and might hit performance



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "AHeise (via GitHub)" <gi...@apache.org>.
AHeise commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2011599746


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +105,65 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.getShardId().equals(DYNAMODB_STREAMS_COMPLETED_SHARD_ID)) {
+                // Restore finished splits state
+                splitFinishedEvents.putAll(split.getFinishedSplitsMap());
+
+                // Replay all stored finished events
+                splitFinishedEvents.values().stream()
+                        .flatMap(Set::stream)
+                        .collect(Collectors.toSet())
+                        .forEach(
+                                splitId ->
+                                        context.sendSourceEventToCoordinator(
+                                                new SplitsFinishedEvent(
+                                                        Collections.singleton(splitId))));
+            } else {
+                dynamoDbStreamsShardSplits.add(split);
+            }
+        }
+        dynamoDbStreamsShardSplits.forEach(this::registerShardMetricGroup);
+        super.addSplits(dynamoDbStreamsShardSplits);
+    }
+
+    /**
+     * At snapshot, we also store the pending finished split ids in the current checkpoint so that
+     * in case we have to restore the reader from state, we also send the finished split ids
+     * otherwise we run a risk of data loss during restarts of the source because of the
+     * SplitsFinishedEvent going missing.
+     *
+     * @param checkpointId
+     * @return
+     */
+    @Override
+    public List<DynamoDbStreamsShardSplit> snapshotState(long checkpointId) {
+        this.currentCheckpointId = checkpointId;
+        List<DynamoDbStreamsShardSplit> splits = super.snapshotState(checkpointId);
+
+        if (!splitFinishedEvents.isEmpty()) {
+            // Always add a dedicated split for finished state
+            splits.add(
+                    new DynamoDbStreamsShardSplit(
+                            "",
+                            DYNAMODB_STREAMS_COMPLETED_SHARD_ID,
+                            StartingPosition.fromStart(),
+                            null,
+                            splitFinishedEvents));
+        }
+        return splits;

Review Comment:
   The access issue can be solved by maintaining a separate `finishedSplits` collection where you add in `onSplitFinished`. `snapshotState` needs then to union the splits from SourceReaderBase and your own splits.
   
   This would then probably also solve `notifyCheckpointCompleted` by actually reducing n to the number of finished splits. (not sure how many splits per checkpoints get finished) If you want to stick to log(N) you could combine both approaches and let `finishedSplits` be a TreeMap again. Then you really just need to add a boolean flag to the split.



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014045507


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +115,54 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.isFinished()) {
+                // Restore finished splits state
+                splitFinishedEvents
+                        .computeIfAbsent(split.getFinishedAfterCheckpoint(), k -> new HashSet<>())
+                        .add(split);
+                // Replay the finished split event
+                context.sendSourceEventToCoordinator(
+                        new SplitsFinishedEvent(Collections.singleton(split.splitId())));
+            } else {
+                dynamoDbStreamsShardSplits.add(split);
+            }
+        }
+        dynamoDbStreamsShardSplits.forEach(this::registerShardMetricGroup);
+        super.addSplits(dynamoDbStreamsShardSplits);
+    }
+
+    /**
+     * At snapshot, we also store the pending finished split ids in the current checkpoint so that
+     * in case we have to restore the reader from state, we also send the finished split ids
+     * otherwise we run a risk of data loss during restarts of the source because of the
+     * SplitsFinishedEvent going missing.
+     *
+     * @param checkpointId
+     * @return
+     */
+    @Override
+    public List<DynamoDbStreamsShardSplit> snapshotState(long checkpointId) {
+        this.currentCheckpointId = checkpointId;
+        List<DynamoDbStreamsShardSplit> splits = super.snapshotState(checkpointId);
+
+        if (!splitFinishedEvents.isEmpty()) {
+            // Add all finished splits to the snapshot
+            splitFinishedEvents.values().forEach(splits::addAll);
+        }
+        return splits;
+    }
+
+    /**
+     * During notifyCheckpointComplete, we should clean up the state of finished splits that are
+     * older than the checkpoint id.
+     *
+     * @param checkpointId
+     */
+    @Override
+    public void notifyCheckpointComplete(long checkpointId) {
+        splitFinishedEvents.headMap(checkpointId, true).clear();

Review Comment:
   good point, any splits which are <= this checkpoint will be cleared. I guess should we remove this true parameter and let the finished splits lay there in the checkpoint for one more checkpoint?



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "AHeise (via GitHub)" <gi...@apache.org>.
AHeise commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014211861


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +115,55 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.isFinished()) {
+                // Replay the finished split event.
+                // We don't need to reload the split finished events in buffer back
+                // since if the next checkpoint completes, these would just be removed from the
+                // buffer. If the next checkpoint doesn't complete,
+                // we would go back to the previous checkpointed
+                // state which will again replay these split finished events.
+                context.sendSourceEventToCoordinator(
+                        new SplitsFinishedEvent(Collections.singleton(split.splitId())));
+            } else {
+                dynamoDbStreamsShardSplits.add(split);
+            }
+        }
+        dynamoDbStreamsShardSplits.forEach(this::registerShardMetricGroup);
+        super.addSplits(dynamoDbStreamsShardSplits);
+    }
+
+    /**
+     * At snapshot, we also store the pending finished split ids in the current checkpoint so that
+     * in case we have to restore the reader from state, we also send the finished split ids
+     * otherwise we run a risk of data loss during restarts of the source because of the
+     * SplitsFinishedEvent going missing.
+     *
+     * @param checkpointId
+     * @return
+     */
+    @Override
+    public List<DynamoDbStreamsShardSplit> snapshotState(long checkpointId) {
+        this.currentCheckpointId = checkpointId;
+        List<DynamoDbStreamsShardSplit> splits = super.snapshotState(checkpointId);
+
+        if (!splitFinishedEvents.isEmpty()) {
+            // Add all finished splits to the snapshot
+            splitFinishedEvents.values().forEach(splits::addAll);

Review Comment:
   This implicitly assumes that the List returned from SourceReaderBase is mutable. I'd make a copy here into an arraylist to be future-proof.



##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -58,10 +65,38 @@ public DynamoDbStreamsSourceReader(
             Map<String, DynamoDbStreamsShardMetrics> shardMetricGroupMap) {
         super(splitFetcherManager, recordEmitter, config, context);
         this.shardMetricGroupMap = shardMetricGroupMap;
+        this.splitFinishedEvents = new TreeMap<>();
+        this.currentCheckpointId = Long.MIN_VALUE;
     }
 
+    /**
+     * We store the finished splits in a map keyed by the checkpoint id.
+     *
+     * @param finishedSplitIds
+     */
     @Override
     protected void onSplitFinished(Map<String, DynamoDbStreamsShardSplitState> finishedSplitIds) {
+        if (finishedSplitIds.isEmpty()) {
+            return;
+        }
+
+        finishedSplitIds.values().stream()
+                .map(
+                        finishedSplit ->
+                                new DynamoDbStreamsShardSplit(
+                                        finishedSplit.getStreamArn(),
+                                        finishedSplit.getShardId(),
+                                        finishedSplit.getNextStartingPosition(),
+                                        finishedSplit
+                                                .getDynamoDbStreamsShardSplit()
+                                                .getParentShardId(),
+                                        true))
+                .forEach(
+                        split ->
+                                splitFinishedEvents
+                                        .computeIfAbsent(currentCheckpointId, k -> new HashSet<>())

Review Comment:
   nit you can pull that part out of the for loop.



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "AHeise (via GitHub)" <gi...@apache.org>.
AHeise commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2011444992


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/enumerator/DynamoDbStreamsSourceEnumerator.java:
##########
@@ -138,14 +138,26 @@ public void handleSourceEvent(int subtaskId, SourceEvent sourceEvent) {
 
     /** When we mark a split as finished, we will only assign its child splits to the subtasks. */
     private void handleFinishedSplits(int subtaskId, SplitsFinishedEvent splitsFinishedEvent) {
+        Set<DynamoDbStreamsShardSplit> splitsAssignment = splitAssignment.get(subtaskId);

Review Comment:
   Unrelated, have you considered a Map indexed by split id?



##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +105,65 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.getShardId().equals(DYNAMODB_STREAMS_COMPLETED_SHARD_ID)) {
+                // Restore finished splits state
+                splitFinishedEvents.putAll(split.getFinishedSplitsMap());
+
+                // Replay all stored finished events
+                splitFinishedEvents.values().stream()
+                        .flatMap(Set::stream)
+                        .collect(Collectors.toSet())
+                        .forEach(
+                                splitId ->
+                                        context.sendSourceEventToCoordinator(
+                                                new SplitsFinishedEvent(
+                                                        Collections.singleton(splitId))));
+            } else {
+                dynamoDbStreamsShardSplits.add(split);
+            }
+        }
+        dynamoDbStreamsShardSplits.forEach(this::registerShardMetricGroup);
+        super.addSplits(dynamoDbStreamsShardSplits);
+    }
+
+    /**
+     * At snapshot, we also store the pending finished split ids in the current checkpoint so that
+     * in case we have to restore the reader from state, we also send the finished split ids
+     * otherwise we run a risk of data loss during restarts of the source because of the
+     * SplitsFinishedEvent going missing.
+     *
+     * @param checkpointId
+     * @return
+     */
+    @Override
+    public List<DynamoDbStreamsShardSplit> snapshotState(long checkpointId) {
+        this.currentCheckpointId = checkpointId;
+        List<DynamoDbStreamsShardSplit> splits = super.snapshotState(checkpointId);
+
+        if (!splitFinishedEvents.isEmpty()) {
+            // Always add a dedicated split for finished state
+            splits.add(
+                    new DynamoDbStreamsShardSplit(
+                            "",
+                            DYNAMODB_STREAMS_COMPLETED_SHARD_ID,
+                            StartingPosition.fromStart(),
+                            null,
+                            splitFinishedEvents));
+        }
+        return splits;

Review Comment:
   While reviewing, I came up with an alternative approach where you use a flag in `DynamoDbStreamsShardSplit` that signals the finished state. Then you need to keep the split around one checkpoint longer.
   Note that in the snapshot, you don't need to know at which checkpoint the split is finished (no need for the TreeMap in the snapshot), you just need to know whether a split has been finished before the checkpoint or not.
   
   So one way would be to have a new field `finishedAfterCheckpoint` in the split snapshot which you set `onSplitFinished` but you keep the split in your state (potentially by maintaining a `finishedSplit` field). In `notifyCheckpointCompleted`, you can remove all splits where `finishedAfterCheckpoint < checkpointId`.
   On recovery, you ignore the specific value of `finishedAfterCheckpoint` and just use it as a flag to resend the event.



##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/enumerator/assigner/UniformShardAssigner.java:
##########
@@ -54,7 +54,8 @@ public int assign(DynamoDbStreamsShardSplit split, Context context) {
 
         Preconditions.checkArgument(
                 selectedSubtask != -1,
-                "Expected at least one registered reader. Unable to assign split.");
+                "Expected at least one registered reader. Unable to assign split with id: "
+                        + split.splitId());

Review Comment:
   nit: I'd use the overload that uses String.format under the hood. Then, you avoid string concatenation until an actual issue arises.



##########
flink-connector-aws/flink-connector-dynamodb/src/test/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReaderTest.java:
##########
@@ -158,4 +165,148 @@ void testAddSplitsRegistersAndUpdatesShardMetricGroup() throws Exception {
         TestUtil.assertMillisBehindLatest(
                 split, TestUtil.MILLIS_BEHIND_LATEST_TEST_VALUE, metricListener);
     }
+
+    @Test
+    void testSnapshotStateWithFinishedSplits() throws Exception {
+        // Create and add a split
+        DynamoDbStreamsShardSplit split = getTestSplit();
+        List<DynamoDbStreamsShardSplit> splits = Collections.singletonList(split);
+        sourceReader.addSplits(splits);
+
+        // Set checkpoint ID by taking initial snapshot
+        List<DynamoDbStreamsShardSplit> initialSnapshot = sourceReader.snapshotState(1L);
+        assertThat(initialSnapshot).hasSize(1).containsExactly(split);
+
+        // Simulate split finishing
+        Map<String, DynamoDbStreamsShardSplitState> finishedSplits = new HashMap<>();
+        finishedSplits.put(split.splitId(), new DynamoDbStreamsShardSplitState(split));
+        sourceReader.onSplitFinished(finishedSplits);
+
+        // Take another snapshot
+        List<DynamoDbStreamsShardSplit> snapshotSplits = sourceReader.snapshotState(1L);
+
+        // Verify we have 2 splits - the original split and the state split
+        assertThat(snapshotSplits).hasSize(2);
+
+        // Find and verify the state split
+        Optional<DynamoDbStreamsShardSplit> stateSplitOptional =
+                snapshotSplits.stream()
+                        .filter(s -> s.getShardId().equals("finished-splits-state"))
+                        .findFirst();
+
+        assertThat(stateSplitOptional)
+                .isPresent()
+                .hasValueSatisfying(
+                        stateSplit -> {
+                            NavigableMap<Long, Set<String>> finishedSplitsMap =
+                                    stateSplit.getFinishedSplitsMap();
+                            assertThat(finishedSplitsMap).hasSize(1).containsKey(1L);
+                            assertThat(finishedSplitsMap.get(1L)).contains(split.splitId());
+                        });
+
+        // Find and verify the original split
+        Optional<DynamoDbStreamsShardSplit> originalSplitOptional =
+                snapshotSplits.stream()
+                        .filter(s -> s.getShardId().equals(split.getShardId()))
+                        .findFirst();
+
+        assertThat(originalSplitOptional)
+                .isPresent()
+                .hasValueSatisfying(
+                        originalSplit ->
+                                assertThat(originalSplit)
+                                        .usingRecursiveComparison()
+                                        .isEqualTo(split));

Review Comment:
   nit: you can shorten this to
   
   ```
   
           assertThat(snapshotSplits)
                   .hasSize(2)
                   .contains(split)
                   .filteredOn(s -> s.getShardId().equals("finished-splits-state"))
                   .singleElement()
                   .extracting(
                           DynamoDbStreamsShardSplit::getFinishedSplitsMap,
                           as(InstanceOfAssertFactories.map(Long.class, Set.class)))
                   .containsExactly(Map.entry(1L, Set.of(split.splitId())));
   ```



##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/split/DynamoDbStreamsShardSplit.java:
##########
@@ -40,6 +43,7 @@ public final class DynamoDbStreamsShardSplit implements SourceSplit {
     private final String shardId;
     private final StartingPosition startingPosition;
     private final String parentShardId;
+    private final NavigableMap<Long, Set<String>> finishedSplitsMap;

Review Comment:
   As mentioned above, you don't need to store a TreeMap here (it would only be needed int the reader). You can flatten the values into a single collection which makes serialization and recovery easier.



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014045507


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +115,54 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.isFinished()) {
+                // Restore finished splits state
+                splitFinishedEvents
+                        .computeIfAbsent(split.getFinishedAfterCheckpoint(), k -> new HashSet<>())
+                        .add(split);
+                // Replay the finished split event
+                context.sendSourceEventToCoordinator(
+                        new SplitsFinishedEvent(Collections.singleton(split.splitId())));
+            } else {
+                dynamoDbStreamsShardSplits.add(split);
+            }
+        }
+        dynamoDbStreamsShardSplits.forEach(this::registerShardMetricGroup);
+        super.addSplits(dynamoDbStreamsShardSplits);
+    }
+
+    /**
+     * At snapshot, we also store the pending finished split ids in the current checkpoint so that
+     * in case we have to restore the reader from state, we also send the finished split ids
+     * otherwise we run a risk of data loss during restarts of the source because of the
+     * SplitsFinishedEvent going missing.
+     *
+     * @param checkpointId
+     * @return
+     */
+    @Override
+    public List<DynamoDbStreamsShardSplit> snapshotState(long checkpointId) {
+        this.currentCheckpointId = checkpointId;
+        List<DynamoDbStreamsShardSplit> splits = super.snapshotState(checkpointId);
+
+        if (!splitFinishedEvents.isEmpty()) {
+            // Add all finished splits to the snapshot
+            splitFinishedEvents.values().forEach(splits::addAll);
+        }
+        return splits;
+    }
+
+    /**
+     * During notifyCheckpointComplete, we should clean up the state of finished splits that are
+     * older than the checkpoint id.
+     *
+     * @param checkpointId
+     */
+    @Override
+    public void notifyCheckpointComplete(long checkpointId) {
+        splitFinishedEvents.headMap(checkpointId, true).clear();

Review Comment:
   good point, any splits which are <= this checkpoint will be cleared. 
   the intended behaviour is as follows:
   - Checkpoint 1 was taken
   - Buffer any finished events between checkpoint 1 and checkpoint 2 in the splitFinishedEvents
   - Checkpoint 2 was taken. Checkpoint 2 will have all splitfinished events happening after checkpoint 1
   - notifyCheckpoint will remove all buffer from 1 and 2
   - new buffer from checkpoint 2 and 3
   - notify checkpoint will remove all buffer <=3
   
   I will update the javadoc to make sure it mentions inclusive



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "hlteoh37 (via GitHub)" <gi...@apache.org>.
hlteoh37 merged PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193


-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "leekeiabstraction (via GitHub)" <gi...@apache.org>.
leekeiabstraction commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014373683


##########
flink-connector-aws/flink-connector-dynamodb/src/test/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReaderTest.java:
##########
@@ -158,4 +163,128 @@ void testAddSplitsRegistersAndUpdatesShardMetricGroup() throws Exception {
         TestUtil.assertMillisBehindLatest(
                 split, TestUtil.MILLIS_BEHIND_LATEST_TEST_VALUE, metricListener);
     }
+
+    @Test
+    void testSnapshotStateWithFinishedSplits() throws Exception {
+        // Create and add a split
+        DynamoDbStreamsShardSplit split = getTestSplit();
+        List<DynamoDbStreamsShardSplit> splits = Collections.singletonList(split);
+        sourceReader.addSplits(splits);
+
+        // Set checkpoint ID by taking initial snapshot
+        List<DynamoDbStreamsShardSplit> initialSnapshot = sourceReader.snapshotState(1L);
+        assertThat(initialSnapshot).hasSize(1).containsExactly(split);
+
+        // Simulate split finishing
+        Map<String, DynamoDbStreamsShardSplitState> finishedSplits = new HashMap<>();
+        finishedSplits.put(split.splitId(), new DynamoDbStreamsShardSplitState(split));
+        sourceReader.onSplitFinished(finishedSplits);
+
+        // Take another snapshot
+        List<DynamoDbStreamsShardSplit> snapshotSplits = sourceReader.snapshotState(2L);
+        List<DynamoDbStreamsShardSplit> snapshotFinishedSplits =
+                snapshotSplits.stream()
+                        .filter(DynamoDbStreamsShardSplit::isFinished)
+                        .collect(Collectors.toList());
+        // Verify we have 2 splits - the original split and the finished split
+        assertThat(snapshotFinishedSplits)

Review Comment:
   Description in comment and actual assertion differs, assertion only asserts 'original' split.



##########
flink-connector-aws/flink-connector-dynamodb/src/test/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReaderTest.java:
##########
@@ -158,4 +163,128 @@ void testAddSplitsRegistersAndUpdatesShardMetricGroup() throws Exception {
         TestUtil.assertMillisBehindLatest(
                 split, TestUtil.MILLIS_BEHIND_LATEST_TEST_VALUE, metricListener);
     }
+
+    @Test
+    void testSnapshotStateWithFinishedSplits() throws Exception {
+        // Create and add a split
+        DynamoDbStreamsShardSplit split = getTestSplit();
+        List<DynamoDbStreamsShardSplit> splits = Collections.singletonList(split);
+        sourceReader.addSplits(splits);
+
+        // Set checkpoint ID by taking initial snapshot
+        List<DynamoDbStreamsShardSplit> initialSnapshot = sourceReader.snapshotState(1L);
+        assertThat(initialSnapshot).hasSize(1).containsExactly(split);
+
+        // Simulate split finishing
+        Map<String, DynamoDbStreamsShardSplitState> finishedSplits = new HashMap<>();
+        finishedSplits.put(split.splitId(), new DynamoDbStreamsShardSplitState(split));
+        sourceReader.onSplitFinished(finishedSplits);
+
+        // Take another snapshot
+        List<DynamoDbStreamsShardSplit> snapshotSplits = sourceReader.snapshotState(2L);
+        List<DynamoDbStreamsShardSplit> snapshotFinishedSplits =
+                snapshotSplits.stream()
+                        .filter(DynamoDbStreamsShardSplit::isFinished)
+                        .collect(Collectors.toList());
+        // Verify we have 2 splits - the original split and the finished split
+        assertThat(snapshotFinishedSplits)
+                .hasSize(1)
+                .allSatisfy(
+                        s -> {
+                            assertThat(s.splitId()).isEqualTo(split.splitId());
+                        });
+    }
+
+    @Test
+    void testAddSplitsWithStateRestoration() throws Exception {
+        // Create finished split with checkpoint id 1

Review Comment:
   nit: Comment describes checkpoint id 1 but checkpoint id 1 is not used



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "leekeiabstraction (via GitHub)" <gi...@apache.org>.
leekeiabstraction commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014123486


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +115,54 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.isFinished()) {
+                // Restore finished splits state
+                splitFinishedEvents
+                        .computeIfAbsent(split.getFinishedDuringCheckpoint(), k -> new HashSet<>())
+                        .add(split);

Review Comment:
   Can you elaborate why we need to restore finished split events here? Wouldn't it be sufficient to just send source event to coordinator? 



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "leekeiabstraction (via GitHub)" <gi...@apache.org>.
leekeiabstraction commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014072074


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/split/DynamoDbStreamsShardSplit.java:
##########
@@ -40,12 +40,22 @@ public final class DynamoDbStreamsShardSplit implements SourceSplit {
     private final String shardId;
     private final StartingPosition startingPosition;
     private final String parentShardId;
+    private final long finishedAfterCheckpoint;

Review Comment:
   I agree that a restart is necessary for the reader to lose track of shards. However, the checkpoint still would cause the issue even if a restart does not occur, for example when resuming from an checkpoint/savepoint. The crux of the issue is not that shardSplit finished after checkpointing or a restart happened, but rather that shardSplit happened before reader completed checkpointing.



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2013348699


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +105,65 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.getShardId().equals(DYNAMODB_STREAMS_COMPLETED_SHARD_ID)) {
+                // Restore finished splits state
+                splitFinishedEvents.putAll(split.getFinishedSplitsMap());
+
+                // Replay all stored finished events
+                splitFinishedEvents.values().stream()
+                        .flatMap(Set::stream)
+                        .collect(Collectors.toSet())
+                        .forEach(
+                                splitId ->
+                                        context.sendSourceEventToCoordinator(
+                                                new SplitsFinishedEvent(
+                                                        Collections.singleton(splitId))));
+            } else {
+                dynamoDbStreamsShardSplits.add(split);
+            }
+        }
+        dynamoDbStreamsShardSplits.forEach(this::registerShardMetricGroup);
+        super.addSplits(dynamoDbStreamsShardSplits);
+    }
+
+    /**
+     * At snapshot, we also store the pending finished split ids in the current checkpoint so that
+     * in case we have to restore the reader from state, we also send the finished split ids
+     * otherwise we run a risk of data loss during restarts of the source because of the
+     * SplitsFinishedEvent going missing.
+     *
+     * @param checkpointId
+     * @return
+     */
+    @Override
+    public List<DynamoDbStreamsShardSplit> snapshotState(long checkpointId) {
+        this.currentCheckpointId = checkpointId;
+        List<DynamoDbStreamsShardSplit> splits = super.snapshotState(checkpointId);
+
+        if (!splitFinishedEvents.isEmpty()) {
+            // Always add a dedicated split for finished state
+            splits.add(
+                    new DynamoDbStreamsShardSplit(
+                            "",
+                            DYNAMODB_STREAMS_COMPLETED_SHARD_ID,
+                            StartingPosition.fromStart(),
+                            null,
+                            splitFinishedEvents));
+        }
+        return splits;

Review Comment:
   changed the implmentation to rather just store a finishedAfterCheckpoint in the DDB Split state. Thanks @AHeise for the suggestion! much neater



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "tjo (via GitHub)" <gi...@apache.org>.
tjo commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2013860291


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -58,10 +65,34 @@ public DynamoDbStreamsSourceReader(
             Map<String, DynamoDbStreamsShardMetrics> shardMetricGroupMap) {
         super(splitFetcherManager, recordEmitter, config, context);
         this.shardMetricGroupMap = shardMetricGroupMap;
+        this.splitFinishedEvents = new TreeMap<>();
+        this.currentCheckpointId = Long.MIN_VALUE;
     }
 
+    /**
+     * We store the finished splits in a map keyed by the checkpoint id.
+     *
+     * @param finishedSplitIds
+     */
     @Override
     protected void onSplitFinished(Map<String, DynamoDbStreamsShardSplitState> finishedSplitIds) {
+        if (finishedSplitIds.isEmpty()) {
+            return;
+        }
+
+        for (Map.Entry<String, DynamoDbStreamsShardSplitState> entry :

Review Comment:
   We could just use `values()` instead of `entrySet()`
   
   or as an alternative use the streaming API:
   ```
   Set<DynamoDbStreamsShardSplit> splitFinishedEventsForCheckpoint = splitFinishedEvents.computeIfAbsent(currentCheckpointId, k -> new HashSet<>());
           finishedSplitIds.values().stream().map(entry ->
                   new DynamoDbStreamsShardSplit(
                           entry.getStreamArn(),
                           entry.getShardId(),
                           entry.getNextStartingPosition(),
                           entry.getDynamoDbStreamsShardSplit().getParentShardId(),
                           currentCheckpointId)
           ).forEach(e -> splitFinishedEventsForCheckpoint.add(e));
   ```



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2013862923


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -58,10 +65,34 @@ public DynamoDbStreamsSourceReader(
             Map<String, DynamoDbStreamsShardMetrics> shardMetricGroupMap) {
         super(splitFetcherManager, recordEmitter, config, context);
         this.shardMetricGroupMap = shardMetricGroupMap;
+        this.splitFinishedEvents = new TreeMap<>();
+        this.currentCheckpointId = Long.MIN_VALUE;
     }
 
+    /**
+     * We store the finished splits in a map keyed by the checkpoint id.
+     *
+     * @param finishedSplitIds
+     */
     @Override
     protected void onSplitFinished(Map<String, DynamoDbStreamsShardSplitState> finishedSplitIds) {
+        if (finishedSplitIds.isEmpty()) {
+            return;
+        }
+
+        for (Map.Entry<String, DynamoDbStreamsShardSplitState> entry :

Review Comment:
   makes sense, i dont really need the entries but rather just need values



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014332598


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/enumerator/DynamoDbStreamsSourceEnumerator.java:
##########
@@ -139,13 +139,25 @@ public void handleSourceEvent(int subtaskId, SourceEvent sourceEvent) {
     /** When we mark a split as finished, we will only assign its child splits to the subtasks. */
     private void handleFinishedSplits(int subtaskId, SplitsFinishedEvent splitsFinishedEvent) {
         splitTracker.markAsFinished(splitsFinishedEvent.getFinishedSplitIds());
-        splitAssignment
-                .get(subtaskId)
-                .removeIf(
-                        split ->
-                                splitsFinishedEvent
-                                        .getFinishedSplitIds()
-                                        .contains(split.splitId()));
+
+        Set<DynamoDbStreamsShardSplit> splitsAssignment = splitAssignment.get(subtaskId);
+        // during recovery, splitAssignment may return null since there might be no split assigned
+        // to the subtask, but there might be SplitsFinishedEvent from that subtask.
+        // We will not do child shard assignment if that is the case since that might lead to child
+        // shards trying to get assigned before there being any readers.
+        if (splitsAssignment == null) {

Review Comment:
   made this a info for now, will make the consistency checks stronger in a separate PR if that works?



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2011539429


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/enumerator/DynamoDbStreamsSourceEnumerator.java:
##########
@@ -138,14 +138,26 @@ public void handleSourceEvent(int subtaskId, SourceEvent sourceEvent) {
 
     /** When we mark a split as finished, we will only assign its child splits to the subtasks. */
     private void handleFinishedSplits(int subtaskId, SplitsFinishedEvent splitsFinishedEvent) {
+        Set<DynamoDbStreamsShardSplit> splitsAssignment = splitAssignment.get(subtaskId);

Review Comment:
   not really, can think about it as a future enhancement



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2013348894


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/split/DynamoDbStreamsShardSplit.java:
##########
@@ -40,6 +43,7 @@ public final class DynamoDbStreamsShardSplit implements SourceSplit {
     private final String shardId;
     private final StartingPosition startingPosition;
     private final String parentShardId;
+    private final NavigableMap<Long, Set<String>> finishedSplitsMap;

Review Comment:
   yip, updated this, will raise a new PR revision once testing is complete



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2011540300


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/enumerator/assigner/UniformShardAssigner.java:
##########
@@ -54,7 +54,8 @@ public int assign(DynamoDbStreamsShardSplit split, Context context) {
 
         Preconditions.checkArgument(
                 selectedSubtask != -1,
-                "Expected at least one registered reader. Unable to assign split.");
+                "Expected at least one registered reader. Unable to assign split with id: "
+                        + split.splitId());

Review Comment:
   agree, will update 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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014043668


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/enumerator/DynamoDbStreamsSourceEnumerator.java:
##########
@@ -138,14 +138,26 @@ public void handleSourceEvent(int subtaskId, SourceEvent sourceEvent) {
 
     /** When we mark a split as finished, we will only assign its child splits to the subtasks. */
     private void handleFinishedSplits(int subtaskId, SplitsFinishedEvent splitsFinishedEvent) {
+        Set<DynamoDbStreamsShardSplit> splitsAssignment = splitAssignment.get(subtaskId);

Review Comment:
   makes sense



##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/enumerator/tracker/SplitTracker.java:
##########
@@ -333,7 +333,13 @@ private boolean verifyParentIsEitherFinishedOrCleanedUp(DynamoDbStreamsShardSpli
                 || isFinished(split.getParentShardId());
     }
 
-    private boolean isFinished(String splitId) {
+    /**
+     * Provides information whether a split is finished or not.
+     *
+     * @param splitId
+     * @return

Review Comment:
   updated in next revision



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014045507


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +115,54 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.isFinished()) {
+                // Restore finished splits state
+                splitFinishedEvents
+                        .computeIfAbsent(split.getFinishedAfterCheckpoint(), k -> new HashSet<>())
+                        .add(split);
+                // Replay the finished split event
+                context.sendSourceEventToCoordinator(
+                        new SplitsFinishedEvent(Collections.singleton(split.splitId())));
+            } else {
+                dynamoDbStreamsShardSplits.add(split);
+            }
+        }
+        dynamoDbStreamsShardSplits.forEach(this::registerShardMetricGroup);
+        super.addSplits(dynamoDbStreamsShardSplits);
+    }
+
+    /**
+     * At snapshot, we also store the pending finished split ids in the current checkpoint so that
+     * in case we have to restore the reader from state, we also send the finished split ids
+     * otherwise we run a risk of data loss during restarts of the source because of the
+     * SplitsFinishedEvent going missing.
+     *
+     * @param checkpointId
+     * @return
+     */
+    @Override
+    public List<DynamoDbStreamsShardSplit> snapshotState(long checkpointId) {
+        this.currentCheckpointId = checkpointId;
+        List<DynamoDbStreamsShardSplit> splits = super.snapshotState(checkpointId);
+
+        if (!splitFinishedEvents.isEmpty()) {
+            // Add all finished splits to the snapshot
+            splitFinishedEvents.values().forEach(splits::addAll);
+        }
+        return splits;
+    }
+
+    /**
+     * During notifyCheckpointComplete, we should clean up the state of finished splits that are
+     * older than the checkpoint id.
+     *
+     * @param checkpointId
+     */
+    @Override
+    public void notifyCheckpointComplete(long checkpointId) {
+        splitFinishedEvents.headMap(checkpointId, true).clear();

Review Comment:
   good point, any splits which are <= this checkpoint will be cleared. I'm thinking should we remove this true parameter and let the finished splits lay there in the checkpoint for one more checkpoint?



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "leekeiabstraction (via GitHub)" <gi...@apache.org>.
leekeiabstraction commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014145553


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +115,54 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.isFinished()) {
+                // Restore finished splits state
+                splitFinishedEvents
+                        .computeIfAbsent(split.getFinishedDuringCheckpoint(), k -> new HashSet<>())
+                        .add(split);

Review Comment:
   If the part which restores the finished split is removed, there is an opportunity to simplify the Split pojo where instead of recording the checkpoint id when the split was finished, we can just have a boolean on whether split is finished.



-- 
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: issues-unsubscribe@flink.apache.org

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


Re: [PR] [FLINK-37416][BugFix][Connectors/DynamoDB] Fix state inconsistency issue in DDB connector when sending split finished event from reader -> enumerator [flink-connector-aws]

Posted by "gguptp (via GitHub)" <gi...@apache.org>.
gguptp commented on code in PR #193:
URL: https://github.com/apache/flink-connector-aws/pull/193#discussion_r2014140238


##########
flink-connector-aws/flink-connector-dynamodb/src/main/java/org/apache/flink/connector/dynamodb/source/reader/DynamoDbStreamsSourceReader.java:
##########
@@ -80,8 +115,54 @@ protected DynamoDbStreamsShardSplit toSplitType(
 
     @Override
     public void addSplits(List<DynamoDbStreamsShardSplit> splits) {
-        splits.forEach(this::registerShardMetricGroup);
-        super.addSplits(splits);
+        List<DynamoDbStreamsShardSplit> dynamoDbStreamsShardSplits = new ArrayList<>();
+        for (DynamoDbStreamsShardSplit split : splits) {
+            if (split.isFinished()) {
+                // Restore finished splits state
+                splitFinishedEvents
+                        .computeIfAbsent(split.getFinishedDuringCheckpoint(), k -> new HashSet<>())
+                        .add(split);

Review Comment:
   I guess this might be redundant. But lets keep it as it might be easier to reason about the algo?



-- 
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: issues-unsubscribe@flink.apache.org

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