You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@paimon.apache.org by "fishfishfishfishaa (via GitHub)" <gi...@apache.org> on 2026/06/28 03:10:04 UTC

[PR] [feature] Support sink.committer-coordinator-operator.enabled [paimon]

fishfishfishfishaa opened a new pull request, #8372:
URL: https://github.com/apache/paimon/pull/8372

   ## Description
   
   This PR implements [PIP-30: Improvement For Paimon Committer In Flink](https://cwiki.apache.org/confluence/display/PAIMON/PIP-30%3A+Improvement+For+Paimon+Committer+In+Flink).
   
   One important background is that, for a given Flink checkpoint, the coordinator checkpoint is triggered before writer tasks start their checkpoint. Because of this ordering, I first tried a minimal prototype which maintained coordinator state through a custom state mechanism when Flink did not expose checkpoint state for this use case: https://github.com/apache/paimon/pull/7963.
   
   However, that approach introduced several problems, including two independent state systems, higher complexity, extra dependency on HDFS, and additional blocking while waiting for custom state to be persisted to HDFS.
   
   Thanks to @liubiao for proposing the current design:
   https://docs.google.com/document/d/1asWKzoytfeB1D8bS_yRIAHnpR40frLf0fnPn2-WSL74/edit?tab=t.0
   
   The key idea is to move the durable file-info state to the writer task side, so it is persisted together with Flink checkpoint state. Meanwhile, PWC keeps an in-memory pending state for received file info. If the coordinator itself fails over, the in-memory committable map can be rebuilt by writer tasks replaying their pending file info from writer state. The coordinator only persists necessary metadata through the normal coordinator checkpoint interface, such as `commitUser`.
   
   Following this direction, this PR focuses the optimization on the unaware bucket append path, while keeping the original `FixedBucketSink` path unaffected.
   
   ## Design
   
   When the option is enabled, writer tasks still flush data and produce committables during `prepareSnapshotPreBarrier`.
   
   In addition, each writer task records the produced file info in writer-side state in a `checkpointId -> fileInfo` form. This state is part of Flink operator state and is persisted together with Flink checkpoints.
   
   During `snapshotState`:
   
   1. The writer first updates its local pending file-info state.
   2. Then it sends the unacknowledged file info to `PaimonWriterCoordinator` through `FileInfoRequest`.
   3. The writer waits for the PWC ACK before returning from `snapshotState`.
   
   If the request fails, writer snapshot fails and the checkpoint cannot complete. If the request blocks for too long, it is guarded by Flink checkpoint timeout.
   
   On the PWC side:
   
   1. PWC validates whether the request comes from a valid registered subtask attempt.
   2. PWC stores the received file info as reliable in-memory pending state.
   3. If the current checkpoint envelope has not received all subtasks, PWC replies ACK immediately.
   4. If the current request is from the last subtask of the checkpoint envelope, PWC stages pending file info up to this checkpoint into the committable map, and then replies ACK.
   5. Later, Flink checkpoint coordinator triggers `notifyCheckpointComplete`, and PWC commits all committables up to that checkpoint.
   
   After commit succeeds, PWC sends `CommitCompleteEvent` to active writer subtasks. Writers use this event to clean local pending state up to the committed checkpoint, preventing writer-side state from growing forever.
   
   ## Recovery Semantics
   
   ### Writer Task Failover
   
   When a writer task fails over, the new attempt restores writer state in `initializeState`.
   
   The recovered writer then sends its pending file info to PWC through the same request path. PWC tracks valid execution attempts through `executionAttemptReady` and `executionAttemptFailed`, so stale attempt requests can be rejected, and pending file info from failed attempts can be cleaned or replaced.
   
   For recovered file info, PWC waits until all recovered writer requests are received, and then calls `filterAndCommitUpToCheckpoint`. If this commit creates a new snapshot, PWC treats it as an incomplete previous commit and triggers one extra failover, following the original recommit semantics.
   
   ### JM / PWC Failover
   
   For JM / PWC failover, PWC does not persist the full in-memory `committable map` as coordinator state.
   
   Instead, PWC only restores necessary coordinator metadata from Flink coordinator checkpoint state, such as `commitUser`. The actual pending file info is restored from writer task state. After recovery, writer tasks replay their pending file info through `FileInfoRequest`, and PWC rebuilds its in-memory committable map from these recovered requests.
   
   In other words, PWC pending commit state is recovered by writer-state replay, not by independently persisting the full coordinator-side committable map.
   
   ### Checkpoint Abort Without Task Failure
   
   If a checkpoint is aborted but writer tasks do not fail, already ACKed file info is kept as reliable pending state in PWC memory.
   
   A later successful checkpoint envelope can stage and commit this file info. This preserves the original semantics that checkpoint abort does not mean data rollback.
   
   ## Scope
   
   This PR focuses on the unaware bucket append path, especially `RowAppendTableSink`, where removing the committer operator can help reduce the failover region.
   
   It does not change the original `FixedBucketSink` commit path. Fixed bucket and other paths involving shuffle, assigner, index, or compact operators are not included in this optimization, because those operators may already bind regions together or require different recovery semantics.
   
   ## Tests
   
   This PR adds and updates tests for the new PWC commit path.
   
   Unit tests cover:
   
   - writer-side coordinated committable state and ACK tracking;
   - `FileInfoRequest` request / ACK behavior;
   - checkpoint complete and checkpoint abort handling in PWC;
   - recovered file info and recommit behavior;
   - stale attempt validation;
   - writer operator interaction with the coordinated file-info sender.
   
   IT coverage verifies coordinator commit behavior and ensures non-target sink paths are not affected.
   
   E2E coverage verifies:
   
   - committing through PWC without the original committer / compact operators in the job plan;
   - checkpoint abort without task failure, followed by successful commit through a later checkpoint;
   - TaskManager failure / region failover behavior;
   - savepoint restore replaying pending file info.


-- 
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@paimon.apache.org

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


Re: [PR] [feature] Support sink.committer-coordinator-operator.enabled [paimon]

Posted by "ifndef-SleePy (via GitHub)" <gi...@apache.org>.
ifndef-SleePy commented on PR #8372:
URL: https://github.com/apache/paimon/pull/8372#issuecomment-4846689102

   If you don't mind, I will open the second PR under https://github.com/apache/paimon/issues/8220.
   
   You can compare it with this PR and check whether the concerns I raised above are valid.
   
   Also, I think it would be helpful to communicate through the mailing list, GitHub issue, or any other convenient place before coding. That should help reduce duplicated work.


-- 
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@paimon.apache.org

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


Re: [PR] [feature] Support sink.committer-coordinator-operator.enabled [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #8372:
URL: https://github.com/apache/paimon/pull/8372#discussion_r3519491432


##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/AppendTableSink.java:
##########
@@ -132,4 +136,17 @@ public DataStream<Committable> doWrite(
 
         return written;
     }
+
+    @Override
+    public DataStreamSink<?> doCommit(DataStream<Committable> written, String commitUser) {
+        Options options = Options.fromMap(table.options());
+        if (options.get(SINK_COMMITTER_COORDINATOR_OPERATOR_ENABLED)
+                && !options.get(PRECOMMIT_COMPACT)) {
+            return written.sinkTo(new DiscardingSink<>())

Review Comment:
   This bypasses the normal  wrapping, so table options that are implemented by wrapping the committer operator are silently ignored when PWC is enabled. For example  and batch tag creation ( in batch runtime) are applied in , but this branch replaces the committer with a bare  and the coordinator does not install equivalent tag handling. Please either preserve those wrappers for the coordinator path or reject these option combinations explicitly; otherwise enabling this option changes existing sink semantics beyond just moving the commit into the coordinator.



##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/AppendTableSink.java:
##########
@@ -132,4 +136,17 @@ public DataStream<Committable> doWrite(
 
         return written;
     }
+
+    @Override
+    public DataStreamSink<?> doCommit(DataStream<Committable> written, String commitUser) {
+        Options options = Options.fromMap(table.options());
+        if (options.get(SINK_COMMITTER_COORDINATOR_OPERATOR_ENABLED)
+                && !options.get(PRECOMMIT_COMPACT)) {
+            return written.sinkTo(new DiscardingSink<>())

Review Comment:
   This bypasses the normal `FlinkSink.doCommit` wrapping, so table options that are implemented by wrapping the committer operator are silently ignored when PWC is enabled. For example `sink.auto-tag-for-savepoint` and batch tag creation (`tag.creation-mode=BATCH` in batch runtime) are applied in `FlinkSink.doCommit`, but this branch replaces the committer with a bare `DiscardingSink` and the coordinator does not install equivalent tag handling. Please either preserve those wrappers for the coordinator path or reject these option combinations explicitly; otherwise enabling this option changes existing sink semantics beyond just moving the commit into the 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@paimon.apache.org

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


Re: [PR] [feature] Support sink.committer-coordinator-operator.enabled [paimon]

Posted by "fishfishfishfishaa (via GitHub)" <gi...@apache.org>.
fishfishfishfishaa commented on PR #8372:
URL: https://github.com/apache/paimon/pull/8372#issuecomment-4894127956

   Thanks for all the suggestion and for sharing the context around #8220.
   
   I agree that the asynchronous implementation in the other PR is a better approach for this design. Since both PRs are trying to solve the same problem, I will close this one to avoid duplicated work.
   
   I’m really glad that I learned a lot from this process, and I sincerely appreciate all the reviewers for spending time reviewing my code and giving valuable feedback. Thanks again for the helpful discussion and guidance.


-- 
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@paimon.apache.org

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


Re: [PR] [feature] Support sink.committer-coordinator-operator.enabled [paimon]

Posted by "Mrart (via GitHub)" <gi...@apache.org>.
Mrart commented on code in PR #8372:
URL: https://github.com/apache/paimon/pull/8372#discussion_r3488864420


##########
paimon-e2e-tests/src/test/java/org/apache/paimon/tests/PaimonWriterCoordinatorE2eTest.java:
##########
@@ -0,0 +1,716 @@
+/*
+ * 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.tests;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.testcontainers.containers.Container;
+import org.testcontainers.containers.ContainerState;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** End-to-end tests for committing an append table through Paimon writer coordinator. */
+@Timeout(300)
+public class PaimonWriterCoordinatorE2eTest extends E2eTestBase {
+
+    private static final long WAIT_TIMEOUT_MS = 120_000L;
+    private static final Pattern VERTEX_PATTERN =
+            Pattern.compile(
+                    "\\\"id\\\"\\s*:\\s*\\\"([^\\\"]+)\\\"[^{}]*"
+                            + "\\\"name\\\"\\s*:\\s*\\\"[^\\\"]*"
+                            + "Writer\\(write-only\\)\\s*:\\s*pip30_sink[^\\\"]*\\\"");
+    private static final Pattern INTEGER_PATTERN = Pattern.compile("(\\d+)");
+
+    public PaimonWriterCoordinatorE2eTest() {
+        super(false, false, false, 2);
+    }
+
+    @Override
+    protected String flinkEnvFile() {
+        return "flink-pwc.env";
+    }
+
+    @Test
+    public void testCheckpointCommitWithWriterCoordinator() throws Exception {
+        TestContext context = createContext();
+        writeRecords(context.inputDirectory, 0, 20);
+
+        String jobId = submit(context);
+        waitForJobStatus(jobId, "RUNNING");
+        waitForWriterSubtasks(jobId);
+        waitForRecords();
+        triggerAndWaitForCompletedCheckpoint(jobId);
+
+        assertThat(rest("GET", "/jobs/" + jobId + "/plan", null))
+                .doesNotContain("Committer", "Compact Coordinator", "Compact Worker");
+        waitUntil(
+                () -> jobManager.getLogs().contains("Paimon writer coordinator starting"),
+                "PWC did not start.");
+
+        cancel(jobId);
+        assertTable(context, 0, 20);
+    }
+
+    @Test
+    public void testPartialCheckpointAbortIsRecoveredByNextCheckpoint() throws Exception {
+        TestContext context = createContext();
+        writeRecords(context.inputDirectory, 0, 20);
+
+        // 先启动流作业并完成一次正常 checkpoint,确保 coordinator 已经完成一次提交。

Review Comment:
   English comment



-- 
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@paimon.apache.org

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


Re: [PR] [feature] Support sink.committer-coordinator-operator.enabled [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #8372:
URL: https://github.com/apache/paimon/pull/8372#discussion_r3503185587


##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/PendingSubtask.java:
##########
@@ -0,0 +1,269 @@
+/*
+ * 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.flink.sink.Committable;
+
+import org.apache.flink.runtime.operators.coordination.OperatorCoordinator;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.Set;
+import java.util.TreeMap;
+
+/** Tracks writer subtasks and pending checkpoint file information for PWC. */
+public class PendingSubtask {
+
+    private final Map<Integer, Map<Integer, OperatorCoordinator.SubtaskGateway>> registeredSubtasks;
+    private final NavigableMap<Long, PendingCheckpoint> checkpoints;
+    private final Map<Long, Map<Integer, FileInfoRequest>> pendingEnvelopes;
+    private final Set<Long> abortedCheckpoints;
+    private final CommitterCoordinator<Committable, ?> coordinator;
+
+    private int parallelism;
+    private long maxCommittedCheckpointId;
+    private long restoredCheckpointId;
+
+    public PendingSubtask(CommitterCoordinator<Committable, ?> coordinator) {
+        this.coordinator = coordinator;
+        this.registeredSubtasks = new HashMap<>();
+        this.checkpoints = new TreeMap<>();
+        this.pendingEnvelopes = new HashMap<>();
+        this.abortedCheckpoints = new HashSet<>();
+        this.maxCommittedCheckpointId = Long.MIN_VALUE;
+        this.restoredCheckpointId = Long.MIN_VALUE;
+    }
+
+    public void init(int parallelism) {
+        this.parallelism = parallelism;
+    }
+
+    public void registerSubtask(
+            int subtask, int attemptNumber, OperatorCoordinator.SubtaskGateway gateway) {
+        Map<Integer, OperatorCoordinator.SubtaskGateway> attempts =
+                registeredSubtasks.computeIfAbsent(subtask, ignored -> new HashMap<>());
+        if (!attempts.isEmpty() && !attempts.containsKey(attemptNumber)) {
+            attempts.clear();
+            removePendingSubtask(subtask);
+        }
+        attempts.put(attemptNumber, gateway);
+    }
+
+    public void unregisterSubtask(int subtask, int attemptNumber, Throwable throwable) {
+        Map<Integer, OperatorCoordinator.SubtaskGateway> attempts = registeredSubtasks.get(subtask);
+        if (attempts != null) {
+            attempts.remove(attemptNumber);
+        }
+        removePendingSubtask(subtask);
+    }
+
+    public boolean isValid(int subtask, int attemptNumber) {
+        Map<Integer, OperatorCoordinator.SubtaskGateway> attempts = registeredSubtasks.get(subtask);
+        return attempts != null && attempts.containsKey(attemptNumber);
+    }
+
+    public Collection<OperatorCoordinator.SubtaskGateway> activeGateways() {
+        Collection<OperatorCoordinator.SubtaskGateway> gateways = new ArrayList<>();
+        for (Map<Integer, OperatorCoordinator.SubtaskGateway> attempts :
+                registeredSubtasks.values()) {
+            gateways.addAll(attempts.values());
+        }
+        return gateways;
+    }
+
+    public CommitResult receive(int subtask, FileInfoRequest request) throws Exception {
+        long envelopeCheckpointId = request.checkpointId();
+        if (envelopeCheckpointId <= maxCommittedCheckpointId) {
+            return new CommitResult(true, 0, maxCommittedCheckpointId, false);
+        }
+
+        recordEnvelope(envelopeCheckpointId, subtask, request);
+        recordFileInfos(subtask, request);
+        if (!envelopeAllReceived(envelopeCheckpointId)) {
+            return CommitResult.NONE;
+        }
+
+        stageCheckpointsUpTo(envelopeCheckpointId);
+
+        if (envelopeCheckpointId != restoredCheckpointId) {
+            return CommitResult.NONE;
+        }
+
+        if (!envelopeAllRecovered(envelopeCheckpointId)) {
+            throw new IllegalStateException(
+                    String.format(
+                            "Restored checkpoint %d contains non-recovered file info.",
+                            restoredCheckpointId));
+        }
+
+        int committedCount = coordinator.filterAndCommitUpToCheckpoint(restoredCheckpointId);
+        maxCommittedCheckpointId = Math.max(maxCommittedCheckpointId, restoredCheckpointId);
+        cleanupCommittedCheckpoints(restoredCheckpointId);
+        return new CommitResult(true, committedCount, restoredCheckpointId, true);
+    }
+
+    public CommitResult notifyCheckpointComplete(long checkpointId) throws Exception {
+        if (checkpointId <= maxCommittedCheckpointId) {
+            return new CommitResult(true, 0, maxCommittedCheckpointId, false);
+        }
+        if (!stagedEnvelope(checkpointId)) {
+            throw new IllegalStateException(
+                    String.format(
+                            "Checkpoint %d completed before PWC staged file info from all subtasks.",
+                            checkpointId));
+        }
+
+        coordinator.notifyCheckpointComplete(checkpointId);
+        maxCommittedCheckpointId = Math.max(maxCommittedCheckpointId, checkpointId);
+        cleanupCommittedCheckpoints(checkpointId);
+        return new CommitResult(true, 0, checkpointId, false);
+    }
+
+    public void notifyCheckpointAborted(long checkpointId) {
+        abortedCheckpoints.add(checkpointId);
+        coordinator.notifyCheckpointAborted(checkpointId);
+    }
+
+    public void restoreCheckpoint(long checkpointId) {
+        restoredCheckpointId = checkpointId;
+    }
+
+    private void recordEnvelope(long checkpointId, int subtask, FileInfoRequest request) {
+        Map<Integer, FileInfoRequest> envelope =
+                pendingEnvelopes.computeIfAbsent(checkpointId, ignored -> new HashMap<>());
+        if (envelope.containsKey(subtask)) {
+            throw new IllegalStateException(
+                    String.format(
+                            "Repeated file info envelope received for checkpoint %d subtask %d.",
+                            checkpointId, subtask));
+        }
+        envelope.put(subtask, request);
+    }
+
+    private void recordFileInfos(int subtask, FileInfoRequest request) throws Exception {
+        Map<Long, List<Committable>> committablesByCheckpoint = new TreeMap<>();
+        for (Committable committable :
+                CoordinatedFileInfoSender.deserializeCommittables(request.serializedData())) {
+            committablesByCheckpoint
+                    .computeIfAbsent(committable.checkpointId(), ignored -> new ArrayList<>())
+                    .add(committable);
+        }
+        for (Map.Entry<Long, List<Committable>> entry : committablesByCheckpoint.entrySet()) {
+            if (entry.getKey() > maxCommittedCheckpointId) {
+                checkpoint(entry.getKey()).receive(subtask, request, entry.getValue());
+            }
+        }
+    }
+
+    private PendingCheckpoint checkpoint(long checkpointId) {
+        return checkpoints.computeIfAbsent(
+                checkpointId, ignored -> new PendingCheckpoint(checkpointId));
+    }
+
+    private boolean envelopeAllReceived(long checkpointId) {
+        Map<Integer, FileInfoRequest> receivedSubtasks = pendingEnvelopes.get(checkpointId);
+        return receivedSubtasks != null
+                && receivedSubtasks.keySet().containsAll(expectedSubtasks());
+    }
+
+    private boolean envelopeAllRecovered(long checkpointId) {
+        if (!envelopeAllReceived(checkpointId)) {
+            return false;
+        }
+        for (FileInfoRequest request : pendingEnvelopes.get(checkpointId).values()) {
+            if (!request.recovered()) {
+                return false;
+            }
+        }
+        for (PendingCheckpoint checkpoint : checkpoints.headMap(checkpointId, true).values()) {
+            if (!checkpoint.staged()) {
+                continue;
+            }
+            for (SubtaskFileInfo fileInfo : checkpoint.fileInfos()) {
+                if (!fileInfo.request().recovered()) {
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+    private Set<Integer> expectedSubtasks() {
+        Set<Integer> subtasks = new HashSet<>();
+        for (int i = 0; i < parallelism; i++) {
+            subtasks.add(i);
+        }
+        return subtasks;
+    }
+
+    private void stageCheckpointsUpTo(long checkpointId) throws Exception {
+        for (PendingCheckpoint checkpoint : checkpoints.headMap(checkpointId, true).values()) {
+            if (!checkpoint.staged()) {
+                saveCheckpoint(checkpoint);
+                checkpoint.markStaged();
+            }
+        }
+    }
+
+    private boolean stagedEnvelope(long checkpointId) {
+        return envelopeAllReceived(checkpointId)
+                && checkpoints.headMap(checkpointId, true).values().stream()
+                        .allMatch(PendingCheckpoint::staged);
+    }
+
+    private void saveCheckpoint(PendingCheckpoint checkpoint) throws Exception {
+        coordinator.save(
+                checkpoint.committablesAfter(maxCommittedCheckpointId),
+                checkpoint.checkpointId(),
+                checkpoint.maxWatermark());
+    }
+
+    private void cleanupCommittedCheckpoints(long checkpointId) {
+        checkpoints.keySet().removeIf(id -> id <= checkpointId);
+        pendingEnvelopes.keySet().removeIf(id -> id <= checkpointId);
+        abortedCheckpoints.removeIf(id -> id <= checkpointId);
+    }
+
+    private void removePendingSubtask(int subtask) {
+        for (PendingCheckpoint checkpoint : checkpoints.values()) {
+            if (!checkpoint.staged()) {

Review Comment:
   Staged checkpoints from this attempt still need to be invalidated if the attempt fails before the checkpoint completes. The coordinator stages file info as soon as all requests arrive, but the Flink checkpoint can still abort afterwards. With parallelism 1, subtask 0 can send CK1 and have CK1 marked staged, then fail before CK1 completes; `removePendingSubtask` leaves the staged CK1 files here. The replacement attempt restores from the previous completed checkpoint and replays the same records into CK2, and completing CK2 then commits both the stale CK1 files from the failed attempt and the replayed CK2 files. Please drop staged data produced by failed attempts until the corresponding checkpoint has completed, or reset the coordinator state for this failure path.



-- 
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@paimon.apache.org

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


Re: [PR] [feature] Support sink.committer-coordinator-operator.enabled [paimon]

Posted by "ifndef-SleePy (via GitHub)" <gi...@apache.org>.
ifndef-SleePy commented on code in PR #8372:
URL: https://github.com/apache/paimon/pull/8372#discussion_r3499836158


##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/CoordinatedFileInfoSender.java:
##########
@@ -0,0 +1,181 @@
+/*
+ * 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.flink.sink.Committable;
+import org.apache.paimon.flink.sink.CommittableSerializer;
+import org.apache.paimon.table.sink.CommitMessageSerializer;
+
+import org.apache.flink.runtime.jobgraph.OperatorID;
+import org.apache.flink.runtime.jobgraph.tasks.TaskOperatorEventGateway;
+import org.apache.flink.runtime.operators.coordination.CoordinationRequest;
+import org.apache.flink.util.Preconditions;
+import org.apache.flink.util.SerializedValue;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+
+/** Sends writer committables to the Paimon writer coordinator. */
+public class CoordinatedFileInfoSender {
+
+    private static final int LENGTH_FIELD_SIZE = 4;
+    private static final int COUNT_FIELD_SIZE = 4;
+
+    private final TaskOperatorEventGateway gateway;
+    private final OperatorID operatorId;
+    private final CommittableSerializer serializer;
+
+    private int subtaskId;
+    private int attemptNumber;
+    private long watermark;
+    private boolean endInput;
+
+    public CoordinatedFileInfoSender(TaskOperatorEventGateway gateway, OperatorID operatorId) {
+        this.gateway = gateway;
+        this.operatorId = operatorId;
+        this.serializer = new CommittableSerializer(new CommitMessageSerializer());
+        this.subtaskId = -1;
+        this.attemptNumber = -1;
+        this.watermark = Long.MIN_VALUE;
+    }
+
+    public void setSubtaskId(int subtaskId) {
+        this.subtaskId = subtaskId;
+    }
+
+    public void setAttemptNumber(int attemptNumber) {
+        this.attemptNumber = attemptNumber;
+    }
+
+    public void processWatermark(long watermark) {
+        if (watermark != Long.MAX_VALUE) {
+            this.watermark = Math.max(this.watermark, watermark);
+        }
+    }
+
+    public boolean isEndInput() {
+        return endInput;
+    }
+
+    public void sendToCoordinator(long checkpointId, List<Committable> committables) {
+        if (checkpointId == CommitterCoordinator.END_INPUT_CHECKPOINT_ID) {
+            endInput = true;
+        }
+        byte[] data = serializeCommittables(committables);
+        FileInfoRequest request =
+                FileInfoRequest.fileInfo(
+                        checkpointId,
+                        subtaskId,
+                        attemptNumber,
+                        watermark,
+                        data,
+                        committables.size());
+        sendRequest(request);
+    }
+
+    public void sendRecoveredFileInfoToCoordinator(
+            long checkpointId, String commitUser, List<Committable> committables) {
+        byte[] data = serializeCommittables(committables);
+        sendRequest(
+                FileInfoRequest.recoveredFileInfo(
+                        checkpointId,
+                        subtaskId,
+                        attemptNumber,
+                        watermark,
+                        data,
+                        committables.size(),
+                        commitUser));
+    }
+
+    private void sendRequest(FileInfoRequest request) {
+        try {
+            SerializedValue<CoordinationRequest> serializedRequest =
+                    new SerializedValue<CoordinationRequest>(request);
+            FileInfoReceivedResponse response =
+                    CoordinationResponseUtils.unwrap(
+                            gateway.sendRequestToCoordinator(operatorId, serializedRequest).get());

Review Comment:
   This is a synchronous call on the writer side. The writer thread will block here until the coordinator processes the request and returns the ACK.
   In high-parallelism jobs, this can become a serious performance bottleneck because checkpoint processing now depends on a synchronous JM-side request/response path.



##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/PaimonWriterCoordinator.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.flink.sink.Committable;
+import org.apache.paimon.flink.sink.Committer;
+import org.apache.paimon.flink.sink.TableWriteOperator;
+import org.apache.paimon.utils.ExceptionUtils;
+
+import org.apache.flink.runtime.jobgraph.OperatorID;
+import org.apache.flink.runtime.operators.coordination.CoordinationRequest;
+import org.apache.flink.runtime.operators.coordination.CoordinationRequestHandler;
+import org.apache.flink.runtime.operators.coordination.CoordinationResponse;
+import org.apache.flink.runtime.operators.coordination.OperatorCoordinator;
+import org.apache.flink.runtime.operators.coordination.OperatorEvent;
+import org.apache.flink.util.ThrowableCatchingRunnable;
+import org.apache.flink.util.function.ThrowingRunnable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadFactory;
+
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * {@link OperatorCoordinator} for {@link TableWriteOperator}. It receives writer file information
+ * and performs global commits in JobManager.
+ */
+public class PaimonWriterCoordinator implements OperatorCoordinator, CoordinationRequestHandler {
+
+    private static final Logger LOG = LoggerFactory.getLogger(PaimonWriterCoordinator.class);
+
+    private final PendingSubtask pendingSubtask;
+    private final CoordinatorExecutorThreadFactory coordinatorThreadFactory;
+    private final CompletableFuture<Void> finalCheckpointCompleted = new CompletableFuture<>();
+
+    private final OperatorCoordinator.Context context;
+    private final CommitterCoordinator<Committable, ?> coordinator;
+    private final String initialCommitUser;
+
+    private @Nullable String commitUser;
+    private ScheduledExecutorService coordinatorExecutor;
+    private boolean started;
+    private boolean freshInstance = true;
+
+    public PaimonWriterCoordinator(
+            boolean streamingCheckpointEnabled,
+            String initialCommitUser,
+            Committer.Factory<Committable, ?> committerFactory,
+            OperatorCoordinator.Context context,
+            CoordinatorExecutorThreadFactory coordinatorThreadFactory,
+            Long endInputWatermark) {
+        this.context = context;
+        this.coordinatorThreadFactory = coordinatorThreadFactory;
+        this.initialCommitUser = initialCommitUser;
+        this.coordinator =
+                new CommitterCoordinator<>(
+                        streamingCheckpointEnabled, committerFactory, endInputWatermark);
+        this.pendingSubtask = new PendingSubtask(this.coordinator);
+    }
+
+    @Override
+    public void start() throws Exception {
+        OperatorID operatorId = context.getOperatorId();
+        LOG.info("Paimon writer coordinator starting, operatorId={}", operatorId);
+        if (commitUser == null) {
+            commitUser = initialCommitUser;
+        }
+        started = true;
+        coordinatorExecutor = Executors.newScheduledThreadPool(1, coordinatorThreadFactory);
+        int parallelism = context.currentParallelism();
+        coordinator.init(parallelism, commitUser);
+        pendingSubtask.init(parallelism);
+    }
+
+    @Override
+    public void executionAttemptReady(int subtask, int attemptNumber, SubtaskGateway gateway) {
+        runInEventLoop(
+                () -> pendingSubtask.registerSubtask(subtask, attemptNumber, gateway),
+                "registering subtask %d attempt %d",
+                subtask,
+                attemptNumber);
+    }
+
+    @Override
+    public void executionAttemptFailed(int subtask, int attemptNumber, Throwable throwable) {
+        runInEventLoop(
+                () -> pendingSubtask.unregisterSubtask(subtask, attemptNumber, throwable),
+                "unregistering subtask %d attempt %d",
+                subtask,
+                attemptNumber);
+    }
+
+    @Override
+    public void handleEventFromOperator(int subtask, int attemptNumber, OperatorEvent event) {
+        freshInstance = false;
+        throw new UnsupportedOperationException(
+                "PWC only accepts file info through coordination requests.");
+    }
+
+    @Override
+    public CompletableFuture<CoordinationResponse> handleCoordinationRequest(
+            CoordinationRequest request) {
+        freshInstance = false;
+        if (request instanceof FileInfoRequest) {
+            return handleFileInfoRequest((FileInfoRequest) request);
+        }
+        CompletableFuture<CoordinationResponse> result = new CompletableFuture<>();
+        result.completeExceptionally(
+                new IllegalArgumentException("Unsupported request type: " + request.getClass()));
+        return result;
+    }
+
+    @Override
+    public void checkpointCoordinator(long checkpointId, CompletableFuture<byte[]> result) {
+        freshInstance = false;
+        LOG.info("PWC snapshot commitUser={}, checkpointId={}", commitUser, checkpointId);
+        checkState(commitUser != null, "PWC has not been started.");
+        result.complete(serializeCoordinatorState(commitUser));
+    }
+
+    @Override
+    public void notifyCheckpointComplete(long checkpointId) {
+        freshInstance = false;
+        runInEventLoop(
+                () -> {
+                    handleCommitResult(pendingSubtask.notifyCheckpointComplete(checkpointId));
+                    if (coordinator.isEndInput()) {
+                        finalCheckpointCompleted.complete(null);
+                    }
+                },
+                "notifying checkpoint %d complete",
+                checkpointId);
+        if (coordinator.isEndInput()) {
+            try {
+                finalCheckpointCompleted.get();
+            } catch (InterruptedException | ExecutionException e) {
+                throw new RuntimeException(e);
+            }
+        }
+    }
+
+    @Override
+    public void notifyCheckpointAborted(long checkpointId) {
+        runInEventLoop(
+                () -> pendingSubtask.notifyCheckpointAborted(checkpointId),
+                "notifying checkpoint %d aborted",
+                checkpointId);
+    }
+
+    @Override
+    public void resetToCheckpoint(long checkpointId, byte[] bytes) throws Exception {
+        LOG.info("PWC resetToCheckpoint: checkpointId={}, fresh={}", checkpointId, freshInstance);
+        if (freshInstance && checkpointId >= 0) {
+            checkState(!started, "PWC can only be restored before it is started.");

Review Comment:
   This does not cover the lifecycle where `resetToCheckpoint()` is invoked after `start()`.



##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/PaimonWriterCoordinator.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.flink.sink.Committable;
+import org.apache.paimon.flink.sink.Committer;
+import org.apache.paimon.flink.sink.TableWriteOperator;
+import org.apache.paimon.utils.ExceptionUtils;
+
+import org.apache.flink.runtime.jobgraph.OperatorID;
+import org.apache.flink.runtime.operators.coordination.CoordinationRequest;
+import org.apache.flink.runtime.operators.coordination.CoordinationRequestHandler;
+import org.apache.flink.runtime.operators.coordination.CoordinationResponse;
+import org.apache.flink.runtime.operators.coordination.OperatorCoordinator;
+import org.apache.flink.runtime.operators.coordination.OperatorEvent;
+import org.apache.flink.util.ThrowableCatchingRunnable;
+import org.apache.flink.util.function.ThrowingRunnable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadFactory;
+
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * {@link OperatorCoordinator} for {@link TableWriteOperator}. It receives writer file information
+ * and performs global commits in JobManager.
+ */
+public class PaimonWriterCoordinator implements OperatorCoordinator, CoordinationRequestHandler {
+
+    private static final Logger LOG = LoggerFactory.getLogger(PaimonWriterCoordinator.class);
+
+    private final PendingSubtask pendingSubtask;
+    private final CoordinatorExecutorThreadFactory coordinatorThreadFactory;
+    private final CompletableFuture<Void> finalCheckpointCompleted = new CompletableFuture<>();
+
+    private final OperatorCoordinator.Context context;
+    private final CommitterCoordinator<Committable, ?> coordinator;
+    private final String initialCommitUser;
+
+    private @Nullable String commitUser;
+    private ScheduledExecutorService coordinatorExecutor;
+    private boolean started;
+    private boolean freshInstance = true;
+
+    public PaimonWriterCoordinator(
+            boolean streamingCheckpointEnabled,
+            String initialCommitUser,
+            Committer.Factory<Committable, ?> committerFactory,
+            OperatorCoordinator.Context context,
+            CoordinatorExecutorThreadFactory coordinatorThreadFactory,
+            Long endInputWatermark) {
+        this.context = context;
+        this.coordinatorThreadFactory = coordinatorThreadFactory;
+        this.initialCommitUser = initialCommitUser;
+        this.coordinator =
+                new CommitterCoordinator<>(
+                        streamingCheckpointEnabled, committerFactory, endInputWatermark);
+        this.pendingSubtask = new PendingSubtask(this.coordinator);
+    }
+
+    @Override
+    public void start() throws Exception {
+        OperatorID operatorId = context.getOperatorId();
+        LOG.info("Paimon writer coordinator starting, operatorId={}", operatorId);
+        if (commitUser == null) {
+            commitUser = initialCommitUser;
+        }
+        started = true;
+        coordinatorExecutor = Executors.newScheduledThreadPool(1, coordinatorThreadFactory);
+        int parallelism = context.currentParallelism();
+        coordinator.init(parallelism, commitUser);
+        pendingSubtask.init(parallelism);
+    }
+
+    @Override
+    public void executionAttemptReady(int subtask, int attemptNumber, SubtaskGateway gateway) {
+        runInEventLoop(
+                () -> pendingSubtask.registerSubtask(subtask, attemptNumber, gateway),
+                "registering subtask %d attempt %d",
+                subtask,
+                attemptNumber);
+    }
+
+    @Override
+    public void executionAttemptFailed(int subtask, int attemptNumber, Throwable throwable) {
+        runInEventLoop(
+                () -> pendingSubtask.unregisterSubtask(subtask, attemptNumber, throwable),
+                "unregistering subtask %d attempt %d",
+                subtask,
+                attemptNumber);
+    }
+
+    @Override
+    public void handleEventFromOperator(int subtask, int attemptNumber, OperatorEvent event) {
+        freshInstance = false;
+        throw new UnsupportedOperationException(
+                "PWC only accepts file info through coordination requests.");
+    }
+
+    @Override
+    public CompletableFuture<CoordinationResponse> handleCoordinationRequest(
+            CoordinationRequest request) {
+        freshInstance = false;
+        if (request instanceof FileInfoRequest) {
+            return handleFileInfoRequest((FileInfoRequest) request);
+        }
+        CompletableFuture<CoordinationResponse> result = new CompletableFuture<>();
+        result.completeExceptionally(
+                new IllegalArgumentException("Unsupported request type: " + request.getClass()));
+        return result;
+    }
+
+    @Override
+    public void checkpointCoordinator(long checkpointId, CompletableFuture<byte[]> result) {
+        freshInstance = false;
+        LOG.info("PWC snapshot commitUser={}, checkpointId={}", commitUser, checkpointId);
+        checkState(commitUser != null, "PWC has not been started.");
+        result.complete(serializeCoordinatorState(commitUser));

Review Comment:
   The coordinator checkpoint state only contains `commitUser`. Any committer/listener state owned by the coordinator-side committer is not persisted 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@paimon.apache.org

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


Re: [PR] [feature] Support sink.committer-coordinator-operator.enabled [paimon]

Posted by "Mrart (via GitHub)" <gi...@apache.org>.
Mrart commented on PR #8372:
URL: https://github.com/apache/paimon/pull/8372#issuecomment-4828078564

   @ifndef-SleePy  @JingsongLi  PTKL


-- 
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@paimon.apache.org

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


Re: [PR] [feature] Support sink.committer-coordinator-operator.enabled [paimon]

Posted by "fishfishfishfishaa (via GitHub)" <gi...@apache.org>.
fishfishfishfishaa closed pull request #8372: [feature] Support sink.committer-coordinator-operator.enabled
URL: https://github.com/apache/paimon/pull/8372


-- 
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@paimon.apache.org

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


Re: [PR] [feature] Support sink.committer-coordinator-operator.enabled [paimon]

Posted by "fishfishfishfishaa (via GitHub)" <gi...@apache.org>.
fishfishfishfishaa commented on code in PR #8372:
URL: https://github.com/apache/paimon/pull/8372#discussion_r3529761460


##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/AppendTableSink.java:
##########
@@ -132,4 +136,17 @@ public DataStream<Committable> doWrite(
 
         return written;
     }
+
+    @Override
+    public DataStreamSink<?> doCommit(DataStream<Committable> written, String commitUser) {
+        Options options = Options.fromMap(table.options());
+        if (options.get(SINK_COMMITTER_COORDINATOR_OPERATOR_ENABLED)
+                && !options.get(PRECOMMIT_COMPACT)) {
+            return written.sinkTo(new DiscardingSink<>())

Review Comment:
   The coordinator path bypasses FlinkSink#doCommit, so the committer-operator wrappers for auto-tag-for-savepoint and batch tag creation are not installed. I added validation for sink.auto-tag-for-savepoint and batch runtime with tag.creation-mode=BATCH when sink.committer-coordinator-operator.enabled is true.



##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/PendingCheckpoint.java:
##########
@@ -0,0 +1,106 @@
+/*
+ * 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.flink.sink.Committable;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeSet;
+
+/** Pending data and state for one checkpoint in PWC. */
+class PendingCheckpoint {
+
+    private final long checkpointId;
+    private final Map<Integer, SubtaskFileInfo> fileInfos;
+    private boolean staged;
+
+    PendingCheckpoint(long checkpointId) {
+        this.checkpointId = checkpointId;
+        this.fileInfos = new HashMap<>();
+    }
+
+    long checkpointId() {
+        return checkpointId;
+    }
+
+    boolean receive(int subtask, FileInfoRequest request, List<Committable> committables) {
+        SubtaskFileInfo previous = fileInfos.get(subtask);
+        if (previous != null) {
+            if (previous.request().samePayload(request)) {
+                return false;
+            }
+            throw new IllegalStateException(
+                    String.format(
+                            "Different FileInfoRequest received for checkpoint %d subtask %d.",
+                            checkpointId, subtask));
+        }
+
+        fileInfos.put(subtask, new SubtaskFileInfo(request, committables));
+        return true;
+    }
+
+    void removeSubtask(int subtask) {
+        fileInfos.remove(subtask);
+    }
+
+    boolean isEmpty() {
+        return fileInfos.isEmpty();
+    }
+
+    boolean staged() {
+        return staged;
+    }
+
+    void markStaged() {
+        staged = true;
+    }
+
+    List<SubtaskFileInfo> fileInfos() {
+        return new ArrayList<>(fileInfos.values());
+    }
+
+    List<Committable> allCommittables() {
+        List<Committable> result = new ArrayList<>();
+        for (Integer subtask : new TreeSet<>(fileInfos.keySet())) {
+            result.addAll(fileInfos.get(subtask).committables());
+        }
+        return result;
+    }
+
+    List<Committable> committablesAfter(long checkpointId) {
+        List<Committable> result = new ArrayList<>();
+        for (Committable committable : allCommittables()) {
+            if (committable.checkpointId() > checkpointId) {
+                result.add(committable);
+            }
+        }
+        return result;
+    }
+
+    long maxWatermark() {
+        long watermark = Long.MIN_VALUE;
+        for (SubtaskFileInfo fileInfo : fileInfos.values()) {
+            watermark = Math.max(watermark, fileInfo.request().watermark());

Review Comment:
   Thanks, agreed. I updated this to use the minimum writer watermark for the checkpoint envelope, matching the previous single committer operator semantics. The [1000, 0] case now commits watermark 0, and I added a regression test for it.



##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/PaimonWriterCoordinator.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.flink.sink.Committable;
+import org.apache.paimon.flink.sink.Committer;
+import org.apache.paimon.flink.sink.TableWriteOperator;
+import org.apache.paimon.utils.ExceptionUtils;
+
+import org.apache.flink.runtime.jobgraph.OperatorID;
+import org.apache.flink.runtime.operators.coordination.CoordinationRequest;
+import org.apache.flink.runtime.operators.coordination.CoordinationRequestHandler;
+import org.apache.flink.runtime.operators.coordination.CoordinationResponse;
+import org.apache.flink.runtime.operators.coordination.OperatorCoordinator;
+import org.apache.flink.runtime.operators.coordination.OperatorEvent;
+import org.apache.flink.util.ThrowableCatchingRunnable;
+import org.apache.flink.util.function.ThrowingRunnable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadFactory;
+
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * {@link OperatorCoordinator} for {@link TableWriteOperator}. It receives writer file information
+ * and performs global commits in JobManager.
+ */
+public class PaimonWriterCoordinator implements OperatorCoordinator, CoordinationRequestHandler {
+
+    private static final Logger LOG = LoggerFactory.getLogger(PaimonWriterCoordinator.class);
+
+    private final PendingSubtask pendingSubtask;
+    private final CoordinatorExecutorThreadFactory coordinatorThreadFactory;
+    private final CompletableFuture<Void> finalCheckpointCompleted = new CompletableFuture<>();
+
+    private final OperatorCoordinator.Context context;
+    private final CommitterCoordinator<Committable, ?> coordinator;
+    private final String initialCommitUser;
+
+    private @Nullable String commitUser;
+    private ScheduledExecutorService coordinatorExecutor;
+    private boolean started;
+    private boolean freshInstance = true;
+
+    public PaimonWriterCoordinator(
+            boolean streamingCheckpointEnabled,
+            String initialCommitUser,
+            Committer.Factory<Committable, ?> committerFactory,
+            OperatorCoordinator.Context context,
+            CoordinatorExecutorThreadFactory coordinatorThreadFactory,
+            Long endInputWatermark) {
+        this.context = context;
+        this.coordinatorThreadFactory = coordinatorThreadFactory;
+        this.initialCommitUser = initialCommitUser;
+        this.coordinator =
+                new CommitterCoordinator<>(
+                        streamingCheckpointEnabled, committerFactory, endInputWatermark);
+        this.pendingSubtask = new PendingSubtask(this.coordinator);
+    }
+
+    @Override
+    public void start() throws Exception {
+        OperatorID operatorId = context.getOperatorId();
+        LOG.info("Paimon writer coordinator starting, operatorId={}", operatorId);
+        if (commitUser == null) {
+            commitUser = initialCommitUser;
+        }
+        started = true;
+        coordinatorExecutor = Executors.newScheduledThreadPool(1, coordinatorThreadFactory);
+        int parallelism = context.currentParallelism();
+        coordinator.init(parallelism, commitUser);
+        pendingSubtask.init(parallelism);
+    }
+
+    @Override
+    public void executionAttemptReady(int subtask, int attemptNumber, SubtaskGateway gateway) {
+        runInEventLoop(
+                () -> pendingSubtask.registerSubtask(subtask, attemptNumber, gateway),
+                "registering subtask %d attempt %d",
+                subtask,
+                attemptNumber);
+    }
+
+    @Override
+    public void executionAttemptFailed(int subtask, int attemptNumber, Throwable throwable) {
+        runInEventLoop(
+                () -> pendingSubtask.unregisterSubtask(subtask, attemptNumber, throwable),
+                "unregistering subtask %d attempt %d",
+                subtask,
+                attemptNumber);
+    }
+
+    @Override
+    public void handleEventFromOperator(int subtask, int attemptNumber, OperatorEvent event) {
+        freshInstance = false;
+        throw new UnsupportedOperationException(
+                "PWC only accepts file info through coordination requests.");
+    }
+
+    @Override
+    public CompletableFuture<CoordinationResponse> handleCoordinationRequest(
+            CoordinationRequest request) {
+        freshInstance = false;
+        if (request instanceof FileInfoRequest) {
+            return handleFileInfoRequest((FileInfoRequest) request);
+        }
+        CompletableFuture<CoordinationResponse> result = new CompletableFuture<>();
+        result.completeExceptionally(
+                new IllegalArgumentException("Unsupported request type: " + request.getClass()));
+        return result;
+    }
+
+    @Override
+    public void checkpointCoordinator(long checkpointId, CompletableFuture<byte[]> result) {
+        freshInstance = false;
+        LOG.info("PWC snapshot commitUser={}, checkpointId={}", commitUser, checkpointId);
+        checkState(commitUser != null, "PWC has not been started.");
+        result.complete(serializeCoordinatorState(commitUser));
+    }
+
+    @Override
+    public void notifyCheckpointComplete(long checkpointId) {
+        freshInstance = false;
+        runInEventLoop(
+                () -> {
+                    handleCommitResult(pendingSubtask.notifyCheckpointComplete(checkpointId));
+                    if (coordinator.isEndInput()) {
+                        finalCheckpointCompleted.complete(null);
+                    }
+                },
+                "notifying checkpoint %d complete",
+                checkpointId);
+        if (coordinator.isEndInput()) {
+            try {
+                finalCheckpointCompleted.get();
+            } catch (InterruptedException | ExecutionException e) {
+                throw new RuntimeException(e);
+            }
+        }
+    }
+
+    @Override
+    public void notifyCheckpointAborted(long checkpointId) {
+        runInEventLoop(
+                () -> pendingSubtask.notifyCheckpointAborted(checkpointId),
+                "notifying checkpoint %d aborted",
+                checkpointId);
+    }
+
+    @Override
+    public void resetToCheckpoint(long checkpointId, byte[] bytes) throws Exception {
+        LOG.info("PWC resetToCheckpoint: checkpointId={}, fresh={}", checkpointId, freshInstance);
+        if (freshInstance && checkpointId >= 0) {
+            checkState(!started, "PWC can only be restored before it is started.");

Review Comment:
   Good catch. I changed the writer coordinator provider to extend `RecreateOnResetOperatorCoordinator.Provider`, same as `DataStatisticsCoordinatorProvider`, so Flink recreates the coordinator on checkpoint reset and restores state before `start()`. This should avoid reusing an already-started coordinator during JM/global failover. 



-- 
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@paimon.apache.org

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


Re: [PR] [feature] Support sink.committer-coordinator-operator.enabled [paimon]

Posted by "JingsongLi (via GitHub)" <gi...@apache.org>.
JingsongLi commented on code in PR #8372:
URL: https://github.com/apache/paimon/pull/8372#discussion_r3503179825


##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/coordinator/PendingCheckpoint.java:
##########
@@ -0,0 +1,106 @@
+/*
+ * 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.flink.sink.Committable;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeSet;
+
+/** Pending data and state for one checkpoint in PWC. */
+class PendingCheckpoint {
+
+    private final long checkpointId;
+    private final Map<Integer, SubtaskFileInfo> fileInfos;
+    private boolean staged;
+
+    PendingCheckpoint(long checkpointId) {
+        this.checkpointId = checkpointId;
+        this.fileInfos = new HashMap<>();
+    }
+
+    long checkpointId() {
+        return checkpointId;
+    }
+
+    boolean receive(int subtask, FileInfoRequest request, List<Committable> committables) {
+        SubtaskFileInfo previous = fileInfos.get(subtask);
+        if (previous != null) {
+            if (previous.request().samePayload(request)) {
+                return false;
+            }
+            throw new IllegalStateException(
+                    String.format(
+                            "Different FileInfoRequest received for checkpoint %d subtask %d.",
+                            checkpointId, subtask));
+        }
+
+        fileInfos.put(subtask, new SubtaskFileInfo(request, committables));
+        return true;
+    }
+
+    void removeSubtask(int subtask) {
+        fileInfos.remove(subtask);
+    }
+
+    boolean isEmpty() {
+        return fileInfos.isEmpty();
+    }
+
+    boolean staged() {
+        return staged;
+    }
+
+    void markStaged() {
+        staged = true;
+    }
+
+    List<SubtaskFileInfo> fileInfos() {
+        return new ArrayList<>(fileInfos.values());
+    }
+
+    List<Committable> allCommittables() {
+        List<Committable> result = new ArrayList<>();
+        for (Integer subtask : new TreeSet<>(fileInfos.keySet())) {
+            result.addAll(fileInfos.get(subtask).committables());
+        }
+        return result;
+    }
+
+    List<Committable> committablesAfter(long checkpointId) {
+        List<Committable> result = new ArrayList<>();
+        for (Committable committable : allCommittables()) {
+            if (committable.checkpointId() > checkpointId) {
+                result.add(committable);
+            }
+        }
+        return result;
+    }
+
+    long maxWatermark() {
+        long watermark = Long.MIN_VALUE;
+        for (SubtaskFileInfo fileInfo : fileInfos.values()) {
+            watermark = Math.max(watermark, fileInfo.request().watermark());

Review Comment:
   This should preserve Flink input-watermark semantics and aggregate the writer watermarks with `min`, not `max`. The previous single committer operator only advanced its input watermark after all upstream channels advanced, so a checkpoint with writer watermarks `[1000, 0]` would commit watermark `0`. With `max` here the coordinator can commit watermark `1000`, which may advance snapshot watermark / partition-mark-done too early while slower writers can still produce older partitions.



-- 
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@paimon.apache.org

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


Re: [PR] [feature] Support sink.committer-coordinator-operator.enabled [paimon]

Posted by "fishfishfishfishaa (via GitHub)" <gi...@apache.org>.
fishfishfishfishaa commented on PR #8372:
URL: https://github.com/apache/paimon/pull/8372#issuecomment-4894412937

   I’ll also try to write up my understanding of this PR later, possibly as a short retrospective, to summarize what I learned from this work and the review discussions. Thanks agains.


-- 
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@paimon.apache.org

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