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

lxy-9602 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/paimon-cpp.git


The following commit(s) were added to refs/heads/main by this push:
     new 2826c265 fix(read): release exported Arrow roots when batch 
publication fails (#586)
2826c265 is described below

commit 2826c2651d6384e3c767720307df552fd6f6a522
Author: Aaron Wu <[email protected]>
AuthorDate: Sun Nov 22 16:01:07 2026 +0800

    fix(read): release exported Arrow roots when batch publication fails (#586)
---
 src/paimon/CMakeLists.txt                          | 10 +++
 .../utils/arrow/arrow_lifetime_failure_test.cpp    | 80 ++++++++++++++++++++++
 src/paimon/common/utils/arrow/mem_utils.cpp        | 25 ++++---
 .../format/parquet/parquet_file_batch_reader.cpp   |  6 ++
 .../parquet/parquet_file_batch_reader_test.cpp     | 51 ++++++++++++++
 5 files changed, 164 insertions(+), 8 deletions(-)

diff --git a/src/paimon/CMakeLists.txt b/src/paimon/CMakeLists.txt
index e0954f77..7f8d5d8f 100644
--- a/src/paimon/CMakeLists.txt
+++ b/src/paimon/CMakeLists.txt
@@ -605,6 +605,16 @@ if(PAIMON_BUILD_TESTS)
                         ${GTEST_LINK_TOOLCHAIN})
         target_link_options(paimon-executor-submission-test PRIVATE 
"LINKER:--wrap=_Znwm")
         set_tests_properties(paimon-executor-submission-test PROPERTIES 
TIMEOUT 30)
+
+        add_paimon_test(arrow_lifetime_failure_test
+                        SOURCES
+                        common/utils/arrow/arrow_lifetime_failure_test.cpp
+                        STATIC_LINK_LIBS
+                        paimon_static
+                        ${GTEST_LINK_TOOLCHAIN})
+        target_link_options(paimon-arrow-lifetime-failure-test PRIVATE
+                            "LINKER:--wrap=_Znwm")
+        set_tests_properties(paimon-arrow-lifetime-failure-test PROPERTIES 
TIMEOUT 30)
     endif()
 
     # The shared HTTP client is compiled only for the components that need 
libcurl,
diff --git a/src/paimon/common/utils/arrow/arrow_lifetime_failure_test.cpp 
b/src/paimon/common/utils/arrow/arrow_lifetime_failure_test.cpp
new file mode 100644
index 00000000..2e527da0
--- /dev/null
+++ b/src/paimon/common/utils/arrow/arrow_lifetime_failure_test.cpp
@@ -0,0 +1,80 @@
+/*
+ * 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.
+ */
+
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <new>
+#include <utility>
+
+#include "gtest/gtest.h"
+#include "paimon/arrow/abi.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+
+namespace {
+thread_local bool fail_next_allocation = false;
+}  // namespace
+
+extern "C" void* __real__Znwm(std::size_t size);
+extern "C" void* __wrap__Znwm(std::size_t size) {
+    if (std::exchange(fail_next_allocation, false)) {
+        throw std::bad_alloc();
+    }
+    return __real__Znwm(size);
+}
+
+namespace paimon::test {
+
+TEST(ArrowLifetimeFailureTest, 
ReleasesBothRootsWhenHoldingLifetimeRunsOutOfMemory) {
+    ArrowArray array{};
+    ArrowSchema schema{};
+    int32_t array_releases = 0;
+    int32_t schema_releases = 0;
+    array.private_data = &array_releases;
+    array.release = [](ArrowArray* root) {
+        ++*static_cast<int32_t*>(root->private_data);
+        root->release = nullptr;
+    };
+    schema.private_data = &schema_releases;
+    schema.release = [](ArrowSchema* root) {
+        ++*static_cast<int32_t*>(root->private_data);
+        root->release = nullptr;
+    };
+    std::shared_ptr<void> owner = std::make_shared<int32_t>(1);
+
+    Status status;
+    bool threw = false;
+    fail_next_allocation = true;
+    try {
+        status = AddArrowArrayLifetime(&array, &schema, owner);
+    } catch (const std::bad_alloc&) {
+        threw = true;
+    }
+    const bool fired = !std::exchange(fail_next_allocation, false);
+
+    EXPECT_TRUE(fired);
+    EXPECT_FALSE(threw);
+    EXPECT_TRUE(status.IsOutOfMemory());
+    EXPECT_EQ(array_releases, 1);
+    EXPECT_EQ(schema_releases, 1);
+    EXPECT_EQ(array.release, nullptr);
+    EXPECT_EQ(schema.release, nullptr);
+}
+
+}  // namespace paimon::test
diff --git a/src/paimon/common/utils/arrow/mem_utils.cpp 
b/src/paimon/common/utils/arrow/mem_utils.cpp
index 348cf4d0..7e97d8c0 100644
--- a/src/paimon/common/utils/arrow/mem_utils.cpp
+++ b/src/paimon/common/utils/arrow/mem_utils.cpp
@@ -52,6 +52,13 @@ bool HasSameOwner(const std::shared_ptr<void>& lhs, const 
std::shared_ptr<void>&
     return !lhs.owner_before(rhs) && !rhs.owner_before(lhs);
 }
 
+void ReleaseExportedRoots(ArrowArray* array, ArrowSchema* schema) {
+    ArrowArrayRelease(array);
+    if (schema != nullptr) {
+        ArrowSchemaRelease(schema);
+    }
+}
+
 class ArrowMemPoolAdaptor : public arrow::MemoryPool {
  public:
     explicit ArrowMemPoolAdaptor(const std::shared_ptr<paimon::MemoryPool>& 
pool)
@@ -136,10 +143,7 @@ Status AddArrowArrayLifetime(ArrowArray* array, 
ArrowSchema* schema,
         return Status::Invalid("cannot add lifetime to a released ArrowArray");
     }
     if (lifetime.use_count() == 0) {
-        ArrowArrayRelease(array);
-        if (schema != nullptr && schema->release != nullptr) {
-            ArrowSchemaRelease(schema);
-        }
+        ReleaseExportedRoots(array, schema);
         return Status::Invalid("cannot add an empty lifetime to an 
ArrowArray");
     }
     if (array->release == ReleaseArrowArray) {
@@ -148,10 +152,15 @@ Status AddArrowArrayLifetime(ArrowArray* array, 
ArrowSchema* schema,
             return Status::OK();
         }
     }
-    std::unique_ptr<ArrowArrayPrivateData> data = 
std::make_unique<ArrowArrayPrivateData>(
-        ArrowArrayPrivateData{array->release, array->private_data, lifetime});
-    array->release = ReleaseArrowArray;
-    array->private_data = data.release();
+    try {
+        auto data = std::make_unique<ArrowArrayPrivateData>(
+            ArrowArrayPrivateData{array->release, array->private_data, 
lifetime});
+        array->release = ReleaseArrowArray;
+        array->private_data = data.release();
+    } catch (const std::bad_alloc&) {
+        ReleaseExportedRoots(array, schema);
+        return Status::OutOfMemory("failed to retain exported ArrowArray 
lifetime");
+    }
     return Status::OK();
 }
 
diff --git a/src/paimon/format/parquet/parquet_file_batch_reader.cpp 
b/src/paimon/format/parquet/parquet_file_batch_reader.cpp
index 50f3b973..d8d5d5d3 100644
--- a/src/paimon/format/parquet/parquet_file_batch_reader.cpp
+++ b/src/paimon/format/parquet/parquet_file_batch_reader.cpp
@@ -30,6 +30,7 @@
 #include "arrow/array/array_nested.h"
 #include "arrow/c/abi.h"
 #include "arrow/c/bridge.h"
+#include "arrow/c/helpers.h"
 #include "arrow/compute/api.h"
 #include "arrow/dataset/dataset.h"
 #include "arrow/dataset/file_base.h"
@@ -778,6 +779,10 @@ Result<BatchReader::ReadBatch> 
ParquetFileBatchReader::NextBatch() {
         PAIMON_RETURN_NOT_OK(GenerateRowMapping(array->length()));
         std::unique_ptr<ArrowArray> c_array = std::make_unique<ArrowArray>();
         std::unique_ptr<ArrowSchema> c_schema = 
std::make_unique<ArrowSchema>();
+        ScopeGuard release_roots([&]() {
+            ArrowArrayRelease(c_array.get());
+            ArrowSchemaRelease(c_schema.get());
+        });
         PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportArray(*array, 
c_array.get(), c_schema.get()));
         PAIMON_RETURN_NOT_OK(AddArrowArrayLifetime(c_array.get(), 
c_schema.get(), arrow_pool_));
 
@@ -786,6 +791,7 @@ Result<BatchReader::ReadBatch> 
ParquetFileBatchReader::NextBatch() {
         metrics_->SetCounter(ParquetMetrics::READ_ROWS, read_rows_);
         metrics_->SetCounter(ParquetMetrics::READ_BATCH_COUNT, 
read_batch_count_);
 
+        release_roots.Release();
         return make_pair(std::move(c_array), std::move(c_schema));
     }
     PAIMON_PARQUET_CATCH_AND_RETURN_STATUS("ParquetFileBatchReader::NextBatch")
diff --git a/src/paimon/format/parquet/parquet_file_batch_reader_test.cpp 
b/src/paimon/format/parquet/parquet_file_batch_reader_test.cpp
index 703541d1..bdbbe993 100644
--- a/src/paimon/format/parquet/parquet_file_batch_reader_test.cpp
+++ b/src/paimon/format/parquet/parquet_file_batch_reader_test.cpp
@@ -25,6 +25,7 @@
 #include <iostream>
 #include <limits>
 #include <memory>
+#include <new>
 #include <string>
 #include <utility>
 #include <vector>
@@ -667,6 +668,56 @@ TEST_F(ParquetFileBatchReaderTest, TestNextBatchSimple) {
     }
 }
 
+TEST_F(ParquetFileBatchReaderTest, ReleasesUnpublishedBatchWhenMetricsFail) {
+    class FailingReadMetrics final : public MetricsImpl {
+     public:
+        void SetCounter(const std::string& name, uint64_t value) override {
+            if (name == ParquetMetrics::READ_ROWS) {
+                failed = true;
+                throw std::bad_alloc();
+            }
+            MetricsImpl::SetCounter(name, value);
+        }
+
+        bool failed = false;
+    };
+
+    const auto file_name = paimon::test::GetDataDir() +
+                           
"parquet/parquet_append_table.db/parquet_append_table/bucket-0/"
+                           
"data-9ea62f34-1dca-49c1-bf7a-d37303d8fb76-0.parquet";
+    const auto initial_bytes = pool_->bytes_allocated();
+    const auto initial_export_bytes = 
arrow::default_memory_pool()->bytes_allocated();
+    auto metrics = std::make_shared<FailingReadMetrics>();
+    auto reader =
+        PrepareParquetFileBatchReader(file_name, schema_, 
/*predicate=*/nullptr,
+                                      /*selection_bitmap=*/std::nullopt, 
/*batch_size=*/1);
+    ASSERT_TRUE(reader);
+    reader->metrics_ = metrics;
+    const auto batch = reader->NextBatch();
+    EXPECT_TRUE(metrics->failed);
+    ASSERT_NOK(batch);
+    EXPECT_TRUE(batch.status().IsInvalid());
+    reader->Close();
+    reader.reset();
+    EXPECT_EQ(pool_->bytes_allocated(), initial_bytes);
+    EXPECT_EQ(arrow::default_memory_pool()->bytes_allocated(), 
initial_export_bytes);
+
+    auto retry = PrepareParquetFileBatchReader(file_name, schema_, 
/*predicate=*/nullptr,
+                                               
/*selection_bitmap=*/std::nullopt, /*batch_size=*/1);
+    ASSERT_TRUE(retry);
+    ASSERT_OK_AND_ASSIGN(auto returned, retry->NextBatch());
+    EXPECT_FALSE(BatchReader::IsEofBatch(returned));
+    {
+        auto array = arrow::ImportArray(returned.first.get(), 
returned.second.get());
+        ASSERT_TRUE(array.ok()) << array.status().ToString();
+        EXPECT_EQ(array.ValueOrDie()->length(), 1);
+    }
+    retry->Close();
+    retry.reset();
+    EXPECT_EQ(pool_->bytes_allocated(), initial_bytes);
+    EXPECT_EQ(arrow::default_memory_pool()->bytes_allocated(), 
initial_export_bytes);
+}
+
 TEST_F(ParquetFileBatchReaderTest, TestNextBatchWithTargetSchema) {
     std::string file_name = paimon::test::GetDataDir() +
                             
"parquet/parquet_append_table.db/parquet_append_table/bucket-0/"

Reply via email to