aiborodin commented on code in PR #16011:
URL: https://github.com/apache/iceberg/pull/16011#discussion_r3127506777


##########
flink/v2.1/flink/src/main/java/org/apache/iceberg/flink/sink/dynamic/JobOperatorKey.java:
##########
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.flink.sink.dynamic;
+
+import java.util.Objects;
+
+class JobOperatorKey {

Review Comment:
   Maybe `SinkOperatorKey`?



##########
flink/v2.1/flink/src/main/java/org/apache/iceberg/flink/sink/dynamic/DynamicCommitter.java:
##########
@@ -119,43 +119,51 @@ public void 
commit(Collection<CommitRequest<DynamicCommittable>> commitRequests)
       DynamicWriteResultAggregator. Iceberg 1.12 will remove this, and users 
should upgrade to the 1.11 release first
       to migrate their state to a single commit request per checkpoint.
     */
-    Map<TableKey, NavigableMap<Long, List<CommitRequest<DynamicCommittable>>>> 
commitRequestMap =
-        Maps.newHashMap();
+    Map<TableKey, Map<JobOperatorKey, NavigableMap<Long, 
List<CommitRequest<DynamicCommittable>>>>>
+        commitRequestMap = Maps.newHashMap();
     for (CommitRequest<DynamicCommittable> request : commitRequests) {
-      NavigableMap<Long, List<CommitRequest<DynamicCommittable>>> committables 
=
-          commitRequestMap.computeIfAbsent(
-              new TableKey(request.getCommittable()), unused -> 
Maps.newTreeMap());
-      committables
-          .computeIfAbsent(request.getCommittable().checkpointId(), unused -> 
Lists.newArrayList())
+      DynamicCommittable committable = request.getCommittable();
+      commitRequestMap
+          .computeIfAbsent(committable.key(), unused -> Maps.newHashMap())
+          .computeIfAbsent(new JobOperatorKey(committable), unused -> 
Maps.newTreeMap())
+          .computeIfAbsent(committable.checkpointId(), unused -> 
Lists.newArrayList())
           .add(request);
     }
 
-    for (Map.Entry<TableKey, NavigableMap<Long, 
List<CommitRequest<DynamicCommittable>>>> entry :
-        commitRequestMap.entrySet()) {
-      Table table = 
catalog.loadTable(TableIdentifier.parse(entry.getKey().tableName()));
-      DynamicCommittable last = 
entry.getValue().lastEntry().getValue().get(0).getCommittable();
-      Snapshot latestSnapshot = table.snapshot(entry.getKey().branch());
-      Iterable<Snapshot> ancestors =
+    for (Map.Entry<
+            TableKey,
+            Map<JobOperatorKey, NavigableMap<Long, 
List<CommitRequest<DynamicCommittable>>>>>
+        tableEntry : commitRequestMap.entrySet()) {
+      TableKey tableKey = tableEntry.getKey();
+      Table table = 
catalog.loadTable(TableIdentifier.parse(tableKey.tableName()));
+      Snapshot latestSnapshot = table.snapshot(tableKey.branch());
+      List<Snapshot> ancestors =

Review Comment:
   Why do we need to change `Iterable<Snapshot>` to `List<Snapshot>` here?



##########
flink/v2.1/flink/src/test/java/org/apache/iceberg/flink/sink/dynamic/TestDynamicIcebergSink.java:
##########
@@ -1091,6 +1093,44 @@ void 
testCommitsOnceWhenConcurrentDuplicateCommit(boolean overwriteMode) throws
     assertThat(totalAddedRecords).isEqualTo(records.size());
   }
 
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  void testSkipsAlreadyCommittedDataAfterJobIdChanges(boolean overwriteMode) 
throws Exception {
+    TableIdentifier tableId = TableIdentifier.of(DATABASE, "t1");
+    List<DynamicIcebergDataImpl> records =
+        Lists.newArrayList(
+            new DynamicIcebergDataImpl(
+                SimpleDataUtil.SCHEMA,
+                tableId.name(),
+                SnapshotRef.MAIN_BRANCH,
+                PartitionSpec.unpartitioned()));
+
+    DataFile seedDataFile =
+        DataFiles.builder(PartitionSpec.unpartitioned())
+            .withPath("/path/to/seed-data-1.parquet")
+            .withFileSizeInBytes(0)
+            .withRecordCount(1)
+            .build();
+
+    executeDynamicSink(
+        records, env, true, 1, new 
ReplayPreviousJobIdCommittableHook(seedDataFile), overwriteMode);
+
+    Table table = CATALOG_EXTENSION.catalog().loadTable(tableId);
+
+    Snapshot mainSnapshot =
+        StreamSupport.stream(table.snapshots().spliterator(), false)
+            .filter(
+                s ->
+                    !ReplayPreviousJobIdCommittableHook.PREVIOUS_JOB_ID.equals(
+                        s.summary().get("flink.job-id")))
+            .filter(s -> s.summary().get("flink.job-id") != null)
+            .reduce((first, second) -> second)
+            .orElseThrow();
+    assertThat(mainSnapshot.summary())

Review Comment:
   We should also assert on the total record count in the table to detect the 
duplication scenario.



##########
flink/v2.1/flink/src/test/java/org/apache/iceberg/flink/sink/dynamic/TestDynamicIcebergSink.java:
##########
@@ -1434,6 +1447,59 @@ public void beforeCommitOperation() {
     }
   }
 
+  /**
+   * Seeds an ancestor snapshot under a synthetic previous jobId and injects a 
replay committable
+   * tagged with that jobId into the main batch. The seed uses {@code 
table.newAppend()} directly
+   * rather than a side committer so the real committable's manifest stays 
intact.
+   */
+  static class ReplayPreviousJobIdCommittableHook implements CommitHook {

Review Comment:
   Can we reuse the `DuplicateCommitHook`?



##########
flink/v2.1/flink/src/test/java/org/apache/iceberg/flink/sink/dynamic/TestDynamicIcebergSink.java:
##########
@@ -1434,6 +1447,59 @@ public void beforeCommitOperation() {
     }
   }
 
+  /**
+   * Seeds an ancestor snapshot under a synthetic previous jobId and injects a 
replay committable
+   * tagged with that jobId into the main batch. The seed uses {@code 
table.newAppend()} directly
+   * rather than a side committer so the real committable's manifest stays 
intact.
+   */
+  static class ReplayPreviousJobIdCommittableHook implements CommitHook {
+    static final String PREVIOUS_JOB_ID = JobID.generate().toHexString();
+
+    private static final String MAX_COMMITTED_CHECKPOINT_ID = 
"flink.max-committed-checkpoint-id";
+    private static final String FLINK_JOB_ID = "flink.job-id";
+    private static final String OPERATOR_ID = "flink.operator-id";
+
+    // Static to survive Flink operator serialization.
+    private static boolean hasTriggered = false;
+
+    private final DataFile seedDataFile;
+
+    ReplayPreviousJobIdCommittableHook(DataFile seedDataFile) {
+      this.seedDataFile = seedDataFile;
+      hasTriggered = false;
+    }
+
+    @Override
+    public void 
beforeCommit(Collection<Committer.CommitRequest<DynamicCommittable>> requests) {
+      if (hasTriggered || requests.isEmpty()) {
+        return;
+      }
+
+      hasTriggered = true;
+      DynamicCommittable original = 
requests.iterator().next().getCommittable();
+
+      Table table =
+          
CATALOG_EXTENSION.catalog().loadTable(TableIdentifier.parse(original.key().tableName()));
+      table
+          .newAppend()
+          .appendFile(seedDataFile)
+          .set(FLINK_JOB_ID, PREVIOUS_JOB_ID)
+          .set(OPERATOR_ID, original.operatorId())
+          .set(MAX_COMMITTED_CHECKPOINT_ID, 
Long.toString(original.checkpointId()))
+          .toBranch(original.key().branch())
+          .commit();
+
+      DynamicCommittable replayed =
+          new DynamicCommittable(
+              original.key(),
+              original.manifests(),
+              PREVIOUS_JOB_ID,
+              original.operatorId(),
+              original.checkpointId());
+      requests.add(new MockCommitRequest<>(replayed));

Review Comment:
   We should make sure we're actually simulating the "hiding" of the committed 
committable. Because I think it currently comes after the new committable in 
the list, which may not reproduce the bug in this test. It may need an earlier 
checkpoint id as well.



##########
flink/v2.1/flink/src/test/java/org/apache/iceberg/flink/sink/dynamic/TestDynamicIcebergSink.java:
##########
@@ -1434,6 +1447,59 @@ public void beforeCommitOperation() {
     }
   }
 
+  /**
+   * Seeds an ancestor snapshot under a synthetic previous jobId and injects a 
replay committable
+   * tagged with that jobId into the main batch. The seed uses {@code 
table.newAppend()} directly
+   * rather than a side committer so the real committable's manifest stays 
intact.
+   */
+  static class ReplayPreviousJobIdCommittableHook implements CommitHook {
+    static final String PREVIOUS_JOB_ID = JobID.generate().toHexString();
+
+    private static final String MAX_COMMITTED_CHECKPOINT_ID = 
"flink.max-committed-checkpoint-id";
+    private static final String FLINK_JOB_ID = "flink.job-id";
+    private static final String OPERATOR_ID = "flink.operator-id";
+
+    // Static to survive Flink operator serialization.
+    private static boolean hasTriggered = false;
+
+    private final DataFile seedDataFile;
+
+    ReplayPreviousJobIdCommittableHook(DataFile seedDataFile) {
+      this.seedDataFile = seedDataFile;
+      hasTriggered = false;
+    }
+
+    @Override
+    public void 
beforeCommit(Collection<Committer.CommitRequest<DynamicCommittable>> requests) {
+      if (hasTriggered || requests.isEmpty()) {
+        return;
+      }
+
+      hasTriggered = true;
+      DynamicCommittable original = 
requests.iterator().next().getCommittable();
+
+      Table table =
+          
CATALOG_EXTENSION.catalog().loadTable(TableIdentifier.parse(original.key().tableName()));
+      table
+          .newAppend()
+          .appendFile(seedDataFile)
+          .set(FLINK_JOB_ID, PREVIOUS_JOB_ID)
+          .set(OPERATOR_ID, original.operatorId())
+          .set(MAX_COMMITTED_CHECKPOINT_ID, 
Long.toString(original.checkpointId()))
+          .toBranch(original.key().branch())
+          .commit();
+
+      DynamicCommittable replayed =
+          new DynamicCommittable(
+              original.key(),
+              original.manifests(),
+              PREVIOUS_JOB_ID,
+              original.operatorId(),
+              original.checkpointId());
+      requests.add(new MockCommitRequest<>(replayed));

Review Comment:
   nit: the collection can be immutable. might be better to make `public void 
beforeCommit(Collection<Committer.CommitRequest<DynamicCommittable>> requests)` 
return the new list of requests.



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

To unsubscribe, e-mail: [email protected]

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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to