You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by "AlexYinHan (via GitHub)" <gi...@apache.org> on 2023/10/12 07:02:31 UTC

[PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

AlexYinHan opened a new pull request, #23514:
URL: https://github.com/apache/flink/pull/23514

   <!--
   *Thank you very much for contributing to Apache Flink - we are happy that you want to help us improve Flink. To help the community review your contribution in the best possible way, please go through the checklist below, which will get the contribution into a shape in which it can be best reviewed.*
   
   *Please understand that we do not do this to make contributions to Flink a hassle. In order to uphold a high standard of quality for code contributions, while at the same time managing a large number of contributions, we need contributors to prepare the contributions well, and give reviewers enough contextual information for the review. Please also understand that contributions that do not follow this guide will take longer to review and thus typically be picked up with lower priority by the community.*
   
   ## Contribution Checklist
   
     - Make sure that the pull request corresponds to a [JIRA issue](https://issues.apache.org/jira/projects/FLINK/issues). Exceptions are made for typos in JavaDoc or documentation files, which need no JIRA issue.
     
     - Name the pull request in the form "[FLINK-XXXX] [component] Title of the pull request", where *FLINK-XXXX* should be replaced by the actual issue number. Skip *component* if you are unsure about which is the best component.
     Typo fixes that have no associated JIRA issue should be named following this pattern: `[hotfix] [docs] Fix typo in event time introduction` or `[hotfix] [javadocs] Expand JavaDoc for PuncuatedWatermarkGenerator`.
   
     - Fill out the template below to describe the changes contributed by the pull request. That will give reviewers the context they need to do the review.
     
     - Make sure that the change passes the automated tests, i.e., `mvn clean verify` passes. You can set up Azure Pipelines CI to do that following [this guide](https://cwiki.apache.org/confluence/display/FLINK/Azure+Pipelines#AzurePipelines-Tutorial:SettingupAzurePipelinesforaforkoftheFlinkrepository).
   
     - Each pull request should address only one issue, not mix up code from multiple issues.
     
     - Each commit in the pull request has a meaningful commit message (including the JIRA id)
   
     - Once all items of the checklist are addressed, remove the above text and this checklist, leaving only the filled out template below.
   
   
   **(The sections below can be removed for hotfixes of typos)**
   -->
   
   ## What is the purpose of the change
   
   As one part of FLIP-306, this PR enables file merging in snapshot by implementing the corresponding output&input streams for ```FileMergingSnapshotManager```
   
   
   ## Brief change log
    - *Add ```createCheckpointStateOutputStream``` in ```FileMergingSnapshotManager```.*
    - *Add output&input streams for file merging checkpoints*
    - *Add ```SegmentFileStateHandle``` to represent a state that is written into a file segment.*
   
   
   ## Verifying this change
   
   Please make sure both new and modified tests in this PR follows the conventions defined in our code quality guide: https://flink.apache.org/contributing/code-style-and-quality-common.html#testing
   
   This change added several UT tests in:
    - ```FileMergingSnapshotManagerTest```
    - ```FileMergingCheckpointStateOutputStreamTest```
    - ```FsSegmentDataInputStreamTest```.
   
   ## Does this pull request potentially affect one of the following parts:
   
     - Dependencies (does it add or upgrade a dependency): (no)
     - The public API, i.e., is any changed class annotated with `@Public(Evolving)`: (no)
     - The serializers: (no)
     - The runtime per-record code paths (performance sensitive): (no)
     - Anything that affects deployment or recovery: JobManager (and its components), Checkpointing, Kubernetes/Yarn, ZooKeeper: (yes)
     - The S3 file system connector: (no)
   
   ## Documentation
   
     - Does this pull request introduce a new feature? (no)
     - If yes, how is the feature documented? (not applicable / docs / JavaDocs / not documented)
   


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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "Zakelly (via GitHub)" <gi...@apache.org>.
Zakelly commented on PR #23514:
URL: https://github.com/apache/flink/pull/23514#issuecomment-1840444858

   > Thanks @fredia and @Zakelly for your comments. Sorry for the late reply. I have addressed your comments. Would you please take another look?
   
   Thanks for your effort. I have no comments but a minor one, PTAL, thanks.


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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "AlexYinHan (via GitHub)" <gi...@apache.org>.
AlexYinHan commented on code in PR #23514:
URL: https://github.com/apache/flink/pull/23514#discussion_r1403094467


##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.fs.FSDataOutputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager;
+import org.apache.flink.runtime.checkpoint.filemerging.SegmentFileStateHandle;
+import org.apache.flink.runtime.state.CheckpointStateOutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * A {@link CheckpointStateOutputStream} that writes into a segment of a file and returns a {@link
+ * SegmentFileStateHandle} upon closing. Multiple {@link FileMergingCheckpointStateOutputStream}
+ * objects can reuse the same underlying file, so that the checkpoint files are merged.
+ *
+ * <p><strong>Important</strong>: This implementation is NOT thread-safe. Multiple data streams
+ * multiplexing the same file should NOT write concurrently. Instead, it is expected that only after
+ * one data stream is closed, will other data streams reuse and write to the same underlying file.
+ */
+public class FileMergingCheckpointStateOutputStream extends CheckpointStateOutputStream {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class);
+
+    /**
+     * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link
+     * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files.
+     */
+    public abstract static class FileMergingSnapshotManagerProxy {
+        /**
+         * Provide a physical file.
+         *
+         * @return Output stream and path of the physical file.
+         * @throws IOException if the physical file cannot be created or opened.
+         */
+        public abstract Tuple2<FSDataOutputStream, Path> providePhysicalFile() throws IOException;
+
+        /**
+         * Close the stream and create a {@link SegmentFileStateHandle} for a file segment.
+         *
+         * @param filePath Path of the physical file.
+         * @param startPos Start position of the segment in the physical file.
+         * @param stateSize Size of the segment.
+         * @return The state handle of the segment.
+         * @throws IOException if any exception happens when closing the file.
+         */
+        public abstract SegmentFileStateHandle closeStreamAndCreateStateHandle(
+                Path filePath, long startPos, long stateSize) throws IOException;
+
+        /**
+         * Notify the {@link FileMergingSnapshotManager} that the stream is closed exceptionally.
+         *
+         * @throws IOException if any exception happens when deleting the file.
+         */
+        public abstract void closeStreamExceptionally() throws IOException;
+    }
+
+    private final FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy;
+
+    private volatile boolean closed;
+
+    /** path of the underlying physical file. */
+    private Path filePath;
+
+    /** the stream that writes to the underlying physical file. */
+    private @Nullable FSDataOutputStream outputStream;
+
+    /** start position in the physical file. */
+    private long startPos;
+
+    /** current position relative to startPos. */
+    long curPosRelative = 0;

Review Comment:
   Yes. I have added the above information in the code comments.



##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.fs.FSDataOutputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager;
+import org.apache.flink.runtime.checkpoint.filemerging.SegmentFileStateHandle;
+import org.apache.flink.runtime.state.CheckpointStateOutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * A {@link CheckpointStateOutputStream} that writes into a segment of a file and returns a {@link
+ * SegmentFileStateHandle} upon closing. Multiple {@link FileMergingCheckpointStateOutputStream}
+ * objects can reuse the same underlying file, so that the checkpoint files are merged.
+ *
+ * <p><strong>Important</strong>: This implementation is NOT thread-safe. Multiple data streams
+ * multiplexing the same file should NOT write concurrently. Instead, it is expected that only after
+ * one data stream is closed, will other data streams reuse and write to the same underlying file.
+ */
+public class FileMergingCheckpointStateOutputStream extends CheckpointStateOutputStream {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class);
+
+    /**
+     * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link
+     * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files.
+     */
+    public abstract static class FileMergingSnapshotManagerProxy {

Review Comment:
   Right. I've changed that into an interface.



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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "curcur (via GitHub)" <gi...@apache.org>.
curcur commented on PR #23514:
URL: https://github.com/apache/flink/pull/23514#issuecomment-1892365742

   The PR looks GTM.
   
   1) I left a few comments.
   2) squash the commits.
   3) There are conflicts, resolve them and after turn green, ping me, and I will merge them.


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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "AlexYinHan (via GitHub)" <gi...@apache.org>.
AlexYinHan commented on code in PR #23514:
URL: https://github.com/apache/flink/pull/23514#discussion_r1403094222


##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FsSegmentDataInputStream.java:
##########
@@ -0,0 +1,136 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.core.fs.FSDataInputStream;
+import org.apache.flink.core.fs.FSDataInputStreamWrapper;
+import org.apache.flink.core.fs.WrappingProxyCloseable;
+
+import java.io.IOException;
+
+/**
+ * This class is a {@link org.apache.flink.util.WrappingProxy} for {@link FSDataInputStream} that is
+ * used to read from a file segment. It is opened with a starting position of the file. It treats
+ * the argument of seek(long) as an offset relative to the starting position, rather than an
+ * absolute value.
+ */
+public class FsSegmentDataInputStream extends FSDataInputStreamWrapper
+        implements WrappingProxyCloseable<FSDataInputStream> {
+
+    private final long startingPosition;
+
+    private long endingPosition;
+
+    private long markPosition;
+
+    private long curPosInFile;
+

Review Comment:
   Sure. This can simplify the code for ```FsSegmentDataInputStream```.
   
   Note that, not all implementations of ```FSDataInputStream``` supports mark/reset. Therefore ```FsSegmentDataInputStream#markSupported()``` does not necessary return 'true' now.



##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileStateHandle.java:
##########
@@ -42,7 +42,7 @@ public class FileStateHandle implements StreamStateHandle {
     private final Path filePath;
 
     /** The size of the state in the file. */
-    private final long stateSize;
+    protected final long stateSize;

Review Comment:
   Make sense. ```SegmentFileStateHandle``` now directly implements ```StreamStateHandle```



##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.fs.FSDataOutputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager;
+import org.apache.flink.runtime.checkpoint.filemerging.SegmentFileStateHandle;
+import org.apache.flink.runtime.state.CheckpointStateOutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * A {@link CheckpointStateOutputStream} that writes into a segment of a file and returns a {@link
+ * SegmentFileStateHandle} upon closing. Multiple {@link FileMergingCheckpointStateOutputStream}
+ * objects can reuse the same underlying file, so that the checkpoint files are merged.
+ *
+ * <p><strong>Important</strong>: This implementation is NOT thread-safe. Multiple data streams
+ * multiplexing the same file should NOT write concurrently. Instead, it is expected that only after
+ * one data stream is closed, will other data streams reuse and write to the same underlying file.
+ */
+public class FileMergingCheckpointStateOutputStream extends CheckpointStateOutputStream {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class);
+
+    /**
+     * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link
+     * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files.
+     */
+    public abstract static class FileMergingSnapshotManagerProxy {
+        /**
+         * Provide a physical file.
+         *
+         * @return Output stream and path of the physical file.
+         * @throws IOException if the physical file cannot be created or opened.
+         */
+        public abstract Tuple2<FSDataOutputStream, Path> providePhysicalFile() throws IOException;
+
+        /**
+         * Close the stream and create a {@link SegmentFileStateHandle} for a file segment.
+         *
+         * @param filePath Path of the physical file.
+         * @param startPos Start position of the segment in the physical file.
+         * @param stateSize Size of the segment.
+         * @return The state handle of the segment.
+         * @throws IOException if any exception happens when closing the file.
+         */
+        public abstract SegmentFileStateHandle closeStreamAndCreateStateHandle(
+                Path filePath, long startPos, long stateSize) throws IOException;
+
+        /**
+         * Notify the {@link FileMergingSnapshotManager} that the stream is closed exceptionally.
+         *
+         * @throws IOException if any exception happens when deleting the file.
+         */
+        public abstract void closeStreamExceptionally() throws IOException;
+    }
+
+    private final FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy;
+
+    private volatile boolean closed;
+
+    /** path of the underlying physical file. */
+    private Path filePath;
+
+    /** the stream that writes to the underlying physical file. */
+    private @Nullable FSDataOutputStream outputStream;
+
+    /** start position in the physical file. */
+    private long startPos;
+
+    /** current position relative to startPos. */
+    long curPosRelative = 0;
+
+    /** the buffer for writing to the physical file. */
+    private final byte[] writeBuffer;
+
+    /** current position in the writeBuffer. */
+    int bufferPos;
+
+    public FileMergingCheckpointStateOutputStream(
+            long checkpointID,
+            int bufferSize,
+            FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy) {
+        this.fileMergingSnapshotManagerProxy = fileMergingSnapshotManagerProxy;
+        this.writeBuffer = new byte[bufferSize];
+    }
+
+    /** Assign a physical file to this stream and initialize the outputStream. */
+    private void initializeOutputStream() throws IOException {
+        Tuple2<FSDataOutputStream, Path> streamAndPath =
+                fileMergingSnapshotManagerProxy.providePhysicalFile();
+        outputStream = streamAndPath.f0;
+        startPos = outputStream.getPos();
+        filePath = streamAndPath.f1;
+    }
+
+    @Override
+    public long getPos() throws IOException {
+        // The starting position is not determined until a physical file has been assigned, so
+        // we return the relative value to the starting position in this method
+        return bufferPos + curPosRelative;
+    }
+
+    @Override
+    public void write(int b) throws IOException {
+        if (bufferPos >= writeBuffer.length) {
+            flushToFile();
+        }
+        writeBuffer[bufferPos++] = (byte) b;
+    }
+
+    @Override
+    public void write(byte[] b, int off, int len) throws IOException {
+        if (len < writeBuffer.length) {
+            // copy it into our write buffer first
+            final int remaining = writeBuffer.length - bufferPos;
+            if (len > remaining) {
+                // copy as much as fits
+                System.arraycopy(b, off, writeBuffer, bufferPos, remaining);
+                off += remaining;
+                len -= remaining;
+                bufferPos += remaining;
+
+                // flushToFile the write buffer to make it clear again
+                flushToFile();
+            }
+
+            // copy what is in the buffer
+            System.arraycopy(b, off, writeBuffer, bufferPos, len);
+            bufferPos += len;
+        } else {
+            // flushToFile the current buffer, outputStream is initialized if it is null
+            flushToFile();
+            // write the bytes directly
+            outputStream.write(b, off, len);
+            curPosRelative += len;
+        }
+    }
+
+    @Override
+    public void flush() throws IOException {
+        if (outputStream != null) {
+            flushToFile();
+        }
+    }
+
+    @Override
+    public void sync() throws IOException {
+        if (outputStream != null) {
+            outputStream.sync();
+        }
+    }
+
+    @Nullable
+    @Override
+    public SegmentFileStateHandle closeAndGetHandle() throws IOException {
+        // check if there was nothing ever written
+        if (outputStream == null && bufferPos == 0) {
+            return null;
+        }
+
+        synchronized (this) {
+            if (!closed) {
+                try {
+                    flushToFile();
+
+                    bufferPos = writeBuffer.length;
+
+                    return fileMergingSnapshotManagerProxy.closeStreamAndCreateStateHandle(
+                            filePath, startPos, curPosRelative);
+                } catch (Exception exception) {
+                    fileMergingSnapshotManagerProxy.closeStreamExceptionally();
+
+                    throw new IOException(
+                            "Could not flush to file and close the file system "
+                                    + "output stream to "
+                                    + filePath
+                                    + " in order to obtain the "
+                                    + "stream state handle",
+                            exception);
+                } finally {
+                    closed = true;
+                }
+            } else {
+                throw new IOException("Stream has already been closed and discarded.");
+            }
+        }
+    }
+
+    /**
+     * This method throws no exception if the close fails, but only logs the error. This is to be
+     * consistent with {@link FsCheckpointStreamFactory.FsCheckpointStateOutputStream#close()}.
+     */
+    @Override
+    public void close() {
+        if (!closed) {
+            closed = true;
+
+            // make sure write requests need to go to 'flushToFile()' where they recognized
+            // that the stream is closed
+            bufferPos = writeBuffer.length;
+            try {
+                fileMergingSnapshotManagerProxy.closeStreamExceptionally();
+            } catch (Throwable throwable) {
+                LOG.warn("Could not close the state stream for {}.", filePath, throwable);
+            }
+        }
+    }
+
+    public void flushToFile() throws IOException {
+        if (!closed) {
+            if (outputStream == null) {
+                initializeOutputStream();
+            }
+
+            if (bufferPos > 0) {
+                outputStream.write(writeBuffer, 0, bufferPos);
+                curPosRelative += bufferPos;
+                bufferPos = 0;
+            }
+        } else {
+            throw new IOException("closed");

Review Comment:
   Done.



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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "curcur (via GitHub)" <gi...@apache.org>.
curcur commented on PR #23514:
URL: https://github.com/apache/flink/pull/23514#issuecomment-1868496305

   CI seems Failed with "[99d7b97](https://github.com/apache/flink/pull/23514/commits/99d7b97cd5844ec6362b30d8f9134509b72cb647)"


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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "AlexYinHan (via GitHub)" <gi...@apache.org>.
AlexYinHan commented on PR #23514:
URL: https://github.com/apache/flink/pull/23514#issuecomment-1824035787

   Thanks @fredia and @Zakelly for your comments. Sorry for the late reply. I have addressed your comments. Would you please take another look?


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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "AlexYinHan (via GitHub)" <gi...@apache.org>.
AlexYinHan commented on PR #23514:
URL: https://github.com/apache/flink/pull/23514#issuecomment-1868986046

   @flinkbot  run azure


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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "curcur (via GitHub)" <gi...@apache.org>.
curcur commented on code in PR #23514:
URL: https://github.com/apache/flink/pull/23514#discussion_r1452491216


##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/StreamTask.java:
##########
@@ -517,24 +517,27 @@ protected StreamTask(
     private CheckpointStorageAccess applyFileMergingCheckpoint(
             CheckpointStorageAccess checkpointStorageAccess,
             FileMergingSnapshotManager fileMergingSnapshotManager) {
-        if (fileMergingSnapshotManager == null) {
-            return checkpointStorageAccess;
-        }
-
-        try {
-            CheckpointStorageWorkerView mergingCheckpointStorageAccess =
-                    checkpointStorageAccess.toFileMergingStorage(
-                            fileMergingSnapshotManager, environment);
-            return (CheckpointStorageAccess) mergingCheckpointStorageAccess;
-        } catch (IOException e) {
-            LOG.warn(
-                    "Initiating FsMergingCheckpointStorageAccess failed"
-                            + "with exception: {}, falling back to original checkpoint storage access {}.",
-                    e.getMessage(),
-                    checkpointStorageAccess.getClass(),
-                    e);
-            return checkpointStorageAccess;
-        }
+        // TODO (FLINK-32440): enable FileMergingCheckpoint by configuration
+        return checkpointStorageAccess;
+        //        if (fileMergingSnapshotManager == null) {
+        //            return checkpointStorageAccess;
+        //        }
+        //
+        //        try {
+        //            CheckpointStorageWorkerView mergingCheckpointStorageAccess =
+        //                    checkpointStorageAccess.toFileMergingStorage(
+        //                            fileMergingSnapshotManager, environment);
+        //            return (CheckpointStorageAccess) mergingCheckpointStorageAccess;
+        //        } catch (IOException e) {
+        //            LOG.warn(
+        //                    "Initiating FsMergingCheckpointStorageAccess failed"
+        //                            + "with exception: {}, falling back to original checkpoint
+        // storage access {}.",
+        //                    e.getMessage(),
+        //                    checkpointStorageAccess.getClass(),
+        //                    e);
+        //            return checkpointStorageAccess;
+        //        }

Review Comment:
   Can not leave code commented like this. Remove them if they are not needed.



##########
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/filemerging/EmptySegmentFileStateHandle.java:
##########
@@ -0,0 +1,47 @@
+/*
+ * 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.flink.runtime.checkpoint.filemerging;
+
+import org.apache.flink.core.fs.FSDataInputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.state.CheckpointedStateScope;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+
+/** An empty {@link SegmentFileStateHandle} that is only used as a placeholder. */
+public class EmptySegmentFileStateHandle extends SegmentFileStateHandle {

Review Comment:
   Is `EmptySegmentFileStateHandle` used in this PR?
   
   If not, please remove it.



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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "Zakelly (via GitHub)" <gi...@apache.org>.
Zakelly commented on code in PR #23514:
URL: https://github.com/apache/flink/pull/23514#discussion_r1415294769


##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.fs.FSDataOutputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager;
+import org.apache.flink.runtime.checkpoint.filemerging.SegmentFileStateHandle;
+import org.apache.flink.runtime.state.CheckpointStateOutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * A {@link CheckpointStateOutputStream} that writes into a segment of a file and returns a {@link
+ * SegmentFileStateHandle} upon closing. Multiple {@link FileMergingCheckpointStateOutputStream}
+ * objects can reuse the same underlying file, so that the checkpoint files are merged.
+ *
+ * <p><strong>Important</strong>: This implementation is NOT thread-safe. Multiple data streams
+ * multiplexing the same file should NOT write concurrently. Instead, it is expected that only after
+ * one data stream is closed, will other data streams reuse and write to the same underlying file.
+ */
+public class FileMergingCheckpointStateOutputStream extends CheckpointStateOutputStream {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class);
+
+    /**
+     * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link
+     * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files.
+     */
+    public abstract static class FileMergingSnapshotManagerProxy {
+        /**
+         * Provide a physical file.
+         *
+         * @return Output stream and path of the physical file.
+         * @throws IOException if the physical file cannot be created or opened.
+         */
+        public abstract Tuple2<FSDataOutputStream, Path> providePhysicalFile() throws IOException;
+
+        /**
+         * Close the stream and create a {@link SegmentFileStateHandle} for a file segment.
+         *
+         * @param filePath Path of the physical file.
+         * @param startPos Start position of the segment in the physical file.
+         * @param stateSize Size of the segment.
+         * @return The state handle of the segment.
+         * @throws IOException if any exception happens when closing the file.
+         */
+        public abstract SegmentFileStateHandle closeStreamAndCreateStateHandle(
+                Path filePath, long startPos, long stateSize) throws IOException;
+
+        /**
+         * Notify the {@link FileMergingSnapshotManager} that the stream is closed exceptionally.
+         *
+         * @throws IOException if any exception happens when deleting the file.
+         */
+        public abstract void closeStreamExceptionally() throws IOException;
+    }
+
+    private final FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy;
+
+    private volatile boolean closed;
+
+    /** path of the underlying physical file. */
+    private Path filePath;
+
+    /** the stream that writes to the underlying physical file. */
+    private @Nullable FSDataOutputStream outputStream;
+
+    /** start position in the physical file. */
+    private long startPos;
+
+    /** current position relative to startPos. */
+    long curPosRelative = 0;
+
+    /** the buffer for writing to the physical file. */
+    private final byte[] writeBuffer;
+
+    /** current position in the writeBuffer. */
+    int bufferPos;
+
+    public FileMergingCheckpointStateOutputStream(
+            long checkpointID,
+            int bufferSize,
+            FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy) {
+        this.fileMergingSnapshotManagerProxy = fileMergingSnapshotManagerProxy;
+        this.writeBuffer = new byte[bufferSize];
+    }
+
+    /** Assign a physical file to this stream and initialize the outputStream. */
+    private void initializeOutputStream() throws IOException {
+        Tuple2<FSDataOutputStream, Path> streamAndPath =
+                fileMergingSnapshotManagerProxy.providePhysicalFile();
+        outputStream = streamAndPath.f0;
+        startPos = outputStream.getPos();
+        filePath = streamAndPath.f1;
+    }
+
+    @Override
+    public long getPos() throws IOException {
+        // The starting position is not determined until a physical file has been assigned, so
+        // we return the relative value to the starting position in this method
+        return bufferPos + curPosRelative;
+    }
+
+    @Override
+    public void write(int b) throws IOException {
+        if (bufferPos >= writeBuffer.length) {
+            flushToFile();
+        }
+        writeBuffer[bufferPos++] = (byte) b;
+    }
+
+    @Override
+    public void write(byte[] b, int off, int len) throws IOException {
+        if (len < writeBuffer.length) {
+            // copy it into our write buffer first
+            final int remaining = writeBuffer.length - bufferPos;
+            if (len > remaining) {
+                // copy as much as fits
+                System.arraycopy(b, off, writeBuffer, bufferPos, remaining);
+                off += remaining;
+                len -= remaining;
+                bufferPos += remaining;
+
+                // flushToFile the write buffer to make it clear again
+                flushToFile();
+            }
+
+            // copy what is in the buffer
+            System.arraycopy(b, off, writeBuffer, bufferPos, len);
+            bufferPos += len;
+        } else {
+            // flushToFile the current buffer, outputStream is initialized if it is null
+            flushToFile();
+            // write the bytes directly
+            outputStream.write(b, off, len);
+            curPosRelative += len;
+        }
+    }
+
+    @Override
+    public void flush() throws IOException {
+        if (outputStream != null) {
+            flushToFile();
+        }
+    }
+
+    @Override
+    public void sync() throws IOException {
+        if (outputStream != null) {
+            outputStream.sync();
+        }
+    }
+
+    @Nullable
+    @Override
+    public SegmentFileStateHandle closeAndGetHandle() throws IOException {
+        // check if there was nothing ever written
+        if (outputStream == null && bufferPos == 0) {
+            return null;
+        }
+
+        synchronized (this) {
+            if (!closed) {
+                try {
+                    flushToFile();

Review Comment:
   If so, we'd better note this down since it violates the behavior of the base interface.
   
   And for calling ```outputStream.sync()``` in ```closeAndGetHandle()```, I think it has been already covered by ```returnPhysicalFileForNextReuse```, WDYT?



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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "AlexYinHan (via GitHub)" <gi...@apache.org>.
AlexYinHan commented on PR #23514:
URL: https://github.com/apache/flink/pull/23514#issuecomment-1903992993

   @curcur I have addressed your comments by removing the unused codes and squashing the commits. The PR is now free of conflicts and has passed the CI tests. PTAL.


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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "AlexYinHan (via GitHub)" <gi...@apache.org>.
AlexYinHan commented on code in PR #23514:
URL: https://github.com/apache/flink/pull/23514#discussion_r1366799252


##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.fs.FSDataOutputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager;
+import org.apache.flink.runtime.checkpoint.filemerging.SegmentFileStateHandle;
+import org.apache.flink.runtime.state.CheckpointStateOutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * A {@link CheckpointStateOutputStream} that writes into a segment of a file and returns a {@link
+ * SegmentFileStateHandle} upon closing. Multiple {@link FileMergingCheckpointStateOutputStream}
+ * objects can reuse the same underlying file, so that the checkpoint files are merged.
+ *
+ * <p><strong>Important</strong>: This implementation is NOT thread-safe. Multiple data streams
+ * multiplexing the same file should NOT write concurrently. Instead, it is expected that only after
+ * one data stream is closed, will other data streams reuse and write to the same underlying file.
+ */
+public class FileMergingCheckpointStateOutputStream extends CheckpointStateOutputStream {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class);
+
+    /**
+     * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link
+     * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files.
+     */
+    public abstract static class FileMergingSnapshotManagerProxy {
+        /**
+         * Provide a physical file.
+         *
+         * @return Output stream and path of the physical file.
+         * @throws IOException if the physical file cannot be created or opened.
+         */
+        public abstract Tuple2<FSDataOutputStream, Path> providePhysicalFile() throws IOException;
+
+        /**
+         * Close the stream and create a {@link SegmentFileStateHandle} for a file segment.
+         *
+         * @param filePath Path of the physical file.
+         * @param startPos Start position of the segment in the physical file.
+         * @param stateSize Size of the segment.
+         * @return The state handle of the segment.
+         * @throws IOException if any exception happens when closing the file.
+         */
+        public abstract SegmentFileStateHandle closeStreamAndCreateStateHandle(
+                Path filePath, long startPos, long stateSize) throws IOException;
+
+        /**
+         * Notify the {@link FileMergingSnapshotManager} that the stream is closed exceptionally.
+         *
+         * @throws IOException if any exception happens when deleting the file.
+         */
+        public abstract void closeStreamExceptionally() throws IOException;
+    }
+
+    private final FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy;
+
+    private volatile boolean closed;
+
+    /** path of the underlying physical file. */
+    private Path filePath;
+
+    /** the stream that writes to the underlying physical file. */
+    private @Nullable FSDataOutputStream outputStream;
+
+    /** start position in the physical file. */
+    private long startPos;
+
+    /** current position relative to startPos. */
+    long curPosRelative = 0;
+
+    /** the buffer for writing to the physical file. */
+    private final byte[] writeBuffer;
+
+    /** current position in the writeBuffer. */
+    int bufferPos;
+
+    public FileMergingCheckpointStateOutputStream(
+            long checkpointID,
+            int bufferSize,
+            FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy) {
+        this.fileMergingSnapshotManagerProxy = fileMergingSnapshotManagerProxy;
+        this.writeBuffer = new byte[bufferSize];
+    }
+
+    /** Assign a physical file to this stream and initialize the outputStream. */
+    private void initializeOutputStream() throws IOException {
+        Tuple2<FSDataOutputStream, Path> streamAndPath =
+                fileMergingSnapshotManagerProxy.providePhysicalFile();
+        outputStream = streamAndPath.f0;
+        startPos = outputStream.getPos();
+        filePath = streamAndPath.f1;
+    }
+
+    @Override
+    public long getPos() throws IOException {
+        // The starting position is not determined until a physical file has been assigned, so
+        // we return the relative value to the starting position in this method
+        return bufferPos + curPosRelative;
+    }
+
+    @Override
+    public void write(int b) throws IOException {
+        if (bufferPos >= writeBuffer.length) {
+            flushToFile();
+        }
+        writeBuffer[bufferPos++] = (byte) b;
+    }
+
+    @Override
+    public void write(byte[] b, int off, int len) throws IOException {
+        if (len < writeBuffer.length) {
+            // copy it into our write buffer first
+            final int remaining = writeBuffer.length - bufferPos;
+            if (len > remaining) {
+                // copy as much as fits
+                System.arraycopy(b, off, writeBuffer, bufferPos, remaining);
+                off += remaining;
+                len -= remaining;
+                bufferPos += remaining;
+
+                // flushToFile the write buffer to make it clear again
+                flushToFile();
+            }
+
+            // copy what is in the buffer
+            System.arraycopy(b, off, writeBuffer, bufferPos, len);
+            bufferPos += len;
+        } else {
+            // flushToFile the current buffer, outputStream is initialized if it is null
+            flushToFile();
+            // write the bytes directly
+            outputStream.write(b, off, len);
+            curPosRelative += len;
+        }
+    }
+
+    @Override
+    public void flush() throws IOException {
+        if (outputStream != null) {
+            flushToFile();
+        }
+    }
+
+    @Override
+    public void sync() throws IOException {
+        if (outputStream != null) {
+            outputStream.sync();
+        }
+    }
+
+    @Nullable
+    @Override
+    public SegmentFileStateHandle closeAndGetHandle() throws IOException {
+        // check if there was nothing ever written
+        if (outputStream == null && bufferPos == 0) {
+            return null;
+        }
+
+        synchronized (this) {
+            if (!closed) {
+                try {
+                    flushToFile();
+
+                    bufferPos = writeBuffer.length;
+
+                    return fileMergingSnapshotManagerProxy.closeStreamAndCreateStateHandle(
+                            filePath, startPos, curPosRelative);
+                } catch (Exception exception) {
+                    fileMergingSnapshotManagerProxy.closeStreamExceptionally();
+
+                    throw new IOException(
+                            "Could not flush to file and close the file system "
+                                    + "output stream to "
+                                    + filePath
+                                    + " in order to obtain the "
+                                    + "stream state handle",
+                            exception);
+                } finally {
+                    closed = true;
+                }
+            } else {
+                throw new IOException("Stream has already been closed and discarded.");
+            }
+        }
+    }
+
+    /**
+     * This method throws no exception if the close fails, but only logs the error. This is to be
+     * consistent with {@link FsCheckpointStreamFactory.FsCheckpointStateOutputStream#close()}.
+     */
+    @Override
+    public void close() {
+        if (!closed) {
+            closed = true;
+
+            // make sure write requests need to go to 'flushToFile()' where they recognized
+            // that the stream is closed
+            bufferPos = writeBuffer.length;
+            try {
+                fileMergingSnapshotManagerProxy.closeStreamExceptionally();

Review Comment:
   Answer to the first question: Yes. 
   
   As declared in ```CheckpointStateOutputStream```, the ```close()``` method is intended to be the "unsuccessful close". For a "successful close",  you should call ```closeAndGetHandle()```.



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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "AlexYinHan (via GitHub)" <gi...@apache.org>.
AlexYinHan commented on code in PR #23514:
URL: https://github.com/apache/flink/pull/23514#discussion_r1402954318


##########
flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/filemerging/FileMergingSnapshotManagerTest.java:
##########
@@ -18,19 +18,28 @@
 package org.apache.flink.runtime.checkpoint.filemerging;
 
 import org.apache.flink.api.common.TaskInfo;
+import org.apache.flink.core.fs.CloseableRegistry;
+import org.apache.flink.core.fs.FSDataInputStream;
 import org.apache.flink.core.fs.FileSystem;
 import org.apache.flink.core.fs.Path;
 import org.apache.flink.core.fs.local.LocalFileSystem;
 import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager.SubtaskKey;
 import org.apache.flink.runtime.jobgraph.OperatorID;
 import org.apache.flink.runtime.state.CheckpointedStateScope;
 import org.apache.flink.runtime.state.filesystem.AbstractFsCheckpointStorageAccess;
+import org.apache.flink.runtime.state.filesystem.FileMergingCheckpointStateOutputStream;
 
+import org.junit.jupiter.api.Assertions;

Review Comment:
   Thanks for the reminder. I have replaced Assertions with AssertJ.



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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "AlexYinHan (via GitHub)" <gi...@apache.org>.
AlexYinHan commented on code in PR #23514:
URL: https://github.com/apache/flink/pull/23514#discussion_r1401882337


##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.fs.FSDataOutputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager;
+import org.apache.flink.runtime.checkpoint.filemerging.SegmentFileStateHandle;
+import org.apache.flink.runtime.state.CheckpointStateOutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * A {@link CheckpointStateOutputStream} that writes into a segment of a file and returns a {@link
+ * SegmentFileStateHandle} upon closing. Multiple {@link FileMergingCheckpointStateOutputStream}
+ * objects can reuse the same underlying file, so that the checkpoint files are merged.
+ *
+ * <p><strong>Important</strong>: This implementation is NOT thread-safe. Multiple data streams
+ * multiplexing the same file should NOT write concurrently. Instead, it is expected that only after
+ * one data stream is closed, will other data streams reuse and write to the same underlying file.
+ */
+public class FileMergingCheckpointStateOutputStream extends CheckpointStateOutputStream {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class);
+
+    /**
+     * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link
+     * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files.
+     */
+    public abstract static class FileMergingSnapshotManagerProxy {
+        /**
+         * Provide a physical file.
+         *
+         * @return Output stream and path of the physical file.
+         * @throws IOException if the physical file cannot be created or opened.
+         */
+        public abstract Tuple2<FSDataOutputStream, Path> providePhysicalFile() throws IOException;
+
+        /**
+         * Close the stream and create a {@link SegmentFileStateHandle} for a file segment.
+         *
+         * @param filePath Path of the physical file.
+         * @param startPos Start position of the segment in the physical file.
+         * @param stateSize Size of the segment.
+         * @return The state handle of the segment.
+         * @throws IOException if any exception happens when closing the file.
+         */
+        public abstract SegmentFileStateHandle closeStreamAndCreateStateHandle(
+                Path filePath, long startPos, long stateSize) throws IOException;
+
+        /**
+         * Notify the {@link FileMergingSnapshotManager} that the stream is closed exceptionally.
+         *
+         * @throws IOException if any exception happens when deleting the file.
+         */
+        public abstract void closeStreamExceptionally() throws IOException;
+    }
+
+    private final FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy;
+
+    private volatile boolean closed;
+
+    /** path of the underlying physical file. */
+    private Path filePath;
+
+    /** the stream that writes to the underlying physical file. */
+    private @Nullable FSDataOutputStream outputStream;
+
+    /** start position in the physical file. */
+    private long startPos;
+
+    /** current position relative to startPos. */
+    long curPosRelative = 0;
+
+    /** the buffer for writing to the physical file. */
+    private final byte[] writeBuffer;
+
+    /** current position in the writeBuffer. */
+    int bufferPos;
+
+    public FileMergingCheckpointStateOutputStream(
+            long checkpointID,
+            int bufferSize,
+            FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy) {
+        this.fileMergingSnapshotManagerProxy = fileMergingSnapshotManagerProxy;
+        this.writeBuffer = new byte[bufferSize];
+    }
+
+    /** Assign a physical file to this stream and initialize the outputStream. */
+    private void initializeOutputStream() throws IOException {
+        Tuple2<FSDataOutputStream, Path> streamAndPath =
+                fileMergingSnapshotManagerProxy.providePhysicalFile();
+        outputStream = streamAndPath.f0;
+        startPos = outputStream.getPos();
+        filePath = streamAndPath.f1;
+    }
+
+    @Override
+    public long getPos() throws IOException {
+        // The starting position is not determined until a physical file has been assigned, so
+        // we return the relative value to the starting position in this method
+        return bufferPos + curPosRelative;
+    }
+
+    @Override
+    public void write(int b) throws IOException {
+        if (bufferPos >= writeBuffer.length) {
+            flushToFile();
+        }
+        writeBuffer[bufferPos++] = (byte) b;
+    }
+
+    @Override
+    public void write(byte[] b, int off, int len) throws IOException {
+        if (len < writeBuffer.length) {
+            // copy it into our write buffer first
+            final int remaining = writeBuffer.length - bufferPos;
+            if (len > remaining) {
+                // copy as much as fits
+                System.arraycopy(b, off, writeBuffer, bufferPos, remaining);
+                off += remaining;
+                len -= remaining;
+                bufferPos += remaining;
+
+                // flushToFile the write buffer to make it clear again
+                flushToFile();
+            }
+
+            // copy what is in the buffer
+            System.arraycopy(b, off, writeBuffer, bufferPos, len);
+            bufferPos += len;
+        } else {
+            // flushToFile the current buffer, outputStream is initialized if it is null
+            flushToFile();
+            // write the bytes directly
+            outputStream.write(b, off, len);
+            curPosRelative += len;
+        }
+    }
+
+    @Override
+    public void flush() throws IOException {
+        if (outputStream != null) {
+            flushToFile();
+        }
+    }
+
+    @Override
+    public void sync() throws IOException {
+        if (outputStream != null) {
+            outputStream.sync();
+        }
+    }
+
+    @Nullable
+    @Override
+    public SegmentFileStateHandle closeAndGetHandle() throws IOException {
+        // check if there was nothing ever written
+        if (outputStream == null && bufferPos == 0) {
+            return null;
+        }
+
+        synchronized (this) {
+            if (!closed) {
+                try {
+                    flushToFile();

Review Comment:
   This class behaves similarly to ```FsCheckpointStateOutputStream```, which never calls ```outputStream.flush()```, but relies on ```outputStream.close()``` to ensure the persistency of data.
   
   So, for ```flush()``` and ```sync()```, maybe we do not need to call ```outputStream.close()```.
   
   Whereas we do need to think about ```closeAndGetHandle()```. I think we should call ```outputStream.sync()```  before returning the ```SegmentFileStateHandle``` instance, to make sure the file segment is visible. WDYT?



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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "AlexYinHan (via GitHub)" <gi...@apache.org>.
AlexYinHan commented on code in PR #23514:
URL: https://github.com/apache/flink/pull/23514#discussion_r1418795527


##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.fs.FSDataOutputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager;
+import org.apache.flink.runtime.checkpoint.filemerging.SegmentFileStateHandle;
+import org.apache.flink.runtime.state.CheckpointStateOutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * A {@link CheckpointStateOutputStream} that writes into a segment of a file and returns a {@link
+ * SegmentFileStateHandle} upon closing. Multiple {@link FileMergingCheckpointStateOutputStream}
+ * objects can reuse the same underlying file, so that the checkpoint files are merged.
+ *
+ * <p><strong>Important</strong>: This implementation is NOT thread-safe. Multiple data streams
+ * multiplexing the same file should NOT write concurrently. Instead, it is expected that only after
+ * one data stream is closed, will other data streams reuse and write to the same underlying file.
+ */
+public class FileMergingCheckpointStateOutputStream extends CheckpointStateOutputStream {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class);
+
+    /**
+     * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link
+     * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files.
+     */
+    public abstract static class FileMergingSnapshotManagerProxy {
+        /**
+         * Provide a physical file.
+         *
+         * @return Output stream and path of the physical file.
+         * @throws IOException if the physical file cannot be created or opened.
+         */
+        public abstract Tuple2<FSDataOutputStream, Path> providePhysicalFile() throws IOException;
+
+        /**
+         * Close the stream and create a {@link SegmentFileStateHandle} for a file segment.
+         *
+         * @param filePath Path of the physical file.
+         * @param startPos Start position of the segment in the physical file.
+         * @param stateSize Size of the segment.
+         * @return The state handle of the segment.
+         * @throws IOException if any exception happens when closing the file.
+         */
+        public abstract SegmentFileStateHandle closeStreamAndCreateStateHandle(
+                Path filePath, long startPos, long stateSize) throws IOException;
+
+        /**
+         * Notify the {@link FileMergingSnapshotManager} that the stream is closed exceptionally.
+         *
+         * @throws IOException if any exception happens when deleting the file.
+         */
+        public abstract void closeStreamExceptionally() throws IOException;
+    }
+
+    private final FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy;
+
+    private volatile boolean closed;
+
+    /** path of the underlying physical file. */
+    private Path filePath;
+
+    /** the stream that writes to the underlying physical file. */
+    private @Nullable FSDataOutputStream outputStream;
+
+    /** start position in the physical file. */
+    private long startPos;
+
+    /** current position relative to startPos. */
+    long curPosRelative = 0;
+
+    /** the buffer for writing to the physical file. */
+    private final byte[] writeBuffer;
+
+    /** current position in the writeBuffer. */
+    int bufferPos;
+
+    public FileMergingCheckpointStateOutputStream(
+            long checkpointID,
+            int bufferSize,
+            FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy) {
+        this.fileMergingSnapshotManagerProxy = fileMergingSnapshotManagerProxy;
+        this.writeBuffer = new byte[bufferSize];
+    }
+
+    /** Assign a physical file to this stream and initialize the outputStream. */
+    private void initializeOutputStream() throws IOException {
+        Tuple2<FSDataOutputStream, Path> streamAndPath =
+                fileMergingSnapshotManagerProxy.providePhysicalFile();
+        outputStream = streamAndPath.f0;
+        startPos = outputStream.getPos();
+        filePath = streamAndPath.f1;
+    }
+
+    @Override
+    public long getPos() throws IOException {
+        // The starting position is not determined until a physical file has been assigned, so
+        // we return the relative value to the starting position in this method
+        return bufferPos + curPosRelative;
+    }
+
+    @Override
+    public void write(int b) throws IOException {
+        if (bufferPos >= writeBuffer.length) {
+            flushToFile();
+        }
+        writeBuffer[bufferPos++] = (byte) b;
+    }
+
+    @Override
+    public void write(byte[] b, int off, int len) throws IOException {
+        if (len < writeBuffer.length) {
+            // copy it into our write buffer first
+            final int remaining = writeBuffer.length - bufferPos;
+            if (len > remaining) {
+                // copy as much as fits
+                System.arraycopy(b, off, writeBuffer, bufferPos, remaining);
+                off += remaining;
+                len -= remaining;
+                bufferPos += remaining;
+
+                // flushToFile the write buffer to make it clear again
+                flushToFile();
+            }
+
+            // copy what is in the buffer
+            System.arraycopy(b, off, writeBuffer, bufferPos, len);
+            bufferPos += len;
+        } else {
+            // flushToFile the current buffer, outputStream is initialized if it is null
+            flushToFile();
+            // write the bytes directly
+            outputStream.write(b, off, len);
+            curPosRelative += len;
+        }
+    }
+
+    @Override
+    public void flush() throws IOException {
+        if (outputStream != null) {
+            flushToFile();
+        }
+    }
+
+    @Override
+    public void sync() throws IOException {
+        if (outputStream != null) {
+            outputStream.sync();
+        }
+    }
+
+    @Nullable
+    @Override
+    public SegmentFileStateHandle closeAndGetHandle() throws IOException {
+        // check if there was nothing ever written
+        if (outputStream == null && bufferPos == 0) {
+            return null;
+        }
+
+        synchronized (this) {
+            if (!closed) {
+                try {
+                    flushToFile();

Review Comment:
   Not sure if this violates the interface behavior.
   
   - `flush` makes no promise for the data persistence. According to its document comments, "A completed flush does not mean that the data is necessarily persistent."
   - as for 'sync', both `FsCheckpointStateOutputStream` and `FileMergingCheckpointStateOutputStream` calls `outputStream.sync` to ensure the the data is persistent.
   
   As i understand it, there seems to be no violation 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@flink.apache.org

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "fredia (via GitHub)" <gi...@apache.org>.
fredia commented on code in PR #23514:
URL: https://github.com/apache/flink/pull/23514#discussion_r1366385484


##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.fs.FSDataOutputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager;
+import org.apache.flink.runtime.checkpoint.filemerging.SegmentFileStateHandle;
+import org.apache.flink.runtime.state.CheckpointStateOutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * A {@link CheckpointStateOutputStream} that writes into a segment of a file and returns a {@link
+ * SegmentFileStateHandle} upon closing. Multiple {@link FileMergingCheckpointStateOutputStream}
+ * objects can reuse the same underlying file, so that the checkpoint files are merged.
+ *
+ * <p><strong>Important</strong>: This implementation is NOT thread-safe. Multiple data streams
+ * multiplexing the same file should NOT write concurrently. Instead, it is expected that only after
+ * one data stream is closed, will other data streams reuse and write to the same underlying file.
+ */
+public class FileMergingCheckpointStateOutputStream extends CheckpointStateOutputStream {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class);
+
+    /**
+     * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link
+     * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files.
+     */
+    public abstract static class FileMergingSnapshotManagerProxy {
+        /**
+         * Provide a physical file.
+         *
+         * @return Output stream and path of the physical file.
+         * @throws IOException if the physical file cannot be created or opened.
+         */
+        public abstract Tuple2<FSDataOutputStream, Path> providePhysicalFile() throws IOException;
+
+        /**
+         * Close the stream and create a {@link SegmentFileStateHandle} for a file segment.
+         *
+         * @param filePath Path of the physical file.
+         * @param startPos Start position of the segment in the physical file.
+         * @param stateSize Size of the segment.
+         * @return The state handle of the segment.
+         * @throws IOException if any exception happens when closing the file.
+         */
+        public abstract SegmentFileStateHandle closeStreamAndCreateStateHandle(
+                Path filePath, long startPos, long stateSize) throws IOException;
+
+        /**
+         * Notify the {@link FileMergingSnapshotManager} that the stream is closed exceptionally.
+         *
+         * @throws IOException if any exception happens when deleting the file.
+         */
+        public abstract void closeStreamExceptionally() throws IOException;
+    }
+
+    private final FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy;
+
+    private volatile boolean closed;
+
+    /** path of the underlying physical file. */
+    private Path filePath;
+
+    /** the stream that writes to the underlying physical file. */
+    private @Nullable FSDataOutputStream outputStream;
+
+    /** start position in the physical file. */
+    private long startPos;
+
+    /** current position relative to startPos. */
+    long curPosRelative = 0;
+
+    /** the buffer for writing to the physical file. */
+    private final byte[] writeBuffer;
+
+    /** current position in the writeBuffer. */
+    int bufferPos;
+
+    public FileMergingCheckpointStateOutputStream(
+            long checkpointID,
+            int bufferSize,
+            FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy) {
+        this.fileMergingSnapshotManagerProxy = fileMergingSnapshotManagerProxy;
+        this.writeBuffer = new byte[bufferSize];
+    }
+
+    /** Assign a physical file to this stream and initialize the outputStream. */
+    private void initializeOutputStream() throws IOException {
+        Tuple2<FSDataOutputStream, Path> streamAndPath =
+                fileMergingSnapshotManagerProxy.providePhysicalFile();
+        outputStream = streamAndPath.f0;
+        startPos = outputStream.getPos();
+        filePath = streamAndPath.f1;
+    }
+
+    @Override
+    public long getPos() throws IOException {
+        // The starting position is not determined until a physical file has been assigned, so
+        // we return the relative value to the starting position in this method
+        return bufferPos + curPosRelative;
+    }
+
+    @Override
+    public void write(int b) throws IOException {
+        if (bufferPos >= writeBuffer.length) {
+            flushToFile();
+        }
+        writeBuffer[bufferPos++] = (byte) b;
+    }
+
+    @Override
+    public void write(byte[] b, int off, int len) throws IOException {
+        if (len < writeBuffer.length) {
+            // copy it into our write buffer first
+            final int remaining = writeBuffer.length - bufferPos;
+            if (len > remaining) {
+                // copy as much as fits
+                System.arraycopy(b, off, writeBuffer, bufferPos, remaining);
+                off += remaining;
+                len -= remaining;
+                bufferPos += remaining;
+
+                // flushToFile the write buffer to make it clear again
+                flushToFile();
+            }
+
+            // copy what is in the buffer
+            System.arraycopy(b, off, writeBuffer, bufferPos, len);
+            bufferPos += len;
+        } else {
+            // flushToFile the current buffer, outputStream is initialized if it is null
+            flushToFile();
+            // write the bytes directly
+            outputStream.write(b, off, len);
+            curPosRelative += len;
+        }
+    }
+
+    @Override
+    public void flush() throws IOException {
+        if (outputStream != null) {
+            flushToFile();
+        }
+    }
+
+    @Override
+    public void sync() throws IOException {
+        if (outputStream != null) {
+            outputStream.sync();
+        }
+    }
+
+    @Nullable
+    @Override
+    public SegmentFileStateHandle closeAndGetHandle() throws IOException {
+        // check if there was nothing ever written
+        if (outputStream == null && bufferPos == 0) {
+            return null;
+        }
+
+        synchronized (this) {
+            if (!closed) {
+                try {
+                    flushToFile();
+
+                    bufferPos = writeBuffer.length;
+
+                    return fileMergingSnapshotManagerProxy.closeStreamAndCreateStateHandle(
+                            filePath, startPos, curPosRelative);
+                } catch (Exception exception) {
+                    fileMergingSnapshotManagerProxy.closeStreamExceptionally();
+
+                    throw new IOException(
+                            "Could not flush to file and close the file system "
+                                    + "output stream to "
+                                    + filePath
+                                    + " in order to obtain the "
+                                    + "stream state handle",
+                            exception);
+                } finally {
+                    closed = true;
+                }
+            } else {
+                throw new IOException("Stream has already been closed and discarded.");
+            }
+        }
+    }
+
+    /**
+     * This method throws no exception if the close fails, but only logs the error. This is to be
+     * consistent with {@link FsCheckpointStreamFactory.FsCheckpointStateOutputStream#close()}.
+     */
+    @Override
+    public void close() {
+        if (!closed) {
+            closed = true;
+
+            // make sure write requests need to go to 'flushToFile()' where they recognized
+            // that the stream is closed
+            bufferPos = writeBuffer.length;
+            try {
+                fileMergingSnapshotManagerProxy.closeStreamExceptionally();

Review Comment:
   Are all `close()` calls exceptions? How about renaming `closeStreamExceptionally()`?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/filemerging/FileMergingSnapshotManagerBase.java:
##########
@@ -206,6 +213,64 @@ protected PhysicalFile createPhysicalFile(SubtaskKey subtaskKey, CheckpointedSta
                 "Could not open output stream for state file merging.", latestException);
     }
 
+    @Override
+    public FileMergingCheckpointStateOutputStream createCheckpointStateOutputStream(

Review Comment:
   Where `FileMergingCheckpointStateOutputStream` will be used?
   I guess we should add `createTaskOwnedStateStream()`  in `FsMergingCheckpointStorageAccess`, and call `createCheckpointStateOutputStream()`, WDYT?



##########
flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/filemerging/FileMergingSnapshotManagerTest.java:
##########
@@ -18,19 +18,28 @@
 package org.apache.flink.runtime.checkpoint.filemerging;
 
 import org.apache.flink.api.common.TaskInfo;
+import org.apache.flink.core.fs.CloseableRegistry;
+import org.apache.flink.core.fs.FSDataInputStream;
 import org.apache.flink.core.fs.FileSystem;
 import org.apache.flink.core.fs.Path;
 import org.apache.flink.core.fs.local.LocalFileSystem;
 import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager.SubtaskKey;
 import org.apache.flink.runtime.jobgraph.OperatorID;
 import org.apache.flink.runtime.state.CheckpointedStateScope;
 import org.apache.flink.runtime.state.filesystem.AbstractFsCheckpointStorageAccess;
+import org.apache.flink.runtime.state.filesystem.FileMergingCheckpointStateOutputStream;
 
+import org.junit.jupiter.api.Assertions;

Review Comment:
   It‘s better to use AssertJ instead of Assertions.
   
   https://flink.apache.org/how-to-contribute/code-style-and-quality-common/#:~:text=Testing-,%23,-Tooling



##########
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/filemerging/SegmentFileStateHandle.java:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.flink.runtime.checkpoint.filemerging;
+
+import org.apache.flink.core.fs.FSDataInputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.state.CheckpointedStateScope;
+import org.apache.flink.runtime.state.filesystem.FileStateHandle;
+import org.apache.flink.runtime.state.filesystem.FsSegmentDataInputStream;
+
+import java.io.IOException;
+import java.util.Objects;
+
+/**
+ * {@link FileStateHandle} for state that was written to a file segment. A {@link
+ * SegmentFileStateHandle} represents a {@link LogicalFile}, which has already been written to a
+ * segment in a physical file.
+ *
+ * <p>TODO (FLINK-32079): serialization and deserialization of {@link SegmentFileStateHandle}.
+ */
+public class SegmentFileStateHandle extends FileStateHandle {
+
+    private static final long serialVersionUID = 1L;
+
+    private final long startPos;
+
+    private final CheckpointedStateScope scope;
+
+    /**
+     * Creates a new segment file state for the given file path.
+     *
+     * @param filePath The path to the file that stores the state.
+     * @param startPos Start position of the segment in the physical file.
+     * @param stateSize Size of the segment.
+     * @param scope The state's scope, whether it is exclusive or shared.
+     */
+    public SegmentFileStateHandle(
+            Path filePath, long startPos, long stateSize, CheckpointedStateScope scope) {
+        super(filePath, stateSize);
+        this.startPos = startPos;
+        this.scope = scope;
+    }
+
+    /**
+     * This method should be empty, so that JM is not in charge of the lifecycle of files in a
+     * file-merging checkpoint.
+     */
+    @Override
+    public void discardState() {}
+
+    @Override
+    public FSDataInputStream openInputStream() throws IOException {
+        FSDataInputStream inputStream = super.openInputStream();
+        return new FsSegmentDataInputStream(inputStream, startPos, stateSize);
+    }
+
+    public long getStartPos() {
+        return startPos;
+    }
+
+    @Override
+    public long getStateSize() {
+        return stateSize;
+    }
+
+    public long getEndPos() {

Review Comment:
   Looks like it's not used by others.



##########
flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/filemerging/FileMergingSnapshotManagerTest.java:
##########
@@ -18,19 +18,28 @@
 package org.apache.flink.runtime.checkpoint.filemerging;
 
 import org.apache.flink.api.common.TaskInfo;
+import org.apache.flink.core.fs.CloseableRegistry;
+import org.apache.flink.core.fs.FSDataInputStream;
 import org.apache.flink.core.fs.FileSystem;
 import org.apache.flink.core.fs.Path;
 import org.apache.flink.core.fs.local.LocalFileSystem;
 import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager.SubtaskKey;
 import org.apache.flink.runtime.jobgraph.OperatorID;
 import org.apache.flink.runtime.state.CheckpointedStateScope;
 import org.apache.flink.runtime.state.filesystem.AbstractFsCheckpointStorageAccess;
+import org.apache.flink.runtime.state.filesystem.FileMergingCheckpointStateOutputStream;
 
+import org.junit.jupiter.api.Assertions;

Review Comment:
   It‘s better to use AssertJ instead of Assertions.
   
   https://flink.apache.org/how-to-contribute/code-style-and-quality-common/#:~:text=Testing-,%23,-Tooling



##########
flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/filemerging/FileMergingSnapshotManagerTest.java:
##########
@@ -249,6 +261,104 @@ void testSizeStatsInPhysicalFile() throws IOException {
         }
     }
 
+    @Test
+    public void testReusedFileWriting() throws Exception {
+        long checkpointId = 1;
+        int streamNum = 10;
+        int perStreamWriteNum = 128;
+
+        // write random bytes and then read them from the file
+        byte[] bytes = new byte[streamNum * perStreamWriteNum];
+        Random rd = new Random();
+        rd.nextBytes(bytes);
+        int byteIndex = 0;
+
+        SegmentFileStateHandle[] handles = new SegmentFileStateHandle[streamNum];
+        try (FileMergingSnapshotManager fmsm = createFileMergingSnapshotManager(checkpointBaseDir);
+                CloseableRegistry closeableRegistry = new CloseableRegistry()) {
+
+            // repeatedly get-write-close streams
+            for (int i = 0; i < streamNum; i++) {
+                FileMergingCheckpointStateOutputStream stream =
+                        fmsm.createCheckpointStateOutputStream(
+                                subtaskKey1, checkpointId, CheckpointedStateScope.EXCLUSIVE);
+                try {
+                    closeableRegistry.registerCloseable(stream);
+                    for (int j = 0; j < perStreamWriteNum; j++) {
+                        stream.write(bytes[byteIndex++]);
+                    }
+                    handles[i] = stream.closeAndGetHandle();
+                } catch (IOException e) {
+                    throw new RuntimeException(e);
+                }
+            }
+
+            // assert the streams writes to the same file correctly
+            byteIndex = 0;
+            Path filePath = null;
+            for (SegmentFileStateHandle handle : handles) {
+                // check file path
+                Path thisFilePath = handle.getFilePath();
+                Assertions.assertTrue(filePath == null || filePath.equals(thisFilePath));
+                filePath = thisFilePath;
+                // check file content
+                FSDataInputStream is = handle.openInputStream();
+
+                closeableRegistry.registerCloseable(is);
+                int readValue;
+
+                while ((readValue = is.read()) != -1) {
+                    assertThat((byte) readValue).isEqualTo(bytes[byteIndex++]);
+                }
+            }
+        }
+    }
+
+    @Test
+    public void testConcurrentWriting() throws Exception {

Review Comment:
   I noticed that `FileMergingCheckpointStateOutputStream` is not thread-safe, how does this test guarantee thread safe?



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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "AlexYinHan (via GitHub)" <gi...@apache.org>.
AlexYinHan commented on code in PR #23514:
URL: https://github.com/apache/flink/pull/23514#discussion_r1402953830


##########
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/filemerging/FileMergingSnapshotManagerBase.java:
##########
@@ -206,6 +213,64 @@ protected PhysicalFile createPhysicalFile(SubtaskKey subtaskKey, CheckpointedSta
                 "Could not open output stream for state file merging.", latestException);
     }
 
+    @Override
+    public FileMergingCheckpointStateOutputStream createCheckpointStateOutputStream(

Review Comment:
   It should be created by a ``` FsCheckpointStreamFactory```, similar to ```FsCheckpointStateOutputStream```. 
   
   I have added a class named ```FsMergingCheckpointStorageLocation```, whose object is created by ```FsMergingCheckpointStorageAccess``` and creates ```FileMergingCheckpointStateOutputStream```.



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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "AlexYinHan (via GitHub)" <gi...@apache.org>.
AlexYinHan commented on code in PR #23514:
URL: https://github.com/apache/flink/pull/23514#discussion_r1366799573


##########
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/filemerging/SegmentFileStateHandle.java:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.flink.runtime.checkpoint.filemerging;
+
+import org.apache.flink.core.fs.FSDataInputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.state.CheckpointedStateScope;
+import org.apache.flink.runtime.state.filesystem.FileStateHandle;
+import org.apache.flink.runtime.state.filesystem.FsSegmentDataInputStream;
+
+import java.io.IOException;
+import java.util.Objects;
+
+/**
+ * {@link FileStateHandle} for state that was written to a file segment. A {@link
+ * SegmentFileStateHandle} represents a {@link LogicalFile}, which has already been written to a
+ * segment in a physical file.
+ *
+ * <p>TODO (FLINK-32079): serialization and deserialization of {@link SegmentFileStateHandle}.
+ */
+public class SegmentFileStateHandle extends FileStateHandle {
+
+    private static final long serialVersionUID = 1L;
+
+    private final long startPos;
+
+    private final CheckpointedStateScope scope;
+
+    /**
+     * Creates a new segment file state for the given file path.
+     *
+     * @param filePath The path to the file that stores the state.
+     * @param startPos Start position of the segment in the physical file.
+     * @param stateSize Size of the segment.
+     * @param scope The state's scope, whether it is exclusive or shared.
+     */
+    public SegmentFileStateHandle(
+            Path filePath, long startPos, long stateSize, CheckpointedStateScope scope) {
+        super(filePath, stateSize);
+        this.startPos = startPos;
+        this.scope = scope;
+    }
+
+    /**
+     * This method should be empty, so that JM is not in charge of the lifecycle of files in a
+     * file-merging checkpoint.
+     */
+    @Override
+    public void discardState() {}
+
+    @Override
+    public FSDataInputStream openInputStream() throws IOException {
+        FSDataInputStream inputStream = super.openInputStream();
+        return new FsSegmentDataInputStream(inputStream, startPos, stateSize);
+    }
+
+    public long getStartPos() {
+        return startPos;
+    }
+
+    @Override
+    public long getStateSize() {
+        return stateSize;
+    }
+
+    public long getEndPos() {

Review Comment:
   Indeed. I've removed that function.



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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "AlexYinHan (via GitHub)" <gi...@apache.org>.
AlexYinHan commented on code in PR #23514:
URL: https://github.com/apache/flink/pull/23514#discussion_r1366803327


##########
flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/filemerging/FileMergingSnapshotManagerTest.java:
##########
@@ -249,6 +261,104 @@ void testSizeStatsInPhysicalFile() throws IOException {
         }
     }
 
+    @Test
+    public void testReusedFileWriting() throws Exception {
+        long checkpointId = 1;
+        int streamNum = 10;
+        int perStreamWriteNum = 128;
+
+        // write random bytes and then read them from the file
+        byte[] bytes = new byte[streamNum * perStreamWriteNum];
+        Random rd = new Random();
+        rd.nextBytes(bytes);
+        int byteIndex = 0;
+
+        SegmentFileStateHandle[] handles = new SegmentFileStateHandle[streamNum];
+        try (FileMergingSnapshotManager fmsm = createFileMergingSnapshotManager(checkpointBaseDir);
+                CloseableRegistry closeableRegistry = new CloseableRegistry()) {
+
+            // repeatedly get-write-close streams
+            for (int i = 0; i < streamNum; i++) {
+                FileMergingCheckpointStateOutputStream stream =
+                        fmsm.createCheckpointStateOutputStream(
+                                subtaskKey1, checkpointId, CheckpointedStateScope.EXCLUSIVE);
+                try {
+                    closeableRegistry.registerCloseable(stream);
+                    for (int j = 0; j < perStreamWriteNum; j++) {
+                        stream.write(bytes[byteIndex++]);
+                    }
+                    handles[i] = stream.closeAndGetHandle();
+                } catch (IOException e) {
+                    throw new RuntimeException(e);
+                }
+            }
+
+            // assert the streams writes to the same file correctly
+            byteIndex = 0;
+            Path filePath = null;
+            for (SegmentFileStateHandle handle : handles) {
+                // check file path
+                Path thisFilePath = handle.getFilePath();
+                Assertions.assertTrue(filePath == null || filePath.equals(thisFilePath));
+                filePath = thisFilePath;
+                // check file content
+                FSDataInputStream is = handle.openInputStream();
+
+                closeableRegistry.registerCloseable(is);
+                int readValue;
+
+                while ((readValue = is.read()) != -1) {
+                    assertThat((byte) readValue).isEqualTo(bytes[byteIndex++]);
+                }
+            }
+        }
+    }
+
+    @Test
+    public void testConcurrentWriting() throws Exception {

Review Comment:
   It is guaranteed by ```FileMergingSnapshotManager```. Only after the previous "Stream" is closed, will it create another "Stream" reusing the same physical file.



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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "curcur (via GitHub)" <gi...@apache.org>.
curcur merged PR #23514:
URL: https://github.com/apache/flink/pull/23514


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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "flinkbot (via GitHub)" <gi...@apache.org>.
flinkbot commented on PR #23514:
URL: https://github.com/apache/flink/pull/23514#issuecomment-1759052156

   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "5e531dee90e96951b572c2e2dddaf7c371b29e5d",
       "status" : "UNKNOWN",
       "url" : "TBD",
       "triggerID" : "5e531dee90e96951b572c2e2dddaf7c371b29e5d",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 5e531dee90e96951b572c2e2dddaf7c371b29e5d UNKNOWN
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run azure` re-run the last Azure build
   </details>


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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "AlexYinHan (via GitHub)" <gi...@apache.org>.
AlexYinHan commented on code in PR #23514:
URL: https://github.com/apache/flink/pull/23514#discussion_r1418798290


##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.fs.FSDataOutputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager;
+import org.apache.flink.runtime.checkpoint.filemerging.SegmentFileStateHandle;
+import org.apache.flink.runtime.state.CheckpointStateOutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * A {@link CheckpointStateOutputStream} that writes into a segment of a file and returns a {@link
+ * SegmentFileStateHandle} upon closing. Multiple {@link FileMergingCheckpointStateOutputStream}
+ * objects can reuse the same underlying file, so that the checkpoint files are merged.
+ *
+ * <p><strong>Important</strong>: This implementation is NOT thread-safe. Multiple data streams
+ * multiplexing the same file should NOT write concurrently. Instead, it is expected that only after
+ * one data stream is closed, will other data streams reuse and write to the same underlying file.
+ */
+public class FileMergingCheckpointStateOutputStream extends CheckpointStateOutputStream {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class);
+
+    /**
+     * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link
+     * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files.
+     */
+    public abstract static class FileMergingSnapshotManagerProxy {
+        /**
+         * Provide a physical file.
+         *
+         * @return Output stream and path of the physical file.
+         * @throws IOException if the physical file cannot be created or opened.
+         */
+        public abstract Tuple2<FSDataOutputStream, Path> providePhysicalFile() throws IOException;
+
+        /**
+         * Close the stream and create a {@link SegmentFileStateHandle} for a file segment.
+         *
+         * @param filePath Path of the physical file.
+         * @param startPos Start position of the segment in the physical file.
+         * @param stateSize Size of the segment.
+         * @return The state handle of the segment.
+         * @throws IOException if any exception happens when closing the file.
+         */
+        public abstract SegmentFileStateHandle closeStreamAndCreateStateHandle(
+                Path filePath, long startPos, long stateSize) throws IOException;
+
+        /**
+         * Notify the {@link FileMergingSnapshotManager} that the stream is closed exceptionally.
+         *
+         * @throws IOException if any exception happens when deleting the file.
+         */
+        public abstract void closeStreamExceptionally() throws IOException;
+    }
+
+    private final FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy;
+
+    private volatile boolean closed;
+
+    /** path of the underlying physical file. */
+    private Path filePath;
+
+    /** the stream that writes to the underlying physical file. */
+    private @Nullable FSDataOutputStream outputStream;
+
+    /** start position in the physical file. */
+    private long startPos;
+
+    /** current position relative to startPos. */
+    long curPosRelative = 0;
+
+    /** the buffer for writing to the physical file. */
+    private final byte[] writeBuffer;
+
+    /** current position in the writeBuffer. */
+    int bufferPos;
+
+    public FileMergingCheckpointStateOutputStream(
+            long checkpointID,
+            int bufferSize,
+            FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy) {
+        this.fileMergingSnapshotManagerProxy = fileMergingSnapshotManagerProxy;
+        this.writeBuffer = new byte[bufferSize];
+    }
+
+    /** Assign a physical file to this stream and initialize the outputStream. */
+    private void initializeOutputStream() throws IOException {
+        Tuple2<FSDataOutputStream, Path> streamAndPath =
+                fileMergingSnapshotManagerProxy.providePhysicalFile();
+        outputStream = streamAndPath.f0;
+        startPos = outputStream.getPos();
+        filePath = streamAndPath.f1;
+    }
+
+    @Override
+    public long getPos() throws IOException {
+        // The starting position is not determined until a physical file has been assigned, so
+        // we return the relative value to the starting position in this method
+        return bufferPos + curPosRelative;
+    }
+
+    @Override
+    public void write(int b) throws IOException {
+        if (bufferPos >= writeBuffer.length) {
+            flushToFile();
+        }
+        writeBuffer[bufferPos++] = (byte) b;
+    }
+
+    @Override
+    public void write(byte[] b, int off, int len) throws IOException {
+        if (len < writeBuffer.length) {
+            // copy it into our write buffer first
+            final int remaining = writeBuffer.length - bufferPos;
+            if (len > remaining) {
+                // copy as much as fits
+                System.arraycopy(b, off, writeBuffer, bufferPos, remaining);
+                off += remaining;
+                len -= remaining;
+                bufferPos += remaining;
+
+                // flushToFile the write buffer to make it clear again
+                flushToFile();
+            }
+
+            // copy what is in the buffer
+            System.arraycopy(b, off, writeBuffer, bufferPos, len);
+            bufferPos += len;
+        } else {
+            // flushToFile the current buffer, outputStream is initialized if it is null
+            flushToFile();
+            // write the bytes directly
+            outputStream.write(b, off, len);
+            curPosRelative += len;
+        }
+    }
+
+    @Override
+    public void flush() throws IOException {
+        if (outputStream != null) {
+            flushToFile();
+        }
+    }
+
+    @Override
+    public void sync() throws IOException {
+        if (outputStream != null) {
+            outputStream.sync();
+        }
+    }
+
+    @Nullable
+    @Override
+    public SegmentFileStateHandle closeAndGetHandle() throws IOException {
+        // check if there was nothing ever written
+        if (outputStream == null && bufferPos == 0) {
+            return null;
+        }
+
+        synchronized (this) {
+            if (!closed) {
+                try {
+                    flushToFile();

Review Comment:
   As for `closeAndGetHandle()`: Yeah, you are right. No need for an extra `outputStream.sync()` as the `returnPhysicalFileForNextReuse ` can handle it. I'd forgotten that.



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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "AlexYinHan (via GitHub)" <gi...@apache.org>.
AlexYinHan commented on PR #23514:
URL: https://github.com/apache/flink/pull/23514#issuecomment-1869314576

   @curcur The CI failure has been addressed. (The file-merging checkpoint was unexpectedly enabled.) Would you please take another look?


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

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


Re: [PR] [FLINK-32073][checkpoint] Implement file merging in snapshot [flink]

Posted by "Zakelly (via GitHub)" <gi...@apache.org>.
Zakelly commented on code in PR #23514:
URL: https://github.com/apache/flink/pull/23514#discussion_r1381343756


##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.fs.FSDataOutputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager;
+import org.apache.flink.runtime.checkpoint.filemerging.SegmentFileStateHandle;
+import org.apache.flink.runtime.state.CheckpointStateOutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * A {@link CheckpointStateOutputStream} that writes into a segment of a file and returns a {@link
+ * SegmentFileStateHandle} upon closing. Multiple {@link FileMergingCheckpointStateOutputStream}
+ * objects can reuse the same underlying file, so that the checkpoint files are merged.
+ *
+ * <p><strong>Important</strong>: This implementation is NOT thread-safe. Multiple data streams
+ * multiplexing the same file should NOT write concurrently. Instead, it is expected that only after
+ * one data stream is closed, will other data streams reuse and write to the same underlying file.
+ */
+public class FileMergingCheckpointStateOutputStream extends CheckpointStateOutputStream {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class);
+
+    /**
+     * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link
+     * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files.
+     */
+    public abstract static class FileMergingSnapshotManagerProxy {
+        /**
+         * Provide a physical file.
+         *
+         * @return Output stream and path of the physical file.
+         * @throws IOException if the physical file cannot be created or opened.
+         */
+        public abstract Tuple2<FSDataOutputStream, Path> providePhysicalFile() throws IOException;
+
+        /**
+         * Close the stream and create a {@link SegmentFileStateHandle} for a file segment.
+         *
+         * @param filePath Path of the physical file.
+         * @param startPos Start position of the segment in the physical file.
+         * @param stateSize Size of the segment.
+         * @return The state handle of the segment.
+         * @throws IOException if any exception happens when closing the file.
+         */
+        public abstract SegmentFileStateHandle closeStreamAndCreateStateHandle(
+                Path filePath, long startPos, long stateSize) throws IOException;
+
+        /**
+         * Notify the {@link FileMergingSnapshotManager} that the stream is closed exceptionally.
+         *
+         * @throws IOException if any exception happens when deleting the file.
+         */
+        public abstract void closeStreamExceptionally() throws IOException;
+    }
+
+    private final FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy;
+
+    private volatile boolean closed;
+
+    /** path of the underlying physical file. */
+    private Path filePath;
+
+    /** the stream that writes to the underlying physical file. */
+    private @Nullable FSDataOutputStream outputStream;
+
+    /** start position in the physical file. */
+    private long startPos;
+
+    /** current position relative to startPos. */
+    long curPosRelative = 0;

Review Comment:
   Do you mean the bytes written into the `outputStream` so far?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.fs.FSDataOutputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager;
+import org.apache.flink.runtime.checkpoint.filemerging.SegmentFileStateHandle;
+import org.apache.flink.runtime.state.CheckpointStateOutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * A {@link CheckpointStateOutputStream} that writes into a segment of a file and returns a {@link
+ * SegmentFileStateHandle} upon closing. Multiple {@link FileMergingCheckpointStateOutputStream}
+ * objects can reuse the same underlying file, so that the checkpoint files are merged.
+ *
+ * <p><strong>Important</strong>: This implementation is NOT thread-safe. Multiple data streams
+ * multiplexing the same file should NOT write concurrently. Instead, it is expected that only after
+ * one data stream is closed, will other data streams reuse and write to the same underlying file.
+ */
+public class FileMergingCheckpointStateOutputStream extends CheckpointStateOutputStream {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class);
+
+    /**
+     * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link
+     * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files.
+     */
+    public abstract static class FileMergingSnapshotManagerProxy {
+        /**
+         * Provide a physical file.
+         *
+         * @return Output stream and path of the physical file.
+         * @throws IOException if the physical file cannot be created or opened.
+         */
+        public abstract Tuple2<FSDataOutputStream, Path> providePhysicalFile() throws IOException;
+
+        /**
+         * Close the stream and create a {@link SegmentFileStateHandle} for a file segment.
+         *
+         * @param filePath Path of the physical file.
+         * @param startPos Start position of the segment in the physical file.
+         * @param stateSize Size of the segment.
+         * @return The state handle of the segment.
+         * @throws IOException if any exception happens when closing the file.
+         */
+        public abstract SegmentFileStateHandle closeStreamAndCreateStateHandle(
+                Path filePath, long startPos, long stateSize) throws IOException;
+
+        /**
+         * Notify the {@link FileMergingSnapshotManager} that the stream is closed exceptionally.
+         *
+         * @throws IOException if any exception happens when deleting the file.
+         */
+        public abstract void closeStreamExceptionally() throws IOException;
+    }
+
+    private final FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy;
+
+    private volatile boolean closed;
+
+    /** path of the underlying physical file. */
+    private Path filePath;
+
+    /** the stream that writes to the underlying physical file. */
+    private @Nullable FSDataOutputStream outputStream;
+
+    /** start position in the physical file. */
+    private long startPos;
+
+    /** current position relative to startPos. */
+    long curPosRelative = 0;
+
+    /** the buffer for writing to the physical file. */
+    private final byte[] writeBuffer;
+
+    /** current position in the writeBuffer. */
+    int bufferPos;
+
+    public FileMergingCheckpointStateOutputStream(
+            long checkpointID,
+            int bufferSize,
+            FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy) {
+        this.fileMergingSnapshotManagerProxy = fileMergingSnapshotManagerProxy;
+        this.writeBuffer = new byte[bufferSize];
+    }
+
+    /** Assign a physical file to this stream and initialize the outputStream. */
+    private void initializeOutputStream() throws IOException {
+        Tuple2<FSDataOutputStream, Path> streamAndPath =
+                fileMergingSnapshotManagerProxy.providePhysicalFile();
+        outputStream = streamAndPath.f0;
+        startPos = outputStream.getPos();
+        filePath = streamAndPath.f1;
+    }
+
+    @Override
+    public long getPos() throws IOException {
+        // The starting position is not determined until a physical file has been assigned, so
+        // we return the relative value to the starting position in this method
+        return bufferPos + curPosRelative;
+    }
+
+    @Override
+    public void write(int b) throws IOException {
+        if (bufferPos >= writeBuffer.length) {
+            flushToFile();
+        }
+        writeBuffer[bufferPos++] = (byte) b;
+    }
+
+    @Override
+    public void write(byte[] b, int off, int len) throws IOException {
+        if (len < writeBuffer.length) {
+            // copy it into our write buffer first
+            final int remaining = writeBuffer.length - bufferPos;
+            if (len > remaining) {
+                // copy as much as fits
+                System.arraycopy(b, off, writeBuffer, bufferPos, remaining);
+                off += remaining;
+                len -= remaining;
+                bufferPos += remaining;
+
+                // flushToFile the write buffer to make it clear again
+                flushToFile();
+            }
+
+            // copy what is in the buffer
+            System.arraycopy(b, off, writeBuffer, bufferPos, len);
+            bufferPos += len;
+        } else {
+            // flushToFile the current buffer, outputStream is initialized if it is null
+            flushToFile();
+            // write the bytes directly
+            outputStream.write(b, off, len);
+            curPosRelative += len;
+        }
+    }
+
+    @Override
+    public void flush() throws IOException {
+        if (outputStream != null) {
+            flushToFile();
+        }
+    }
+
+    @Override
+    public void sync() throws IOException {
+        if (outputStream != null) {
+            outputStream.sync();
+        }
+    }
+
+    @Nullable
+    @Override
+    public SegmentFileStateHandle closeAndGetHandle() throws IOException {
+        // check if there was nothing ever written
+        if (outputStream == null && bufferPos == 0) {
+            return null;
+        }
+
+        synchronized (this) {
+            if (!closed) {
+                try {
+                    flushToFile();
+
+                    bufferPos = writeBuffer.length;
+
+                    return fileMergingSnapshotManagerProxy.closeStreamAndCreateStateHandle(
+                            filePath, startPos, curPosRelative);
+                } catch (Exception exception) {
+                    fileMergingSnapshotManagerProxy.closeStreamExceptionally();
+
+                    throw new IOException(
+                            "Could not flush to file and close the file system "
+                                    + "output stream to "
+                                    + filePath
+                                    + " in order to obtain the "
+                                    + "stream state handle",
+                            exception);
+                } finally {
+                    closed = true;
+                }
+            } else {
+                throw new IOException("Stream has already been closed and discarded.");
+            }
+        }
+    }
+
+    /**
+     * This method throws no exception if the close fails, but only logs the error. This is to be
+     * consistent with {@link FsCheckpointStreamFactory.FsCheckpointStateOutputStream#close()}.
+     */
+    @Override
+    public void close() {
+        if (!closed) {
+            closed = true;
+
+            // make sure write requests need to go to 'flushToFile()' where they recognized
+            // that the stream is closed
+            bufferPos = writeBuffer.length;
+            try {
+                fileMergingSnapshotManagerProxy.closeStreamExceptionally();
+            } catch (Throwable throwable) {
+                LOG.warn("Could not close the state stream for {}.", filePath, throwable);
+            }
+        }
+    }
+
+    public void flushToFile() throws IOException {
+        if (!closed) {
+            if (outputStream == null) {
+                initializeOutputStream();
+            }
+
+            if (bufferPos > 0) {
+                outputStream.write(writeBuffer, 0, bufferPos);
+                curPosRelative += bufferPos;
+                bufferPos = 0;
+            }
+        } else {
+            throw new IOException("closed");

Review Comment:
   Maybe more info for this exception?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.fs.FSDataOutputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager;
+import org.apache.flink.runtime.checkpoint.filemerging.SegmentFileStateHandle;
+import org.apache.flink.runtime.state.CheckpointStateOutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * A {@link CheckpointStateOutputStream} that writes into a segment of a file and returns a {@link
+ * SegmentFileStateHandle} upon closing. Multiple {@link FileMergingCheckpointStateOutputStream}
+ * objects can reuse the same underlying file, so that the checkpoint files are merged.
+ *
+ * <p><strong>Important</strong>: This implementation is NOT thread-safe. Multiple data streams
+ * multiplexing the same file should NOT write concurrently. Instead, it is expected that only after
+ * one data stream is closed, will other data streams reuse and write to the same underlying file.
+ */
+public class FileMergingCheckpointStateOutputStream extends CheckpointStateOutputStream {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class);
+
+    /**
+     * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link
+     * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files.
+     */
+    public abstract static class FileMergingSnapshotManagerProxy {

Review Comment:
   Can this abstract class be an interface?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.fs.FSDataOutputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager;
+import org.apache.flink.runtime.checkpoint.filemerging.SegmentFileStateHandle;
+import org.apache.flink.runtime.state.CheckpointStateOutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * A {@link CheckpointStateOutputStream} that writes into a segment of a file and returns a {@link
+ * SegmentFileStateHandle} upon closing. Multiple {@link FileMergingCheckpointStateOutputStream}
+ * objects can reuse the same underlying file, so that the checkpoint files are merged.
+ *
+ * <p><strong>Important</strong>: This implementation is NOT thread-safe. Multiple data streams
+ * multiplexing the same file should NOT write concurrently. Instead, it is expected that only after
+ * one data stream is closed, will other data streams reuse and write to the same underlying file.
+ */
+public class FileMergingCheckpointStateOutputStream extends CheckpointStateOutputStream {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class);
+
+    /**
+     * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link
+     * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files.
+     */
+    public abstract static class FileMergingSnapshotManagerProxy {
+        /**
+         * Provide a physical file.
+         *
+         * @return Output stream and path of the physical file.
+         * @throws IOException if the physical file cannot be created or opened.
+         */
+        public abstract Tuple2<FSDataOutputStream, Path> providePhysicalFile() throws IOException;
+
+        /**
+         * Close the stream and create a {@link SegmentFileStateHandle} for a file segment.
+         *
+         * @param filePath Path of the physical file.
+         * @param startPos Start position of the segment in the physical file.
+         * @param stateSize Size of the segment.
+         * @return The state handle of the segment.
+         * @throws IOException if any exception happens when closing the file.
+         */
+        public abstract SegmentFileStateHandle closeStreamAndCreateStateHandle(
+                Path filePath, long startPos, long stateSize) throws IOException;
+
+        /**
+         * Notify the {@link FileMergingSnapshotManager} that the stream is closed exceptionally.
+         *
+         * @throws IOException if any exception happens when deleting the file.
+         */
+        public abstract void closeStreamExceptionally() throws IOException;
+    }
+
+    private final FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy;
+
+    private volatile boolean closed;
+
+    /** path of the underlying physical file. */
+    private Path filePath;
+
+    /** the stream that writes to the underlying physical file. */
+    private @Nullable FSDataOutputStream outputStream;
+
+    /** start position in the physical file. */
+    private long startPos;
+
+    /** current position relative to startPos. */
+    long curPosRelative = 0;
+
+    /** the buffer for writing to the physical file. */
+    private final byte[] writeBuffer;
+
+    /** current position in the writeBuffer. */
+    int bufferPos;
+
+    public FileMergingCheckpointStateOutputStream(
+            long checkpointID,
+            int bufferSize,
+            FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy) {
+        this.fileMergingSnapshotManagerProxy = fileMergingSnapshotManagerProxy;
+        this.writeBuffer = new byte[bufferSize];
+    }
+
+    /** Assign a physical file to this stream and initialize the outputStream. */
+    private void initializeOutputStream() throws IOException {
+        Tuple2<FSDataOutputStream, Path> streamAndPath =
+                fileMergingSnapshotManagerProxy.providePhysicalFile();
+        outputStream = streamAndPath.f0;
+        startPos = outputStream.getPos();
+        filePath = streamAndPath.f1;
+    }
+
+    @Override
+    public long getPos() throws IOException {
+        // The starting position is not determined until a physical file has been assigned, so
+        // we return the relative value to the starting position in this method
+        return bufferPos + curPosRelative;
+    }
+
+    @Override
+    public void write(int b) throws IOException {
+        if (bufferPos >= writeBuffer.length) {
+            flushToFile();
+        }
+        writeBuffer[bufferPos++] = (byte) b;
+    }
+
+    @Override
+    public void write(byte[] b, int off, int len) throws IOException {
+        if (len < writeBuffer.length) {
+            // copy it into our write buffer first
+            final int remaining = writeBuffer.length - bufferPos;
+            if (len > remaining) {
+                // copy as much as fits
+                System.arraycopy(b, off, writeBuffer, bufferPos, remaining);
+                off += remaining;
+                len -= remaining;
+                bufferPos += remaining;
+
+                // flushToFile the write buffer to make it clear again
+                flushToFile();
+            }
+
+            // copy what is in the buffer
+            System.arraycopy(b, off, writeBuffer, bufferPos, len);
+            bufferPos += len;
+        } else {
+            // flushToFile the current buffer, outputStream is initialized if it is null
+            flushToFile();
+            // write the bytes directly
+            outputStream.write(b, off, len);
+            curPosRelative += len;
+        }
+    }
+
+    @Override
+    public void flush() throws IOException {
+        if (outputStream != null) {
+            flushToFile();

Review Comment:
   and `outputStream.flush();` ?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileStateHandle.java:
##########
@@ -42,7 +42,7 @@ public class FileStateHandle implements StreamStateHandle {
     private final Path filePath;
 
     /** The size of the state in the file. */
-    private final long stateSize;
+    protected final long stateSize;

Review Comment:
   I suggest the `SegmentFileStateHandle` could directly implement `StreamStateHandle` without extending the `FileStateHandle` since they have little common part.



##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.fs.FSDataOutputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager;
+import org.apache.flink.runtime.checkpoint.filemerging.SegmentFileStateHandle;
+import org.apache.flink.runtime.state.CheckpointStateOutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * A {@link CheckpointStateOutputStream} that writes into a segment of a file and returns a {@link
+ * SegmentFileStateHandle} upon closing. Multiple {@link FileMergingCheckpointStateOutputStream}
+ * objects can reuse the same underlying file, so that the checkpoint files are merged.
+ *
+ * <p><strong>Important</strong>: This implementation is NOT thread-safe. Multiple data streams
+ * multiplexing the same file should NOT write concurrently. Instead, it is expected that only after
+ * one data stream is closed, will other data streams reuse and write to the same underlying file.
+ */
+public class FileMergingCheckpointStateOutputStream extends CheckpointStateOutputStream {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class);
+
+    /**
+     * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link
+     * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files.
+     */
+    public abstract static class FileMergingSnapshotManagerProxy {
+        /**
+         * Provide a physical file.
+         *
+         * @return Output stream and path of the physical file.
+         * @throws IOException if the physical file cannot be created or opened.
+         */
+        public abstract Tuple2<FSDataOutputStream, Path> providePhysicalFile() throws IOException;
+
+        /**
+         * Close the stream and create a {@link SegmentFileStateHandle} for a file segment.
+         *
+         * @param filePath Path of the physical file.
+         * @param startPos Start position of the segment in the physical file.
+         * @param stateSize Size of the segment.
+         * @return The state handle of the segment.
+         * @throws IOException if any exception happens when closing the file.
+         */
+        public abstract SegmentFileStateHandle closeStreamAndCreateStateHandle(
+                Path filePath, long startPos, long stateSize) throws IOException;
+
+        /**
+         * Notify the {@link FileMergingSnapshotManager} that the stream is closed exceptionally.
+         *
+         * @throws IOException if any exception happens when deleting the file.
+         */
+        public abstract void closeStreamExceptionally() throws IOException;
+    }
+
+    private final FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy;
+
+    private volatile boolean closed;
+
+    /** path of the underlying physical file. */
+    private Path filePath;
+
+    /** the stream that writes to the underlying physical file. */
+    private @Nullable FSDataOutputStream outputStream;
+
+    /** start position in the physical file. */
+    private long startPos;
+
+    /** current position relative to startPos. */
+    long curPosRelative = 0;
+
+    /** the buffer for writing to the physical file. */
+    private final byte[] writeBuffer;
+
+    /** current position in the writeBuffer. */
+    int bufferPos;
+
+    public FileMergingCheckpointStateOutputStream(
+            long checkpointID,
+            int bufferSize,
+            FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy) {
+        this.fileMergingSnapshotManagerProxy = fileMergingSnapshotManagerProxy;
+        this.writeBuffer = new byte[bufferSize];
+    }
+
+    /** Assign a physical file to this stream and initialize the outputStream. */
+    private void initializeOutputStream() throws IOException {
+        Tuple2<FSDataOutputStream, Path> streamAndPath =
+                fileMergingSnapshotManagerProxy.providePhysicalFile();
+        outputStream = streamAndPath.f0;
+        startPos = outputStream.getPos();
+        filePath = streamAndPath.f1;
+    }
+
+    @Override
+    public long getPos() throws IOException {
+        // The starting position is not determined until a physical file has been assigned, so
+        // we return the relative value to the starting position in this method
+        return bufferPos + curPosRelative;
+    }
+
+    @Override
+    public void write(int b) throws IOException {
+        if (bufferPos >= writeBuffer.length) {
+            flushToFile();
+        }
+        writeBuffer[bufferPos++] = (byte) b;
+    }
+
+    @Override
+    public void write(byte[] b, int off, int len) throws IOException {
+        if (len < writeBuffer.length) {
+            // copy it into our write buffer first
+            final int remaining = writeBuffer.length - bufferPos;
+            if (len > remaining) {
+                // copy as much as fits
+                System.arraycopy(b, off, writeBuffer, bufferPos, remaining);
+                off += remaining;
+                len -= remaining;
+                bufferPos += remaining;
+
+                // flushToFile the write buffer to make it clear again
+                flushToFile();
+            }
+
+            // copy what is in the buffer
+            System.arraycopy(b, off, writeBuffer, bufferPos, len);
+            bufferPos += len;
+        } else {
+            // flushToFile the current buffer, outputStream is initialized if it is null
+            flushToFile();
+            // write the bytes directly
+            outputStream.write(b, off, len);
+            curPosRelative += len;
+        }
+    }
+
+    @Override
+    public void flush() throws IOException {
+        if (outputStream != null) {
+            flushToFile();
+        }
+    }
+
+    @Override
+    public void sync() throws IOException {
+        if (outputStream != null) {
+            outputStream.sync();

Review Comment:
   maybe call `flush()` first?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FsSegmentDataInputStream.java:
##########
@@ -0,0 +1,136 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.core.fs.FSDataInputStream;
+import org.apache.flink.core.fs.FSDataInputStreamWrapper;
+import org.apache.flink.core.fs.WrappingProxyCloseable;
+
+import java.io.IOException;
+
+/**
+ * This class is a {@link org.apache.flink.util.WrappingProxy} for {@link FSDataInputStream} that is
+ * used to read from a file segment. It is opened with a starting position of the file. It treats
+ * the argument of seek(long) as an offset relative to the starting position, rather than an
+ * absolute value.
+ */
+public class FsSegmentDataInputStream extends FSDataInputStreamWrapper
+        implements WrappingProxyCloseable<FSDataInputStream> {
+
+    private final long startingPosition;
+
+    private long endingPosition;
+
+    private long markPosition;
+
+    private long curPosInFile;
+

Review Comment:
   I'm wondering if we could let this class simply proxy operations to the `FSDataInputStreamWrapper` and omit these members?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FileMergingCheckpointStateOutputStream.java:
##########
@@ -0,0 +1,255 @@
+/*
+ * 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.flink.runtime.state.filesystem;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.core.fs.FSDataOutputStream;
+import org.apache.flink.core.fs.Path;
+import org.apache.flink.runtime.checkpoint.filemerging.FileMergingSnapshotManager;
+import org.apache.flink.runtime.checkpoint.filemerging.SegmentFileStateHandle;
+import org.apache.flink.runtime.state.CheckpointStateOutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+
+/**
+ * A {@link CheckpointStateOutputStream} that writes into a segment of a file and returns a {@link
+ * SegmentFileStateHandle} upon closing. Multiple {@link FileMergingCheckpointStateOutputStream}
+ * objects can reuse the same underlying file, so that the checkpoint files are merged.
+ *
+ * <p><strong>Important</strong>: This implementation is NOT thread-safe. Multiple data streams
+ * multiplexing the same file should NOT write concurrently. Instead, it is expected that only after
+ * one data stream is closed, will other data streams reuse and write to the same underlying file.
+ */
+public class FileMergingCheckpointStateOutputStream extends CheckpointStateOutputStream {
+
+    private static final Logger LOG =
+            LoggerFactory.getLogger(FileMergingCheckpointStateOutputStream.class);
+
+    /**
+     * A proxy of the {@link FileMergingSnapshotManager} that owns this {@link
+     * FileMergingCheckpointStateOutputStream}, with the interfaces for dealing with physical files.
+     */
+    public abstract static class FileMergingSnapshotManagerProxy {
+        /**
+         * Provide a physical file.
+         *
+         * @return Output stream and path of the physical file.
+         * @throws IOException if the physical file cannot be created or opened.
+         */
+        public abstract Tuple2<FSDataOutputStream, Path> providePhysicalFile() throws IOException;
+
+        /**
+         * Close the stream and create a {@link SegmentFileStateHandle} for a file segment.
+         *
+         * @param filePath Path of the physical file.
+         * @param startPos Start position of the segment in the physical file.
+         * @param stateSize Size of the segment.
+         * @return The state handle of the segment.
+         * @throws IOException if any exception happens when closing the file.
+         */
+        public abstract SegmentFileStateHandle closeStreamAndCreateStateHandle(
+                Path filePath, long startPos, long stateSize) throws IOException;
+
+        /**
+         * Notify the {@link FileMergingSnapshotManager} that the stream is closed exceptionally.
+         *
+         * @throws IOException if any exception happens when deleting the file.
+         */
+        public abstract void closeStreamExceptionally() throws IOException;
+    }
+
+    private final FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy;
+
+    private volatile boolean closed;
+
+    /** path of the underlying physical file. */
+    private Path filePath;
+
+    /** the stream that writes to the underlying physical file. */
+    private @Nullable FSDataOutputStream outputStream;
+
+    /** start position in the physical file. */
+    private long startPos;
+
+    /** current position relative to startPos. */
+    long curPosRelative = 0;
+
+    /** the buffer for writing to the physical file. */
+    private final byte[] writeBuffer;
+
+    /** current position in the writeBuffer. */
+    int bufferPos;
+
+    public FileMergingCheckpointStateOutputStream(
+            long checkpointID,
+            int bufferSize,
+            FileMergingSnapshotManagerProxy fileMergingSnapshotManagerProxy) {
+        this.fileMergingSnapshotManagerProxy = fileMergingSnapshotManagerProxy;
+        this.writeBuffer = new byte[bufferSize];
+    }
+
+    /** Assign a physical file to this stream and initialize the outputStream. */
+    private void initializeOutputStream() throws IOException {
+        Tuple2<FSDataOutputStream, Path> streamAndPath =
+                fileMergingSnapshotManagerProxy.providePhysicalFile();
+        outputStream = streamAndPath.f0;
+        startPos = outputStream.getPos();
+        filePath = streamAndPath.f1;
+    }
+
+    @Override
+    public long getPos() throws IOException {
+        // The starting position is not determined until a physical file has been assigned, so
+        // we return the relative value to the starting position in this method
+        return bufferPos + curPosRelative;
+    }
+
+    @Override
+    public void write(int b) throws IOException {
+        if (bufferPos >= writeBuffer.length) {
+            flushToFile();
+        }
+        writeBuffer[bufferPos++] = (byte) b;
+    }
+
+    @Override
+    public void write(byte[] b, int off, int len) throws IOException {
+        if (len < writeBuffer.length) {
+            // copy it into our write buffer first
+            final int remaining = writeBuffer.length - bufferPos;
+            if (len > remaining) {
+                // copy as much as fits
+                System.arraycopy(b, off, writeBuffer, bufferPos, remaining);
+                off += remaining;
+                len -= remaining;
+                bufferPos += remaining;
+
+                // flushToFile the write buffer to make it clear again
+                flushToFile();
+            }
+
+            // copy what is in the buffer
+            System.arraycopy(b, off, writeBuffer, bufferPos, len);
+            bufferPos += len;
+        } else {
+            // flushToFile the current buffer, outputStream is initialized if it is null
+            flushToFile();
+            // write the bytes directly
+            outputStream.write(b, off, len);
+            curPosRelative += len;
+        }
+    }
+
+    @Override
+    public void flush() throws IOException {
+        if (outputStream != null) {
+            flushToFile();
+        }
+    }
+
+    @Override
+    public void sync() throws IOException {
+        if (outputStream != null) {
+            outputStream.sync();
+        }
+    }
+
+    @Nullable
+    @Override
+    public SegmentFileStateHandle closeAndGetHandle() throws IOException {
+        // check if there was nothing ever written
+        if (outputStream == null && bufferPos == 0) {
+            return null;
+        }
+
+        synchronized (this) {
+            if (!closed) {
+                try {
+                    flushToFile();

Review Comment:
   I have not find any call of `outputStream.flush()` before returning the `SegmentFileStateHandle` instance. Is it an expected behaviour?



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

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