ifndef-SleePy commented on code in PR #8401:
URL: https://github.com/apache/paimon/pull/8401#discussion_r3505730441


##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/CommittingWriteOperatorCoordinator.java:
##########
@@ -0,0 +1,561 @@
+/*
+ * 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.coordinator;
+
+import org.apache.paimon.annotation.VisibleForTesting;
+import org.apache.paimon.flink.sink.Committable;
+import org.apache.paimon.flink.sink.Committer;
+import org.apache.paimon.flink.sink.state.CoordinatorState;
+import org.apache.paimon.flink.sink.state.CoordinatorStateSerializer;
+import org.apache.paimon.flink.sink.state.MemoryBackendStateStore;
+import org.apache.paimon.manifest.ManifestCommittable;
+
+import org.apache.flink.api.common.typeutils.base.ListSerializer;
+import org.apache.flink.core.io.SimpleVersionedSerialization;
+import org.apache.flink.runtime.jobgraph.OperatorID;
+import org.apache.flink.runtime.operators.coordination.OperatorCoordinator;
+import org.apache.flink.runtime.operators.coordination.OperatorEvent;
+import 
org.apache.flink.runtime.operators.coordination.RecreateOnResetOperatorCoordinator;
+import org.apache.flink.util.function.ThrowingRunnable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.TreeMap;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import static org.apache.paimon.utils.Preconditions.checkState;
+
+/**
+ * {@link OperatorCoordinator} that runs the Paimon committer on the 
JobManager for the
+ * unaware-bucket append write path. Writers stream per-checkpoint 
committables to this coordinator
+ * over the {@link OperatorEvent} channel; on {@link 
#notifyCheckpointComplete} the coordinator
+ * aligns committables across subtasks and commits them from a dedicated 
single-thread executor, so
+ * the JM main thread is never blocked by table I/O.
+ *
+ * <p>Wrap this class with a {@link RecreateOnResetOperatorCoordinator} (see 
{@link Provider}). The
+ * wrapper discards this instance on global failover and creates a new one in 
its place, which keeps
+ * the lifecycle inside a single instance simple. See {@link 
#resetToCheckpoint} and {@link State}
+ * for the resulting state machine.
+ */
+public class CommittingWriteOperatorCoordinator implements OperatorCoordinator 
{
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(CommittingWriteOperatorCoordinator.class);
+
+    private static final long NO_WATERMARK = Long.MIN_VALUE;
+
+    private final OperatorCoordinator.Context context;
+    private final Committer.Factory<Committable, ManifestCommittable> 
committerFactory;
+    private final boolean streamingCheckpointEnabled;
+    private final boolean failoverAfterRecovery;
+    private final int parallelism;
+
+    private final WriterCommittables[] subtaskCommittables;
+    private final ListSerializer<Committable> committableSerializer;
+    private final CoordinatorStateSerializer stateSerializer;
+    private final ExecutorService commitExecutor;
+
+    // Populated by resetToCheckpoint and consumed by start. Plain fields are 
sufficient: both
+    // callbacks run on the same scheduler thread in order.
+    private long restoredCheckpointId = OperatorCoordinator.NO_CHECKPOINT;
+    private byte[] restoredCheckpointData;
+
+    private State state;
+    private Committer<Committable, ManifestCommittable> committer;
+    private String commitUser;
+    private MemoryBackendStateStore stateStore;
+
+    public CommittingWriteOperatorCoordinator(
+            OperatorCoordinator.Context context,
+            Committer.Factory<Committable, ManifestCommittable> 
committerFactory,
+            boolean streamingCheckpointEnabled,
+            String initialCommitUser,
+            boolean failoverAfterRecovery) {
+        this.context = context;
+        this.committerFactory = committerFactory;
+        this.streamingCheckpointEnabled = streamingCheckpointEnabled;
+        this.commitUser = initialCommitUser;
+        this.failoverAfterRecovery = failoverAfterRecovery;
+        this.parallelism = context.currentParallelism();
+        this.subtaskCommittables = new WriterCommittables[parallelism];
+        this.committableSerializer = 
CommittableEvent.createCommittableListSerializer();
+        this.stateSerializer = new CoordinatorStateSerializer();
+        this.commitExecutor =
+                Executors.newSingleThreadExecutor(
+                        new 
CoordinatorExecutorThreadFactory("WriteCommitCoordinator", context));
+        this.state = State.CREATED;
+    }
+
+    @Override
+    public void start() throws Exception {
+        // Invoked at most once. If resetToCheckpoint ran first it already 
moved state to RESTORING
+        // and stashed the bytes; otherwise we are in CREATED and there is 
nothing to restore.
+        checkState(
+                state == State.CREATED || state == State.RESTORING,
+                "Coordinator already started, illegal state %s",
+                state);
+        runInEventLoop(
+                () -> {
+                    if (state == State.RESTORING) {
+                        restoreState(restoredCheckpointId, 
restoredCheckpointData);
+                        // not needed after deserialization; release the 
reference
+                        restoredCheckpointData = null;
+                        initializeCommitter();
+                        // stay in RESTORING until writers re-emit 
committables and align catches up
+                    } else {
+                        restoreState(OperatorCoordinator.NO_CHECKPOINT, null);
+                        initializeCommitter();
+                        transitionState(State.RUNNING);
+                    }
+                },
+                "starting");
+    }
+
+    @Override
+    public void close() throws Exception {
+        transitionState(State.CLOSED);
+        if (commitExecutor != null) {
+            commitExecutor.shutdownNow();
+        }
+        if (committer != null) {
+            committer.close();
+            committer = null;
+        }
+    }
+
+    @Override
+    public void checkpointCoordinator(long checkpointId, 
CompletableFuture<byte[]> result) {
+        runCheckpointInEventLoop(
+                () -> {
+                    if (state != State.RUNNING) {
+                        // if checkpoint is executed before finishing 
restoring, just fail it
+                        result.completeExceptionally(
+                                new IllegalStateException(
+                                        "Checkpoint of commit coordinator 
should be taken in RUNNING state, while current state is "
+                                                + state));
+                        return;
+                    }
+                    committer.snapshotState();
+                    byte[] checkpointData =
+                            
SimpleVersionedSerialization.writeVersionAndSerialize(
+                                    stateSerializer,
+                                    new CoordinatorState(
+                                            commitUser, 
stateStore.getSerializedStates()));
+                    result.complete(checkpointData);
+                },
+                result,
+                "taking checkpoint %d",
+                checkpointId);
+    }
+
+    @Override
+    public void handleEventFromOperator(int subtask, int attemptNumber, 
OperatorEvent event) {
+        runInEventLoop(
+                () -> {
+                    if (event instanceof CommittableEvent) {
+                        handleCommittableEvent(subtask, (CommittableEvent) 
event);

Review Comment:
   Thanks for reviewing. That's really a good point. This was actually 
considered during the initial design; after carefully reviewing Flink's 
`OperatorCoordinator` implementation, I simplified this part. This can be 
understood as Flink doing the fencing: in 
`DefaultOperatorCoordinatorHandler.deliverOperatorEventToCoordinator` , events 
from non- RUNNING executions are filtered out, so the coordinator will not 
receive events from a failed task. The only case is that an event is received 
first and then the coordinator is notified that the attempt has failed, so 
resetting in the subtaskReset method is enough.



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to