diff --git a/docs/source/user_guide/global_index.rst b/docs/source/user_guide/global_index.rst index 38fd8be11..ace494293 100644 --- a/docs/source/user_guide/global_index.rst +++ b/docs/source/user_guide/global_index.rst @@ -353,8 +353,19 @@ 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. +- After split filtering, a single eligible index search runs on the calling thread. Multiple + searches are submitted to the executor given to ``WithExecutor()``, and the caller waits for them. + 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``. +- Submitting nested tasks to the same executor and waiting for them can cause a deadlock. + For example, calling a reader's ``Visit*()`` method from a task on the executor supplied to + ``GlobalIndexScan`` can submit shard searches to that same executor and wait for them. With + only one worker, the calling task occupies the worker, so the queued shard searches cannot run. + This also applies to ``FullTextSearchBuilder::WithExecutor()``. Even with one split, planning + or lower-level reads may submit tasks to the same executor and wait for them. - 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..80d37c73a 100644 --- a/include/paimon/global_index/global_index_reader.h +++ b/include/paimon/global_index/global_index_reader.h @@ -56,7 +56,13 @@ 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 Visit* calls from multiple threads; + /// false otherwise. + /// Query arguments must not be modified during a call. User callbacks, memory pools and + /// custom index I/O (including file systems) must support the calls made concurrently. + /// 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..256d0dcff 100644 --- a/include/paimon/table/source/full_text_search_builder.h +++ b/include/paimon/table/source/full_text_search_builder.h @@ -102,9 +102,11 @@ 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). + /// A single eligible index search runs on the calling thread; multiple searches are submitted + /// to this executor and awaited. Nested submission and waiting on the same executor can + /// deadlock, including during planning or reads even when only one split remains. 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.cpp b/src/paimon/common/global_index/sorted_file_global_index_reader.cpp index 9624d5ace..ab2bcf97f 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 @@ -28,6 +28,7 @@ #include "paimon/common/executor/future.h" #include "paimon/common/global_index/global_index_utils.h" #include "paimon/common/predicate/like_optimization.h" +#include "paimon/common/utils/scope_guard.h" #include "paimon/global_index/bitmap_global_index_result.h" #include "paimon/utils/roaring_bitmap64.h" @@ -262,6 +263,14 @@ Result> SortedFileGlobalIndexReader::VisitSel } else { std::vector> futures; futures.reserve(readers.size()); + // Keep borrowed query arguments alive until all accepted file visits finish. + ScopeGuard drain([&futures] { + for (auto& future : futures) { + if (future.valid()) { + future.wait(); + } + } + }); for (const std::shared_ptr& reader : readers) { futures.push_back( Via(executor_.get(), [visitor, reader]() { return visitor(reader); })); 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.cpp b/src/paimon/common/global_index/union_global_index_reader.cpp index e47448130..43a5921f1 100644 --- a/src/paimon/common/global_index/union_global_index_reader.cpp +++ b/src/paimon/common/global_index/union_global_index_reader.cpp @@ -26,6 +26,7 @@ #include "paimon/common/executor/future.h" #include "paimon/common/global_index/global_index_utils.h" #include "paimon/common/global_index/scored_global_index_result_utils.h" +#include "paimon/common/utils/scope_guard.h" #include "paimon/global_index/bitmap_scored_global_index_result.h" #include "paimon/predicate/full_text_search.h" #include "paimon/utils/roaring_bitmap64.h" @@ -301,6 +302,14 @@ std::vector UnionGlobalIndexReader::ExecuteAllReadersWithIndex( // Parallel: submit all tasks to executor, then collect results in submission order std::vector> futures; futures.reserve(readers_.size()); + // Wait for accepted tasks before unwinding if submission or result collection throws. + ScopeGuard drain([&futures] { + for (auto& future : futures) { + if (future.valid()) { + future.wait(); + } + } + }); for (size_t index = 0; index < readers_.size(); ++index) { futures.push_back(Via(executor_.get(), [action, index, reader = readers_[index]]() -> R { return action(index, reader); 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/common/global_index/union_global_index_reader_test.cpp b/src/paimon/common/global_index/union_global_index_reader_test.cpp index d9e046672..5023a2011 100644 --- a/src/paimon/common/global_index/union_global_index_reader_test.cpp +++ b/src/paimon/common/global_index/union_global_index_reader_test.cpp @@ -19,9 +19,12 @@ #include "paimon/common/global_index/union_global_index_reader.h" +#include +#include #include #include #include +#include #include #include #include @@ -85,19 +88,32 @@ class FakeSortedFileGlobalIndexReader : public SortedFileGlobalIndexReader { std::map> readers_; }; -// Runs the first task immediately and defers the rest. This makes it possible to verify that -// queued tasks own their action even if collecting an earlier future throws. +// Runs the first task immediately and defers the rest to verify draining on exceptional exits. class DeferAfterFirstExecutor : public Executor { public: + explicit DeferAfterFirstExecutor(bool reject_third = false) : reject_third_(reject_third) {} + void Add(std::function func) override { - if (submission_count_++ == 0) { - func(); - } else { - pending_tasks_.push(std::move(func)); + { + std::lock_guard lock(mutex_); + ++submission_count_; + if (reject_third_ && submission_count_ == 3) { + last_submission_.set_value(); + throw std::runtime_error("submission exception"); + } + if (!reject_third_ && submission_count_ == 2) { + last_submission_.set_value(); + } + if (submission_count_ != 1 && !released_) { + pending_tasks_.push(std::move(func)); + return; + } } + func(); } void ShutdownNow() override { + std::lock_guard lock(mutex_); std::queue> empty; pending_tasks_.swap(empty); } @@ -107,19 +123,35 @@ class DeferAfterFirstExecutor : public Executor { } uint32_t SubmissionCount() const { + std::lock_guard lock(mutex_); return submission_count_; } + bool WaitUntilLastSubmission() { + return last_submission_.get_future().wait_for(std::chrono::seconds(5)) == + std::future_status::ready; + } + void RunPendingTasks() { - while (!pending_tasks_.empty()) { - std::function task = std::move(pending_tasks_.front()); - pending_tasks_.pop(); + std::queue> tasks; + { + std::lock_guard lock(mutex_); + released_ = true; + tasks.swap(pending_tasks_); + } + while (!tasks.empty()) { + std::function task = std::move(tasks.front()); + tasks.pop(); task(); } } private: + bool reject_third_; + bool released_ = false; + mutable std::mutex mutex_; uint32_t submission_count_ = 0; + std::promise last_submission_; std::queue> pending_tasks_; }; @@ -331,22 +363,41 @@ TEST_F(UnionGlobalIndexReaderTest, TestErrorPropagationWithExecutor) { ASSERT_NOK_WITH_MSG(union_reader.VisitIsNotNull(), "Unknown error for reader2"); } -TEST_F(UnionGlobalIndexReaderTest, TestDeferredTaskOwnsActionAfterEarlierFutureThrows) { - auto throwing_reader = std::make_shared(); - auto deferred_reader = std::make_shared(); - throwing_reader->SetThrowException("reader exception"); - deferred_reader->SetDefaultResult({2}); +TEST_F(UnionGlobalIndexReaderTest, TestDrainsAcceptedTasksBeforeExceptionEscapes) { + for (bool reject_submission : {false, true}) { + SCOPED_TRACE(reject_submission); + auto throwing_reader = std::make_shared(); + auto deferred_reader = std::make_shared(); + throwing_reader->SetThrowException("reader exception"); + deferred_reader->SetDefaultResult({2}); - std::vector> readers = {throwing_reader, deferred_reader}; - auto executor = std::make_shared(); - UnionGlobalIndexReader union_reader(std::move(readers), /*row_ranges=*/{}, - /*search_ranges=*/{}, executor); - ASSERT_THROW( - { [[maybe_unused]] auto result = union_reader.VisitIsNotNull(); }, std::runtime_error); - ASSERT_EQ(deferred_reader->InvocationCount(), 0); - - executor->RunPendingTasks(); - ASSERT_EQ(deferred_reader->InvocationCount(), 1); + std::vector> readers = {throwing_reader, + deferred_reader}; + if (reject_submission) { + readers.push_back(std::make_shared()); + } + auto executor = std::make_shared(reject_submission); + UnionGlobalIndexReader union_reader(std::move(readers), /*row_ranges=*/{}, + /*search_ranges=*/{}, executor); + auto query = std::async(std::launch::async, [&union_reader]() -> std::string { + try { + [[maybe_unused]] auto result = union_reader.VisitIsNotNull(); + } catch (const std::runtime_error& error) { + return error.what(); + } + return ""; + }); + const bool submitted = executor->WaitUntilLastSubmission(); + const std::future_status status = query.wait_for(std::chrono::milliseconds(100)); + // Release pending work before assertions so failures do not leave the query blocked. + executor->RunPendingTasks(); + const std::string error = query.get(); + + ASSERT_TRUE(submitted); + ASSERT_EQ(status, std::future_status::timeout); + ASSERT_EQ(error, reject_submission ? "submission exception" : "reader exception"); + ASSERT_EQ(deferred_reader->InvocationCount(), 1); + } } TEST_F(UnionGlobalIndexReaderTest, TestVisitEqualUnion) { diff --git a/src/paimon/common/utils/dense_hash_table.h b/src/paimon/common/utils/dense_hash_table.h index 097978af6..501279797 100644 --- a/src/paimon/common/utils/dense_hash_table.h +++ b/src/paimon/common/utils/dense_hash_table.h @@ -119,22 +119,27 @@ class DenseHashTable { } std::optional Find(Key key) const { + std::optional result; if (key == kEmptyKey || key == kOtherSpecialKey) { const Bucket bucket = ReadBucket(header_.bucket_count + (key == kOtherSpecialKey)); - return bucket.key == 0 ? std::nullopt : std::optional(bucket.value); + if (bucket.key != 0) { + result = bucket.value; + } + return result; } uint64_t index = key % header_.bucket_count; for (uint64_t probe = 0; probe < header_.bucket_count; ++probe) { const Bucket bucket = ReadBucket(index); if (bucket.key == kEmptyKey) { - return std::nullopt; + break; } if (bucket.key == key) { - return bucket.value; + result = bucket.value; + break; } index = (index + 1) % header_.bucket_count; } - return std::nullopt; + return result; } /// Writes the container layout at the stream's current position. The caller owns flush/close. 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..24769cd0f 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,27 @@ 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. Shards call the supplier again after preloading; these calls must not + /// wait for work on `executor`. Use `CacheLiveRows()` for a snapshot-scoped loader so that + /// shard calls return cached live rows after successful preloading. /// @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..090fe5081 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,10 @@ #include #include "gtest/gtest.h" +#include "paimon/common/global_index/offset_global_index_reader.h" +#include "paimon/common/utils/scope_guard.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 +47,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 +360,88 @@ 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; + workers.reserve(4); + { + ScopeGuard release_workers([&start] { start.set_value(); }); + 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 = iteration * 4 + thread_id; + const int32_t parity = query_id % 2; + const auto 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); + } + })); + } + } + 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 +459,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.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, diff --git a/src/paimon/indexer/lumina/lumina_global_index.h b/src/paimon/indexer/lumina/lumina_global_index.h index 20293d50d..02d930beb 100644 --- a/src/paimon/indexer/lumina/lumina_global_index.h +++ b/src/paimon/indexer/lumina/lumina_global_index.h @@ -132,8 +132,8 @@ class LuminaIndexReader : public GlobalIndexReader { ~LuminaIndexReader() override = default; - /// @note `VisitVectorSearch` is thread-safe (not coroutine-safe) while other `VisitXXX` is not - /// thread-safe. + /// @note `VisitVectorSearch` supports concurrent calls from multiple threads, but not + /// coroutine re-entry. Other `Visit*` methods are unsupported and return nullptr results. Result> VisitVectorSearch( const std::shared_ptr& vector_search) override; diff --git a/test/inte/global_index_test.cpp b/test/inte/global_index_test.cpp index 045642760..361d41ca3 100644 --- a/test/inte/global_index_test.cpp +++ b/test/inte/global_index_test.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -6428,6 +6429,122 @@ TEST_P(GlobalIndexTest, TestBTreeWithLumina) { } #endif +#if defined(PAIMON_ENABLE_FULL_TEXT) && defined(PAIMON_ENABLE_LUMINA) +TEST_P(GlobalIndexTest, TestConcurrentTantivyAndLuminaSearch) { + arrow::FieldVector fields = {arrow::field("f0", arrow::utf8()), + arrow::field("f1", arrow::list(arrow::float32()))}; + auto schema = arrow::schema(fields); + std::map options = {{Options::FILE_FORMAT, file_format_}, + {Options::FILE_SYSTEM, "local"}, + {Options::ROW_TRACKING_ENABLED, "true"}, + {Options::DATA_EVOLUTION_ENABLED, "true"}, + {Options::DELETION_VECTORS_ENABLED, "true"}}; + std::map index_options = { + {"full-text.tokenizer", "default"}, {"lumina.index.dimension", "4"}, + {"lumina.index.type", "bruteforce"}, {"lumina.distance.metric", "l2"}, + {"lumina.encoding.type", "rawf32"}, {"lumina.search.parallel_number", "10"}}; + CreateTable(/*partition_keys=*/{}, schema, options); + const std::string table_path = PathUtil::JoinPath(dir_->Str(), "foo.db/bar"); + auto data = arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_(fields), R"([ +["apple", [0.0, 0.0, 0.0, 0.0]], +["banana banana banana banana", [1.0, 0.0, 0.0, 0.0]], +["apple apple", [2.0, 0.0, 0.0, 0.0]], +["banana", [3.0, 0.0, 0.0, 0.0]], +["apple apple apple", [4.0, 0.0, 0.0, 0.0]], +["banana banana", [5.0, 0.0, 0.0, 0.0]], +["apple apple apple apple", [6.0, 0.0, 0.0, 0.0]], +["banana banana banana", [7.0, 0.0, 0.0, 0.0]] + ])") + .ValueOrDie(); + ASSERT_OK_AND_ASSIGN(auto commit_msgs, WriteArray(table_path, schema->field_names(), data)); + ASSERT_OK(Commit(table_path, commit_msgs)); + for (const Range& range : {Range(0, 3), Range(4, 7)}) { + ASSERT_OK(WriteIndex(table_path, {}, "f0", "full-text", index_options, range)); + ASSERT_OK(WriteIndex(table_path, {}, "f1", "lumina", index_options, range)); + } + + // Delete rows after indexing so both real backends must apply the snapshot's DV. + ASSERT_OK_AND_ASSIGN(auto split, ScanData(table_path, {})); + ASSERT_OK_AND_ASSIGN(std::vector anchor_files, + DeletionVectorTestHelper::RetrieveAnchorFileNames(split->DataFiles())); + ASSERT_EQ(anchor_files.size(), 1u); + ASSERT_OK_AND_ASSIGN(std::shared_ptr dv_commit_msg, + DeletionVectorTestHelper::CreateDeletionVectorCommitMessage( + dir_->GetFileSystem(), table_path, file_format_, commit_msgs[0], + {{anchor_files[0], /*deleted_positions=*/{1, 6}}}, pool_)); + ASSERT_OK(Commit(table_path, {dv_commit_msg})); + + ASSERT_OK_AND_ASSIGN(std::shared_ptr executor, + CreateDefaultExecutor(/*thread_count=*/4)); + const std::vector queries = {R"({"match":{"query":"apple"}})", + R"({"match":{"query":"banana"}})"}; + // Let match distinguish the terms; the input filter includes deleted and nonmatching rows. + const RoaringBitmap64 all_rows = RoaringBitmap64::From({0, 1, 2, 3, 4, 5, 6, 7}); + const std::vector> live_ids = {{0, 2, 4}, {3, 5, 7}}; + ASSERT_OK_AND_ASSIGN( + auto scan, + GlobalIndexScan::Create(table_path, /*snapshot_id=*/std::nullopt, + /*partitions=*/std::nullopt, index_options, fs_, executor, pool_)); + ASSERT_OK_AND_ASSIGN(auto text_reader, scan->CreateReader("f0", "full-text", std::nullopt)); + ASSERT_OK_AND_ASSIGN(auto vector_reader, scan->CreateReader("f1", "lumina", std::nullopt)); + ASSERT_TRUE(text_reader); + ASSERT_TRUE(vector_reader); + ASSERT_TRUE(text_reader->IsThreadSafe()); + ASSERT_TRUE(vector_reader->IsThreadSafe()); + auto check_result = [](const std::shared_ptr& result, + const std::vector& expected) { + ASSERT_TRUE(result); + ASSERT_OK_AND_ASSIGN(auto iter, result->CreateIterator()); + for (int64_t row_id : expected) { + ASSERT_TRUE(iter->HasNext()); + ASSERT_EQ(iter->Next(), row_id); + } + ASSERT_FALSE(iter->HasNext()); + }; + + std::promise start; + std::shared_future ready = start.get_future().share(); + auto query_text = [&](int32_t variant) { + ready.wait(); + SCOPED_TRACE(queries[variant]); + auto search = std::make_shared("f0", queries[variant], + /*limit=*/8, all_rows); + for (int32_t iteration = 0; iteration < 16; ++iteration) { + SCOPED_TRACE(iteration); + ASSERT_OK_AND_ASSIGN(auto result, text_reader->VisitFullTextSearch(search)); + check_result(result, live_ids[variant]); + } + }; + auto query_vector = [&](int32_t variant) { + ready.wait(); + SCOPED_TRACE(variant); + const float query_value = variant == 0 ? 0.5f : 8.5f; + const std::vector query = {query_value, 0.0f, 0.0f, 0.0f}; + auto search = std::make_shared( + "f1", /*limit=*/8, query, [variant](int64_t row_id) { return row_id % 2 == variant; }, + /*predicate=*/nullptr, /*distance_type=*/std::nullopt, index_options); + for (int32_t iteration = 0; iteration < 16; ++iteration) { + SCOPED_TRACE(iteration); + ASSERT_OK_AND_ASSIGN(auto result, vector_reader->VisitVectorSearch(search)); + check_result(result, live_ids[variant]); + } + }; + + std::vector> workers; + workers.reserve(4); + { + ScopeGuard release_workers([&start] { start.set_value(); }); + workers.push_back(std::async(std::launch::async, query_text, /*variant=*/0)); + workers.push_back(std::async(std::launch::async, query_text, /*variant=*/1)); + workers.push_back(std::async(std::launch::async, query_vector, /*variant=*/0)); + workers.push_back(std::async(std::launch::async, query_vector, /*variant=*/1)); + } + for (auto& worker : workers) { + worker.get(); + } +} +#endif + std::vector GetTestValuesForGlobalIndexTest() { std::vector values; values.emplace_back("parquet", false);