This is an automated email from the ASF dual-hosted git repository.

JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git


The following commit(s) were added to refs/heads/master by this push:
     new ba05e40b43 [core] Release primary-key writer resources on close 
(#11234)
ba05e40b43 is described below

commit ba05e40b43dca40dab9315137bcb093e2c3227ec
Author: YueZhang <[email protected]>
AuthorDate: Wed Nov 18 22:58:18 2026 -0500

    [core] Release primary-key writer resources on close (#11234)
---
 .../apache/paimon/mergetree/MergeTreeWriter.java   |  19 ++-
 .../paimon/table/PrimaryKeyWriterCloseTest.java    | 136 +++++++++++++++
 .../table/PrimaryKeyWriterCompactionCloseTest.java | 190 +++++++++++++++++++++
 3 files changed, 340 insertions(+), 5 deletions(-)

diff --git 
a/paimon-core/src/main/java/org/apache/paimon/mergetree/MergeTreeWriter.java 
b/paimon-core/src/main/java/org/apache/paimon/mergetree/MergeTreeWriter.java
index 2d58056b1e..0d7ad80148 100644
--- a/paimon-core/src/main/java/org/apache/paimon/mergetree/MergeTreeWriter.java
+++ b/paimon-core/src/main/java/org/apache/paimon/mergetree/MergeTreeWriter.java
@@ -368,12 +368,21 @@ public class MergeTreeWriter implements 
RecordWriter<KeyValue>, MemoryOwner {
 
     @Override
     public void close() throws Exception {
-        writerFactory.abortManagedBlobWrites();
-        // cancel compaction so that it does not block job cancelling
-        compactManager.cancelCompaction();
-        sync();
-        compactManager.close();
+        if (writeBuffer != null) {
+            writeBuffer.clear();
+        }
+        IOUtils.closeAll(
+                writerFactory::abortManagedBlobWrites,
+                () -> {
+                    // cancel compaction so that it does not block job 
cancelling
+                    compactManager.cancelCompaction();
+                    sync();
+                },
+                compactManager::close,
+                this::cleanTemporaryFiles);
+    }
 
+    private void cleanTemporaryFiles() throws Exception {
         // delete temporary files
         List<DataFileMeta> delete = new ArrayList<>(newFiles);
         newFiles.clear();
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeyWriterCloseTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeyWriterCloseTest.java
new file mode 100644
index 0000000000..b178b6f68b
--- /dev/null
+++ 
b/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeyWriterCloseTest.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.paimon.table;
+
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.data.BinaryString;
+import org.apache.paimon.data.GenericRow;
+import org.apache.paimon.disk.IOManager;
+import org.apache.paimon.memory.HeapMemorySegmentPool;
+import org.apache.paimon.memory.MemoryPoolFactory;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.table.sink.BatchTableCommit;
+import org.apache.paimon.table.sink.BatchTableWrite;
+import org.apache.paimon.table.sink.BatchWriteBuilder;
+import org.apache.paimon.types.DataTypes;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.SoftAssertions.assertSoftly;
+
+/** Tests for releasing primary-key write buffers when a table writer is 
closed. */
+class PrimaryKeyWriterCloseTest extends TableTestBase {
+
+    @ParameterizedTest
+    @CsvSource({"false,false", "true,false", "false,true", "true,true"})
+    void testCloseReleasesWriteBuffer(boolean spillable, boolean 
commitBeforeClose)
+            throws Exception {
+        FileStoreTable table = createTable(spillable);
+        HeapMemorySegmentPool pool = new HeapMemorySegmentPool(3 * 4096L, 
4096);
+        MemoryPoolFactory poolFactory = new MemoryPoolFactory(pool);
+        Path spillDirectory = tempPath.resolve("spill");
+        Files.createDirectories(spillDirectory);
+        String value = String.join("", java.util.Collections.nCopies(900, 
"x"));
+        int count = spillable ? 100 : 1;
+        try (IOManager io = IOManager.create(spillDirectory.toString())) {
+            BatchWriteBuilder builder = table.newBatchWriteBuilder();
+            try (BatchTableWrite write = builder.newWrite();
+                    BatchTableCommit commit = builder.newCommit()) {
+                write.withMemoryPoolFactory(poolFactory);
+                write.withIOManager(io);
+                for (int i = 0; i < count; i++) {
+                    write.write(GenericRow.of(i, 
BinaryString.fromString(value)));
+                }
+                assertThat(pool.freePages()).isLessThan(3);
+                if (spillable) {
+                    assertThat(filesIn(spillDirectory)).isNotEmpty();
+                }
+                if (commitBeforeClose) {
+                    commit.commit(write.prepareCommit());
+                }
+            }
+            // Check before closing the externally owned IO manager or 
releasing the shared pool.
+            List<Path> remainingFiles = filesIn(spillDirectory);
+            assertSoftly(
+                    softly -> {
+                        softly.assertThat(pool.freePages()).isEqualTo(3);
+                        softly.assertThat(remainingFiles).isEmpty();
+                    });
+            if (commitBeforeClose) {
+                assertThat(read(table))
+                        .allSatisfy(row -> 
assertThat(row.getString(1).toString()).isEqualTo(value))
+                        .extracting(row -> row.getInt(0))
+                        .containsExactlyInAnyOrderElementsOf(
+                                IntStream.range(0, 
count).boxed().collect(Collectors.toList()));
+            } else {
+                
assertThat(table.snapshotManager().latestSnapshotId()).isNull();
+            }
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    void testCloseAllowsSharedPoolReuse(boolean spillable) throws Exception {
+        FileStoreTable table = createTable(spillable);
+        HeapMemorySegmentPool pool = new HeapMemorySegmentPool(3 * 4096L, 
4096);
+        MemoryPoolFactory poolFactory = new MemoryPoolFactory(pool);
+        try (IOManager io = IOManager.create(tempPath.toString())) {
+            for (int i = 0; i < 3; i++) {
+                try (BatchTableWrite write = 
table.newBatchWriteBuilder().newWrite()) {
+                    write.withMemoryPoolFactory(poolFactory);
+                    write.withIOManager(io);
+                    write.write(GenericRow.of(i, 
BinaryString.fromString("value")));
+                }
+            }
+            assertThat(pool.freePages()).isEqualTo(3);
+            assertThat(table.snapshotManager().latestSnapshotId()).isNull();
+        }
+    }
+
+    private FileStoreTable createTable(boolean spillable) throws Exception {
+        catalog.createTable(
+                identifier(),
+                Schema.newBuilder()
+                        .column("k", DataTypes.INT())
+                        .column("v", DataTypes.STRING())
+                        .primaryKey("k")
+                        .option(CoreOptions.BUCKET.key(), "1")
+                        .option(CoreOptions.WRITE_BUFFER_SPILLABLE.key(), 
String.valueOf(spillable))
+                        .option(CoreOptions.WRITE_ONLY.key(), "true")
+                        .build(),
+                false);
+        return (FileStoreTable) catalog.getTable(identifier());
+    }
+
+    private static List<Path> filesIn(Path directory) throws Exception {
+        try (Stream<Path> files = Files.walk(directory)) {
+            return 
files.filter(Files::isRegularFile).collect(Collectors.toList());
+        }
+    }
+}
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeyWriterCompactionCloseTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeyWriterCompactionCloseTest.java
new file mode 100644
index 0000000000..4bccf09436
--- /dev/null
+++ 
b/paimon-core/src/test/java/org/apache/paimon/table/PrimaryKeyWriterCompactionCloseTest.java
@@ -0,0 +1,190 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.paimon.table;
+
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.compact.CompactResult;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.data.BinaryString;
+import org.apache.paimon.data.GenericRow;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.fs.PositionOutputStream;
+import org.apache.paimon.io.DataFileMeta;
+import org.apache.paimon.mergetree.SortedRun;
+import org.apache.paimon.mergetree.compact.CompactRewriter;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.table.sink.StreamTableCommit;
+import org.apache.paimon.table.sink.StreamTableWrite;
+import org.apache.paimon.table.sink.TableWriteImpl;
+import org.apache.paimon.types.DataTypes;
+import org.apache.paimon.utils.IOUtils;
+import org.apache.paimon.utils.TraceableFileIO;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.catchThrowable;
+import static org.assertj.core.api.SoftAssertions.assertSoftly;
+
+/** Tests for releasing owned compaction rewriters after asynchronous failure. 
*/
+class PrimaryKeyWriterCompactionCloseTest extends TableTestBase {
+
+    @ParameterizedTest
+    @CsvSource({"false,false", "false,true", "true,false", "true,true"})
+    void testCloseReleasesRewriter(boolean failCompaction, boolean 
failRewriterClose)
+            throws Exception {
+        catalog.createTable(
+                identifier(),
+                Schema.newBuilder()
+                        .column("k", DataTypes.INT())
+                        .column("v", DataTypes.STRING())
+                        .primaryKey("k")
+                        .option(CoreOptions.BUCKET.key(), "1")
+                        .option(CoreOptions.WRITE_ONLY.key(), "false")
+                        
.option(CoreOptions.NUM_SORTED_RUNS_COMPACTION_TRIGGER.key(), "99")
+                        .build(),
+                false);
+        FileStoreTable table = (FileStoreTable) catalog.getTable(identifier());
+        Path resourcePath = new 
Path(tempPath.resolve("rewriter-resource").toString());
+        PositionOutputStream resource = new 
TraceableFileIO().newOutputStream(resourcePath, false);
+        AtomicBoolean closed = new AtomicBoolean();
+        AtomicReference<CompactRewriter> created = new AtomicReference<>();
+        CountDownLatch completed = new CountDownLatch(1);
+        ThreadPoolExecutor executor =
+                new ThreadPoolExecutor(
+                        1, 1, 0L, TimeUnit.MILLISECONDS, new 
LinkedBlockingQueue<>()) {
+                    @Override
+                    protected void afterExecute(Runnable task, Throwable 
failure) {
+                        super.afterExecute(task, failure);
+                        completed.countDown();
+                    }
+                };
+        StreamTableWrite write = table.newWrite("close-contract");
+        StreamTableCommit commit = table.newCommit("close-contract");
+        try {
+            ((TableWriteImpl<?>) write).withCompactExecutor(executor);
+            write.withCompactRewriterFactory(
+                    (partition, bucket, delegate) -> {
+                        CompactRewriter rewriter =
+                                new CompactRewriter() {
+                                    @Override
+                                    public CompactResult rewrite(
+                                            int level,
+                                            boolean dropDelete,
+                                            List<List<SortedRun>> sections)
+                                            throws Exception {
+                                        if (failCompaction) {
+                                            throw new IOException("expected 
compaction failure");
+                                        }
+                                        return delegate.rewrite(level, 
dropDelete, sections);
+                                    }
+
+                                    @Override
+                                    public CompactResult upgrade(int level, 
DataFileMeta file)
+                                            throws Exception {
+                                        if (failCompaction) {
+                                            throw new IOException("expected 
compaction failure");
+                                        }
+                                        return delegate.upgrade(level, file);
+                                    }
+
+                                    @Override
+                                    public void close() throws IOException {
+                                        closed.set(true);
+                                        try {
+                                            IOUtils.closeAll(delegate, 
resource);
+                                        } catch (Exception e) {
+                                            throw new IOException(e);
+                                        }
+                                        if (failRewriterClose) {
+                                            throw new IOException(
+                                                    "expected rewriter close 
failure");
+                                        }
+                                    }
+                                };
+                        created.set(rewriter);
+                        return rewriter;
+                    });
+            write.write(GenericRow.of(1, 
BinaryString.fromString("committed")));
+            commit.commit(0, write.prepareCommit(false, 0));
+            assertThat(read(table))
+                    .extracting(row -> row.getString(1).toString())
+                    .containsExactly("committed");
+            write.compact(BinaryRow.EMPTY_ROW, 0, true);
+            assertThat(completed.await(10, TimeUnit.SECONDS)).isTrue();
+            Throwable failure = catchThrowable(write::close);
+            List<?> openResources =
+                    TraceableFileIO.openOutputStreams(
+                            p -> p.toString().equals(resourcePath.toString()));
+            assertThat(read(table))
+                    .extracting(row -> row.getString(1).toString())
+                    .containsExactly("committed");
+            assertSoftly(
+                    softly -> {
+                        softly.assertThat(closed.get()).isTrue();
+                        softly.assertThat(openResources).isEmpty();
+                        if (failCompaction) {
+                            softly.assertThat(failure)
+                                    .hasRootCauseMessage("expected compaction 
failure");
+                            if (failRewriterClose) {
+                                softly.assertThat(failure.getSuppressed())
+                                        .anySatisfy(
+                                                suppressed ->
+                                                        assertThat(suppressed)
+                                                                .hasMessage(
+                                                                        
"expected rewriter close failure"));
+                            }
+                        } else if (failRewriterClose) {
+                            softly.assertThat(failure)
+                                    .hasMessage("expected rewriter close 
failure");
+                        } else {
+                            softly.assertThat(failure).isNull();
+                        }
+                    });
+            assertThat(read(table))
+                    .extracting(row -> row.getString(1).toString())
+                    .containsExactly("committed");
+        } finally {
+            // Keep the test process clean even when the close-under-test 
misses its owner.
+            try {
+                if (created.get() != null) {
+                    if (!closed.get()) {
+                        created.get().close();
+                    }
+                } else {
+                    resource.close();
+                }
+            } catch (IOException ignored) {
+            }
+            commit.close();
+            executor.shutdownNow();
+            assertThat(executor.awaitTermination(10, 
TimeUnit.SECONDS)).isTrue();
+        }
+    }
+}

Reply via email to