Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions docs/source/user_guide/global_index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion include/paimon/global_index/global_index_reader.h
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,11 @@ class PAIMON_EXPORT GlobalIndexReader : public FunctionVisitor<std::shared_ptr<G
virtual Result<std::shared_ptr<ScoredGlobalIndexResult>> VisitFullTextSearch(
const std::shared_ptr<FullTextSearch>& 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Account for query lifetime after an exceptional exit. UnionGlobalIndexReader can unwind on an Executor::Add() or future.get() exception while accepted tasks still hold the original search object or its pre-filter. TestDeferredTaskOwnsActionAfterEarlierFutureThrows demonstrates that a queued task can run after the visit unwinds. A caller following the new wording can reuse the query or release objects borrowed by its pre-filter at that point, while a shard may still access them. Please drain accepted tasks before unwinding, or document that the arguments and callback state must remain valid and immutable until the accepted work finishes.

/// used concurrently must be thread-safe. Reader lifetime must cover all outstanding calls.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Document the concurrency requirement for custom file systems. A multi-shard search can lazily open index files through the same GlobalIndexFileManager and call FileSystem::Open() concurrently. For example, FullTextGlobalIndexReader serializes opening within a shard with its own mutex, and different shards have distinct mutexes. An IsThreadSafe() result of true therefore still requires the supplied storage implementation to support the calls made concurrently. Please state this on the file_system parameter of both Create() overloads, and include custom index I/O in the reader's concurrency contract.

/// 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").
Expand Down
8 changes: 6 additions & 2 deletions include/paimon/global_index/global_index_scan.h
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.
Expand Down
5 changes: 2 additions & 3 deletions include/paimon/table/source/full_text_search_builder.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<MemoryPool>& 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,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Document the executor re-entry restriction at the public entry point. If a task on a one-worker executor calls ExecuteLocal() with that same executor and two eligible splits, Read() queues both shard searches behind the caller and waits for them. Builder users can hit this deadlock without ever calling GlobalIndexReader::IsThreadSafe(). Please document the restriction beside WithExecutor() and in the user guide, including planning and filtering operations that can wait for manifest work on the same pool.

/// `global-index.thread-num` determines the pool size (default: CPU count).
FullTextSearchBuilder& WithExecutor(const std::shared_ptr<Executor>& executor);

/// Sets the file system to access the table with. If not set, the file system is created from
Expand Down
2 changes: 2 additions & 0 deletions src/paimon/common/global_index/offset_global_index_reader.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::shared_ptr<GlobalIndexResult>> VisitIsNotNull() override;
Expand Down
3 changes: 3 additions & 0 deletions src/paimon/common/global_index/union_global_index_reader.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions src/paimon/core/global_index/global_index_scan_impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ class GlobalIndexScanImpl : public GlobalIndexScan {
const std::vector<std::shared_ptr<IndexFileMeta>>& index_files,
const std::shared_ptr<Executor>& executor, const std::shared_ptr<MemoryPool>& 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<std::shared_ptr<Executor>> GetOrCreateExecutor(
const std::shared_ptr<Executor>& executor, const CoreOptions& options);

Expand Down
8 changes: 6 additions & 2 deletions src/paimon/core/global_index/live_row_global_index_reader.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<Result<std::shared_ptr<const RoaringBitmap64>>()>;

/// 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<Result<std::optional<RoaringBitmap64>>()> 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The live-rows supplier can still run on a shard worker after preloading. CreateUnion() passes the same supplier to each LiveRowGlobalIndexReader, and the shard visits invoke it again. With two shards and a one-worker executor, an uncached supplier that submits manifest work to that executor and waits can deadlock even when the query starts on an external thread. Please document that after preloading, shard-side supplier calls must return without waiting for work on executor. CacheLiveRows() provides that behavior for a snapshot-scoped loader.

/// 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
Expand Down
118 changes: 118 additions & 0 deletions src/paimon/core/global_index/live_row_global_index_reader_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@

#include "paimon/core/global_index/live_row_global_index_reader.h"

#include <atomic>
#include <cstdint>
#include <future>
#include <map>
#include <memory>
#include <mutex>
Expand All @@ -30,7 +32,9 @@
#include <vector>

#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"
Expand All @@ -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<std::shared_ptr<ScoredGlobalIndexResult>> VisitVectorSearch(
const std::shared_ptr<VectorSearch>& search) override {
return Search(search->pre_filter, search->query.front());
}

Result<std::shared_ptr<ScoredGlobalIndexResult>> VisitFullTextSearch(
const std::shared_ptr<FullTextSearch>& search) override {
return Search(
[search](int64_t row_id) {
return !search->include_row_ids || search->include_row_ids->Contains(row_id);
},
static_cast<float>(search->limit));
}

private:
Result<std::shared_ptr<ScoredGlobalIndexResult>> Search(const VectorSearch::PreFilter& filter,
float query_score) {
RoaringBitmap64 rows;
std::vector<float> 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<float>(row_id) + 0.1f);
}
}
return std::make_shared<BitmapScoredGlobalIndexResult>(std::move(rows), std::move(scores));
}
};
} // namespace

