fishfishfishfishaa commented on code in PR #8401:
URL: https://github.com/apache/paimon/pull/8401#discussion_r3505096968


##########
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);
+                    } else {
+                        // TODO: watermark handling
+                        // TODO: end input handling
+                        throw new UnsupportedOperationException("Unsupported 
event type: " + event);
+                    }
+                },
+                "handling operator event %s from subtask %d (#%d)",
+                event,
+                subtask,
+                attemptNumber);
+    }
+
+    @Override
+    public void notifyCheckpointComplete(long checkpointId) {
+        runInEventLoop(
+                () -> {
+                    if (state != State.RUNNING) {
+                        throw new IllegalStateException(
+                                "Completing checkpoint should be notified in 
RUNNING state, while current state is "
+                                        + state);
+                    }
+                    // writers always report a committable per (subtask, 
checkpoint) during
+                    // snapshot, even if empty; missing means the writer is 
broken
+                    if (!alignCommittables(checkpointId)) {
+                        throw new IllegalStateException("Not all committables 
reported by writer");

Review Comment:
   The writer and coordinator process committables asynchronously. It is 
possible for a writer to finish its checkpoint while the coordinator has not 
yet collected all committable/file info events, for example due to network 
delay or coordinator event-loop lag. In such cases, alignCommittables failure 
may only mean delayed event processing rather than an unrecoverable error; the 
missing file info may still arrive later if the writer snapshot has succeeded.
   The design doc currently describes the Writer-Coordinator FileInfo handoff 
as synchronous. I agree that the async design can reduce blocking in the writer 
checkpoint path, but then the design doc should be updated to describe the 
actual async protocol.



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