Copilot commented on code in PR #29890:
URL: https://github.com/apache/flink/pull/29890#discussion_r4645128181


##########
flink-filesystems/flink-s3-fs-native/src/main/java/org/apache/flink/fs/s3native/writer/NativeS3RecoverableFsDataOutputStream.java:
##########
@@ -180,41 +209,134 @@ public void write(byte[] b, int off, int len) throws 
IOException {
 
         if (currentPartSize >= minPartSize) {
             uploadCurrentPart();
-            createNewTempFile();
+            startNewPart();
         }
     }
 
     @Override
     public void flush() throws IOException {
-        if (closed) {
-            throw new IOException("Stream is closed");
-        }
+        checkUsable();
         currentOutputStream.flush();
     }
 
     @Override
     public void sync() throws IOException {
+        checkUsable();
+        persist();
+    }
+
+    private void checkUsable() throws IOException {
         if (closed) {
             throw new IOException("Stream is closed");
         }
-        persist();
+        final IOException failure = uploadFailure.get();
+        if (failure != null) {
+            throw new IOException(
+                    "A part upload of this stream failed. The stream cannot be 
used anymore and "
+                            + "must be recovered from the last checkpoint.",
+                    failure);
+        }
     }
 
     private void uploadCurrentPart() throws IOException {
-        currentOutputStream.close();
+        final PendingPartUpload upload;
+        lock();
+        try {
+            // close() may have run concurrently and released the buffer.
+            checkUsable();
+            currentOutputStream.close();
+
+            upload = new PendingPartUpload(nextPartNumber, currentTempFile, 
currentPartSize);
+            pendingUploads.addLast(upload);
+            nextPartNumber++;
+            numBytesInParts += currentPartSize;
+            currentOutputStream = null;
+            currentFileStream = null;
+            currentTempFile = null;
+            currentPartSize = 0;
+        } finally {
+            unlock();
+        }
+
+        // Blocks while the maximum number of uploads is in flight. Called 
from write(), this does
+        // not hold the lock, so close() is not blocked by back-pressure.
+        try {
+            uploadExecutor.execute(() -> uploadPart(upload));
+        } catch (RuntimeException e) {
+            final IOException failure = recordUploadFailure(upload, e);
+            upload.future.completeExceptionally(e);
+            throw failure;

Review Comment:
   If executor admission throws an `Error`, such as native-thread exhaustion, 
this catch is bypassed after the part has entered `pendingUploads`. No task 
completes its future, so later `close()` waits forever and cannot clean up the 
part file. Complete the future for every submission failure before allocating 
an exception wrapper, and rethrow fatal errors.



##########
flink-filesystems/flink-s3-fs-native/src/main/java/org/apache/flink/fs/s3native/writer/NativeS3RecoverableFsDataOutputStream.java:
##########
@@ -180,41 +209,134 @@ public void write(byte[] b, int off, int len) throws 
IOException {
 
         if (currentPartSize >= minPartSize) {
             uploadCurrentPart();
-            createNewTempFile();
+            startNewPart();
         }
     }
 
     @Override
     public void flush() throws IOException {
-        if (closed) {
-            throw new IOException("Stream is closed");
-        }
+        checkUsable();
         currentOutputStream.flush();
     }
 
     @Override
     public void sync() throws IOException {
+        checkUsable();
+        persist();
+    }
+
+    private void checkUsable() throws IOException {
         if (closed) {
             throw new IOException("Stream is closed");
         }
-        persist();
+        final IOException failure = uploadFailure.get();
+        if (failure != null) {
+            throw new IOException(
+                    "A part upload of this stream failed. The stream cannot be 
used anymore and "
+                            + "must be recovered from the last checkpoint.",
+                    failure);
+        }
     }
 
     private void uploadCurrentPart() throws IOException {
-        currentOutputStream.close();
+        final PendingPartUpload upload;
+        lock();
+        try {
+            // close() may have run concurrently and released the buffer.
+            checkUsable();
+            currentOutputStream.close();
+
+            upload = new PendingPartUpload(nextPartNumber, currentTempFile, 
currentPartSize);
+            pendingUploads.addLast(upload);
+            nextPartNumber++;
+            numBytesInParts += currentPartSize;
+            currentOutputStream = null;
+            currentFileStream = null;
+            currentTempFile = null;
+            currentPartSize = 0;
+        } finally {
+            unlock();
+        }
+
+        // Blocks while the maximum number of uploads is in flight. Called 
from write(), this does
+        // not hold the lock, so close() is not blocked by back-pressure.
+        try {
+            uploadExecutor.execute(() -> uploadPart(upload));
+        } catch (RuntimeException e) {
+            final IOException failure = recordUploadFailure(upload, e);
+            upload.future.completeExceptionally(e);
+            throw failure;
+        }
+        completeFinishedUploads();
+    }
+
+    private void startNewPart() throws IOException {
+        lock();
+        try {
+            // close() may have run while uploadCurrentPart() waited for a 
free upload slot.
+            checkUsable();
+            createNewTempFile();
+        } finally {
+            unlock();
+        }
+    }
+
+    private void uploadPart(PendingPartUpload upload) {
+        try {
+            if (closed) {
+                throw new IOException("The stream was closed before the part 
upload started.");
+            }
+            final NativeS3ObjectOperations.UploadPartResult result =
+                    s3AccessHelper.uploadPart(
+                            key, uploadId, upload.partNumber, upload.file, 
upload.length);
+            Files.deleteIfExists(upload.file.toPath());
+            upload.future.complete(new PartETag(result.getPartNumber(), 
result.getETag()));
+        } catch (Throwable t) {
+            // Recorded before the future completes, so that whoever sees the 
failed future also
+            // sees the stream as failed.
+            recordUploadFailure(upload, t);
+            upload.future.completeExceptionally(t);

Review Comment:
   Wrapping JVM-fatal errors in an `IOException` bypasses 
`Task.preProcessException()`'s fatal-error and configured exit-on-OOM handling. 
Complete the pending future, but route these errors through the appropriate 
fatal-error handling rather than treating them as ordinary upload failures. 
Rethrowing alone is insufficient: the logging-only uncaught-exception handler 
in `NativeS3FileSystem.java:151–157` also needs to preserve this behavior.



##########
flink-filesystems/flink-s3-fs-native/src/test/java/org/apache/flink/fs/s3native/writer/NativeS3RecoverableFsDataOutputStreamTest.java:
##########
@@ -216,10 +233,206 @@ protected void deleteTempFile(File file) throws 
IOException {
         assertThat(countLocalFilesIn(dir)).isZero();
     }
 
+    @Test
+    void partUploadsRunConcurrentlyUpToTheLimit() throws Exception {
+        s3.uploadPartGate = new CountDownLatch(1);
+        NativeS3RecoverableFsDataOutputStream asyncStream =
+                newAsyncStream(tmp.resolve("concurrent"), 2);
+
+        asyncStream.write(bytes('A', 10), 0, 10);
+        asyncStream.write(bytes('B', 10), 0, 10);
+        // Both writes returned while their parts are still being uploaded.
+        waitUntilCondition(() -> s3.inFlightUploads.get() == 2);
+
+        CheckedThread thirdPart =
+                new CheckedThread() {
+                    @Override
+                    public void go() throws Exception {
+                        asyncStream.write(bytes('C', 10), 0, 10);
+                    }
+                };
+        thirdPart.start();
+        // The third part has to wait for a free upload slot.
+        waitUntilCondition(() -> thirdPart.getState() == Thread.State.WAITING);
+        assertThat(s3.inFlightUploads).hasValue(2);
+
+        s3.uploadPartGate.countDown();
+        thirdPart.sync();
+        asyncStream.closeForCommit().commit();
+
+        assertThat(s3.maxInFlightUploads).hasValue(2);
+        assertThat(s3.committedObjects.get(KEY))
+                .containsExactly(concat(bytes('A', 10), bytes('B', 10), 
bytes('C', 10)));
+    }
+
+    @Test
+    void persistWaitsForInFlightPartUploads() throws Exception {
+        s3.uploadPartGate = new CountDownLatch(1);
+        NativeS3RecoverableFsDataOutputStream asyncStream =
+                newAsyncStream(tmp.resolve("persist"), 2);
+        asyncStream.write(bytes('A', 10), 0, 10);
+        asyncStream.write(bytes('B', 3), 0, 3);
+
+        NativeS3Recoverable[] recoverable = new NativeS3Recoverable[1];
+        CheckedThread persisting =
+                new CheckedThread() {
+                    @Override
+                    public void go() throws Exception {
+                        recoverable[0] = (NativeS3Recoverable) 
asyncStream.persist();
+                    }
+                };
+        persisting.start();
+        waitUntilCondition(() -> persisting.getState() == 
Thread.State.WAITING);
+        assertThat(s3.objects).as("the tail is stored after the parts are 
uploaded").isEmpty();
+
+        s3.uploadPartGate.countDown();
+        persisting.sync();
+
+        assertThat(recoverable[0].parts()).hasSize(1);
+        assertThat(recoverable[0].numBytesInParts()).isEqualTo(10L);
+        assertThat(recoverable[0].incompleteObjectLength()).isEqualTo(3L);
+        assertThat(asyncStream.getPos()).isEqualTo(13L);
+        asyncStream.close();
+    }
+
+    @Test
+    void asyncPartUploadFailureSurfacesOnPersistAndBreaksTheStream() throws 
Exception {
+        s3.uploadPartGate = new CountDownLatch(1);
+        s3.failUploadPart = true;
+        Path dir = tmp.resolve("async-failure");
+        NativeS3RecoverableFsDataOutputStream asyncStream = 
newAsyncStream(dir, 2);
+
+        // The write does not wait for the part upload, so it cannot see its 
failure.
+        asyncStream.write(bytes('A', 10), 0, 10);
+        s3.uploadPartGate.countDown();
+
+        assertThatThrownBy(asyncStream::persist)
+                .isInstanceOf(IOException.class)
+                .hasStackTraceContaining("Failed to upload part 1")
+                .hasRootCauseMessage("injected uploadPart failure for 
uploadId: U2");
+        assertThatThrownBy(() -> asyncStream.write(bytes('B', 1), 0, 1))
+                .isInstanceOf(IOException.class)
+                .hasMessageContaining("must be recovered from the last 
checkpoint");
+        assertThatThrownBy(asyncStream::closeForCommit)
+                .isInstanceOf(IOException.class)
+                .hasMessageContaining("must be recovered from the last 
checkpoint");
+
+        assertThat(s3.abortAttempts).isZero();
+        assertThat(countLocalFilesIn(dir)).as("the failed part's temp file is 
deleted").isZero();
+    }
+
+    @Test
+    void partUploadFailureStopsWritesWhileEarlierPartsAreInFlight() throws 
Exception {
+        s3.uploadPartGate = new CountDownLatch(1);
+        s3.failingPartNumber = 2;
+        Path dir = tmp.resolve("out-of-order-failure");
+        NativeS3RecoverableFsDataOutputStream asyncStream = 
newAsyncStream(dir, 3);
+
+        asyncStream.write(bytes('A', 10), 0, 10);
+        asyncStream.write(bytes('B', 10), 0, 10);

Review Comment:
   Part 2 bypasses `uploadPartGate`, so it can fail before this `write()` 
reaches `startNewPart()`. That method calls `checkUsable()` and throws, causing 
the test to fail at this unguarded write instead of reaching the assertions 
below. Please gate part 2's failure separately and release it only after this 
write returns, keeping part 1 blocked, so the intended out-of-order failure 
scenario is deterministic.



##########
flink-filesystems/flink-s3-fs-native/src/main/java/org/apache/flink/fs/s3native/writer/NativeS3RecoverableFsDataOutputStream.java:
##########
@@ -327,6 +457,15 @@ private void releaseLocalResources() throws IOException {
                 collected = ExceptionUtils.firstOrSuppressed(e, collected);
             }
         }
+        for (PendingPartUpload upload : pendingUploads) {
+            // join() is not interruptible, and handle() turns a failed upload 
into a result.
+            upload.future.handle((ignored, error) -> null).join();

Review Comment:
   `close()` now waits on unfinished S3 requests without a timeout and cannot 
be interrupted, so a stalled upload can block FileSink failure cleanup 
indefinitely or trigger the TaskManager cancellation watchdog. The sync CRT 
client ignores `s3.socket.timeout` and has no API-call deadline. Bound upload 
termination during disposal while ensuring that no old upload can overwrite a 
part after checkpoint recovery; simply dropping this wait is unsafe.



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to