class LiveRowGlobalIndexReaderTest : public ::testing::Test {
public:
static LiveRowGlobalIndexReader::LiveRowsSupplier Supply(
Expand Down Expand Up @@ -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> executor;
if (parallel_shards) {
ASSERT_OK_AND_ASSIGN(executor, CreateDefaultExecutor(/*thread_count=*/4));
}
std::vector<std::shared_ptr<GlobalIndexReader>> shards;
for (int64_t offset : {100, 200}) {
shards.push_back(std::make_shared<OffsetGlobalIndexReader>(
std::make_shared<FilteringGlobalIndexReader>(), offset, offset + 3));
}
std::atomic<int32_t> load_count{0};
auto supplier = LiveRowGlobalIndexReader::CacheLiveRows(
[&]() -> Result<std::optional<RoaringBitmap64>> {
++load_count;
// Shards cover [100, 103] and [200, 203]; DV deletes 101 and 202.
return std::optional<RoaringBitmap64>(
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<void> start;
std::shared_future<void> ready = start.get_future().share();
std::vector<std::future<void>> 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();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make the test observe overlapping queries with different filters. The start promise releases the callers. Each query can complete before the next enters while still satisfying every assertion. All four callers also use the same filter parity in a given iteration (thread_id * 16 + iteration), which can hide filter reuse when they progress together. Can one fake shard hold its first visit until a second visit with the opposite filter arrives, with a bounded wait? In the executor-backed case, also verify that shard work is submitted to the injected executor.

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<float>(query_id + 3);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix the clang-tidy failure on this declaration. The clang-debug-x86_64 job passes CTest, then fails check-clang-tidy with modernize-use-auto here. const auto query_score = static_cast<float>(query_id + 3); preserves the type and clears the diagnostic. CI log

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<float> expected_scores =
parity == 0 ? std::vector<float>{query_score + 0.1f, query_score + 2.1f,
query_score + 0.1f}
: std::vector<float>{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<ScoredGlobalIndexResult> result,
vector_query ? reader->VisitVectorSearch(vector)
: reader->VisitFullTextSearch(text));
auto scored =
std::dynamic_pointer_cast<BitmapScoredGlobalIndexResult>(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<MockGlobalIndexReader>();
mock_reader->SetDefaultResult({1, 2});
Expand All @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -622,7 +622,7 @@ Result<std::shared_ptr<ScoredGlobalIndexResult>> DataEvolutionFullTextRead::Sear
}
}
});
if (searches.size() <= 1) {
if (!executor_ || searches.size() <= 1) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The null-executor fallback is unreachable through Create(). That is the only construction path and it stores the non-null result of GetOrCreateExecutor(), including when the builder is given WithExecutor(nullptr). Invalid thread counts fail before SearchSplits() runs. Please drop this branch and the corresponding behavior claim, or expose a supported serial path and exercise it with at least two eligible splits.

for (const auto& search : searches) {
results.push_back(search());
}
Expand Down
4 changes: 2 additions & 2 deletions src/paimon/core/table/source/data_evolution_full_text_read.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::unique_ptr<DataEvolutionFullTextRead>> Create(
const std::string& root_path, const std::shared_ptr<TableSchema>& table_schema,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<FullTextSearchBuilder> 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<FullTextSearchBuilder> 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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<TableSchema>& table_schema,
Expand Down
Loading