From 0342ba41507c7e5a014edd3cd687499eadfccd96 Mon Sep 17 00:00:00 2001 From: lxy264173 Date: Tue, 24 Nov 2026 16:40:32 +0800 Subject: [PATCH] test(global-index): verify concurrent queries through reader wrappers --- docs/source/user_guide/global_index.rst | 8 +- .../paimon/global_index/global_index_reader.h | 6 +- .../paimon/global_index/global_index_scan.h | 8 +- .../table/source/full_text_search_builder.h | 5 +- .../global_index/offset_global_index_reader.h | 2 + .../sorted_file_global_index_reader.h | 1 + .../global_index/union_global_index_reader.h | 3 + .../global_index/global_index_scan_impl.h | 4 +- .../live_row_global_index_reader.h | 8 +- .../live_row_global_index_reader_test.cpp | 118 ++++++++++++++++++ .../source/data_evolution_full_text_read.cpp | 2 +- .../source/data_evolution_full_text_read.h | 4 +- .../data_evolution_full_text_read_test.cpp | 8 +- .../source/data_evolution_full_text_scan.h | 2 +- 14 files changed, 160 insertions(+), 19 deletions(-) diff --git a/docs/source/user_guide/global_index.rst b/docs/source/user_guide/global_index.rst index 38fd8be11..e366f2293 100644 --- a/docs/source/user_guide/global_index.rst +++ b/docs/source/user_guide/global_index.rst @@ -353,8 +353,12 @@ at its cutoff. The merge breaks ties among the returned candidates by ascending shard. - With deletion vectors, only the rows live in that snapshot are ranked, as described for ``GlobalIndexScan`` above. -- The shards are searched in parallel on the executor given to ``WithExecutor()``, or else on one - with ``global-index.thread-num`` threads, and each returns at most ``limit`` rows. +- The shards are searched on the executor given to ``WithExecutor()``. Without an explicit + executor, ``global-index.thread-num`` controls outer concurrency and defaults to the CPU count + (or 1 if unavailable). + Each shard returns at most ``limit`` rows. ``GlobalIndexScan`` follows the same policy. + Bitmap/BTree readers retain independent default 4-thread pools for multi-file reads, regardless + of ``global-index.thread-num``. - If Paimon C++ is built without the backend of a ``full-text`` or ``lucene-fts`` index, the search fails instead of skipping the index and leaving its rows out of the result. - A column with a primary-key full-text index (``pk-full-text.index.columns``) cannot be searched diff --git a/include/paimon/global_index/global_index_reader.h b/include/paimon/global_index/global_index_reader.h index 94d9ecef8..ca435016b 100644 --- a/include/paimon/global_index/global_index_reader.h +++ b/include/paimon/global_index/global_index_reader.h @@ -56,7 +56,11 @@ class PAIMON_EXPORT GlobalIndexReader : public FunctionVisitor> VisitFullTextSearch( const std::shared_ptr& full_text_search) = 0; - /// @return true if the reader is thread-safe; false otherwise. + /// @return true if the same reader supports concurrent queries; false otherwise. + /// Query arguments must not be modified during a call, and user callbacks and memory pools + /// used concurrently must be thread-safe. Reader lifetime must cover all outstanding calls. + /// Submitting nested tasks to the same thread pool and blocking while waiting for them + /// may cause a deadlock. virtual bool IsThreadSafe() const = 0; /// @return An identifier representing the index type. (e.g., "btree", "lumina"). diff --git a/include/paimon/global_index/global_index_scan.h b/include/paimon/global_index/global_index_scan.h index 288bfbb14..ad06f675e 100644 --- a/include/paimon/global_index/global_index_scan.h +++ b/include/paimon/global_index/global_index_scan.h @@ -50,7 +50,9 @@ class PAIMON_EXPORT GlobalIndexScan { /// If not provided (nullptr), it is inferred from the `FILE_SYSTEM` /// key in the `options` parameter. /// @param executor The executor to be used for asynchronous operations during global - /// index scan. + /// index scan. If nullptr, `global-index.thread-num` determines outer + /// pool size (default: CPU count). + /// Bitmap/BTree multi-file readers retain their independent pools. /// @param pool Memory pool for temporary allocations; if nullptr, uses default. /// @return A `Result` containing a unique pointer to the created scanner, /// or an error if initialization fails (e.g., I/O error, invalid snapshot id, @@ -73,7 +75,9 @@ class PAIMON_EXPORT GlobalIndexScan { /// @param file_system File system for accessing index files. If nullptr, it is /// inferred from the `FILE_SYSTEM` key in `options`. /// @param executor The executor to be used for asynchronous operations during global - /// index scan. + /// index scan. If nullptr, `global-index.thread-num` determines outer + /// pool size (default: CPU count). + /// Bitmap/BTree multi-file readers retain their independent pools. /// @param pool Memory pool for temporary allocations; if nullptr, uses default. /// @return A `Result` containing a unique pointer to the created scanner, /// or an error if initialization fails. diff --git a/include/paimon/table/source/full_text_search_builder.h b/include/paimon/table/source/full_text_search_builder.h index df80bbfca..e1138674d 100644 --- a/include/paimon/table/source/full_text_search_builder.h +++ b/include/paimon/table/source/full_text_search_builder.h @@ -102,9 +102,8 @@ class PAIMON_EXPORT FullTextSearchBuilder { /// Sets the memory pool. If not set, the default pool is used. FullTextSearchBuilder& WithMemoryPool(const std::shared_ptr& memory_pool); - /// Sets the executor that searches splits in parallel and reads manifests. If not set, each - /// read creates an executor with `global-index.thread-num` threads, which defaults to the - /// number of CPUs. + /// Sets the executor that searches splits in parallel and reads manifests. If not set, + /// `global-index.thread-num` determines the pool size (default: CPU count). FullTextSearchBuilder& WithExecutor(const std::shared_ptr& executor); /// Sets the file system to access the table with. If not set, the file system is created from diff --git a/src/paimon/common/global_index/offset_global_index_reader.h b/src/paimon/common/global_index/offset_global_index_reader.h index de86fdee3..3f8f74424 100644 --- a/src/paimon/common/global_index/offset_global_index_reader.h +++ b/src/paimon/common/global_index/offset_global_index_reader.h @@ -29,6 +29,8 @@ namespace paimon { /// A GlobalIndexReader that wraps another reader and applies an offset to all row ids in the /// results. This is used to convert local row IDs into global row IDs. +/// Concurrent queries are supported when the wrapped reader is thread-safe. Query rewriting +/// and result offsetting use per-call state. class OffsetGlobalIndexReader : public GlobalIndexReader { public: /// Constructs an OffsetGlobalIndexReader. diff --git a/src/paimon/common/global_index/sorted_file_global_index_reader.h b/src/paimon/common/global_index/sorted_file_global_index_reader.h index 2411d16e0..23d4abfe6 100644 --- a/src/paimon/common/global_index/sorted_file_global_index_reader.h +++ b/src/paimon/common/global_index/sorted_file_global_index_reader.h @@ -33,6 +33,7 @@ namespace paimon { /// Base reader for sorted global index files with manifest-level min/max pruning. +/// A null executor evaluates selected files serially on the calling thread. class SortedFileGlobalIndexReader : public GlobalIndexReader { public: Result> VisitIsNotNull() override; diff --git a/src/paimon/common/global_index/union_global_index_reader.h b/src/paimon/common/global_index/union_global_index_reader.h index 811e24620..55f666ee1 100644 --- a/src/paimon/common/global_index/union_global_index_reader.h +++ b/src/paimon/common/global_index/union_global_index_reader.h @@ -35,6 +35,9 @@ namespace paimon { /// /// When an executor is provided, all sub-reader actions are submitted in parallel and results are /// collected in submission order. Otherwise, sub-readers are evaluated sequentially. +/// Concurrent queries are supported when all sub-readers are thread-safe. Each query owns its +/// execution and merge state. Callers must not occupy the executor's workers while waiting for +/// queries that submit work to that same executor. class UnionGlobalIndexReader : public GlobalIndexReader { public: /// Constructs a UnionGlobalIndexReader. diff --git a/src/paimon/core/global_index/global_index_scan_impl.h b/src/paimon/core/global_index/global_index_scan_impl.h index 6083aee02..48e8b20c8 100644 --- a/src/paimon/core/global_index/global_index_scan_impl.h +++ b/src/paimon/core/global_index/global_index_scan_impl.h @@ -57,8 +57,8 @@ class GlobalIndexScanImpl : public GlobalIndexScan { const std::vector>& index_files, const std::shared_ptr& executor, const std::shared_ptr& pool); - /// Returns `executor` if it is not null, or else creates an executor with - /// `global-index.thread-num` threads, which defaults to the number of CPUs. + /// Returns an explicitly supplied executor unchanged. Otherwise, creates a pool with + /// `global-index.thread-num` threads (default: CPU count). Non-positive counts are invalid. static Result> GetOrCreateExecutor( const std::shared_ptr& executor, const CoreOptions& options); diff --git a/src/paimon/core/global_index/live_row_global_index_reader.h b/src/paimon/core/global_index/live_row_global_index_reader.h index 72fb5dc45..ef72d6943 100644 --- a/src/paimon/core/global_index/live_row_global_index_reader.h +++ b/src/paimon/core/global_index/live_row_global_index_reader.h @@ -39,21 +39,25 @@ namespace paimon { /// from the whole index. As Java `AbstractDataEvolutionVectorRead#preFilters` does, a vector search /// restricts its pre-filter to those live rows. Predicate visits are delegated unchanged, as the /// read drops deleted rows from their untruncated results. +/// Concurrent queries require a thread-safe wrapped reader and supplier. class LiveRowGlobalIndexReader : public GlobalIndexReader { public: /// Supplies the global row ids of live rows, or null when every row is live. + /// Must support concurrent calls when shared by parallel shards or concurrent queries. + /// Returned bitmaps must remain immutable for the lifetime of queries using them. using LiveRowsSupplier = std::function>()>; /// Returns a supplier that calls `load` on its first call and shares the live rows it returns /// with later calls, so they are read at most once. A failed load is retried on the next call. + /// The returned supplier is thread-safe. static LiveRowsSupplier CacheLiveRows( std::function>()> load); /// Creates a union of the shard readers of one index whose full-text and vector searches rank /// only live rows. Each shard reader is wrapped in a LiveRowGlobalIndexReader. When a search /// may rank rows of a shard, live rows are loaded on the visiting thread before it fans out to - /// the shards, so a load that reads manifests on `executor` never waits for it from one of its - /// own threads. + /// the shards. Callers must run outside `executor` when loading or searching waits for tasks + /// on that executor. /// @param shard_readers Readers of the shards. They take and return global row ids. /// @param shard_ranges The global row id range (both ends inclusive) of each shard. /// @param search_ranges The global row ids each shard ranks in a full-text search, as diff --git a/src/paimon/core/global_index/live_row_global_index_reader_test.cpp b/src/paimon/core/global_index/live_row_global_index_reader_test.cpp index 5447ed974..e09137128 100644 --- a/src/paimon/core/global_index/live_row_global_index_reader_test.cpp +++ b/src/paimon/core/global_index/live_row_global_index_reader_test.cpp @@ -19,7 +19,9 @@ #include "paimon/core/global_index/live_row_global_index_reader.h" +#include #include +#include #include #include #include @@ -30,7 +32,9 @@ #include #include "gtest/gtest.h" +#include "paimon/common/global_index/offset_global_index_reader.h" #include "paimon/executor.h" +#include "paimon/global_index/bitmap_scored_global_index_result.h" #include "paimon/memory/memory_pool.h" #include "paimon/predicate/full_text_search.h" #include "paimon/predicate/literal.h" @@ -42,6 +46,40 @@ #include "paimon/utils/roaring_bitmap64.h" namespace paimon::test { +namespace { +// Applies filters to local row ids and scores each row using the query value and local row id. +class FilteringGlobalIndexReader : public MockGlobalIndexReader { + public: + Result> VisitVectorSearch( + const std::shared_ptr& search) override { + return Search(search->pre_filter, search->query.front()); + } + + Result> VisitFullTextSearch( + const std::shared_ptr& search) override { + return Search( + [search](int64_t row_id) { + return !search->include_row_ids || search->include_row_ids->Contains(row_id); + }, + static_cast(search->limit)); + } + + private: + Result> Search(const VectorSearch::PreFilter& filter, + float query_score) { + RoaringBitmap64 rows; + std::vector scores; + for (int64_t row_id = 0; row_id < 4; ++row_id) { + if (!filter || filter(row_id)) { + rows.Add(row_id); + scores.push_back(query_score + static_cast(row_id) + 0.1f); + } + } + return std::make_shared(std::move(rows), std::move(scores)); + } +}; +} // namespace + class LiveRowGlobalIndexReaderTest : public ::testing::Test { public: static LiveRowGlobalIndexReader::LiveRowsSupplier Supply( @@ -321,6 +359,84 @@ TEST_F(LiveRowGlobalIndexReaderTest, TestLiveRowsErrorOnlyFailsSearchesThatRankR ASSERT_EQ(captured->include_row_ids.value(), RoaringBitmap64::From({100})); } +TEST_F(LiveRowGlobalIndexReaderTest, TestConcurrentSearch) { + for (bool parallel_shards : {false, true}) { + SCOPED_TRACE(parallel_shards); + std::shared_ptr executor; + if (parallel_shards) { + ASSERT_OK_AND_ASSIGN(executor, CreateDefaultExecutor(/*thread_count=*/4)); + } + std::vector> shards; + for (int64_t offset : {100, 200}) { + shards.push_back(std::make_shared( + std::make_shared(), offset, offset + 3)); + } + std::atomic load_count{0}; + auto supplier = LiveRowGlobalIndexReader::CacheLiveRows( + [&]() -> Result> { + ++load_count; + // Shards cover [100, 103] and [200, 203]; DV deletes 101 and 202. + return std::optional( + RoaringBitmap64::From({100, 102, 103, 200, 201, 203})); + }); + auto reader = LiveRowGlobalIndexReader::CreateUnion( + std::move(shards), {Range(100, 103), Range(200, 203)}, + {Range(100, 103), Range(200, 203)}, executor, supplier); + ASSERT_TRUE(reader->IsThreadSafe()); + + std::promise start; + std::shared_future ready = start.get_future().share(); + std::vector> workers; + for (int32_t thread_id = 0; thread_id < 4; ++thread_id) { + workers.push_back(std::async(std::launch::async, [reader, ready, thread_id]() { + ready.wait(); + for (int32_t iteration = 0; iteration < 16; ++iteration) { + const int32_t query_id = thread_id * 16 + iteration; + const int32_t parity = query_id % 2; + const float query_score = static_cast(query_id + 3); + const RoaringBitmap64 expected_rows = + parity == 0 ? RoaringBitmap64::From({100, 102, 200}) + : RoaringBitmap64::From({103, 201, 203}); + // Scores follow ascending global row ids; offset changes ids, not scores. + const std::vector expected_scores = + parity == 0 ? std::vector{query_score + 0.1f, query_score + 2.1f, + query_score + 0.1f} + : std::vector{query_score + 3.1f, query_score + 1.1f, + query_score + 3.1f}; + auto vector = + SearchVector([parity](int64_t row_id) { return row_id % 2 == parity; }); + vector->query = {query_score}; + auto text = Search(parity == 0 ? RoaringBitmap64::From({100, 102, 200, 202}) + : RoaringBitmap64::From({101, 103, 201, 203})); + text->limit = query_id + 3; + for (bool vector_query : {false, true}) { + ASSERT_OK_AND_ASSIGN(std::shared_ptr result, + vector_query ? reader->VisitVectorSearch(vector) + : reader->VisitFullTextSearch(text)); + auto scored = + std::dynamic_pointer_cast(result); + ASSERT_TRUE(scored); + ASSERT_OK_AND_ASSIGN(const RoaringBitmap64* rows, scored->GetBitmap()); + ASSERT_EQ(*rows, expected_rows); + const auto& scores = scored->GetScores(); + ASSERT_EQ(scores.size(), expected_scores.size()); + for (size_t i = 0; i < scores.size(); ++i) { + ASSERT_FLOAT_EQ(scores[i], expected_scores[i]); + } + } + ASSERT_TRUE(vector->pre_filter(parity == 0 ? 202 : 101)); + ASSERT_EQ(text->include_row_ids->Cardinality(), 4); + } + })); + } + start.set_value(); + for (auto& worker : workers) { + worker.get(); + } + ASSERT_EQ(load_count.load(), 1); + } +} + TEST_F(LiveRowGlobalIndexReaderTest, TestOtherVisitsDoNotReadLiveRows) { auto mock_reader = std::make_shared(); mock_reader->SetDefaultResult({1, 2}); @@ -338,6 +454,8 @@ TEST_F(LiveRowGlobalIndexReaderTest, TestOtherVisitsDoNotReadLiveRows) { ASSERT_EQ(call_count, 0); ASSERT_EQ(reader.GetIndexType(), "fake"); ASSERT_TRUE(reader.IsThreadSafe()); + mock_reader->SetThreadSafe(false); + ASSERT_FALSE(reader.IsThreadSafe()); } } // namespace paimon::test diff --git a/src/paimon/core/table/source/data_evolution_full_text_read.cpp b/src/paimon/core/table/source/data_evolution_full_text_read.cpp index 57c6e7ff1..eae9a36d0 100644 --- a/src/paimon/core/table/source/data_evolution_full_text_read.cpp +++ b/src/paimon/core/table/source/data_evolution_full_text_read.cpp @@ -622,7 +622,7 @@ Result> DataEvolutionFullTextRead::Sear } } }); - if (searches.size() <= 1) { + if (!executor_ || searches.size() <= 1) { for (const auto& search : searches) { results.push_back(search()); } diff --git a/src/paimon/core/table/source/data_evolution_full_text_read.h b/src/paimon/core/table/source/data_evolution_full_text_read.h index 91f4c6ab2..70992778d 100644 --- a/src/paimon/core/table/source/data_evolution_full_text_read.h +++ b/src/paimon/core/table/source/data_evolution_full_text_read.h @@ -57,8 +57,8 @@ class DataEvolutionFullTextRead : public FullTextRead { /// @param text_field The searched column. /// @param query The JSON query. /// @param limit The number of rows to return; must be positive. - /// @param executor Executor to search splits on, or null to create one with - /// `global-index.thread-num` threads. + /// @param executor Executor to search splits on, or null to use + /// `global-index.thread-num` (default: CPU count). /// @param pool Memory pool for reading indexes, manifests and candidate rows. static Result> Create( const std::string& root_path, const std::shared_ptr& table_schema, diff --git a/src/paimon/core/table/source/data_evolution_full_text_read_test.cpp b/src/paimon/core/table/source/data_evolution_full_text_read_test.cpp index aafc9a3a6..51f5bc588 100644 --- a/src/paimon/core/table/source/data_evolution_full_text_read_test.cpp +++ b/src/paimon/core/table/source/data_evolution_full_text_read_test.cpp @@ -909,9 +909,11 @@ TEST_F(DataEvolutionFullTextReadTest, TestBuilderValidatesSettings) { ASSERT_NOK_WITH_MSG(invalid_mode->NewFullTextScan(), "invalid full-text-index.search-mode: invalid"); - std::unique_ptr no_thread = NewBuilder(3); - no_thread->AddOption(Options::GLOBAL_INDEX_THREAD_NUM, "0"); - ASSERT_NOK_WITH_MSG(no_thread->NewFullTextRead(), "invalid global index thread number 0"); + for (const char* thread_num : {"0", "-1"}) { + std::unique_ptr no_thread = NewBuilder(3); + no_thread->AddOption(Options::GLOBAL_INDEX_THREAD_NUM, thread_num); + ASSERT_NOK_WITH_MSG(no_thread->NewFullTextRead(), "invalid global index thread number"); + } FullTextSearchBuilder missing_column(table_path_); missing_column.SetQuery("missing", kQuery).SetLimit(3); diff --git a/src/paimon/core/table/source/data_evolution_full_text_scan.h b/src/paimon/core/table/source/data_evolution_full_text_scan.h index 443e9eb4a..1bef4000c 100644 --- a/src/paimon/core/table/source/data_evolution_full_text_scan.h +++ b/src/paimon/core/table/source/data_evolution_full_text_scan.h @@ -68,7 +68,7 @@ class DataEvolutionFullTextScan : public FullTextScan { /// @param filter Row filter beyond the partition filter, or null for all rows. /// @param text_field The searched column. /// @param executor Executor to read manifests on in the `detail` search mode, or null - /// to create one with `global-index.thread-num` threads if needed. + /// to use `global-index.thread-num` (default: CPU count). /// @param pool Memory pool for reading index manifests. DataEvolutionFullTextScan(const std::string& root_path, const std::shared_ptr& table_schema,