Skip to content
Merged
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
15 changes: 13 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,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
Expand Down
8 changes: 7 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,13 @@ 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 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").
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
8 changes: 5 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,11 @@ 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,
Comment thread
lxy-9602 marked this conversation as resolved.
Resolved
/// `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>& 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 @@ -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"

Expand Down Expand Up @@ -262,6 +263,14 @@ Result<std::shared_ptr<GlobalIndexResult>> SortedFileGlobalIndexReader::VisitSel
} else {
std::vector<std::future<ReaderResult>> 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<GlobalIndexReader>& reader : readers) {
futures.push_back(
Via(executor_.get(), [visitor, reader]() { return visitor(reader); }));
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
9 changes: 9 additions & 0 deletions src/paimon/common/global_index/union_global_index_reader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -301,6 +302,14 @@ std::vector<R> UnionGlobalIndexReader::ExecuteAllReadersWithIndex(
// Parallel: submit all tasks to executor, then collect results in submission order
std::vector<std::future<R>> futures;
futures.reserve(readers_.size());
// Wait for accepted tasks before unwinding if submission or result collection throws.
ScopeGuard drain([&futures] {
Comment thread
lxy-9602 marked this conversation as resolved.
Resolved
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);
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
99 changes: 75 additions & 24 deletions src/paimon/common/global_index/union_global_index_reader_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@

#include "paimon/common/global_index/union_global_index_reader.h"

#include <chrono>
#include <future>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <queue>
#include <stdexcept>
Expand Down Expand Up @@ -85,19 +88,32 @@ class FakeSortedFileGlobalIndexReader : public SortedFileGlobalIndexReader {
std::map<std::string, std::shared_ptr<GlobalIndexReader>> 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<void()> func) override {
if (submission_count_++ == 0) {
func();
} else {
pending_tasks_.push(std::move(func));
{
std::lock_guard<std::mutex> 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<std::mutex> lock(mutex_);
std::queue<std::function<void()>> empty;
pending_tasks_.swap(empty);
}
Expand All @@ -107,19 +123,35 @@ class DeferAfterFirstExecutor : public Executor {
}

uint32_t SubmissionCount() const {
std::lock_guard<std::mutex> 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<void()> task = std::move(pending_tasks_.front());
pending_tasks_.pop();
std::queue<std::function<void()>> tasks;
{
std::lock_guard<std::mutex> lock(mutex_);
released_ = true;
tasks.swap(pending_tasks_);
}
while (!tasks.empty()) {
std::function<void()> 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<void> last_submission_;
std::queue<std::function<void()>> pending_tasks_;
};

Expand Down Expand Up @@ -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<MockGlobalIndexReader>();
auto deferred_reader = std::make_shared<MockGlobalIndexReader>();
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<MockGlobalIndexReader>();
auto deferred_reader = std::make_shared<MockGlobalIndexReader>();
throwing_reader->SetThrowException("reader exception");
deferred_reader->SetDefaultResult({2});

std::vector<std::shared_ptr<GlobalIndexReader>> readers = {throwing_reader, deferred_reader};
auto executor = std::make_shared<DeferAfterFirstExecutor>();
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<std::shared_ptr<GlobalIndexReader>> readers = {throwing_reader,
deferred_reader};
if (reject_submission) {
readers.push_back(std::make_shared<MockGlobalIndexReader>());
}
auto executor = std::make_shared<DeferAfterFirstExecutor>(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) {
Expand Down
13 changes: 9 additions & 4 deletions src/paimon/common/utils/dense_hash_table.h
Original file line number Diff line number Diff line change
Expand Up @@ -119,22 +119,27 @@ class DenseHashTable {
}

std::optional<Value> Find(Key key) const {
std::optional<Value> result;
if (key == kEmptyKey || key == kOtherSpecialKey) {
const Bucket bucket = ReadBucket(header_.bucket_count + (key == kOtherSpecialKey));
return bucket.key == 0 ? std::nullopt : std::optional<Value>(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.
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
10 changes: 8 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,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<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
Comment thread
lxy-9602 marked this conversation as resolved.
Resolved
/// 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
Expand Down
Loading
Loading