You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@paimon.apache.org by lz...@apache.org on 2023/05/30 06:18:46 UTC
[incubator-paimon] branch master updated: [feature] Add multi-table committer (#1229)
This is an automated email from the ASF dual-hosted git repository.
lzljs3620320 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-paimon.git
The following commit(s) were added to refs/heads/master by this push:
new 1732f3612 [feature] Add multi-table committer (#1229)
1732f3612 is described below
commit 1732f36129c2694643df71e409306937f666fb92
Author: Dian Qi <qi...@163.com>
AuthorDate: Tue May 30 14:18:42 2023 +0800
[feature] Add multi-table committer (#1229)
---
.../manifest/WrappedManifestCommittable.java | 103 ++++
.../manifest/WrappedManifestCommittableTest.java | 46 ++
.../RestoreAndFailCommittableStateManager.java | 22 +-
.../paimon/flink/sink/StoreMultiCommitter.java | 188 +++++++
.../sink/WrappedManifestCommittableSerializer.java | 115 ++++
.../paimon/flink/sink/CommitterOperatorTest.java | 6 +-
.../paimon/flink/sink/StoreMultiCommitterTest.java | 577 +++++++++++++++++++++
.../WrappedManifestCommittableSerializerTest.java | 104 ++++
8 files changed, 1146 insertions(+), 15 deletions(-)
diff --git a/paimon-core/src/main/java/org/apache/paimon/manifest/WrappedManifestCommittable.java b/paimon-core/src/main/java/org/apache/paimon/manifest/WrappedManifestCommittable.java
new file mode 100644
index 000000000..5b72f8d8c
--- /dev/null
+++ b/paimon-core/src/main/java/org/apache/paimon/manifest/WrappedManifestCommittable.java
@@ -0,0 +1,103 @@
+/*
+ * 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.paimon.manifest;
+
+import org.apache.paimon.catalog.Identifier;
+
+import java.util.Comparator;
+import java.util.Map;
+import java.util.Objects;
+import java.util.TreeMap;
+
+/** Manifest commit message. */
+public class WrappedManifestCommittable {
+
+ private Map<Identifier, ManifestCommittable> manifestCommittables;
+
+ public WrappedManifestCommittable() {
+ this.manifestCommittables =
+ new TreeMap<>(
+ Comparator.comparing(Identifier::getDatabaseName)
+ .thenComparing(Identifier::getObjectName));
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ WrappedManifestCommittable that = (WrappedManifestCommittable) o;
+
+ if (manifestCommittables.size() != that.manifestCommittables.size()) {
+ return false;
+ }
+
+ for (Map.Entry<Identifier, ManifestCommittable> entry : manifestCommittables.entrySet()) {
+ if (!Objects.equals(entry.getValue(), that.manifestCommittables.get(entry.getKey()))) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(manifestCommittables.values().toArray(new Object[0]));
+ }
+
+ @Override
+ public String toString() {
+ return String.format(
+ "WrappedManifestCommittable {" + "manifestCommittables = %s",
+ formatManifestCommittables());
+ }
+
+ private String formatManifestCommittables() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("{");
+ for (Identifier id : manifestCommittables.keySet()) {
+ ManifestCommittable committable = manifestCommittables.get(id);
+ sb.append(String.format("%s=%s, ", id.getFullName(), committable.toString()));
+ }
+ if (manifestCommittables.size() > 0) {
+ sb.delete(sb.length() - 2, sb.length());
+ }
+ sb.append("}");
+ return sb.toString();
+ }
+
+ public ManifestCommittable computeCommittableIfAbsent(
+ Identifier identifier, long checkpointId, long watermark) {
+ return manifestCommittables.computeIfAbsent(
+ identifier, id -> new ManifestCommittable(checkpointId, watermark));
+ }
+
+ public ManifestCommittable putManifestCommittable(
+ Identifier identifier, ManifestCommittable manifestCommittable) {
+ return manifestCommittables.put(identifier, manifestCommittable);
+ }
+
+ public Map<Identifier, ManifestCommittable> getManifestCommittables() {
+ return manifestCommittables;
+ }
+}
diff --git a/paimon-core/src/test/java/org/apache/paimon/manifest/WrappedManifestCommittableTest.java b/paimon-core/src/test/java/org/apache/paimon/manifest/WrappedManifestCommittableTest.java
new file mode 100644
index 000000000..67ec4c9c7
--- /dev/null
+++ b/paimon-core/src/test/java/org/apache/paimon/manifest/WrappedManifestCommittableTest.java
@@ -0,0 +1,46 @@
+/*
+ * 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.paimon.manifest;
+
+import org.apache.paimon.catalog.Identifier;
+
+import org.junit.jupiter.api.Test;
+
+import static org.apache.paimon.manifest.ManifestCommittableSerializerTest.create;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class WrappedManifestCommittableTest {
+
+ @Test
+ public void testEquals() {
+ ManifestCommittable committable1 = create();
+ ManifestCommittable committable2 = create();
+
+ WrappedManifestCommittable wrapped1 = new WrappedManifestCommittable();
+ wrapped1.putManifestCommittable(Identifier.create("db", "table1"), committable1);
+ wrapped1.putManifestCommittable(Identifier.create("db", "table2"), committable2);
+
+ // add manifest committables in reverse order
+ WrappedManifestCommittable wrapped2 = new WrappedManifestCommittable();
+ wrapped2.putManifestCommittable(Identifier.create("db", "table2"), committable2);
+ wrapped2.putManifestCommittable(Identifier.create("db", "table1"), committable1);
+
+ assertThat(wrapped1).isEqualTo(wrapped2);
+ }
+}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RestoreAndFailCommittableStateManager.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RestoreAndFailCommittableStateManager.java
index 1260be3ef..42c7bcabd 100644
--- a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RestoreAndFailCommittableStateManager.java
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RestoreAndFailCommittableStateManager.java
@@ -41,27 +41,26 @@ import java.util.List;
* <p>Useful for committing snapshots containing records. For example snapshots produced by table
* store writers.
*/
-public class RestoreAndFailCommittableStateManager
- implements CommittableStateManager<ManifestCommittable> {
+public class RestoreAndFailCommittableStateManager<GlobalCommitT>
+ implements CommittableStateManager<GlobalCommitT> {
private static final long serialVersionUID = 1L;
/** The committable's serializer. */
- private final SerializableSupplier<SimpleVersionedSerializer<ManifestCommittable>>
+ private final SerializableSupplier<SimpleVersionedSerializer<GlobalCommitT>>
committableSerializer;
- /** ManifestCommittable state of this job. Used to filter out previous successful commits. */
- private ListState<ManifestCommittable> streamingCommitterState;
+ /** GlobalCommitT state of this job. Used to filter out previous successful commits. */
+ private ListState<GlobalCommitT> streamingCommitterState;
public RestoreAndFailCommittableStateManager(
- SerializableSupplier<SimpleVersionedSerializer<ManifestCommittable>>
- committableSerializer) {
+ SerializableSupplier<SimpleVersionedSerializer<GlobalCommitT>> committableSerializer) {
this.committableSerializer = committableSerializer;
}
@Override
public void initializeState(
- StateInitializationContext context, Committer<?, ManifestCommittable> committer)
+ StateInitializationContext context, Committer<?, GlobalCommitT> committer)
throws Exception {
streamingCommitterState =
new SimpleVersionedListState<>(
@@ -71,14 +70,13 @@ public class RestoreAndFailCommittableStateManager
"streaming_committer_raw_states",
BytePrimitiveArraySerializer.INSTANCE)),
committableSerializer.get());
- List<ManifestCommittable> restored = new ArrayList<>();
+ List<GlobalCommitT> restored = new ArrayList<>();
streamingCommitterState.get().forEach(restored::add);
streamingCommitterState.clear();
recover(restored, committer);
}
- private void recover(
- List<ManifestCommittable> committables, Committer<?, ManifestCommittable> committer)
+ private void recover(List<GlobalCommitT> committables, Committer<?, GlobalCommitT> committer)
throws Exception {
committables = committer.filterRecoveredCommittables(committables);
if (!committables.isEmpty()) {
@@ -92,7 +90,7 @@ public class RestoreAndFailCommittableStateManager
}
@Override
- public void snapshotState(StateSnapshotContext context, List<ManifestCommittable> committables)
+ public void snapshotState(StateSnapshotContext context, List<GlobalCommitT> committables)
throws Exception {
streamingCommitterState.update(committables);
}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/StoreMultiCommitter.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/StoreMultiCommitter.java
new file mode 100644
index 000000000..f4e1be5f6
--- /dev/null
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/StoreMultiCommitter.java
@@ -0,0 +1,188 @@
+/*
+ * 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.paimon.flink.sink;
+
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.manifest.ManifestCommittable;
+import org.apache.paimon.manifest.WrappedManifestCommittable;
+import org.apache.paimon.operation.Lock;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.sink.CommitMessage;
+
+import org.apache.flink.api.java.tuple.Tuple2;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.stream.Collectors;
+
+/**
+ * {@link StoreMultiCommitter} for multiple dynamic store. During the commit process, it will group
+ * the WrappedManifestCommittables by their table identifier and use different committers to commit
+ * to different tables.
+ */
+public class StoreMultiCommitter
+ implements Committer<MultiTableCommittable, WrappedManifestCommittable> {
+
+ private Catalog catalog;
+ private final String commitUser;
+ // To make the commit behavior consistent with that of Committer,
+ // StoreMultiCommitter manages multiple committers which are
+ // referenced by table id.
+ private Map<Identifier, StoreCommitter> tableCommitters;
+ private Lock.Factory lockFactory = Lock.emptyFactory();
+
+ public StoreMultiCommitter(String commitUser, Catalog.Loader catalogLoader) {
+ this.catalog = catalogLoader.load();
+ this.commitUser = commitUser;
+ this.tableCommitters = new HashMap<>();
+ }
+
+ @Override
+ public List<WrappedManifestCommittable> filterRecoveredCommittables(
+ List<WrappedManifestCommittable> globalCommittables) {
+ // key by table id
+ Map<Identifier, List<ManifestCommittable>> committableMap =
+ groupByTable(globalCommittables);
+
+ Map<Long, WrappedManifestCommittable> result = new TreeMap<>();
+
+ for (Map.Entry<Identifier, List<ManifestCommittable>> entry : committableMap.entrySet()) {
+ Identifier tableId = entry.getKey();
+ List<ManifestCommittable> committableList = entry.getValue();
+ StoreCommitter committer = getStoreCommitter(tableId);
+ List<ManifestCommittable> filteredCommittables =
+ committer.filterRecoveredCommittables(committableList);
+
+ for (ManifestCommittable filteredCommittable : filteredCommittables) {
+ long identifier = filteredCommittable.identifier();
+ WrappedManifestCommittable wrappedFilteredCommittable =
+ result.computeIfAbsent(identifier, id -> new WrappedManifestCommittable());
+
+ wrappedFilteredCommittable.putManifestCommittable(tableId, filteredCommittable);
+ }
+ }
+
+ return new LinkedList<>(result.values());
+ }
+
+ @Override
+ public WrappedManifestCommittable combine(
+ long checkpointId, long watermark, List<MultiTableCommittable> committables) {
+ WrappedManifestCommittable wrappedManifestCommittable = new WrappedManifestCommittable();
+ for (MultiTableCommittable committable : committables) {
+
+ ManifestCommittable manifestCommittable =
+ wrappedManifestCommittable.computeCommittableIfAbsent(
+ Identifier.create(committable.getDatabase(), committable.getTable()),
+ checkpointId,
+ watermark);
+
+ switch (committable.kind()) {
+ case FILE:
+ CommitMessage file = (CommitMessage) committable.wrappedCommittable();
+ manifestCommittable.addFileCommittable(file);
+ break;
+ case LOG_OFFSET:
+ LogOffsetCommittable offset =
+ (LogOffsetCommittable) committable.wrappedCommittable();
+ manifestCommittable.addLogOffset(offset.bucket(), offset.offset());
+ break;
+ }
+ }
+ return wrappedManifestCommittable;
+ }
+
+ @Override
+ public void commit(List<WrappedManifestCommittable> committables)
+ throws IOException, InterruptedException {
+
+ // key by table id
+ Map<Identifier, List<ManifestCommittable>> committableMap = groupByTable(committables);
+
+ for (Map.Entry<Identifier, List<ManifestCommittable>> entry : committableMap.entrySet()) {
+ Identifier tableId = entry.getKey();
+ List<ManifestCommittable> committableList = entry.getValue();
+ StoreCommitter committer = getStoreCommitter(tableId);
+ committer.commit(committableList);
+ }
+ }
+
+ private Map<Identifier, List<ManifestCommittable>> groupByTable(
+ List<WrappedManifestCommittable> committables) {
+ return committables.stream()
+ .flatMap(
+ wrapped -> {
+ Map<Identifier, ManifestCommittable> manifestCommittables =
+ wrapped.getManifestCommittables();
+ return manifestCommittables.entrySet().stream()
+ .map(entry -> Tuple2.of(entry.getKey(), entry.getValue()));
+ })
+ .collect(
+ Collectors.groupingBy(
+ t -> t.f0, Collectors.mapping(t -> t.f1, Collectors.toList())));
+ }
+
+ @Override
+ public Map<Long, List<MultiTableCommittable>> groupByCheckpoint(
+ Collection<MultiTableCommittable> committables) {
+ Map<Long, List<MultiTableCommittable>> grouped = new HashMap<>();
+ for (MultiTableCommittable c : committables) {
+ grouped.computeIfAbsent(c.checkpointId(), k -> new ArrayList<>()).add(c);
+ }
+ return grouped;
+ }
+
+ private StoreCommitter getStoreCommitter(Identifier tableId) {
+ StoreCommitter committer = tableCommitters.get(tableId);
+
+ if (committer == null) {
+ FileStoreTable table;
+ try {
+ table = (FileStoreTable) catalog.getTable(tableId);
+ } catch (Catalog.TableNotExistException e) {
+ throw new RuntimeException(
+ String.format(
+ "Failed to get committer for table %s", tableId.getFullName()),
+ e);
+ }
+ committer =
+ new StoreCommitter(
+ table.newCommit(commitUser)
+ .withLock(lockFactory.create())
+ .ignoreEmptyCommit(false));
+ tableCommitters.put(tableId, committer);
+ }
+
+ return committer;
+ }
+
+ @Override
+ public void close() throws Exception {
+ for (StoreCommitter committer : tableCommitters.values()) {
+ committer.close();
+ }
+ }
+}
diff --git a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/WrappedManifestCommittableSerializer.java b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/WrappedManifestCommittableSerializer.java
new file mode 100644
index 000000000..65eb12a13
--- /dev/null
+++ b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/WrappedManifestCommittableSerializer.java
@@ -0,0 +1,115 @@
+/*
+ * 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.paimon.flink.sink;
+
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.data.serializer.VersionedSerializer;
+import org.apache.paimon.io.DataInputDeserializer;
+import org.apache.paimon.io.DataOutputViewStreamWrapper;
+import org.apache.paimon.manifest.ManifestCommittable;
+import org.apache.paimon.manifest.ManifestCommittableSerializer;
+import org.apache.paimon.manifest.WrappedManifestCommittable;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
+
+/** {@link VersionedSerializer} for {@link ManifestCommittable}. */
+public class WrappedManifestCommittableSerializer
+ implements VersionedSerializer<WrappedManifestCommittable> {
+
+ protected static final int CURRENT_VERSION = 1;
+
+ private final ManifestCommittableSerializer manifestCommittableSerializer;
+
+ public WrappedManifestCommittableSerializer() {
+ this.manifestCommittableSerializer = new ManifestCommittableSerializer();
+ }
+
+ @Override
+ public int getVersion() {
+ return CURRENT_VERSION;
+ }
+
+ @Override
+ public byte[] serialize(WrappedManifestCommittable wrapped) throws IOException {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ DataOutputViewStreamWrapper view = new DataOutputViewStreamWrapper(out);
+
+ // Serialize ManifestCommittable map inside WrappedManifestCommittable
+ Map<Identifier, ManifestCommittable> map = wrapped.getManifestCommittables();
+ view.writeInt(map.size());
+ for (Map.Entry<Identifier, ManifestCommittable> entry : map.entrySet()) {
+ byte[] serializedKey = entry.getKey().getFullName().getBytes(StandardCharsets.UTF_8);
+ byte[] serializedValue = manifestCommittableSerializer.serialize(entry.getValue());
+ view.writeInt(serializedKey.length);
+ view.write(serializedKey);
+ view.writeInt(serializedValue.length);
+ view.write(serializedValue);
+ }
+ return out.toByteArray();
+ }
+
+ @Override
+ public WrappedManifestCommittable deserialize(int version, byte[] serialized)
+ throws IOException {
+ if (version != CURRENT_VERSION) {
+ throw new UnsupportedOperationException(
+ "Expecting WrappedManifestCommittable version to be "
+ + CURRENT_VERSION
+ + ", but found "
+ + version
+ + ".\nWrappedManifestCommittable is not a compatible data structure. "
+ + "Please restart the job afresh (do not recover from savepoint).");
+ }
+
+ DataInputDeserializer view = new DataInputDeserializer(serialized);
+
+ // Deserialize ManifestCommittable map inside WrappedManifestCommittable
+ int mapSize = view.readInt();
+ WrappedManifestCommittable wrappedManifestCommittable = new WrappedManifestCommittable();
+ for (int i = 0; i < mapSize; i++) {
+ int keyLength = view.readInt();
+ byte[] serializedKey = new byte[keyLength];
+ view.read(serializedKey);
+ Identifier key =
+ Identifier.fromString(new String(serializedKey, StandardCharsets.UTF_8));
+ int valueLength = view.readInt();
+ byte[] serializedValue = new byte[valueLength];
+ view.read(serializedValue);
+ ManifestCommittable value =
+ manifestCommittableSerializer.deserialize(
+ manifestCommittableSerializer.getVersion(), serializedValue);
+ wrappedManifestCommittable.putManifestCommittable(key, value);
+ }
+
+ return wrappedManifestCommittable;
+ }
+
+ private Map<Integer, Long> deserializeOffsets(DataInputDeserializer view) throws IOException {
+ int size = view.readInt();
+ Map<Integer, Long> offsets = new HashMap<>(size);
+ for (int i = 0; i < size; i++) {
+ offsets.put(view.readInt(), view.readLong());
+ }
+ return offsets;
+ }
+}
diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/CommitterOperatorTest.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/CommitterOperatorTest.java
index b7dcd24f7..8c700a442 100644
--- a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/CommitterOperatorTest.java
+++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/CommitterOperatorTest.java
@@ -235,7 +235,7 @@ public class CommitterOperatorTest extends CommitterOperatorTestBase {
private OneInputStreamOperatorTestHarness<Committable, Committable>
createRecoverableTestHarness(FileStoreTable table) throws Exception {
CommitterOperator<Committable, ManifestCommittable> operator =
- new CommitterOperator<Committable, ManifestCommittable>(
+ new CommitterOperator<>(
true,
initialCommitUser,
user ->
@@ -243,7 +243,7 @@ public class CommitterOperatorTest extends CommitterOperatorTestBase {
table.newStreamWriteBuilder()
.withCommitUser(user)
.newCommit()),
- new RestoreAndFailCommittableStateManager(
+ new RestoreAndFailCommittableStateManager<>(
() ->
new VersionedSerializerWrapper<>(
new ManifestCommittableSerializer())));
@@ -253,7 +253,7 @@ public class CommitterOperatorTest extends CommitterOperatorTestBase {
private OneInputStreamOperatorTestHarness<Committable, Committable> createLossyTestHarness(
FileStoreTable table) throws Exception {
CommitterOperator<Committable, ManifestCommittable> operator =
- new CommitterOperator<Committable, ManifestCommittable>(
+ new CommitterOperator<>(
true,
initialCommitUser,
user ->
diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/StoreMultiCommitterTest.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/StoreMultiCommitterTest.java
new file mode 100644
index 000000000..10eec4c90
--- /dev/null
+++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/StoreMultiCommitterTest.java
@@ -0,0 +1,577 @@
+/*
+ * 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.paimon.flink.sink;
+
+import org.apache.paimon.catalog.Catalog;
+import org.apache.paimon.catalog.CatalogContext;
+import org.apache.paimon.catalog.CatalogFactory;
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.data.BinaryString;
+import org.apache.paimon.data.GenericRow;
+import org.apache.paimon.data.InternalRow;
+import org.apache.paimon.flink.VersionedSerializerWrapper;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.fs.local.LocalFileIO;
+import org.apache.paimon.manifest.WrappedManifestCommittable;
+import org.apache.paimon.options.CatalogOptions;
+import org.apache.paimon.options.Options;
+import org.apache.paimon.reader.RecordReader;
+import org.apache.paimon.reader.RecordReaderIterator;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.sink.CommitMessage;
+import org.apache.paimon.table.sink.StreamTableWrite;
+import org.apache.paimon.table.sink.StreamWriteBuilder;
+import org.apache.paimon.table.source.TableRead;
+import org.apache.paimon.types.DataType;
+import org.apache.paimon.types.DataTypes;
+import org.apache.paimon.types.RowType;
+import org.apache.paimon.utils.CloseableIterator;
+import org.apache.paimon.utils.SnapshotManager;
+import org.apache.paimon.utils.TraceableFileIO;
+
+import org.apache.flink.api.common.ExecutionConfig;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.runtime.checkpoint.OperatorSubtaskState;
+import org.apache.flink.runtime.state.StateInitializationContext;
+import org.apache.flink.runtime.state.StateSnapshotContext;
+import org.apache.flink.streaming.api.watermark.Watermark;
+import org.apache.flink.streaming.util.OneInputStreamOperatorTestHarness;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.UUID;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.fail;
+
+class StoreMultiCommitterTest {
+ private String initialCommitUser;
+ private Path warehouse;
+ private Catalog.Loader catalogLoader;
+ private Catalog catalog;
+ private String databaseName;
+ private Identifier firstTable;
+ private Identifier secondTable;
+ private Path firstTablePath;
+ private Path secondTablePath;
+ @TempDir public java.nio.file.Path tempDir;
+
+ private void createTestTables(Catalog catalog, Tuple2<Identifier, Schema>... tableSpecs)
+ throws Exception {
+ for (Tuple2<Identifier, Schema> spec : tableSpecs) {
+ catalog.createTable(spec.f0, spec.f1, false);
+ }
+ }
+
+ @BeforeEach
+ public void beforeEach() throws Exception {
+ initialCommitUser = UUID.randomUUID().toString();
+ warehouse = new Path(TraceableFileIO.SCHEME + "://" + tempDir.toString());
+ databaseName = "test_db";
+ firstTable = Identifier.create(databaseName, "test_table1");
+ secondTable = Identifier.create(databaseName, "test_table2");
+
+ catalogLoader = createCatalogLoader();
+ catalog = catalogLoader.load();
+ catalog.createDatabase(databaseName, true);
+
+ RowType rowType1 =
+ RowType.of(
+ new DataType[] {DataTypes.INT(), DataTypes.BIGINT()},
+ new String[] {"a", "b"});
+ RowType rowType2 =
+ RowType.of(
+ new DataType[] {
+ DataTypes.INT(), DataTypes.DOUBLE(), DataTypes.VARCHAR(5),
+ },
+ new String[] {"a", "b", "c"});
+ Options conf = new Options();
+
+ Schema firstTableSchema =
+ new Schema(
+ rowType1.getFields(),
+ Collections.emptyList(),
+ Collections.emptyList(),
+ conf.toMap(),
+ "");
+ Schema secondTableSchema =
+ new Schema(
+ rowType2.getFields(),
+ Collections.emptyList(),
+ Collections.emptyList(),
+ conf.toMap(),
+ "");
+ createTestTables(
+ catalog,
+ Tuple2.of(firstTable, firstTableSchema),
+ Tuple2.of(secondTable, secondTableSchema));
+ firstTablePath = ((FileStoreTable) catalog.getTable(firstTable)).location();
+ secondTablePath = ((FileStoreTable) catalog.getTable(secondTable)).location();
+ }
+
+ // ------------------------------------------------------------------------
+ // Recoverable operator tests
+ // ------------------------------------------------------------------------
+
+ @Test
+ public void testFailIntentionallyAfterRestore() throws Exception {
+ FileStoreTable table = (FileStoreTable) catalog.getTable(firstTable);
+
+ // write to first table
+ OneInputStreamOperatorTestHarness<MultiTableCommittable, MultiTableCommittable>
+ testHarness = createRecoverableTestHarness();
+ testHarness.open();
+ StreamTableWrite write =
+ table.newStreamWriteBuilder().withCommitUser(initialCommitUser).newWrite();
+ write.write(GenericRow.of(1, 10L));
+ write.write(GenericRow.of(2, 20L));
+
+ long timestamp = 1;
+ for (CommitMessage committable : write.prepareCommit(false, 8)) {
+ testHarness.processElement(
+ getMultiTableCommittable(
+ firstTable, new Committable(8, Committable.Kind.FILE, committable)),
+ timestamp++);
+ }
+ // checkpoint is completed but not notified, so no snapshot is committed
+ OperatorSubtaskState snapshot = testHarness.snapshot(0, timestamp++);
+ assertThat(table.snapshotManager().latestSnapshotId()).isNull();
+
+ testHarness = createRecoverableTestHarness();
+ try {
+ // commit snapshot from state, fail intentionally
+ testHarness.initializeState(snapshot);
+ testHarness.open();
+ fail("Expecting intentional exception");
+ } catch (Exception e) {
+ assertThat(e)
+ .hasMessageContaining(
+ "This exception is intentionally thrown "
+ + "after committing the restored checkpoints. "
+ + "By restarting the job we hope that "
+ + "writers can start writing based on these new commits.");
+ }
+ assertResultsForFirstTable(table, "1, 10", "2, 20");
+
+ // snapshot is successfully committed, no failure is needed
+ testHarness = createRecoverableTestHarness();
+ testHarness.initializeState(snapshot);
+ testHarness.open();
+ assertResultsForFirstTable(table, "1, 10", "2, 20");
+
+ // write to second table
+ table = (FileStoreTable) catalog.getTable(secondTable);
+
+ write = table.newStreamWriteBuilder().withCommitUser(initialCommitUser).newWrite();
+ write.write(GenericRow.of(3, 30.0, BinaryString.fromString("s3")));
+ write.write(GenericRow.of(4, 40.0, BinaryString.fromString("s4")));
+
+ for (CommitMessage committable : write.prepareCommit(false, 9)) {
+ testHarness.processElement(
+ getMultiTableCommittable(
+ secondTable, new Committable(9, Committable.Kind.FILE, committable)),
+ timestamp++);
+ }
+
+ // test restore and fail for second table
+ // checkpoint is completed but not notified, so no snapshot is committed
+ snapshot = testHarness.snapshot(1, timestamp++);
+ assertThat(table.snapshotManager().latestSnapshotId()).isNull();
+
+ testHarness = createRecoverableTestHarness();
+ try {
+ // commit snapshot from state, fail intentionally
+ testHarness.initializeState(snapshot);
+ testHarness.open();
+ fail("Expecting intentional exception");
+ } catch (Exception e) {
+ assertThat(e)
+ .hasMessageContaining(
+ "This exception is intentionally thrown "
+ + "after committing the restored checkpoints. "
+ + "By restarting the job we hope that "
+ + "writers can start writing based on these new commits.");
+ }
+ assertResultsForSecondTable(table, "3, 30.0, s3", "4, 40.0, s4");
+
+ // snapshot is successfully committed, no failure is needed
+ testHarness = createRecoverableTestHarness();
+ testHarness.initializeState(snapshot);
+ testHarness.open();
+ assertResultsForSecondTable(table, "3, 30.0, s3", "4, 40.0, s4");
+ }
+
+ @Test
+ public void testCheckpointAbort() throws Exception {
+ FileStoreTable table1 = (FileStoreTable) catalog.getTable(firstTable);
+ FileStoreTable table2 = (FileStoreTable) catalog.getTable(secondTable);
+ OneInputStreamOperatorTestHarness<MultiTableCommittable, MultiTableCommittable>
+ testHarness = createRecoverableTestHarness();
+ testHarness.open();
+
+ StreamTableWrite write1 =
+ table1.newStreamWriteBuilder().withCommitUser(initialCommitUser).newWrite();
+
+ StreamTableWrite write2 =
+ table2.newStreamWriteBuilder().withCommitUser(initialCommitUser).newWrite();
+
+ // only write to first table
+ // files from multiple checkpoint
+ // but no snapshot
+ long cpId = 0;
+ for (int i = 0; i < 10; i++) {
+ cpId++;
+ write1.write(GenericRow.of(1, 10L));
+ write1.write(GenericRow.of(2, 20L));
+ for (CommitMessage committable : write1.prepareCommit(false, cpId)) {
+ testHarness.processElement(
+ getMultiTableCommittable(
+ firstTable,
+ new Committable(cpId, Committable.Kind.FILE, committable)),
+ 1);
+ }
+ }
+
+ // checkpoint is completed but not notified, so no snapshot is committed
+ testHarness.snapshot(cpId, 1);
+ testHarness.notifyOfCompletedCheckpoint(cpId);
+
+ SnapshotManager snapshotManager1 =
+ new SnapshotManager(LocalFileIO.create(), firstTablePath);
+ SnapshotManager snapshotManager2 =
+ new SnapshotManager(LocalFileIO.create(), secondTablePath);
+
+ // should create 10 snapshots for first table
+ assertThat(snapshotManager1.latestSnapshotId()).isEqualTo(cpId);
+ // should not create snapshot for second table
+ assertThat(snapshotManager2.latestSnapshotId()).isNull();
+
+ // another 10 checkpoints where records are written to first and second table
+ for (int i = 0; i < 10; i++) {
+ cpId++;
+ write1.write(GenericRow.of(3, 30L));
+ write1.write(GenericRow.of(3, 40L));
+ write2.write(GenericRow.of(3, 30.0, BinaryString.fromString("s3")));
+ write2.write(GenericRow.of(3, 40.0, BinaryString.fromString("s4")));
+ for (CommitMessage committable : write1.prepareCommit(false, cpId)) {
+ testHarness.processElement(
+ getMultiTableCommittable(
+ firstTable,
+ new Committable(cpId, Committable.Kind.FILE, committable)),
+ 1);
+ }
+
+ for (CommitMessage committable : write2.prepareCommit(false, cpId)) {
+ testHarness.processElement(
+ getMultiTableCommittable(
+ secondTable,
+ new Committable(cpId, Committable.Kind.FILE, committable)),
+ 1);
+ }
+ }
+
+ testHarness.snapshot(cpId, 2);
+ testHarness.notifyOfCompletedCheckpoint(cpId);
+
+ // should create 20 snapshots in total for first table
+ assertThat(snapshotManager1.latestSnapshotId()).isEqualTo(20);
+ // should create 10 snapshots for second table
+ assertThat(snapshotManager2.latestSnapshotId()).isEqualTo(10);
+ }
+
+ // ------------------------------------------------------------------------
+ // Lossy operator tests
+ // ------------------------------------------------------------------------
+
+ @Test
+ public void testSnapshotLostWhenFailed() throws Exception {
+ FileStoreTable table1 = (FileStoreTable) catalog.getTable(firstTable);
+ FileStoreTable table2 = (FileStoreTable) catalog.getTable(secondTable);
+
+ StreamTableWrite write1 =
+ table1.newStreamWriteBuilder().withCommitUser(initialCommitUser).newWrite();
+
+ StreamTableWrite write2 =
+ table2.newStreamWriteBuilder().withCommitUser(initialCommitUser).newWrite();
+
+ OneInputStreamOperatorTestHarness<MultiTableCommittable, MultiTableCommittable>
+ testHarness = createLossyTestHarness();
+ testHarness.open();
+
+ long timestamp = 1;
+
+ StreamWriteBuilder streamWriteBuilder1 =
+ table1.newStreamWriteBuilder().withCommitUser(initialCommitUser);
+ StreamWriteBuilder streamWriteBuilder2 =
+ table2.newStreamWriteBuilder().withCommitUser(initialCommitUser);
+ // this checkpoint is notified, should be committed
+ write1.write(GenericRow.of(1, 10L));
+ write1.write(GenericRow.of(2, 20L));
+ for (CommitMessage committable : write1.prepareCommit(false, 1)) {
+ testHarness.processElement(
+ getMultiTableCommittable(
+ firstTable, new Committable(1, Committable.Kind.FILE, committable)),
+ timestamp++);
+ }
+ testHarness.snapshot(1, timestamp++);
+ testHarness.notifyOfCompletedCheckpoint(1);
+
+ // this checkpoint is not notified, should not be committed
+ write1.write(GenericRow.of(3, 30L));
+ write1.write(GenericRow.of(4, 40L));
+ write2.write(GenericRow.of(3, 30.0, BinaryString.fromString("s3")));
+ write2.write(GenericRow.of(3, 40.0, BinaryString.fromString("s4")));
+ for (CommitMessage committable : write1.prepareCommit(false, 2)) {
+ testHarness.processElement(
+ getMultiTableCommittable(
+ firstTable, new Committable(2, Committable.Kind.FILE, committable)),
+ timestamp++);
+ }
+ for (CommitMessage committable : write2.prepareCommit(false, 2)) {
+ testHarness.processElement(
+ getMultiTableCommittable(
+ secondTable, new Committable(2, Committable.Kind.FILE, committable)),
+ timestamp++);
+ }
+ OperatorSubtaskState snapshot = testHarness.snapshot(2, timestamp++);
+
+ // reopen test harness
+ write1.close();
+ write2.close();
+ testHarness.close();
+
+ testHarness = createLossyTestHarness();
+ testHarness.initializeState(snapshot);
+ testHarness.open();
+
+ // this checkpoint is notified, should be committed
+ write1 = streamWriteBuilder1.newWrite();
+ write1.write(GenericRow.of(5, 50L));
+ write1.write(GenericRow.of(6, 60L));
+ write2 = streamWriteBuilder2.newWrite();
+ write2.write(GenericRow.of(5, 50.0, BinaryString.fromString("s5")));
+ write2.write(GenericRow.of(6, 60.0, BinaryString.fromString("s6")));
+ for (CommitMessage committable : write1.prepareCommit(false, 3)) {
+ testHarness.processElement(
+ getMultiTableCommittable(
+ firstTable, new Committable(3, Committable.Kind.FILE, committable)),
+ timestamp++);
+ }
+ for (CommitMessage committable : write2.prepareCommit(false, 2)) {
+ testHarness.processElement(
+ getMultiTableCommittable(
+ secondTable, new Committable(2, Committable.Kind.FILE, committable)),
+ timestamp++);
+ }
+ testHarness.snapshot(3, timestamp++);
+ testHarness.notifyOfCompletedCheckpoint(3);
+
+ write1.close();
+ write2.close();
+ testHarness.close();
+
+ assertResultsForFirstTable(table1, "1, 10", "2, 20", "5, 50", "6, 60");
+ assertResultsForSecondTable(table2, "5, 50.0, s5", "6, 60.0, s6");
+ }
+
+ @Test
+ public void testWatermarkCommit() throws Exception {
+ FileStoreTable table1 = (FileStoreTable) catalog.getTable(firstTable);
+ FileStoreTable table2 = (FileStoreTable) catalog.getTable(secondTable);
+
+ StreamTableWrite write1 =
+ table1.newStreamWriteBuilder().withCommitUser(initialCommitUser).newWrite();
+
+ StreamTableWrite write2 =
+ table2.newStreamWriteBuilder().withCommitUser(initialCommitUser).newWrite();
+
+ OneInputStreamOperatorTestHarness<MultiTableCommittable, MultiTableCommittable>
+ testHarness = createRecoverableTestHarness();
+ testHarness.open();
+ long timestamp = 0;
+ long cpId = 1;
+
+ // only write to first table on before first watermark
+ write1.write(GenericRow.of(1, 10L));
+ testHarness.processElement(
+ getMultiTableCommittable(
+ firstTable,
+ new Committable(
+ cpId,
+ Committable.Kind.FILE,
+ write1.prepareCommit(true, cpId).get(0))),
+ timestamp++);
+ testHarness.processWatermark(new Watermark(1024));
+ testHarness.snapshot(cpId, timestamp++);
+ testHarness.notifyOfCompletedCheckpoint(cpId);
+ assertThat(table1.snapshotManager().latestSnapshot().watermark()).isEqualTo(1024L);
+ assertThat(table2.snapshotManager().latestSnapshot()).isNull();
+
+ // write to both tables on second watermark
+ cpId = 2;
+ write1.write(GenericRow.of(1, 20L));
+ write2.write(GenericRow.of(1, 20.0, BinaryString.fromString("s2")));
+ testHarness.processElement(
+ getMultiTableCommittable(
+ firstTable,
+ new Committable(
+ cpId,
+ Committable.Kind.FILE,
+ write1.prepareCommit(true, cpId).get(0))),
+ timestamp++);
+ testHarness.processWatermark(new Watermark(2048));
+ testHarness.snapshot(cpId, timestamp++);
+ testHarness.notifyOfCompletedCheckpoint(cpId);
+ assertThat(table1.snapshotManager().latestSnapshot().watermark()).isEqualTo(2048L);
+ assertThat(table1.snapshotManager().latestSnapshot().watermark()).isEqualTo(2048L);
+ }
+
+ // ------------------------------------------------------------------------
+ // Test utils
+ // ------------------------------------------------------------------------
+
+ private OneInputStreamOperatorTestHarness<MultiTableCommittable, MultiTableCommittable>
+ createRecoverableTestHarness() throws Exception {
+ CommitterOperator<MultiTableCommittable, WrappedManifestCommittable> operator =
+ new CommitterOperator<>(
+ true,
+ initialCommitUser,
+ user -> new StoreMultiCommitter(initialCommitUser, catalogLoader),
+ new RestoreAndFailCommittableStateManager<>(
+ () ->
+ new VersionedSerializerWrapper<>(
+ new WrappedManifestCommittableSerializer())));
+ return createTestHarness(operator);
+ }
+
+ private OneInputStreamOperatorTestHarness<MultiTableCommittable, MultiTableCommittable>
+ createLossyTestHarness() throws Exception {
+ CommitterOperator<MultiTableCommittable, WrappedManifestCommittable> operator =
+ new CommitterOperator<>(
+ true,
+ initialCommitUser,
+ user -> new StoreMultiCommitter(initialCommitUser, catalogLoader),
+ new CommittableStateManager<WrappedManifestCommittable>() {
+ @Override
+ public void initializeState(
+ StateInitializationContext context,
+ Committer<?, WrappedManifestCommittable> committer) {}
+
+ @Override
+ public void snapshotState(
+ StateSnapshotContext context,
+ List<WrappedManifestCommittable> committables) {}
+ });
+ return createTestHarness(operator);
+ }
+
+ private OneInputStreamOperatorTestHarness<MultiTableCommittable, MultiTableCommittable>
+ createTestHarness(
+ CommitterOperator<MultiTableCommittable, WrappedManifestCommittable> operator)
+ throws Exception {
+ TypeSerializer<MultiTableCommittable> serializer =
+ new MultiTableCommittableTypeInfo().createSerializer(new ExecutionConfig());
+ OneInputStreamOperatorTestHarness<MultiTableCommittable, MultiTableCommittable> harness =
+ new OneInputStreamOperatorTestHarness<>(operator, serializer);
+ harness.setup(serializer);
+ return harness;
+ }
+
+ private Catalog.Loader createCatalogLoader() {
+ Options catalogOptions = createCatalogOptions(warehouse);
+ return () -> CatalogFactory.createCatalog(CatalogContext.create(catalogOptions));
+ }
+
+ private Options createCatalogOptions(Path warehouse) {
+ Options conf = new Options();
+ conf.set(CatalogOptions.WAREHOUSE, warehouse.getPath());
+ conf.set(CatalogOptions.URI, "");
+
+ return conf;
+ }
+
+ protected void assertResultsForFirstTable(FileStoreTable table, String... expected) {
+ TableRead read = table.newReadBuilder().newRead();
+ List<String> actual = new ArrayList<>();
+ table.newReadBuilder()
+ .newScan()
+ .plan()
+ .splits()
+ .forEach(
+ s -> {
+ try {
+ RecordReader<InternalRow> recordReader = read.createReader(s);
+ CloseableIterator<InternalRow> it =
+ new RecordReaderIterator<>(recordReader);
+ while (it.hasNext()) {
+ InternalRow row = it.next();
+ actual.add(row.getInt(0) + ", " + row.getLong(1));
+ }
+ it.close();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ });
+ Collections.sort(actual);
+ assertThat(actual).isEqualTo(Arrays.asList(expected));
+ }
+
+ private void assertResultsForSecondTable(FileStoreTable table, String... expected) {
+ TableRead read = table.newReadBuilder().newRead();
+ List<String> actual = new ArrayList<>();
+ table.newReadBuilder()
+ .newScan()
+ .plan()
+ .splits()
+ .forEach(
+ s -> {
+ try {
+ RecordReader<InternalRow> recordReader = read.createReader(s);
+ CloseableIterator<InternalRow> it =
+ new RecordReaderIterator<>(recordReader);
+ while (it.hasNext()) {
+ InternalRow row = it.next();
+ actual.add(
+ row.getInt(0)
+ + ", "
+ + row.getDouble(1)
+ + ", "
+ + row.getString(2));
+ }
+ it.close();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ });
+ Collections.sort(actual);
+ assertThat(actual).isEqualTo(Arrays.asList(expected));
+ }
+
+ private MultiTableCommittable getMultiTableCommittable(
+ Identifier tableId, Committable committable) {
+ return MultiTableCommittable.fromCommittable(tableId, committable);
+ }
+}
diff --git a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/WrappedManifestCommittableSerializerTest.java b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/WrappedManifestCommittableSerializerTest.java
new file mode 100644
index 000000000..127b1e9fa
--- /dev/null
+++ b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/WrappedManifestCommittableSerializerTest.java
@@ -0,0 +1,104 @@
+/*
+ * 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.paimon.flink.sink;
+
+import org.apache.paimon.catalog.Identifier;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.io.CompactIncrement;
+import org.apache.paimon.io.NewFilesIncrement;
+import org.apache.paimon.manifest.ManifestCommittable;
+import org.apache.paimon.manifest.WrappedManifestCommittable;
+import org.apache.paimon.table.sink.CommitMessage;
+import org.apache.paimon.table.sink.CommitMessageImpl;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.apache.paimon.io.DataFileTestUtils.row;
+import static org.apache.paimon.manifest.ManifestCommittableSerializerTest.randomCompactIncrement;
+import static org.apache.paimon.manifest.ManifestCommittableSerializerTest.randomNewFilesIncrement;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class WrappedManifestCommittableSerializerTest {
+
+ private static final AtomicInteger ID = new AtomicInteger();
+ private static final int VERSION = WrappedManifestCommittableSerializer.CURRENT_VERSION;
+
+ @Test
+ public void testCommittableSerDe() throws IOException {
+ WrappedManifestCommittableSerializer serializer = serializer();
+ ManifestCommittable committable1 = createManifestCommittable();
+ ManifestCommittable committable2 = createManifestCommittable();
+ WrappedManifestCommittable wrappedManifestCommittable = new WrappedManifestCommittable();
+ wrappedManifestCommittable.putManifestCommittable(
+ Identifier.create("db", "table1"), committable1);
+ wrappedManifestCommittable.putManifestCommittable(
+ Identifier.create("db", "table2"), committable2);
+ byte[] serialized = serializer.serialize(wrappedManifestCommittable);
+ WrappedManifestCommittable deserialize = serializer.deserialize(VERSION, serialized);
+ Map<Identifier, ManifestCommittable> manifestCommittables =
+ deserialize.getManifestCommittables();
+
+ assertThat(manifestCommittables.size()).isEqualTo(2);
+ assertThat(deserialize).isEqualTo(wrappedManifestCommittable);
+ }
+
+ public static WrappedManifestCommittableSerializer serializer() {
+ return new WrappedManifestCommittableSerializer();
+ }
+
+ public static ManifestCommittable createManifestCommittable() {
+ ThreadLocalRandom rnd = ThreadLocalRandom.current();
+ ManifestCommittable committable =
+ rnd.nextBoolean()
+ ? new ManifestCommittable(rnd.nextLong(), rnd.nextLong())
+ : new ManifestCommittable(rnd.nextLong(), null);
+ addFileCommittables(committable, row(0), 0);
+ addFileCommittables(committable, row(0), 1);
+ addFileCommittables(committable, row(1), 0);
+ addFileCommittables(committable, row(1), 1);
+ return committable;
+ }
+
+ public static void addFileCommittables(
+ ManifestCommittable committable, BinaryRow partition, int bucket) {
+ List<CommitMessage> commitMessages = new ArrayList<>();
+ int length = ThreadLocalRandom.current().nextInt(10) + 1;
+ for (int i = 0; i < length; i++) {
+ NewFilesIncrement newFilesIncrement = randomNewFilesIncrement();
+ CompactIncrement compactIncrement = randomCompactIncrement();
+ CommitMessage commitMessage =
+ new CommitMessageImpl(partition, bucket, newFilesIncrement, compactIncrement);
+ commitMessages.add(commitMessage);
+ committable.addFileCommittable(commitMessage);
+ }
+
+ if (!committable.logOffsets().containsKey(bucket)) {
+ int offset = ID.incrementAndGet();
+ committable.addLogOffset(bucket, offset);
+ assertThat(committable.logOffsets().get(bucket)).isEqualTo(offset);
+ }
+ }
+}