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

SteNicholas 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 3a332805 perf(global-index): materialize bitmap results eagerly and 
batch unions (#552)
3a332805 is described below

commit 3a332805bb56c5a234042e83006ccea9d937ca1b
Author: lxy <[email protected]>
AuthorDate: Thu Nov 12 19:47:36 2026 +0800

    perf(global-index): materialize bitmap results eagerly and batch unions 
(#552)
---
 .../global_index/bitmap_global_index_result.h      | 21 +++---
 include/paimon/global_index/global_index_result.h  |  3 +-
 .../bitmap/bitmap_global_index_test.cpp            |  7 ++
 .../global_index/bitmap/bitmap_index_reader.cpp    |  4 +-
 .../global_index/bitmap/bitmap_index_reader.h      |  2 +-
 .../global_index/bitmap_global_index_result.cpp    | 70 ++++++-----------
 .../bitmap_global_index_result_test.cpp            | 88 +++++++++++++++-------
 .../bitmap_scored_global_index_result.cpp          |  4 +-
 .../bitmap_scored_global_index_result_test.cpp     |  6 +-
 .../btree/btree_global_index_reader.cpp            | 34 ++++-----
 .../btree/lazy_filtered_btree_reader.cpp           |  4 +-
 .../common/global_index/global_index_result.cpp    |  7 +-
 .../global_index/global_index_result_test.cpp      |  3 +-
 .../common/global_index/global_index_utils.h       | 35 +++++++++
 .../global_index/global_index_utils_test.cpp       | 50 ++++++++++++
 .../sorted_file_global_index_reader.cpp            | 16 ++--
 .../global_index/union_global_index_reader.cpp     | 11 +--
 .../global_index/wrap/file_index_reader_wrapper.h  | 13 ++--
 .../wrap/file_index_reader_wrapper_test.cpp        |  8 +-
 .../global_index_evaluator_impl_test.cpp           |  3 +-
 .../core/table/source/filtered_row_id_reader.cpp   |  3 +-
 .../table/source/primary_key_sorted_index_scan.cpp |  4 +-
 .../source/primary_key_sorted_index_scan_test.cpp  |  4 +-
 src/paimon/testing/mock/mock_global_index_reader.h |  4 +-
 24 files changed, 245 insertions(+), 159 deletions(-)

diff --git a/include/paimon/global_index/bitmap_global_index_result.h 
b/include/paimon/global_index/bitmap_global_index_result.h
index 8587459f..93133e60 100644
--- a/include/paimon/global_index/bitmap_global_index_result.h
+++ b/include/paimon/global_index/bitmap_global_index_result.h
@@ -19,6 +19,7 @@
 
 #pragma once
 
+#include <functional>
 #include <memory>
 #include <string>
 #include <utility>
@@ -29,15 +30,15 @@
 #include "paimon/visibility.h"
 
 namespace paimon {
-/// Represents a global index query result backed by a Roaring bitmap. 
Supplier-backed results
-/// materialize their matching row ids on the first GetBitmap() call, avoiding 
unnecessary work
-/// when the result is not used. OR between bitmap results materializes both 
operands immediately
-/// and returns a cached bitmap without retaining the input results.
+/// Represents a global index query result backed by a Roaring bitmap.
 class PAIMON_EXPORT BitmapGlobalIndexResult : public GlobalIndexResult {
  public:
     using BitmapSupplier = std::function<Result<RoaringBitmap64>()>;
-    explicit BitmapGlobalIndexResult(BitmapSupplier bitmap_supplier)
-        : bitmap_supplier_(bitmap_supplier) {}
+    explicit BitmapGlobalIndexResult(RoaringBitmap64 bitmap) : 
bitmap_(std::move(bitmap)) {}
+
+    /// Executes the supplier immediately and returns its bitmap, or 
propagates its error.
+    /// The returned result does not retain the supplier or its captures.
+    static Result<std::shared_ptr<BitmapGlobalIndexResult>> 
Create(BitmapSupplier bitmap_supplier);
 
     class Iterator : public GlobalIndexResult::Iterator {
      public:
@@ -75,9 +76,7 @@ class PAIMON_EXPORT BitmapGlobalIndexResult : public 
GlobalIndexResult {
 
     /// @return A non-owning, const pointer to the bitmap. The returned 
pointer is valid as long as
     ///         this BitmapGlobalIndexResult object is alive. The caller must 
not modify the bitmap.
-    /// @note Supplier-backed results construct the bitmap on the first call 
to this method.
-    ///       Precomputed results and subsequent calls return the cached 
instance.
-    ///       Materialization may involve non-trivial CPU/IO cost. **Not 
thread-safe**.
+    /// @note Returns the stored bitmap without performing computation or I/O.
     Result<const RoaringBitmap64*> GetBitmap() const;
 
     /// Creates `BitmapGlobalIndexResult` for all row ids in the given ranges.
@@ -85,8 +84,6 @@ class PAIMON_EXPORT BitmapGlobalIndexResult : public 
GlobalIndexResult {
     static std::shared_ptr<BitmapGlobalIndexResult> FromRanges(const 
std::vector<Range>& ranges);
 
  private:
-    mutable bool initialized_ = false;
-    BitmapSupplier bitmap_supplier_;
-    mutable RoaringBitmap64 bitmap_;
+    RoaringBitmap64 bitmap_;
 };
 }  // namespace paimon
diff --git a/include/paimon/global_index/global_index_result.h 
b/include/paimon/global_index/global_index_result.h
index bb16d6e6..17926764 100644
--- a/include/paimon/global_index/global_index_result.h
+++ b/include/paimon/global_index/global_index_result.h
@@ -52,8 +52,7 @@ class PAIMON_EXPORT GlobalIndexResult : public 
std::enable_shared_from_this<Glob
     /// @return A `Result<bool>` where:
     ///         - `true` indicates the result is empty (no matching rows),
     ///         - `false` indicates at least one matching row exists,
-    ///         - An error is returned only if internal state is corrupted or 
I/O fails
-    ///           (e.g., during lazy loading of index data).
+    ///         - An error is returned if the implementation cannot inspect 
its state.
     virtual Result<bool> IsEmpty() const = 0;
 
     /// Creates a new iterator over the selected row ids.
diff --git a/src/paimon/common/global_index/bitmap/bitmap_global_index_test.cpp 
b/src/paimon/common/global_index/bitmap/bitmap_global_index_test.cpp
index 972fb00c..914fe77a 100644
--- a/src/paimon/common/global_index/bitmap/bitmap_global_index_test.cpp
+++ b/src/paimon/common/global_index/bitmap/bitmap_global_index_test.cpp
@@ -114,6 +114,8 @@ TEST_F(BitmapGlobalIndexTest, WriteAndReadStringPredicates) 
{
                          CreateReader(field->type(), metas[0]));
     ASSERT_FALSE(reader->IsThreadSafe());
     ASSERT_EQ(reader->GetIndexType(), "bitmap");
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<GlobalIndexResult> saved_result,
+                         reader->VisitEqual(StringLiteral("apple")));
     CheckResult(reader->VisitIsNull(), {2, 6});
     CheckResult(reader->VisitIsNotNull(), {0, 1, 3, 4, 5});
     CheckResult(reader->VisitEqual(StringLiteral("apple")), {0, 1});
@@ -184,6 +186,11 @@ TEST_F(BitmapGlobalIndexTest, 
WriteAndReadStringPredicates) {
     ASSERT_NOK_WITH_MSG(reader->VisitFullTextSearch(nullptr),
                         "Full text search is not supported in 
BitmapIndexReader");
     ASSERT_OK(reader->Close());
+    ASSERT_NOK_WITH_MSG(reader->VisitEqual(StringLiteral("apple")), "closed 
BitmapIndexReader");
+    std::weak_ptr<BitmapIndexReader> weak_reader = reader;
+    reader.reset();
+    ASSERT_TRUE(weak_reader.expired());
+    CheckResult(saved_result, {0, 1});
 }
 
 TEST_F(BitmapGlobalIndexTest, WriteAndReadLogicalIntegerOrder) {
diff --git a/src/paimon/common/global_index/bitmap/bitmap_index_reader.cpp 
b/src/paimon/common/global_index/bitmap/bitmap_index_reader.cpp
index baa41c9a..5a88e6dc 100644
--- a/src/paimon/common/global_index/bitmap/bitmap_index_reader.cpp
+++ b/src/paimon/common/global_index/bitmap/bitmap_index_reader.cpp
@@ -62,9 +62,9 @@ BitmapIndexReader::~BitmapIndexReader() {
     [[maybe_unused]] Status close_status = Close();
 }
 
-std::shared_ptr<GlobalIndexResult> BitmapIndexReader::CreateResult(
+Result<std::shared_ptr<GlobalIndexResult>> BitmapIndexReader::CreateResult(
     std::function<Result<RoaringBitmap64>()> supplier) {
-    return std::make_shared<BitmapGlobalIndexResult>(std::move(supplier));
+    return BitmapGlobalIndexResult::Create(std::move(supplier));
 }
 
 Result<std::shared_ptr<GlobalIndexResult>> BitmapIndexReader::VisitIsNotNull() 
{
diff --git a/src/paimon/common/global_index/bitmap/bitmap_index_reader.h 
b/src/paimon/common/global_index/bitmap/bitmap_index_reader.h
index 350a6dad..16166126 100644
--- a/src/paimon/common/global_index/bitmap/bitmap_index_reader.h
+++ b/src/paimon/common/global_index/bitmap/bitmap_index_reader.h
@@ -98,7 +98,7 @@ class BitmapIndexReader : public GlobalIndexReader,
           file_size_(file_size),
           pool_(std::move(pool)) {}
 
-    std::shared_ptr<GlobalIndexResult> CreateResult(
+    Result<std::shared_ptr<GlobalIndexResult>> CreateResult(
         std::function<Result<RoaringBitmap64>()> supplier);
 
     Result<RoaringBitmap64> IsNull();
diff --git a/src/paimon/common/global_index/bitmap_global_index_result.cpp 
b/src/paimon/common/global_index/bitmap_global_index_result.cpp
index ea9a03a1..4924032d 100644
--- a/src/paimon/common/global_index/bitmap_global_index_result.cpp
+++ b/src/paimon/common/global_index/bitmap_global_index_result.cpp
@@ -19,6 +19,12 @@
 #include "paimon/global_index/bitmap_global_index_result.h"
 
 namespace paimon {
+Result<std::shared_ptr<BitmapGlobalIndexResult>> 
BitmapGlobalIndexResult::Create(
+    BitmapSupplier bitmap_supplier) {
+    PAIMON_ASSIGN_OR_RAISE(RoaringBitmap64 bitmap, bitmap_supplier());
+    return std::make_shared<BitmapGlobalIndexResult>(std::move(bitmap));
+}
+
 Result<std::unique_ptr<GlobalIndexResult::Iterator>> 
BitmapGlobalIndexResult::CreateIterator()
     const {
     PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap64* bitmap, GetBitmap());
@@ -30,13 +36,8 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BitmapGlobalIndexResult::And(
     const std::shared_ptr<GlobalIndexResult>& other) {
     auto typed_result = 
std::dynamic_pointer_cast<BitmapGlobalIndexResult>(other);
     if (typed_result) {
-        auto supplier = [typed_result, result = 
std::dynamic_pointer_cast<BitmapGlobalIndexResult>(
-                                           shared_from_this())]() -> 
Result<RoaringBitmap64> {
-            PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap64* r1, 
result->GetBitmap());
-            PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap64* r2, 
typed_result->GetBitmap());
-            return RoaringBitmap64::And(*r1, *r2);
-        };
-        return std::make_shared<BitmapGlobalIndexResult>(supplier);
+        return std::make_shared<BitmapGlobalIndexResult>(
+            RoaringBitmap64::And(bitmap_, typed_result->bitmap_));
     }
     return GlobalIndexResult::And(other);
 }
@@ -45,16 +46,8 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BitmapGlobalIndexResult::Or(
     const std::shared_ptr<GlobalIndexResult>& other) {
     auto typed_result = 
std::dynamic_pointer_cast<BitmapGlobalIndexResult>(other);
     if (typed_result) {
-        // Repeated lazy ORs build deep supplier chains that retain operands 
and materialized
-        // intermediate unions. Merge eagerly to avoid deep recursion and let 
previous results
-        // be released when callers drop them. AND remains lazy so callers 
that short-circuit
-        // can avoid materializing unused intersections.
-        PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap64* r1, GetBitmap());
-        PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap64* r2, 
typed_result->GetBitmap());
-        auto result = 
std::make_shared<BitmapGlobalIndexResult>(BitmapSupplier{});
-        result->bitmap_ = RoaringBitmap64::Or(*r1, *r2);
-        result->initialized_ = true;
-        return result;
+        return std::make_shared<BitmapGlobalIndexResult>(
+            RoaringBitmap64::Or(bitmap_, typed_result->bitmap_));
     }
     return GlobalIndexResult::Or(other);
 }
@@ -63,49 +56,32 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BitmapGlobalIndexResult::AddOffset(in
     if (offset == 0) {
         return shared_from_this();
     }
-    auto supplier = [offset, result = 
std::dynamic_pointer_cast<BitmapGlobalIndexResult>(
-                                 shared_from_this())]() -> 
Result<RoaringBitmap64> {
-        PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap64* bitmap, 
result->GetBitmap());
-        RoaringBitmap64 bitmap64;
-        for (auto iter = bitmap->Begin(); iter != bitmap->End(); ++iter) {
-            bitmap64.Add(offset + (*iter));
-        }
-        bitmap64.RunOptimize();
-        return bitmap64;
-    };
-    return std::make_shared<BitmapGlobalIndexResult>(supplier);
+    RoaringBitmap64 bitmap64;
+    for (auto iter = bitmap_.Begin(); iter != bitmap_.End(); ++iter) {
+        bitmap64.Add(offset + (*iter));
+    }
+    bitmap64.RunOptimize();
+    return std::make_shared<BitmapGlobalIndexResult>(std::move(bitmap64));
 }
 
 Result<const RoaringBitmap64*> BitmapGlobalIndexResult::GetBitmap() const {
-    if (!initialized_) {
-        PAIMON_ASSIGN_OR_RAISE(bitmap_, bitmap_supplier_());
-        initialized_ = true;
-    }
     return &bitmap_;
 }
 
 Result<bool> BitmapGlobalIndexResult::IsEmpty() const {
-    PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap64* bitmap, GetBitmap());
-    return bitmap->IsEmpty();
+    return bitmap_.IsEmpty();
 }
 
 std::string BitmapGlobalIndexResult::ToString() const {
-    auto bitmap = GetBitmap();
-    if (!bitmap.ok()) {
-        return bitmap.status().ToString();
-    }
-    return bitmap.value()->ToString();
+    return bitmap_.ToString();
 }
 
 std::shared_ptr<BitmapGlobalIndexResult> BitmapGlobalIndexResult::FromRanges(
     const std::vector<Range>& ranges) {
-    BitmapGlobalIndexResult::BitmapSupplier supplier = [ranges]() -> 
Result<RoaringBitmap64> {
-        RoaringBitmap64 bitmap;
-        for (const auto& range : ranges) {
-            bitmap.AddRange(range.from, range.to + 1);
-        }
-        return bitmap;
-    };
-    return std::make_shared<BitmapGlobalIndexResult>(supplier);
+    RoaringBitmap64 bitmap;
+    for (const auto& range : ranges) {
+        bitmap.AddRange(range.from, range.to + 1);
+    }
+    return std::make_shared<BitmapGlobalIndexResult>(std::move(bitmap));
 }
 }  // namespace paimon
diff --git a/src/paimon/common/global_index/bitmap_global_index_result_test.cpp 
b/src/paimon/common/global_index/bitmap_global_index_result_test.cpp
index e7233043..22d9fc76 100644
--- a/src/paimon/common/global_index/bitmap_global_index_result_test.cpp
+++ b/src/paimon/common/global_index/bitmap_global_index_result_test.cpp
@@ -77,7 +77,8 @@ TEST_F(BitmapGlobalIndexResultTest, TestIterator) {
         auto bitmap_supplier = [&]() -> Result<RoaringBitmap64> {
             return RoaringBitmap64::From(expected_ids);
         };
-        auto index_result = 
std::make_shared<BitmapGlobalIndexResult>(bitmap_supplier);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<BitmapGlobalIndexResult> 
index_result,
+                             BitmapGlobalIndexResult::Create(bitmap_supplier));
         if (expected_ids.empty()) {
             ASSERT_TRUE(index_result->IsEmpty().value());
         }
@@ -101,11 +102,13 @@ TEST_F(BitmapGlobalIndexResultTest, TestAnd) {
         auto bitmap_supplier1 = [&]() -> Result<RoaringBitmap64> {
             return RoaringBitmap64::From(left);
         };
-        auto index_result1 = 
std::make_shared<BitmapGlobalIndexResult>(bitmap_supplier1);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<BitmapGlobalIndexResult> 
index_result1,
+                             
BitmapGlobalIndexResult::Create(bitmap_supplier1));
         auto bitmap_supplier2 = [&]() -> Result<RoaringBitmap64> {
             return RoaringBitmap64::From(right);
         };
-        auto index_result2 = 
std::make_shared<BitmapGlobalIndexResult>(bitmap_supplier2);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<BitmapGlobalIndexResult> 
index_result2,
+                             
BitmapGlobalIndexResult::Create(bitmap_supplier2));
 
         ASSERT_OK_AND_ASSIGN(auto result, index_result1->And(index_result2));
         ASSERT_EQ(result->ToString(), expected_str);
@@ -123,7 +126,8 @@ TEST_F(BitmapGlobalIndexResultTest, 
TestBitmapResultAndOtherResult) {
     auto bitmap_supplier1 = [&]() -> Result<RoaringBitmap64> {
         return RoaringBitmap64::From({1, 2, 3});
     };
-    auto index_result1 = 
std::make_shared<BitmapGlobalIndexResult>(bitmap_supplier1);
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<BitmapGlobalIndexResult> 
index_result1,
+                         BitmapGlobalIndexResult::Create(bitmap_supplier1));
 
     auto fake_result = 
std::make_shared<FakeGlobalIndexResult>(std::vector<int64_t>({1l, 2l, 7l}));
 
@@ -137,11 +141,13 @@ TEST_F(BitmapGlobalIndexResultTest, TestOr) {
         auto bitmap_supplier1 = [&]() -> Result<RoaringBitmap64> {
             return RoaringBitmap64::From(left);
         };
-        auto index_result1 = 
std::make_shared<BitmapGlobalIndexResult>(bitmap_supplier1);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<BitmapGlobalIndexResult> 
index_result1,
+                             
BitmapGlobalIndexResult::Create(bitmap_supplier1));
         auto bitmap_supplier2 = [&]() -> Result<RoaringBitmap64> {
             return RoaringBitmap64::From(right);
         };
-        auto index_result2 = 
std::make_shared<BitmapGlobalIndexResult>(bitmap_supplier2);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<BitmapGlobalIndexResult> 
index_result2,
+                             
BitmapGlobalIndexResult::Create(bitmap_supplier2));
 
         ASSERT_OK_AND_ASSIGN(auto result, index_result1->Or(index_result2));
         ASSERT_EQ(result->ToString(), expected_str);
@@ -155,27 +161,29 @@ TEST_F(BitmapGlobalIndexResultTest, TestOr) {
                      "{1,2,3,9223372036854775807}");
 }
 
-TEST_F(BitmapGlobalIndexResultTest, TestOrPropagatesSupplierErrorsImmediately) 
{
-    for (bool fail_left : {true, false}) {
-        auto left =
-            std::make_shared<BitmapGlobalIndexResult>([fail_left]() -> 
Result<RoaringBitmap64> {
-                if (fail_left) {
-                    return Status::Invalid("left supplier failed");
-                }
-                return RoaringBitmap64::From({1});
-            });
-        auto right = std::make_shared<BitmapGlobalIndexResult>(
-            []() -> Result<RoaringBitmap64> { return Status::Invalid("right 
supplier failed"); });
-        const char* expected_error = fail_left ? "left supplier failed" : 
"right supplier failed";
-        ASSERT_NOK_WITH_MSG(left->Or(right), expected_error);
-    }
+TEST_F(BitmapGlobalIndexResultTest, TestOperationsDoNotRetainOperands) {
+    auto left = 
std::make_shared<BitmapGlobalIndexResult>(RoaringBitmap64::From({1, 2}));
+    auto right = 
std::make_shared<BitmapGlobalIndexResult>(RoaringBitmap64::From({2, 3}));
+    std::weak_ptr<GlobalIndexResult> weak_left = left;
+    std::weak_ptr<GlobalIndexResult> weak_right = right;
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<GlobalIndexResult> intersection, 
left->And(right));
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<GlobalIndexResult> union_result, 
left->Or(right));
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<GlobalIndexResult> offset_result, 
left->AddOffset(10));
+    left.reset();
+    right.reset();
+    ASSERT_TRUE(weak_left.expired());
+    ASSERT_TRUE(weak_right.expired());
+    ASSERT_EQ(intersection->ToString(), "{2}");
+    ASSERT_EQ(union_result->ToString(), "{1,2,3}");
+    ASSERT_EQ(offset_result->ToString(), "{11,12}");
 }
 
 TEST_F(BitmapGlobalIndexResultTest, TestBitmapResultOrOtherResult) {
     auto bitmap_supplier1 = [&]() -> Result<RoaringBitmap64> {
         return RoaringBitmap64::From({1, 2, 3});
     };
-    auto index_result1 = 
std::make_shared<BitmapGlobalIndexResult>(bitmap_supplier1);
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<BitmapGlobalIndexResult> 
index_result1,
+                         BitmapGlobalIndexResult::Create(bitmap_supplier1));
 
     auto fake_result = 
std::make_shared<FakeGlobalIndexResult>(std::vector<int64_t>({1l, 2l, 7l}));
 
@@ -187,8 +195,33 @@ TEST_F(BitmapGlobalIndexResultTest, 
TestInvalidBitmapResult) {
     auto bitmap_supplier = [&]() -> Result<RoaringBitmap64> {
         return Status::Invalid("invalid supplier");
     };
-    auto result = std::make_shared<BitmapGlobalIndexResult>(bitmap_supplier);
-    ASSERT_TRUE(result->ToString().find("Invalid: invalid supplier") != 
std::string::npos);
+    ASSERT_NOK_WITH_MSG(BitmapGlobalIndexResult::Create(bitmap_supplier), 
"invalid supplier");
+}
+
+TEST_F(BitmapGlobalIndexResultTest, TestCreateMaterializesAndReleasesSupplier) 
{
+    auto source = std::make_shared<RoaringBitmap64>(RoaringBitmap64::From({1, 
4, 7}));
+    std::weak_ptr<RoaringBitmap64> weak_source = source;
+    int32_t supplier_calls = 0;
+    ASSERT_OK_AND_ASSIGN(
+        std::shared_ptr<BitmapGlobalIndexResult> result,
+        BitmapGlobalIndexResult::Create(
+            [source = std::move(source), &supplier_calls]() -> 
Result<RoaringBitmap64> {
+                ++supplier_calls;
+                return *source;
+            }));
+    ASSERT_EQ(supplier_calls, 1);
+    ASSERT_TRUE(weak_source.expired());
+    ASSERT_OK_AND_ASSIGN(const RoaringBitmap64* first, result->GetBitmap());
+    ASSERT_OK_AND_ASSIGN(const RoaringBitmap64* second, result->GetBitmap());
+    ASSERT_EQ(first, second);
+    ASSERT_EQ(result->ToString(), "{1,4,7}");
+    ASSERT_OK_AND_ASSIGN(bool empty, result->IsEmpty());
+    ASSERT_FALSE(empty);
+    ASSERT_OK_AND_ASSIGN(std::unique_ptr<GlobalIndexResult::Iterator> iterator,
+                         result->CreateIterator());
+    ASSERT_TRUE(iterator->HasNext());
+    ASSERT_EQ(iterator->Next(), 1);
+    ASSERT_EQ(supplier_calls, 1);
 }
 
 TEST_F(BitmapGlobalIndexResultTest, TestFromRanges) {
@@ -209,15 +242,16 @@ TEST_F(BitmapGlobalIndexResultTest, TestFromRanges) {
 TEST_F(BitmapGlobalIndexResultTest, TestAddOffset) {
     {
         int32_t supplier_calls = 0;
-        auto result = std::make_shared<BitmapGlobalIndexResult>(
-            [&supplier_calls]() -> Result<RoaringBitmap64> {
+        ASSERT_OK_AND_ASSIGN(
+            std::shared_ptr<BitmapGlobalIndexResult> result,
+            BitmapGlobalIndexResult::Create([&supplier_calls]() -> 
Result<RoaringBitmap64> {
                 ++supplier_calls;
                 return RoaringBitmap64::From({0, 1, 2, 3, 4, 5});
-            });
+            }));
         ASSERT_OK_AND_ASSIGN(std::shared_ptr<GlobalIndexResult> 
result_with_offset,
                              result->AddOffset(0));
         ASSERT_EQ(result_with_offset.get(), result.get());
-        ASSERT_EQ(supplier_calls, 0);
+        ASSERT_EQ(supplier_calls, 1);
         ASSERT_EQ(result_with_offset->ToString(), "{0,1,2,3,4,5}");
         ASSERT_EQ(supplier_calls, 1);
 
diff --git 
a/src/paimon/common/global_index/bitmap_scored_global_index_result.cpp 
b/src/paimon/common/global_index/bitmap_scored_global_index_result.cpp
index 4beb10ea..de1f9c63 100644
--- a/src/paimon/common/global_index/bitmap_scored_global_index_result.cpp
+++ b/src/paimon/common/global_index/bitmap_scored_global_index_result.cpp
@@ -69,7 +69,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BitmapScoredGlobalIndexResult::And(
             PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap64* r2, 
result->GetBitmap());
             return RoaringBitmap64::And(*r1, *r2);
         };
-        return std::make_shared<BitmapGlobalIndexResult>(supplier);
+        return BitmapGlobalIndexResult::Create(std::move(supplier));
     }
     auto bitmap_other = 
std::dynamic_pointer_cast<BitmapGlobalIndexResult>(other);
     if (bitmap_other) {
@@ -119,7 +119,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BitmapScoredGlobalIndexResult::Or(
             PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap64* r2, 
result->GetBitmap());
             return RoaringBitmap64::Or(*r1, *r2);
         };
-        return std::make_shared<BitmapGlobalIndexResult>(supplier);
+        return BitmapGlobalIndexResult::Create(std::move(supplier));
     }
     return GlobalIndexResult::Or(other);
 }
diff --git 
a/src/paimon/common/global_index/bitmap_scored_global_index_result_test.cpp 
b/src/paimon/common/global_index/bitmap_scored_global_index_result_test.cpp
index 25540dad..b7e1ed76 100644
--- a/src/paimon/common/global_index/bitmap_scored_global_index_result_test.cpp
+++ b/src/paimon/common/global_index/bitmap_scored_global_index_result_test.cpp
@@ -143,7 +143,8 @@ TEST_F(BitmapScoredGlobalIndexResultTest, 
TestAndBitmapResult) {
             auto bitmap_supplier2 = [&]() -> Result<RoaringBitmap64> {
                 return RoaringBitmap64::From(right_ids);
             };
-            auto index_result2 = 
std::make_shared<BitmapGlobalIndexResult>(bitmap_supplier2);
+            ASSERT_OK_AND_ASSIGN(std::shared_ptr<BitmapGlobalIndexResult> 
index_result2,
+                                 
BitmapGlobalIndexResult::Create(bitmap_supplier2));
 
             ASSERT_OK_AND_ASSIGN(auto result, 
index_result1->And(index_result2));
             ASSERT_EQ(result->ToString(), expected_str);
@@ -204,7 +205,8 @@ TEST_F(BitmapScoredGlobalIndexResultTest, 
TestOrBitmapResult) {
         auto bitmap_supplier2 = [&]() -> Result<RoaringBitmap64> {
             return RoaringBitmap64::From(right_ids);
         };
-        auto index_result2 = 
std::make_shared<BitmapGlobalIndexResult>(bitmap_supplier2);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<BitmapGlobalIndexResult> 
index_result2,
+                             
BitmapGlobalIndexResult::Create(bitmap_supplier2));
 
         ASSERT_OK_AND_ASSIGN(auto result, index_result1->Or(index_result2));
         ASSERT_EQ(result->ToString(), expected_str);
diff --git a/src/paimon/common/global_index/btree/btree_global_index_reader.cpp 
b/src/paimon/common/global_index/btree/btree_global_index_reader.cpp
index f42d13f8..793e9e68 100644
--- a/src/paimon/common/global_index/btree/btree_global_index_reader.cpp
+++ b/src/paimon/common/global_index/btree/btree_global_index_reader.cpp
@@ -67,14 +67,14 @@ BTreeGlobalIndexReader::BTreeGlobalIndexReader(
       comparator_(key_serializer_->CreateComparator()) {}
 
 Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitIsNotNull() {
-    return std::make_shared<BitmapGlobalIndexResult>(
+    return BitmapGlobalIndexResult::Create(
         [reader = shared_from_this()]() -> Result<RoaringBitmap64> {
             return reader->AllNonNullRows();
         });
 }
 
 Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitIsNull() {
-    return std::make_shared<BitmapGlobalIndexResult>(
+    return BitmapGlobalIndexResult::Create(
         [reader = shared_from_this()]() -> Result<RoaringBitmap64> {
             if (!reader->row_id_filter_) {
                 return reader->null_bitmap_;
@@ -92,7 +92,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitStartsWi
     if (prefix.GetType() == FieldType::STRING) {
         auto prefix_str = prefix.GetValue<std::string>();
         if (prefix_str.empty()) {
-            return std::make_shared<BitmapGlobalIndexResult>(
+            return BitmapGlobalIndexResult::Create(
                 [reader = shared_from_this()]() -> Result<RoaringBitmap64> {
                     return reader->AllNonNullRows();
                 });
@@ -114,7 +114,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitStartsWi
 
         if (!overflow) {
             Literal upper_bound(FieldType::STRING, upper_str.data(), 
upper_str.size());
-            return std::make_shared<BitmapGlobalIndexResult>(
+            return BitmapGlobalIndexResult::Create(
                 [reader = shared_from_this(), prefix = prefix,
                  upper_bound = std::move(upper_bound)]() -> 
Result<RoaringBitmap64> {
                     return reader->RangeQuery(prefix, upper_bound, 
/*from_inclusive=*/true,
@@ -123,14 +123,14 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitStartsWi
         }
 
         // All bytes were 0xFF, use max_key_ as upper bound
-        return std::make_shared<BitmapGlobalIndexResult>(
+        return BitmapGlobalIndexResult::Create(
             [reader = shared_from_this(), prefix = prefix]() -> 
Result<RoaringBitmap64> {
                 return reader->RangeQuery(prefix, reader->max_key_, 
/*from_inclusive=*/true,
                                           /*to_inclusive=*/true);
             });
     }
 
-    return std::make_shared<BitmapGlobalIndexResult>(
+    return BitmapGlobalIndexResult::Create(
         [reader = shared_from_this()]() -> Result<RoaringBitmap64> {
             return reader->AllNonNullRows();
         });
@@ -138,7 +138,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitStartsWi
 
 Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitEndsWith(
     const Literal& suffix) {
-    return std::make_shared<BitmapGlobalIndexResult>(
+    return BitmapGlobalIndexResult::Create(
         [reader = shared_from_this()]() -> Result<RoaringBitmap64> {
             return reader->AllNonNullRows();
         });
@@ -146,7 +146,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitEndsWith
 
 Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitContains(
     const Literal& literal) {
-    return std::make_shared<BitmapGlobalIndexResult>(
+    return BitmapGlobalIndexResult::Create(
         [reader = shared_from_this()]() -> Result<RoaringBitmap64> {
             return reader->AllNonNullRows();
         });
@@ -176,7 +176,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitLike(
             return VisitStartsWith(prefix_literal);
         }
     }
-    return std::make_shared<BitmapGlobalIndexResult>(
+    return BitmapGlobalIndexResult::Create(
         [reader = shared_from_this()]() -> Result<RoaringBitmap64> {
             return reader->AllNonNullRows();
         });
@@ -184,7 +184,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitLike(
 
 Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitLessThan(
     const Literal& literal) {
-    return std::make_shared<BitmapGlobalIndexResult>(
+    return BitmapGlobalIndexResult::Create(
         [reader = shared_from_this(), literal = literal]() -> 
Result<RoaringBitmap64> {
             return reader->RangeQuery(reader->min_key_, literal, 
/*from_inclusive=*/true,
                                       /*to_inclusive=*/false);
@@ -193,7 +193,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitLessThan
 
 Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitGreaterOrEqual(
     const Literal& literal) {
-    return std::make_shared<BitmapGlobalIndexResult>(
+    return BitmapGlobalIndexResult::Create(
         [reader = shared_from_this(), literal = literal]() -> 
Result<RoaringBitmap64> {
             return reader->RangeQuery(literal, reader->max_key_, 
/*from_inclusive=*/true,
                                       /*to_inclusive=*/true);
@@ -202,7 +202,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitGreaterO
 
 Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitNotEqual(
     const Literal& literal) {
-    return std::make_shared<BitmapGlobalIndexResult>(
+    return BitmapGlobalIndexResult::Create(
         [reader = shared_from_this(), literal = literal]() -> 
Result<RoaringBitmap64> {
             PAIMON_ASSIGN_OR_RAISE(RoaringBitmap64 result, 
reader->AllNonNullRows());
             PAIMON_ASSIGN_OR_RAISE(RoaringBitmap64 equal_result,
@@ -215,7 +215,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitNotEqual
 
 Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitLessOrEqual(
     const Literal& literal) {
-    return std::make_shared<BitmapGlobalIndexResult>(
+    return BitmapGlobalIndexResult::Create(
         [reader = shared_from_this(), literal = literal]() -> 
Result<RoaringBitmap64> {
             return reader->RangeQuery(reader->min_key_, literal, 
/*from_inclusive=*/true,
                                       /*to_inclusive=*/true);
@@ -224,7 +224,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitLessOrEq
 
 Result<std::shared_ptr<GlobalIndexResult>> BTreeGlobalIndexReader::VisitEqual(
     const Literal& literal) {
-    return std::make_shared<BitmapGlobalIndexResult>(
+    return BitmapGlobalIndexResult::Create(
         [reader = shared_from_this(), literal = literal]() -> 
Result<RoaringBitmap64> {
             return reader->PointQuery(literal);
         });
@@ -232,7 +232,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitEqual(
 
 Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitGreaterThan(
     const Literal& literal) {
-    return std::make_shared<BitmapGlobalIndexResult>(
+    return BitmapGlobalIndexResult::Create(
         [reader = shared_from_this(), literal = literal]() -> 
Result<RoaringBitmap64> {
             return reader->RangeQuery(literal, reader->max_key_, 
/*from_inclusive=*/false,
                                       /*to_inclusive=*/true);
@@ -241,7 +241,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
BTreeGlobalIndexReader::VisitGreaterT
 
 Result<std::shared_ptr<GlobalIndexResult>> BTreeGlobalIndexReader::VisitIn(
     const std::vector<Literal>& literals) {
-    return std::make_shared<BitmapGlobalIndexResult>(
+    return BitmapGlobalIndexResult::Create(
         [reader = shared_from_this(), literals = literals]() -> 
Result<RoaringBitmap64> {
             RoaringBitmap64 result;
             for (const auto& literal : literals) {
@@ -274,7 +274,7 @@ Result<RoaringBitmap64> 
BTreeGlobalIndexReader::PointQuery(const Literal& litera
 
 Result<std::shared_ptr<GlobalIndexResult>> BTreeGlobalIndexReader::VisitNotIn(
     const std::vector<Literal>& literals) {
-    return std::make_shared<BitmapGlobalIndexResult>(
+    return BitmapGlobalIndexResult::Create(
         [reader = shared_from_this(), literals = literals]() -> 
Result<RoaringBitmap64> {
             PAIMON_ASSIGN_OR_RAISE(RoaringBitmap64 result, 
reader->AllNonNullRows());
             PAIMON_ASSIGN_OR_RAISE(std::shared_ptr<GlobalIndexResult> 
in_result,
diff --git 
a/src/paimon/common/global_index/btree/lazy_filtered_btree_reader.cpp 
b/src/paimon/common/global_index/btree/lazy_filtered_btree_reader.cpp
index 0dd9aa73..cf28da93 100644
--- a/src/paimon/common/global_index/btree/lazy_filtered_btree_reader.cpp
+++ b/src/paimon/common/global_index/btree/lazy_filtered_btree_reader.cpp
@@ -217,9 +217,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
LazyFilteredBTreeReader::VisitGreater
 Result<std::shared_ptr<GlobalIndexResult>> 
LazyFilteredBTreeReader::FullResult() const {
     assert(total_row_count_ > 0);
     if (row_id_filter_) {
-        RoaringBitmap64 filter = row_id_filter_.value();
-        return std::make_shared<BitmapGlobalIndexResult>(
-            [filter = std::move(filter)]() -> Result<RoaringBitmap64> { return 
filter; });
+        return 
std::make_shared<BitmapGlobalIndexResult>(row_id_filter_.value());
     }
     return BitmapGlobalIndexResult::FromRanges({Range(0, total_row_count_ - 
1)});
 }
diff --git a/src/paimon/common/global_index/global_index_result.cpp 
b/src/paimon/common/global_index/global_index_result.cpp
index d2b94f21..93af7fd5 100644
--- a/src/paimon/common/global_index/global_index_result.cpp
+++ b/src/paimon/common/global_index/global_index_result.cpp
@@ -62,7 +62,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
GlobalIndexResult::And(
         bitmap1 &= bitmap2;
         return bitmap1;
     };
-    return std::make_shared<BitmapGlobalIndexResult>(supplier);
+    return BitmapGlobalIndexResult::Create(std::move(supplier));
 }
 
 Result<std::shared_ptr<GlobalIndexResult>> GlobalIndexResult::Or(
@@ -81,7 +81,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
GlobalIndexResult::Or(
         }
         return bitmap;
     };
-    return std::make_shared<BitmapGlobalIndexResult>(supplier);
+    return BitmapGlobalIndexResult::Create(std::move(supplier));
 }
 
 Result<PAIMON_UNIQUE_PTR<Bytes>> GlobalIndexResult::Serialize(
@@ -122,8 +122,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
GlobalIndexResult::Deserialize(
 
     PAIMON_ASSIGN_OR_RAISE(int32_t score_len, in.ReadValue<int32_t>());
     if (score_len == 0) {
-        return std::make_shared<BitmapGlobalIndexResult>(
-            [bitmap]() -> Result<RoaringBitmap64> { return bitmap; });
+        return std::make_shared<BitmapGlobalIndexResult>(std::move(bitmap));
     }
     if (score_len != bitmap.Cardinality()) {
         return Status::Invalid("row id count mismatches score count");
diff --git a/src/paimon/common/global_index/global_index_result_test.cpp 
b/src/paimon/common/global_index/global_index_result_test.cpp
index 3179e671..06568627 100644
--- a/src/paimon/common/global_index/global_index_result_test.cpp
+++ b/src/paimon/common/global_index/global_index_result_test.cpp
@@ -114,8 +114,7 @@ TEST_F(GlobalIndexResultTest, 
TestSerializeAndDeserializeSimple) {
 
     auto bitmap = RoaringBitmap64::From(
         {1l, 2l, 3l, 4l, 5l, 10l, 2247483647l, 2147483647l, 2147483648l, 
2147483649l, 2147483650l});
-    auto expected_result = std::make_shared<BitmapGlobalIndexResult>(
-        [bitmap]() -> Result<RoaringBitmap64> { return bitmap; });
+    auto expected_result = 
std::make_shared<BitmapGlobalIndexResult>(std::move(bitmap));
     ASSERT_EQ(expected_result->ToString(), typed_result->ToString());
     ASSERT_OK_AND_ASSIGN(auto serialize_bytes, 
GlobalIndexResult::Serialize(index_result, pool));
     ASSERT_EQ(byte_buffer, std::vector<uint8_t>(serialize_bytes->data(),
diff --git a/src/paimon/common/global_index/global_index_utils.h 
b/src/paimon/common/global_index/global_index_utils.h
index a9676538..749820ac 100644
--- a/src/paimon/common/global_index/global_index_utils.h
+++ b/src/paimon/common/global_index/global_index_utils.h
@@ -18,12 +18,15 @@
  */
 
 #pragma once
+#include <memory>
 #include <optional>
+#include <vector>
 
 #include "arrow/c/abi.h"
 #include "arrow/c/helpers.h"
 #include "fmt/format.h"
 #include "paimon/common/utils/scope_guard.h"
+#include "paimon/global_index/bitmap_global_index_result.h"
 #include "paimon/status.h"
 #include "paimon/utils/range.h"
 #include "paimon/utils/roaring_bitmap64.h"
@@ -33,6 +36,38 @@ class GlobalIndexUtils {
     GlobalIndexUtils() = delete;
     ~GlobalIndexUtils() = delete;
 
+    /// Unions non-null results, returning nullptr for an empty vector.
+    /// Bitmap results are merged in one batch; other results use their 
virtual Or methods.
+    static Result<std::shared_ptr<GlobalIndexResult>> UnionResults(
+        const std::vector<std::shared_ptr<GlobalIndexResult>>& results) {
+        if (results.empty()) {
+            return std::shared_ptr<GlobalIndexResult>();
+        }
+        std::vector<const RoaringBitmap64*> bitmaps;
+        bitmaps.reserve(results.size());
+        for (const std::shared_ptr<GlobalIndexResult>& result : results) {
+            if (result == nullptr) {
+                return Status::Invalid("Cannot union a null global index 
result.");
+            }
+            auto bitmap_result = 
std::dynamic_pointer_cast<BitmapGlobalIndexResult>(result);
+            if (bitmap_result != nullptr) {
+                PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap64* bitmap, 
bitmap_result->GetBitmap());
+                bitmaps.push_back(bitmap);
+            }
+        }
+        if (results.size() == 1) {
+            return results.front();
+        }
+        if (bitmaps.size() == results.size()) {
+            return 
std::make_shared<BitmapGlobalIndexResult>(RoaringBitmap64::FastUnion(bitmaps));
+        }
+        std::shared_ptr<GlobalIndexResult> merged_result = results.front();
+        for (size_t i = 1; i < results.size(); ++i) {
+            PAIMON_ASSIGN_OR_RAISE(merged_result, 
merged_result->Or(results[i]));
+        }
+        return merged_result;
+    }
+
     static Status CheckRelativeRowIds(::ArrowArray* c_arrow_array,
                                       const std::vector<int64_t>& 
relative_row_ids,
                                       std::optional<int64_t> 
expected_next_row_id) {
diff --git a/src/paimon/common/global_index/global_index_utils_test.cpp 
b/src/paimon/common/global_index/global_index_utils_test.cpp
index 3894e74e..27b8664b 100644
--- a/src/paimon/common/global_index/global_index_utils_test.cpp
+++ b/src/paimon/common/global_index/global_index_utils_test.cpp
@@ -21,12 +21,14 @@
 
 #include <cstdint>
 #include <limits>
+#include <memory>
 #include <optional>
 #include <vector>
 
 #include "arrow/api.h"
 #include "arrow/c/bridge.h"
 #include "gtest/gtest.h"
+#include "paimon/global_index/bitmap_scored_global_index_result.h"
 #include "paimon/testing/utils/testharness.h"
 #include "paimon/utils/range.h"
 #include "paimon/utils/roaring_bitmap64.h"
@@ -49,6 +51,54 @@ class GlobalIndexUtilsTest : public ::testing::Test {
     }
 };
 
+TEST_F(GlobalIndexUtilsTest, TestUnionResults) {
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<GlobalIndexResult> unavailable,
+                         GlobalIndexUtils::UnionResults({}));
+    ASSERT_EQ(unavailable, nullptr);
+    ASSERT_NOK_WITH_MSG(GlobalIndexUtils::UnionResults({nullptr}), "null 
global index result");
+
+    const int64_t high_row_id = int64_t{1} << 32;
+    auto left = 
std::make_shared<BitmapGlobalIndexResult>(RoaringBitmap64::From({1, 
high_row_id}));
+    auto right = 
std::make_shared<BitmapGlobalIndexResult>(RoaringBitmap64::From({2, 
high_row_id}));
+    auto empty = std::make_shared<BitmapGlobalIndexResult>(RoaringBitmap64());
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<GlobalIndexResult> single,
+                         GlobalIndexUtils::UnionResults({left}));
+    ASSERT_EQ(single, left);
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<GlobalIndexResult> merged,
+                         GlobalIndexUtils::UnionResults({left, empty, right}));
+    auto bitmap_result = 
std::dynamic_pointer_cast<BitmapGlobalIndexResult>(merged);
+    ASSERT_TRUE(bitmap_result);
+    ASSERT_OK_AND_ASSIGN(const RoaringBitmap64* bitmap, 
bitmap_result->GetBitmap());
+    ASSERT_EQ(*bitmap, RoaringBitmap64::From({1, 2, high_row_id}));
+    ASSERT_OK_AND_ASSIGN(const RoaringBitmap64* left_bitmap, 
left->GetBitmap());
+    ASSERT_EQ(*left_bitmap, RoaringBitmap64::From({1, high_row_id}));
+    ASSERT_OK_AND_ASSIGN(const RoaringBitmap64* right_bitmap, 
right->GetBitmap());
+    ASSERT_EQ(*right_bitmap, RoaringBitmap64::From({2, high_row_id}));
+}
+
+TEST_F(GlobalIndexUtilsTest, TestUnionResultsPreservesScoredSemantics) {
+    auto left = 
std::make_shared<BitmapScoredGlobalIndexResult>(RoaringBitmap64::From({1}),
+                                                                
std::vector<float>{0.5f});
+    auto right = 
std::make_shared<BitmapScoredGlobalIndexResult>(RoaringBitmap64::From({2}),
+                                                                 
std::vector<float>{1.5f});
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<GlobalIndexResult> merged,
+                         GlobalIndexUtils::UnionResults({left, right}));
+    auto scored_result = 
std::dynamic_pointer_cast<BitmapScoredGlobalIndexResult>(merged);
+    ASSERT_TRUE(scored_result);
+    ASSERT_EQ(scored_result->GetScores(), (std::vector<float>{0.5f, 1.5f}));
+    ASSERT_OK_AND_ASSIGN(const RoaringBitmap64* bitmap, 
scored_result->GetBitmap());
+    ASSERT_EQ(*bitmap, RoaringBitmap64::From({1, 2}));
+
+    ASSERT_NOK_WITH_MSG(GlobalIndexUtils::UnionResults({left, right, left}), 
"same row id");
+
+    auto unscored = 
std::make_shared<BitmapGlobalIndexResult>(RoaringBitmap64::From({3}));
+    ASSERT_OK_AND_ASSIGN(merged, GlobalIndexUtils::UnionResults({left, 
unscored}));
+    auto bitmap_result = 
std::dynamic_pointer_cast<BitmapGlobalIndexResult>(merged);
+    ASSERT_TRUE(bitmap_result);
+    ASSERT_OK_AND_ASSIGN(bitmap, bitmap_result->GetBitmap());
+    ASSERT_EQ(*bitmap, RoaringBitmap64::From({1, 3}));
+}
+
 TEST_F(GlobalIndexUtilsTest, TestNullArrowArray) {
     std::vector<int64_t> row_ids = {0, 1, 2};
     ASSERT_NOK_WITH_MSG(GlobalIndexUtils::CheckRelativeRowIds(nullptr, 
row_ids, std::nullopt),
diff --git a/src/paimon/common/global_index/sorted_file_global_index_reader.cpp 
b/src/paimon/common/global_index/sorted_file_global_index_reader.cpp
index d647e7eb..9624d5ac 100644
--- a/src/paimon/common/global_index/sorted_file_global_index_reader.cpp
+++ b/src/paimon/common/global_index/sorted_file_global_index_reader.cpp
@@ -26,6 +26,7 @@
 #include <utility>
 
 #include "paimon/common/executor/future.h"
+#include "paimon/common/global_index/global_index_utils.h"
 #include "paimon/common/predicate/like_optimization.h"
 #include "paimon/global_index/bitmap_global_index_result.h"
 #include "paimon/utils/roaring_bitmap64.h"
@@ -34,7 +35,7 @@ namespace paimon {
 namespace {
 
 std::shared_ptr<GlobalIndexResult> EmptyResult() {
-    return std::make_shared<BitmapGlobalIndexResult>([]() { return 
RoaringBitmap64(); });
+    return std::make_shared<BitmapGlobalIndexResult>(RoaringBitmap64());
 }
 
 }  // namespace
@@ -268,20 +269,17 @@ Result<std::shared_ptr<GlobalIndexResult>> 
SortedFileGlobalIndexReader::VisitSel
         results = CollectAll(futures);
     }
 
-    std::shared_ptr<GlobalIndexResult> merged_result = nullptr;
+    std::vector<std::shared_ptr<GlobalIndexResult>> index_results;
+    index_results.reserve(results.size());
     for (ReaderResult& result_or_status : results) {
         PAIMON_ASSIGN_OR_RAISE(std::shared_ptr<GlobalIndexResult> result,
                                std::move(result_or_status));
         if (result == nullptr) {
             continue;
         }
-        if (merged_result == nullptr) {
-            merged_result = std::move(result);
-        } else {
-            PAIMON_ASSIGN_OR_RAISE(merged_result, merged_result->Or(result));
-        }
+        index_results.push_back(std::move(result));
     }
-    return merged_result;
+    return GlobalIndexUtils::UnionResults(index_results);
 }
 
 Result<std::shared_ptr<GlobalIndexReader>> 
SortedFileGlobalIndexReader::GetOrCreateReader(
@@ -312,7 +310,7 @@ Result<std::shared_ptr<GlobalIndexResult>> 
SortedFileGlobalIndexReader::Compleme
         }
         return result;
     };
-    return std::make_shared<BitmapGlobalIndexResult>(std::move(supplier));
+    return BitmapGlobalIndexResult::Create(std::move(supplier));
 }
 
 bool SortedFileGlobalIndexReader::FallbackScanEnabled(
diff --git a/src/paimon/common/global_index/union_global_index_reader.cpp 
b/src/paimon/common/global_index/union_global_index_reader.cpp
index c6744f23..e4744813 100644
--- a/src/paimon/common/global_index/union_global_index_reader.cpp
+++ b/src/paimon/common/global_index/union_global_index_reader.cpp
@@ -254,21 +254,18 @@ Result<std::shared_ptr<ScoredGlobalIndexResult>> 
UnionGlobalIndexReader::UnionSc
 Result<std::shared_ptr<GlobalIndexResult>> 
UnionGlobalIndexReader::Union(ReaderAction action) {
     auto results = 
ExecuteAllReaders<Result<std::shared_ptr<GlobalIndexResult>>>(action);
 
-    std::shared_ptr<GlobalIndexResult> merged_result = nullptr;
+    std::vector<std::shared_ptr<GlobalIndexResult>> index_results;
+    index_results.reserve(results.size());
     for (auto& result_or_status : results) {
         PAIMON_ASSIGN_OR_RAISE(std::shared_ptr<GlobalIndexResult> result,
                                std::move(result_or_status));
         if (result == nullptr) {
             return std::shared_ptr<GlobalIndexResult>(nullptr);
         }
-        if (merged_result == nullptr) {
-            merged_result = std::move(result);
-        } else {
-            PAIMON_ASSIGN_OR_RAISE(merged_result, merged_result->Or(result));
-        }
+        index_results.push_back(std::move(result));
     }
 
-    return merged_result;
+    return GlobalIndexUtils::UnionResults(index_results);
 }
 
 bool UnionGlobalIndexReader::IsThreadSafe() const {
diff --git a/src/paimon/common/global_index/wrap/file_index_reader_wrapper.h 
b/src/paimon/common/global_index/wrap/file_index_reader_wrapper.h
index 8b2154b9..7cdba935 100644
--- a/src/paimon/common/global_index/wrap/file_index_reader_wrapper.h
+++ b/src/paimon/common/global_index/wrap/file_index_reader_wrapper.h
@@ -145,15 +145,12 @@ class FileIndexReaderWrapper : public GlobalIndexReader {
         if (auto remain = std::dynamic_pointer_cast<Remain>(result)) {
             return std::shared_ptr<GlobalIndexResult>();
         } else if (auto skip = std::dynamic_pointer_cast<Skip>(result)) {
-            return std::make_shared<BitmapGlobalIndexResult>(
-                []() -> Result<RoaringBitmap64> { return RoaringBitmap64(); });
+            return 
std::make_shared<BitmapGlobalIndexResult>(RoaringBitmap64());
         } else if (auto bitmap_result = 
std::dynamic_pointer_cast<BitmapIndexResult>(result)) {
-            return std::make_shared<BitmapGlobalIndexResult>(
-                [bitmap_result]() -> Result<RoaringBitmap64> {
-                    PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap32* bitmap,
-                                           bitmap_result->GetBitmap());
-                    return RoaringBitmap64(*bitmap);
-                });
+            return BitmapGlobalIndexResult::Create([bitmap_result]() -> 
Result<RoaringBitmap64> {
+                PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap32* bitmap, 
bitmap_result->GetBitmap());
+                return RoaringBitmap64(*bitmap);
+            });
         }
         return Status::Invalid(
             "invalid FileIndexResult, supposed to be Remain or Skip or 
BitmapIndexResult");
diff --git 
a/src/paimon/common/global_index/wrap/file_index_reader_wrapper_test.cpp 
b/src/paimon/common/global_index/wrap/file_index_reader_wrapper_test.cpp
index 93246059..366434a9 100644
--- a/src/paimon/common/global_index/wrap/file_index_reader_wrapper_test.cpp
+++ b/src/paimon/common/global_index/wrap/file_index_reader_wrapper_test.cpp
@@ -52,12 +52,18 @@ TEST(FileIndexReaderWrapperTest, TestToGlobalIndexResult) {
         check_result(global_result, {});
     }
     {
-        auto bitmap_supplier = []() -> Result<RoaringBitmap32> {
+        int32_t supplier_calls = 0;
+        auto bitmap_supplier = [&supplier_calls]() -> Result<RoaringBitmap32> {
+            ++supplier_calls;
             return RoaringBitmap32::From({1, 4, 2147483647});
         };
         auto file_result = 
std::make_shared<BitmapIndexResult>(bitmap_supplier);
         ASSERT_OK_AND_ASSIGN(auto global_result,
                              
FileIndexReaderWrapper::ToGlobalIndexResult(file_result));
+        ASSERT_EQ(supplier_calls, 1);
+        std::weak_ptr<BitmapIndexResult> weak_file_result = file_result;
+        file_result.reset();
+        ASSERT_TRUE(weak_file_result.expired());
         check_result(global_result, {1l, 4l, 2147483647l});
     }
     {
diff --git a/src/paimon/core/global_index/global_index_evaluator_impl_test.cpp 
b/src/paimon/core/global_index/global_index_evaluator_impl_test.cpp
index b33ca72a..99fad093 100644
--- a/src/paimon/core/global_index/global_index_evaluator_impl_test.cpp
+++ b/src/paimon/core/global_index/global_index_evaluator_impl_test.cpp
@@ -132,8 +132,7 @@ class RecordingGlobalIndexReader : public 
MockGlobalIndexReader {
         for (int64_t position : positions) {
             bitmap.Add(position);
         }
-        return std::make_shared<BitmapGlobalIndexResult>(
-            [bitmap = std::move(bitmap)]() -> Result<RoaringBitmap64> { return 
bitmap; });
+        return std::make_shared<BitmapGlobalIndexResult>(std::move(bitmap));
     }
 
     static std::shared_ptr<GlobalIndexResult> NotEvaluable() {
diff --git a/src/paimon/core/table/source/filtered_row_id_reader.cpp 
b/src/paimon/core/table/source/filtered_row_id_reader.cpp
index e30e79d3..6c7d54f1 100644
--- a/src/paimon/core/table/source/filtered_row_id_reader.cpp
+++ b/src/paimon/core/table/source/filtered_row_id_reader.cpp
@@ -170,8 +170,7 @@ Result<RoaringBitmap64> 
FilteredRowIdReader::MatchingRowIds(const RoaringBitmap6
     ScanContextBuilder scan_builder(root_path_);
     scan_builder.SetOptions(pinned_options)
         .SetPredicate(partition_filter_)
-        .SetGlobalIndexResult(std::make_shared<BitmapGlobalIndexResult>(
-            [rows]() -> Result<RoaringBitmap64> { return rows; }))
+        .SetGlobalIndexResult(std::make_shared<BitmapGlobalIndexResult>(rows))
         .WithFileSystem(options_.GetFileSystem())
         .WithMemoryPool(pool_)
         .WithExecutor(executor_);
diff --git a/src/paimon/core/table/source/primary_key_sorted_index_scan.cpp 
b/src/paimon/core/table/source/primary_key_sorted_index_scan.cpp
index bd6cc4d2..3b7ce3a9 100644
--- a/src/paimon/core/table/source/primary_key_sorted_index_scan.cpp
+++ b/src/paimon/core/table/source/primary_key_sorted_index_scan.cpp
@@ -175,9 +175,7 @@ class SharedGroupReader {
         std::vector<std::shared_ptr<GlobalIndexResult>> localized;
         localized.reserve(source_count);
         for (RoaringBitmap64& partition : partitions) {
-            auto bitmap = 
std::make_shared<RoaringBitmap64>(std::move(partition));
-            localized.push_back(std::make_shared<BitmapGlobalIndexResult>(
-                [bitmap]() -> Result<RoaringBitmap64> { return *bitmap; }));
+            
localized.push_back(std::make_shared<BitmapGlobalIndexResult>(std::move(partition)));
         }
         return localized;
     }
diff --git 
a/src/paimon/core/table/source/primary_key_sorted_index_scan_test.cpp 
b/src/paimon/core/table/source/primary_key_sorted_index_scan_test.cpp
index 29efa29f..827a9fdb 100644
--- a/src/paimon/core/table/source/primary_key_sorted_index_scan_test.cpp
+++ b/src/paimon/core/table/source/primary_key_sorted_index_scan_test.cpp
@@ -117,9 +117,7 @@ class StubGlobalIndexReader : public MockGlobalIndexReader {
         if (equal_call_count_ != nullptr) {
             (*equal_call_count_)++;
         }
-        RoaringBitmap64 copy = equal_result_;
-        return std::make_shared<BitmapGlobalIndexResult>(
-            [bitmap = std::move(copy)]() -> Result<RoaringBitmap64> { return 
bitmap; });
+        return std::make_shared<BitmapGlobalIndexResult>(equal_result_);
     }
     Result<std::shared_ptr<GlobalIndexResult>> VisitNotEqual(const Literal& 
literal) override {
         return NotEvaluable();
diff --git a/src/paimon/testing/mock/mock_global_index_reader.h 
b/src/paimon/testing/mock/mock_global_index_reader.h
index 9dd9ffc3..4e90ec30 100644
--- a/src/paimon/testing/mock/mock_global_index_reader.h
+++ b/src/paimon/testing/mock/mock_global_index_reader.h
@@ -209,9 +209,7 @@ class MockGlobalIndexReader : public GlobalIndexReader {
         if (return_nullptr_) {
             return std::shared_ptr<GlobalIndexResult>(nullptr);
         }
-        auto ids = default_result_;
-        return std::make_shared<BitmapGlobalIndexResult>(
-            [ids]() { return RoaringBitmap64::From(ids); });
+        return 
std::make_shared<BitmapGlobalIndexResult>(RoaringBitmap64::From(default_result_));
     }
 
  private:

Reply via email to