From 7333df0fd2a988c59771bc59b903606d196daa4b Mon Sep 17 00:00:00 2001 From: Nicholas Jiang Date: Mon, 30 Nov 2026 19:30:13 +0800 Subject: [PATCH] feat(parquet): bound input prefetch with a row-group window Arrow could pre-buffer every selected row group before returning the first batch, letting compressed input memory grow with wide scans. Issue #602 calls for bounding Parquet input pre-buffering with a sliding row-group window. - Prefetch projected column chunks and selected pages in a sliding window covering the current row group and configurable lookahead via parquet.read.cache-option.prefetch-row-groups (default 1, 0 disables lookahead). - Apply parquet.read.cache-option.window-size-limit (default 128 MiB, 0 disables the window) to subsequent lookahead, counting coalesced gaps and in-flight reads while still prefetching at least the current row group when enabled. - Reuse buffered input on seeks within the window, retire consumed groups after their final batch and drain submitted reads before releasing buffers from consumed or discarded groups. - Fall back to on-demand reads after prefetch failures and preserve row-group and page pruning, file row IDs, batch order and returned Arrow batch lifetimes. - Cover bounded wide-string scans, lookahead limits, oversized current groups, coalesced gaps, seeks, early close and prefetch failures. Document the window options and lifecycle behavior. --- cmake_modules/arrow.diff | 151 ++--- docs/source/user_guide/prefetch.rst | 47 +- .../arrow/arrow_input_stream_adapter.cpp | 35 +- .../format/parquet/file_reader_wrapper.cpp | 534 ++++++++--------- .../format/parquet/file_reader_wrapper.h | 103 ++-- .../parquet/file_reader_wrapper_test.cpp | 558 +++++++++++++++--- .../page_filtered_row_group_reader.cpp | 34 +- .../parquet/page_filtered_row_group_reader.h | 18 +- .../page_filtered_row_group_reader_test.cpp | 155 ++--- .../parquet/parquet_file_batch_reader.cpp | 21 +- .../parquet_file_batch_reader_test.cpp | 83 +++ .../format/parquet/parquet_format_defs.h | 11 + 12 files changed, 1121 insertions(+), 629 deletions(-) diff --git a/cmake_modules/arrow.diff b/cmake_modules/arrow.diff index aeaf5d3fe..e7351669a 100644 --- a/cmake_modules/arrow.diff +++ b/cmake_modules/arrow.diff @@ -60,6 +60,41 @@ index 8cb3ec83f5..9aad83ac95 100644 -DWITH_PYTHON=OFF -DWITH_QT5=OFF -DWITH_ZLIB=OFF) +diff --git a/cpp/src/arrow/io/caching.cc b/cpp/src/arrow/io/caching.cc +--- a/cpp/src/arrow/io/caching.cc ++++ b/cpp/src/arrow/io/caching.cc +@@ -330,7 +330,15 @@ Future<> ReadRangeCache::Wait() { return impl_->Wait(); } + Future<> ReadRangeCache::WaitFor(std::vector ranges) { + return impl_->WaitFor(std::move(ranges)); + } +- ++ ++void ReadRangeCache::WaitForInFlight() { ++ for (const auto& entry : impl_->entries) { ++ if (entry.future.is_valid()) { ++ entry.future.Wait(); ++ } ++ } ++} ++ + } // namespace internal + } // namespace io + } // namespace arrow +diff --git a/cpp/src/arrow/io/caching.h b/cpp/src/arrow/io/caching.h +--- a/cpp/src/arrow/io/caching.h ++++ b/cpp/src/arrow/io/caching.h +@@ -142,6 +142,10 @@ class ARROW_EXPORT ReadRangeCache { + /// \brief Wait until all given ranges have been cached. + Future<> WaitFor(std::vector ranges); +- ++ ++ /// Wait for submitted reads without initiating I/O for untouched lazy ranges. ++ /// Call only after all users of this cache have stopped issuing reads. ++ void WaitForInFlight(); ++ + protected: + struct Impl; + struct LazyImpl; diff --git a/cpp/src/arrow/io/interfaces.h b/cpp/src/arrow/io/interfaces.h index b36c38c6d4..f974a33073 100644 --- a/cpp/src/arrow/io/interfaces.h @@ -931,20 +966,11 @@ diff --git a/cpp/src/parquet/file_reader.cc b/cpp/src/parquet/file_reader.cc index 3e9eeea6c6..671ebe4644 100644 --- a/cpp/src/parquet/file_reader.cc +++ b/cpp/src/parquet/file_reader.cc -@@ -207,6 +207,117 @@ const RowGroupMetaData* RowGroupReader::metadata() const { return contents_->met +@@ -207,6 +207,100 @@ const RowGroupMetaData* RowGroupReader::metadata() const { return contents_->met return {col_start, col_length}; } -+// CachedInputStream: InputStream adapter that reads through ReadRangeCache with -+// zero-cost skip for non-cached pages. Used for page-level caching where only -+// specific pages are pre-buffered. -+// -+// Key behavior: -+// - Read(): On cache hit, returns cached data. On cache miss, returns zero-filled -+// buffer (zero I/O). This makes InputStream::Advance() (which calls Read() and -+// discards) effectively free for skipped pages. -+// - Peek(): Always falls back to source on cache miss, because PageReader uses -+// Peek() to read Thrift page headers (~30 bytes) which must have real data. ++// Reads cached ranges and falls back to positional file I/O on cache misses. +class CachedInputStream : public ::arrow::io::InputStream { + public: + CachedInputStream( @@ -975,31 +1001,21 @@ index 3e9eeea6c6..671ebe4644 100644 + if (result.ok()) { + peek_buffer_ = *result; + } else { -+ // Peek is used for Thrift page headers (~30 bytes) — must read real data + ARROW_ASSIGN_OR_RAISE(peek_buffer_, + source_->ReadAt(range.offset, range.length)); + } ++ peek_offset_ = range.offset; + return std::string_view( + reinterpret_cast(peek_buffer_->data()), + static_cast(peek_buffer_->size())); + } + + ::arrow::Result Read(int64_t nbytes, void* out) override { -+ int64_t to_read = std::min(nbytes, length_ - position_); -+ if (to_read <= 0) return 0; -+ ::arrow::io::ReadRange range{base_offset_ + position_, to_read}; -+ auto result = cache_->Read(range); -+ if (result.ok()) { -+ auto& buf = *result; -+ memcpy(out, buf->data(), static_cast(buf->size())); -+ position_ += buf->size(); -+ return buf->size(); ++ ARROW_ASSIGN_OR_RAISE(auto buffer, Read(nbytes)); ++ if (buffer->size() > 0) { ++ memcpy(out, buffer->data(), static_cast(buffer->size())); + } -+ // Cache miss: fall back to real I/O from source -+ ARROW_ASSIGN_OR_RAISE(auto buf, source_->ReadAt(range.offset, range.length)); -+ memcpy(out, buf->data(), static_cast(buf->size())); -+ position_ += buf->size(); -+ return buf->size(); ++ return buffer->size(); + } + + ::arrow::Result> Read(int64_t nbytes) override { @@ -1008,22 +1024,23 @@ index 3e9eeea6c6..671ebe4644 100644 + return std::make_shared<::arrow::Buffer>(nullptr, 0); + } + ::arrow::io::ReadRange range{base_offset_ + position_, to_read}; ++ // The header peek may already cover the page body. ++ if (peek_buffer_ && ++ ::arrow::io::ReadRange{peek_offset_, peek_buffer_->size()}.Contains(range)) { ++ position_ += to_read; ++ return ::arrow::SliceBuffer(peek_buffer_, range.offset - peek_offset_, to_read); ++ } + auto result = cache_->Read(range); + if (result.ok()) { + position_ += (*result)->size(); + return *result; + } -+ // Cache miss: fall back to real I/O from source + ARROW_ASSIGN_OR_RAISE(auto buf, source_->ReadAt(range.offset, range.length)); + position_ += buf->size(); -+ return std::shared_ptr<::arrow::Buffer>(std::move(buf)); ++ return buf; + } + -+ // Override Advance to avoid real I/O for skipped pages. -+ // The default InputStream::Advance() calls Read() and discards the result, -+ // which would trigger source_->ReadAt() on cache miss — defeating page-level -+ // I/O skipping via data_page_filter. Since Advance() is only used to skip -+ // over data that will not be consumed, we can safely just move the position. ++ // The base implementation would read the bytes it skips. + ::arrow::Status Advance(int64_t nbytes) override { + if (nbytes <= 0) { + return ::arrow::Status::OK(); @@ -1043,69 +1060,58 @@ index 3e9eeea6c6..671ebe4644 100644 + int64_t length_; + int64_t position_ = 0; + bool closed_ = false; ++ int64_t peek_offset_ = 0; + std::shared_ptr<::arrow::Buffer> peek_buffer_; +}; + // RowGroupReader::Contents implementation for the Parquet file specification class SerializedRowGroup : public RowGroupReader::Contents { public: -@@ -242,6 +353,11 @@ class SerializedRowGroup : public RowGroupReader::Contents { +@@ -242,6 +336,9 @@ class SerializedRowGroup : public RowGroupReader::Contents { // segments. PARQUET_ASSIGN_OR_THROW(auto buffer, cached_source_->Read(col_range)); stream = std::make_shared<::arrow::io::BufferReader>(buffer); + } else if (cached_source_) { -+ // Page-level caching: read through cache with fallback to source. -+ // Advance() is zero-cost for skipped pages via data_page_filter. + stream = std::make_shared( + cached_source_, source_, col_range.offset, col_range.length); } else { stream = properties_.GetStream(source_, col_range.offset, col_range.length); } -@@ -417,6 +533,26 @@ class SerializedFile : public ParquetFileReader::Contents { +@@ -417,6 +514,17 @@ class SerializedFile : public ParquetFileReader::Contents { return cached_source_->WaitFor(ranges); } -+ void PreBufferRanges(const std::vector<::arrow::io::ReadRange>& ranges, -+ const ::arrow::io::IOContext& ctx, -+ const ::arrow::io::CacheOptions& options) { -+ cached_source_ = -+ std::make_shared<::arrow::io::internal::ReadRangeCache>(source_, ctx, options); -+ // Do NOT set prebuffered_column_chunks_ bitmap — GetColumnPageReader will -+ // use CachedInputStream path instead of full-chunk BufferReader path. -+ prebuffered_column_chunks_.clear(); -+ PARQUET_THROW_NOT_OK(cached_source_->Cache(ranges)); ++ std::shared_ptr<::arrow::io::internal::ReadRangeCache> MakePreBufferCache( ++ const ::arrow::io::IOContext& ctx, ++ const ::arrow::io::CacheOptions& options) const { ++ return std::make_shared<::arrow::io::internal::ReadRangeCache>(source_, ctx, options); + } + -+ ::arrow::Future<> WhenBufferedRanges( -+ const std::vector<::arrow::io::ReadRange>& ranges) const { -+ if (!cached_source_) { -+ return ::arrow::Status::Invalid( -+ "Must call PreBufferRanges before WhenBufferedRanges"); -+ } -+ return cached_source_->WaitFor(ranges); ++ void SetPreBufferCache(std::shared_ptr<::arrow::io::internal::ReadRangeCache> cache) { ++ cached_source_ = std::move(cache); ++ prebuffered_column_chunks_.clear(); + } + // Metadata/footer parsing. Divided up to separate sync/async paths, and to use // exceptions for error handling (with the async path converting to Future/Status). -@@ -911,6 +1047,22 @@ void ParquetFileReader::PreBuffer(const std::vector& row_groups, +@@ -911,6 +1019,21 @@ void ParquetFileReader::PreBuffer(const std::vector& row_groups, return file->WhenBuffered(row_groups, column_indices); } -+void ParquetFileReader::PreBufferRanges( -+ const std::vector<::arrow::io::ReadRange>& ranges, ++std::shared_ptr<::arrow::io::internal::ReadRangeCache> ParquetFileReader::MakePreBufferCache( + const ::arrow::io::IOContext& ctx, -+ const ::arrow::io::CacheOptions& options) { -+ SerializedFile* file = -+ ::arrow::internal::checked_cast(contents_.get()); -+ file->PreBufferRanges(ranges, ctx, options); ++ const ::arrow::io::CacheOptions& options) const { ++ const auto* file = ++ ::arrow::internal::checked_cast(contents_.get()); ++ return file->MakePreBufferCache(ctx, options); +} + -+::arrow::Future<> ParquetFileReader::WhenBufferedRanges( -+ const std::vector<::arrow::io::ReadRange>& ranges) const { ++void ParquetFileReader::SetPreBufferCache( ++ std::shared_ptr<::arrow::io::internal::ReadRangeCache> cache) { + SerializedFile* file = + ::arrow::internal::checked_cast(contents_.get()); -+ return file->WhenBufferedRanges(ranges); ++ file->SetPreBufferCache(std::move(cache)); +} + // ---------------------------------------------------------------------- @@ -1115,20 +1121,17 @@ diff --git a/cpp/src/parquet/file_reader.h b/cpp/src/parquet/file_reader.h index b59b59f95c..657a438a3a 100644 --- a/cpp/src/parquet/file_reader.h +++ b/cpp/src/parquet/file_reader.h -@@ -210,6 +210,17 @@ class PARQUET_EXPORT ParquetFileReader { +@@ -210,6 +210,14 @@ class PARQUET_EXPORT ParquetFileReader { ::arrow::Future<> WhenBuffered(const std::vector& row_groups, const std::vector& column_indices) const; -+ /// Pre-buffer arbitrary byte ranges (e.g., page-level ranges from OffsetIndex). -+ /// Unlike PreBuffer(), this does NOT set the column bitmap, so -+ /// GetColumnPageReader will use CachedInputStream (page-level cache path). -+ void PreBufferRanges(const std::vector<::arrow::io::ReadRange>& ranges, -+ const ::arrow::io::IOContext& ctx, -+ const ::arrow::io::CacheOptions& options); -+ -+ /// Wait for arbitrary byte ranges to be pre-buffered. -+ ::arrow::Future<> WhenBufferedRanges( -+ const std::vector<::arrow::io::ReadRange>& ranges) const; ++ /// Create a range cache without changing the cache used by column readers. ++ std::shared_ptr<::arrow::io::internal::ReadRangeCache> MakePreBufferCache( ++ const ::arrow::io::IOContext& ctx, const ::arrow::io::CacheOptions& options) const; ++ ++ /// Set the cache for subsequently opened column readers. With an empty cache, ++ /// the readers use positional I/O and can skip page ranges without reading them. ++ void SetPreBufferCache(std::shared_ptr<::arrow::io::internal::ReadRangeCache> cache); + private: // Holds a pointer to an instance of Contents implementation diff --git a/docs/source/user_guide/prefetch.rst b/docs/source/user_guide/prefetch.rst index 1cd89f538..f37e038d7 100644 --- a/docs/source/user_guide/prefetch.rst +++ b/docs/source/user_guide/prefetch.rst @@ -47,20 +47,39 @@ Below we detail how these strategies are applied to Parquet and ORC. Parquet ======== -Parquet files are organized into RowGroups and Pages. Since C++ Parquet does -not support row-level seeking, prefetching can only be done at the RowGroup -level. This naturally avoids read amplification, but introduces a new -challenge: if a file contains only a small number of RowGroups, parallelism is -severely limited. Therefore, we recommend users reduce RowGroup size when -writing Parquet files to increase opportunities for parallel processing. - -Another critical difference is the read behavior compared to ORC. ORC strictly -returns RecordBatches aligned to Stripe boundaries, whereas C++ Parquet may -return a RecordBatch containing data from multiple RowGroups. This can lead to -output order confusion during parallel reads. We modified C++ Parquet internals -to return results strictly aligned to RowGroup boundaries, matching ORC's -behavior. With this change, parallel reading no longer requires complex seek -operations, improving overall read efficiency. +Parquet read ranges and returned batches align to row-group boundaries. This +lets parallel readers merge results in file row order. Within a group, page +indexes can narrow the byte ranges read for projected columns. + +When Arrow input pre-buffering is enabled, each Parquet reader keeps a sliding +window covering the current row group and up to +``parquet.read.cache-option.prefetch-row-groups`` subsequent row groups. The +byte budget covers projected column chunks, selected pages and any gaps +included when combining byte ranges. The reader reserves those bytes before +submitting reads and releases the reservation when the group leaves the window +and its submitted reads have finished. At least the current row group is +prefetched even when its projected ranges exceed the budget; subsequent row +groups are prefetched only while both the lookahead count and the byte budget +allow. If merging ranges would make a group that otherwise fits exceed the +budget, the reader prefetches its individual ranges instead. + +The reader retires each group when it returns that group's final batch. +Seeking to a group still in the window reuses its prefetched input. When a +seek or close discards groups, the reader waits for their submitted reads +before releasing their buffers. + +``parquet.read.cache-option.window-size-limit`` sets the per-reader byte budget +and defaults to ``134217728`` (128 MiB). Set it to ``0`` or set +``parquet.read.enable-pre-buffer`` to ``false`` to disable the window +completely, including pre-buffering of the current row group. +``parquet.read.cache-option.prefetch-row-groups`` sets the number of subsequent +row groups to prefetch beyond the current one and defaults to ``1``; set it to +``0`` to disable lookahead while still prefetching the current row group. With +``parquet.read.cache-option.lazy`` enabled, reads start when the decoder +accesses the cached ranges. The window still reserves their bytes. When the +shared read-ahead cache handles prefetching, it supplies the input and the +Parquet window is disabled. Allocator overhead, on-demand reads and decoded +batches use additional memory. ORC === diff --git a/src/paimon/common/utils/arrow/arrow_input_stream_adapter.cpp b/src/paimon/common/utils/arrow/arrow_input_stream_adapter.cpp index 8c940271e..9a410b8b8 100644 --- a/src/paimon/common/utils/arrow/arrow_input_stream_adapter.cpp +++ b/src/paimon/common/utils/arrow/arrow_input_stream_adapter.cpp @@ -20,6 +20,7 @@ #include "paimon/common/utils/arrow/arrow_input_stream_adapter.h" #include +#include #include #include @@ -147,18 +148,30 @@ arrow::Future> ArrowInputStreamAdapter::ReadAsync std::shared_ptr buffer = std::move(buffer_result).ValueUnsafe(); buffer = KeepMemoryPoolAlive(std::move(buffer), pool_); std::shared_ptr> storage_read_bytes = storage_read_bytes_; - input_stream_->ReadAsync( - reinterpret_cast(buffer->mutable_data()), nbytes, position, - [fut, buffer, storage_read_bytes, nbytes](Status callback_status) mutable { - if (callback_status.ok()) { - if (storage_read_bytes) { - storage_read_bytes->fetch_add(static_cast(nbytes)); + char* data = reinterpret_cast(buffer->mutable_data()); + try { + input_stream_->ReadAsync( + data, nbytes, position, + [future = fut, buffer = std::move(buffer), storage_read_bytes, + nbytes](Status callback_status) mutable { + // Drop the callback's future so a retained callback cannot pin the buffer. + auto completed = std::move(future); + if (callback_status.ok()) { + if (storage_read_bytes) { + storage_read_bytes->fetch_add(static_cast(nbytes)); + } + completed.MarkFinished(std::move(buffer)); + } else { + buffer.reset(); + completed.MarkFinished(ToArrowStatus(callback_status)); } - fut.MarkFinished(std::move(buffer)); - } else { - fut.MarkFinished(ToArrowStatus(callback_status)); - } - }); + }); + } catch (const std::exception& e) { + // Report the failed submission through its future so other reads can still be drained. + if (!fut.is_finished()) { + fut.MarkFinished(arrow::Status::IOError(e.what())); + } + } return fut; } diff --git a/src/paimon/format/parquet/file_reader_wrapper.cpp b/src/paimon/format/parquet/file_reader_wrapper.cpp index 6f575a531..d89ba0b10 100644 --- a/src/paimon/format/parquet/file_reader_wrapper.cpp +++ b/src/paimon/format/parquet/file_reader_wrapper.cpp @@ -24,6 +24,7 @@ #include #include "arrow/io/interfaces.h" +#include "arrow/io/util_internal.h" #include "arrow/record_batch.h" #include "arrow/util/range.h" #include "fmt/format.h" @@ -72,16 +73,13 @@ class CachedRowGroupPageIndexReader : public ::parquet::RowGroupPageIndexReader std::map> offset_indexes_; }; -// Merge overlapping or adjacent ReadRanges into a minimal set of non-overlapping ranges. -// PreBufferRanges requires non-overlapping ranges, so this is necessary when combining -// ranges from multiple sources (page-level ranges, column chunk ranges, etc.). +// Arrow's coalescer requires non-overlapping ranges. std::vector<::arrow::io::ReadRange> MergeOverlappingRanges( std::vector<::arrow::io::ReadRange> ranges) { if (ranges.empty()) { return ranges; } - // Sort by offset std::sort(ranges.begin(), ranges.end(), [](const ::arrow::io::ReadRange& a, const ::arrow::io::ReadRange& b) { return a.offset < b.offset; @@ -93,16 +91,13 @@ std::vector<::arrow::io::ReadRange> MergeOverlappingRanges( for (size_t i = 1; i < ranges.size(); ++i) { auto& last = merged.back(); const auto& curr = ranges[i]; - // Check if current range overlaps or is adjacent to the last merged range int64_t last_end = last.offset + last.length; - if (curr.offset <= last_end) { - // Merge: extend the last range if current extends beyond it + if (curr.offset < last_end) { int64_t curr_end = curr.offset + curr.length; if (curr_end > last_end) { last.length = curr_end - last.offset; } } else { - // No overlap, add as new range merged.push_back(curr); } } @@ -110,15 +105,30 @@ std::vector<::arrow::io::ReadRange> MergeOverlappingRanges( return merged; } +Status ValidateReadRange(const ::arrow::io::ReadRange& range) { + PAIMON_RETURN_NOT_OK(ValidateValueNonNegative(range.offset, "pre-buffer range offset")); + PAIMON_RETURN_NOT_OK(ValidateValueNonNegative(range.length, "pre-buffer range length")); + if (range.offset > std::numeric_limits::max() - range.length) { + return Status::Invalid(fmt::format("pre-buffer range overflows: offset={}, length={}", + range.offset, range.length)); + } + return Status::OK(); +} + } // namespace Result> FileReaderWrapper::Create( std::unique_ptr<::parquet::arrow::FileReader>&& file_reader, int64_t batch_size, - bool enable_offset_index_cache, std::shared_ptr<::arrow::MemoryPool> pool) { + bool enable_offset_index_cache, int64_t prefetch_budget, int64_t prefetch_row_groups, + std::shared_ptr<::arrow::MemoryPool> pool) { try { if (file_reader == nullptr) { return Status::Invalid("file reader wrapper create failed. file reader is nullptr"); } + if (file_reader->properties().pre_buffer() || prefetch_budget < 0 || + prefetch_row_groups < 0) { + return Status::Invalid("FileReaderWrapper requires explicit, bounded pre-buffering"); + } std::vector> all_row_group_ranges; auto meta_data = file_reader->parquet_reader()->metadata(); // prepare [start_row_idx, end_row_idx) for all row groups @@ -137,7 +147,8 @@ Result> FileReaderWrapper::Create( std::vector columns_indices = arrow::internal::Iota(file_reader->parquet_reader()->metadata()->num_columns()); auto file_reader_wrapper = std::unique_ptr(new FileReaderWrapper( - std::move(file_reader), all_row_group_ranges, num_rows, batch_size, pool)); + std::move(file_reader), all_row_group_ranges, num_rows, batch_size, prefetch_budget, + prefetch_row_groups, std::move(pool))); file_reader_wrapper->enable_offset_index_cache_ = enable_offset_index_cache; std::vector all_target_row_groups; for (int32_t i = 0; i < file_reader_wrapper->GetNumberOfRowGroups(); i++) { @@ -152,7 +163,7 @@ Result> FileReaderWrapper::Create( } FileReaderWrapper::~FileReaderWrapper() { - WaitForPendingPreBuffer(); + ResetPrefetchWindow(); } Result> FileReaderWrapper::GetSchema() const { @@ -166,6 +177,10 @@ Result> FileReaderWrapper::GetSchema() const { Status FileReaderWrapper::Close() { try { + ScopeGuard reset([this]() { ResetPrefetchWindow(); }); + SetCurrentRowGroup(target_row_groups_.size()); + pending_seek_row_group_idx_.reset(); + reader_initialized_ = true; if (batch_reader_) { PAIMON_RETURN_NOT_OK_FROM_ARROW(batch_reader_->Close()); } @@ -177,53 +192,80 @@ Status FileReaderWrapper::Close() { FileReaderWrapper::FileReaderWrapper( std::unique_ptr<::parquet::arrow::FileReader>&& file_reader, const std::vector>& all_row_group_ranges, uint64_t num_rows, - int64_t batch_size, std::shared_ptr<::arrow::MemoryPool> pool) + int64_t batch_size, int64_t prefetch_budget, int64_t prefetch_row_groups, + std::shared_ptr<::arrow::MemoryPool> pool) : file_reader_(std::move(file_reader)), all_row_group_ranges_(all_row_group_ranges), pool_(std::move(pool)), batch_size_(batch_size), + prefetch_budget_(prefetch_budget), + max_prefetch_row_groups_(prefetch_row_groups), num_rows_(num_rows) {} -void FileReaderWrapper::WaitForPendingPreBuffer() { - if (!prebuffered_ranges_.empty() && file_reader_) { - // Wait for all outstanding PreBuffer async reads to complete before destruction. - // Without this, JindoSDK async pread callbacks may fire after the underlying - // buffers and memory pool are freed, causing use-after-free crashes. - auto status = - file_reader_->parquet_reader()->WhenBufferedRanges(prebuffered_ranges_).status(); - (void)status; // Best-effort; ignore errors during cleanup - prebuffered_ranges_.clear(); +void FileReaderWrapper::RetirePrefetchedRowGroupsBefore(uint64_t index) { + while (!prefetched_row_groups_.empty() && prefetched_row_groups_.front().target_index < index) { + const auto& group = prefetched_row_groups_.front(); + // Keep the byte reservation until all submitted reads for this group finish. + group.cache->WaitForInFlight(); + reserved_prefetch_bytes_ -= group.bytes; + prefetched_row_groups_.pop_front(); } } -void FileReaderWrapper::AdvanceToNextRowGroup() { - current_row_group_idx_++; - // Skip row groups excluded by read range. - while (current_row_group_idx_ < target_row_groups_.size() && - target_row_groups_[current_row_group_idx_].IsExcludedByReadRange()) { - current_row_group_idx_++; - } - if (current_row_group_idx_ >= target_row_groups_.size()) { - next_row_to_read_ = num_rows_; - } else { - next_row_to_read_ = - all_row_group_ranges_[target_row_groups_[current_row_group_idx_].GetRowGroupIndex()] - .first; +void FileReaderWrapper::ResetRowGroupReader() { + batch_reader_.reset(); + file_reader_->parquet_reader()->SetPreBufferCache(nullptr); +} + +void FileReaderWrapper::ResetPrefetchWindow() { + ResetRowGroupReader(); + RetirePrefetchedRowGroupsBefore(target_row_groups_.size()); + pending_prefetch_plan_.reset(); + next_prefetch_row_group_idx_ = current_row_group_idx_; +} + +uint64_t FileReaderWrapper::NextReadableRowGroup(uint64_t index) const { + for (; index < target_row_groups_.size(); ++index) { + const auto& target = target_row_groups_[index]; + if (!target.IsExcludedByReadRange()) { + const auto& range = all_row_group_ranges_[target.GetRowGroupIndex()]; + if (range.first != range.second) { + break; + } + } } + return index; +} + +void FileReaderWrapper::SetCurrentRowGroup(uint64_t index) { + current_row_group_idx_ = index; + filtered_row_offset_ = 0; + next_row_to_read_ = + index < target_row_groups_.size() + ? all_row_group_ranges_[target_row_groups_[index].GetRowGroupIndex()].first + : num_rows_; +} + +void FileReaderWrapper::AdvanceToNextRowGroup() { + ResetRowGroupReader(); + SetCurrentRowGroup(NextReadableRowGroup(current_row_group_idx_ + 1)); + RetirePrefetchedRowGroupsBefore(current_row_group_idx_); +} + +void FileReaderWrapper::InitializeReadPosition() { + SetCurrentRowGroup(NextReadableRowGroup(pending_seek_row_group_idx_.value_or(0))); + next_prefetch_row_group_idx_ = current_row_group_idx_; + pending_seek_row_group_idx_.reset(); + previous_first_row_ = std::numeric_limits::max(); + reader_initialized_ = true; } Status FileReaderWrapper::SeekToRow(uint64_t row_number) { try { - current_page_filtered_reader_.reset(); - filtered_global_offset_ = 0; - - for (uint64_t i = 0; i < target_row_groups_.size(); i++) { - if (target_row_groups_[i].IsExcludedByReadRange()) { - continue; - } + uint64_t i = NextReadableRowGroup(0); + for (; i < target_row_groups_.size(); i = NextReadableRowGroup(i + 1)) { int32_t rg_id = target_row_groups_[i].GetRowGroupIndex(); - uint64_t rg_start = all_row_group_ranges_[rg_id].first; - uint64_t rg_end = all_row_group_ranges_[rg_id].second; + auto [rg_start, rg_end] = all_row_group_ranges_[rg_id]; if (row_number > rg_start && row_number < rg_end) { return Status::Invalid( fmt::format("seek to row failed. row number {} should not be in the middle of " @@ -231,44 +273,19 @@ Status FileReaderWrapper::SeekToRow(uint64_t row_number) { row_number)); } if (rg_start >= row_number) { - current_row_group_idx_ = i; - next_row_to_read_ = rg_start; - - if (!reader_initialized_) { - // PrepareForReading (first Next()) will build batch_reader_, so just - // record the seeked start for it. Building batch_reader_ here would be - // discarded by PrepareForReading, and the arrow GetRecordBatchReader - // eagerly reads every column chunk, so building twice doubles the - // requested bytes. - pending_start_idx_ = i; - batch_reader_.reset(); - return Status::OK(); - } - - // Rebuild batch_reader_ for non-page-filtered RGs at/after seek position. - std::vector fully_matched_indices; - for (uint64_t j = i; j < target_row_groups_.size(); j++) { - if (!target_row_groups_[j].IsExcludedByReadRange() && - !target_row_groups_[j].IsPartiallyMatched()) { - fully_matched_indices.push_back(target_row_groups_[j].GetRowGroupIndex()); - } - } - if (!fully_matched_indices.empty()) { - PAIMON_RETURN_NOT_OK_FROM_ARROW(file_reader_->GetRecordBatchReader( - fully_matched_indices, target_column_indices_, &batch_reader_)); - } else { - batch_reader_.reset(); - } - return Status::OK(); + break; } } - next_row_to_read_ = num_rows_; - current_row_group_idx_ = target_row_groups_.size(); + const bool reuse_window = i >= current_row_group_idx_ && i <= next_prefetch_row_group_idx_; + SetCurrentRowGroup(i); + if (reuse_window) { + ResetRowGroupReader(); + RetirePrefetchedRowGroupsBefore(i); + } else { + ResetPrefetchWindow(); + } if (!reader_initialized_) { - // Seek past the last row group before initialization: the deferred - // PrepareForReading must start at EOF as well. - pending_start_idx_ = target_row_groups_.size(); - batch_reader_.reset(); + pending_seek_row_group_idx_ = i; } return Status::OK(); } @@ -276,61 +293,30 @@ Status FileReaderWrapper::SeekToRow(uint64_t row_number) { } Result> FileReaderWrapper::NextPageFiltered() { - int32_t rg_id = target_row_groups_[current_row_group_idx_].GetRowGroupIndex(); - - // Construct the per-RG streaming reader on demand. - if (!current_page_filtered_reader_) { - const auto& target_rg = target_row_groups_[current_row_group_idx_]; - auto row_group_page_index_reader = GetRowGroupPageIndexReader(rg_id); - auto page_ranges = PageFilteredRowGroupReader::ComputePageRanges( - target_rg, target_column_indices_, row_group_page_index_reader, - file_reader_->parquet_reader()); - bool pre_buffered = !prebuffered_ranges_.empty(); - int64_t max_chunksize = batch_size_ > 0 ? batch_size_ : std::numeric_limits::max(); - PAIMON_ASSIGN_OR_RAISE( - current_page_filtered_reader_, - PageFilteredRowGroupReader::ReadFilteredRowGroup( - target_rg, target_column_indices_, file_reader_->properties().cache_options(), - pre_buffered, page_ranges, max_chunksize, row_group_page_index_reader, pool_, - file_reader_.get())); - current_filtered_row_ranges_ = target_rg.GetRowRanges(); - current_filtered_rg_start_ = all_row_group_ranges_[rg_id].first; - filtered_global_offset_ = 0; - } + const auto& target = target_row_groups_[current_row_group_idx_]; + const uint64_t rg_start = all_row_group_ranges_[target.GetRowGroupIndex()].first; + const auto& row_ranges = target.GetRowRanges(); std::shared_ptr record_batch; - PAIMON_RETURN_NOT_OK_FROM_ARROW(current_page_filtered_reader_->ReadNext(&record_batch)); - + PAIMON_RETURN_NOT_OK_FROM_ARROW(batch_reader_->ReadNext(&record_batch)); if (record_batch) { - auto original_row = - current_filtered_row_ranges_.MapFilteredIndexToOriginalRow(filtered_global_offset_); - previous_first_row_ = original_row.has_value() ? current_filtered_rg_start_ + - static_cast(*original_row) - : current_filtered_rg_start_; - filtered_global_offset_ += record_batch->num_rows(); - // Advance to the next row that survives filtering, or to the row group end when the - // filtered ranges are exhausted, so that next_row_to_read_ tracks the streaming position. - auto next_original_row = - current_filtered_row_ranges_.MapFilteredIndexToOriginalRow(filtered_global_offset_); - next_row_to_read_ = - next_original_row.has_value() - ? current_filtered_rg_start_ + static_cast(*next_original_row) - : all_row_group_ranges_[rg_id].second; + auto original_row = row_ranges.MapFilteredIndexToOriginalRow(filtered_row_offset_); + previous_first_row_ = rg_start + static_cast(original_row.value_or(0)); + filtered_row_offset_ += record_batch->num_rows(); + auto next_original_row = row_ranges.MapFilteredIndexToOriginalRow(filtered_row_offset_); + if (next_original_row.has_value()) { + next_row_to_read_ = rg_start + static_cast(*next_original_row); + } else { + AdvanceToNextRowGroup(); + } return record_batch; } - // RG exhausted — reset and advance. - current_page_filtered_reader_.reset(); - filtered_global_offset_ = 0; AdvanceToNextRowGroup(); return std::shared_ptr(); } Result> FileReaderWrapper::NextFullyMatched() { - if (!batch_reader_) { - return std::shared_ptr(); - } - PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr record_batch, batch_reader_->Next()); if (!record_batch) { @@ -386,10 +372,14 @@ std::shared_ptr<::parquet::RowGroupPageIndexReader> FileReaderWrapper::GetRowGro Result> FileReaderWrapper::Next() { try { if (PAIMON_UNLIKELY(!reader_initialized_)) { - PAIMON_RETURN_NOT_OK(PrepareForReading(target_row_groups_, target_column_indices_)); + InitializeReadPosition(); } while (current_row_group_idx_ < target_row_groups_.size()) { + if (!batch_reader_) { + PAIMON_RETURN_NOT_OK(FillPrefetchWindow()); + PAIMON_RETURN_NOT_OK(OpenCurrentRowGroup()); + } bool is_partially_matched = target_row_groups_[current_row_group_idx_].IsPartiallyMatched(); PAIMON_ASSIGN_OR_RAISE(std::shared_ptr batch, @@ -397,11 +387,8 @@ Result> FileReaderWrapper::Next() { if (batch) { return batch; } else if (!is_partially_matched) { - // Null from fully-matched path means batch_reader_ is globally exhausted. break; } - // current_row_group_idx_ has been advanced in NextPageFiltered() or NextFullyMatched(), - // loop to try next RG. } previous_first_row_ = next_row_to_read_; @@ -426,193 +413,194 @@ Result>> FileReaderWrapper::GetRowGrou Status FileReaderWrapper::PrepareForReadingLazy( const std::vector& target_row_groups, const std::vector& column_indices) { + ResetPrefetchWindow(); target_row_groups_ = target_row_groups; target_column_indices_ = column_indices; reader_initialized_ = false; - pending_start_idx_.reset(); + pending_seek_row_group_idx_.reset(); return Status::OK(); } -Result> FileReaderWrapper::CollectPreBufferRanges( - const std::vector& column_indices, uint64_t start_idx) { - return DoCollectPreBufferRanges(column_indices, /*skip_read_range_excluded=*/true, start_idx); -} - -Result> FileReaderWrapper::DoCollectPreBufferRanges( - const std::vector& column_indices, bool skip_read_range_excluded, uint64_t start_idx) { +Result> FileReaderWrapper::CollectRowGroupRanges( + const TargetRowGroup& target) { try { + auto* parquet_reader = file_reader_->parquet_reader(); + int32_t rg_index = target.GetRowGroupIndex(); std::vector<::arrow::io::ReadRange> ranges; - auto file_metadata = file_reader_->parquet_reader()->metadata(); - - for (uint64_t idx = start_idx; idx < target_row_groups_.size(); idx++) { - const auto& trg = target_row_groups_[idx]; - if (skip_read_range_excluded && trg.IsExcludedByReadRange()) { - continue; - } - - if (trg.IsPartiallyMatched()) { - // Page-filtered RGs: only matching page byte ranges. - auto row_group_page_index_reader = - GetRowGroupPageIndexReader(trg.GetRowGroupIndex()); - auto page_ranges = PageFilteredRowGroupReader::ComputePageRanges( - trg, column_indices, row_group_page_index_reader, - file_reader_->parquet_reader()); - ranges.insert(ranges.end(), std::make_move_iterator(page_ranges.begin()), - std::make_move_iterator(page_ranges.end())); - } else { - // Fully-matched RGs: entire column chunk ranges. - auto rg_metadata = file_metadata->RowGroup(trg.GetRowGroupIndex()); - for (int32_t col_idx : column_indices) { - auto col_chunk = rg_metadata->ColumnChunk(col_idx); - int64_t offset = col_chunk->data_page_offset(); - if (col_chunk->has_dictionary_page() && - col_chunk->dictionary_page_offset() > 0 && - offset > col_chunk->dictionary_page_offset()) { - offset = col_chunk->dictionary_page_offset(); - } - ranges.push_back({offset, col_chunk->total_compressed_size()}); + if (target.IsPartiallyMatched()) { + ranges = PageFilteredRowGroupReader::ComputePageRanges( + target, target_column_indices_, GetRowGroupPageIndexReader(rg_index), + parquet_reader); + } else { + auto rg_metadata = parquet_reader->metadata()->RowGroup(rg_index); + for (int32_t col_idx : target_column_indices_) { + auto col_chunk = rg_metadata->ColumnChunk(col_idx); + int64_t offset = col_chunk->data_page_offset(); + if (col_chunk->has_dictionary_page() && col_chunk->dictionary_page_offset() > 0) { + offset = std::min(offset, col_chunk->dictionary_page_offset()); } + ranges.push_back({offset, col_chunk->total_compressed_size()}); } } + for (const auto& range : ranges) { + PAIMON_RETURN_NOT_OK(ValidateReadRange(range)); + } return ranges; } - PAIMON_PARQUET_CATCH_AND_RETURN_STATUS("FileReaderWrapper::DoCollectPreBufferRanges") + PAIMON_PARQUET_CATCH_AND_RETURN_STATUS("FileReaderWrapper::CollectRowGroupRanges") } Result>> FileReaderWrapper::GetPreBufferRanges() { - PAIMON_ASSIGN_OR_RAISE(std::vector<::arrow::io::ReadRange> ranges, - DoCollectPreBufferRanges(target_column_indices_, - /*skip_read_range_excluded=*/false, - /*start_idx=*/0)); std::vector> pre_buffer_ranges; - pre_buffer_ranges.reserve(ranges.size()); - for (const auto& range : ranges) { - // Ranges come from signed parquet metadata; a corrupt footer may hold negative or - // overflowing values. Validate before converting to uint64_t, since downstream - // range coalescing does unchecked offset + length arithmetic on them. - PAIMON_RETURN_NOT_OK(ValidateValueNonNegative(range.offset, "pre-buffer range offset")); - PAIMON_RETURN_NOT_OK(ValidateValueNonNegative(range.length, "pre-buffer range length")); - if (range.offset > std::numeric_limits::max() - range.length) { - return Status::Invalid(fmt::format("pre-buffer range overflows: offset={}, length={}", - range.offset, range.length)); + for (const auto& target : target_row_groups_) { + PAIMON_ASSIGN_OR_RAISE(std::vector<::arrow::io::ReadRange> ranges, + CollectRowGroupRanges(target)); + for (const auto& range : ranges) { + pre_buffer_ranges.emplace_back(static_cast(range.offset), + static_cast(range.length)); } - pre_buffer_ranges.emplace_back(static_cast(range.offset), - static_cast(range.length)); } return pre_buffer_ranges; } -void FileReaderWrapper::DispatchPreBuffer(std::vector<::arrow::io::ReadRange> ranges) { - const auto& cache_opts = file_reader_->properties().cache_options(); - ::arrow::io::IOContext io_ctx(pool_.get()); - auto merged_ranges = MergeOverlappingRanges(std::move(ranges)); - try { - file_reader_->parquet_reader()->PreBufferRanges(merged_ranges, io_ctx, cache_opts); - prebuffered_ranges_ = std::move(merged_ranges); - } catch (const std::exception&) { - prebuffered_ranges_.clear(); +Result FileReaderWrapper::PlanRowGroupPrefetch( + const TargetRowGroup& target) { + PAIMON_ASSIGN_OR_RAISE(std::vector<::arrow::io::ReadRange> ranges, + CollectRowGroupRanges(target)); + ranges = MergeOverlappingRanges(std::move(ranges)); + int64_t bytes = 0; + for (const auto& range : ranges) { + if (range.length > std::numeric_limits::max() - bytes) { + return Status::Invalid("pre-buffer range total bytes overflows int64"); + } + bytes += range.length; + } + if (bytes == 0) { + return PrefetchPlan{{}, 0}; } -} -Status FileReaderWrapper::PrepareForReading(const std::vector& target_row_groups, - const std::vector& column_indices) { - try { - current_page_filtered_reader_.reset(); - filtered_global_offset_ = 0; - target_row_groups_ = target_row_groups; - target_column_indices_ = column_indices; - - // Find the first row group to read: skip read-range-excluded ones, and honor a - // seek issued while the reader was still uninitialized (SeekToRow defers reader - // construction to here). - uint64_t first_active_idx = 0; - while (first_active_idx < target_row_groups_.size() && - target_row_groups_[first_active_idx].IsExcludedByReadRange()) { - first_active_idx++; - } - if (pending_start_idx_.has_value()) { - first_active_idx = std::max(first_active_idx, pending_start_idx_.value()); - pending_start_idx_.reset(); + const auto& options = file_reader_->properties().cache_options(); + if (options.hole_size_limit == 0) { + return PrefetchPlan{std::move(ranges), bytes}; + } + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW( + std::vector<::arrow::io::ReadRange> coalesced, + ::arrow::io::internal::CoalesceReadRanges(ranges, options.hole_size_limit, + options.range_size_limit)); + int64_t coalesced_bytes = 0; + bool coalesced_overflow = false; + for (const auto& range : coalesced) { + if (range.length > std::numeric_limits::max() - coalesced_bytes) { + coalesced_overflow = true; + break; } + coalesced_bytes += range.length; + } + // Coalesce if within budget, or for oversized groups prefetched only as the current group. + if (!coalesced_overflow && (coalesced_bytes <= prefetch_budget_ || bytes > prefetch_budget_)) { + return PrefetchPlan{std::move(coalesced), coalesced_bytes}; + } + return PrefetchPlan{std::move(ranges), bytes}; +} + +Status FileReaderWrapper::FillPrefetchWindow() { + if (prefetch_budget_ == 0 || target_column_indices_.empty()) { + return Status::OK(); + } - // Partition into fully-matched and page-filtered row groups, skipping excluded ones. - std::vector fully_matched_row_groups; - uint64_t active_count = 0; - for (uint64_t i = first_active_idx; i < target_row_groups_.size(); i++) { - const auto& trg = target_row_groups_[i]; - if (trg.IsExcludedByReadRange()) { - continue; + auto* parquet_reader = file_reader_->parquet_reader(); + auto options = file_reader_->properties().cache_options(); + // Prevent the cache from adding gaps beyond the byte reservation. + options.hole_size_limit = 0; + ::arrow::io::IOContext io_context(pool_.get()); + + while (next_prefetch_row_group_idx_ < target_row_groups_.size()) { + const bool is_current = next_prefetch_row_group_idx_ == current_row_group_idx_; + if (!is_current) { + const bool current_is_prefetched = + !prefetched_row_groups_.empty() && + prefetched_row_groups_.front().target_index == current_row_group_idx_; + const int64_t prefetched_lookahead = + static_cast(prefetched_row_groups_.size()) - + (current_is_prefetched ? 1 : 0); + if (prefetched_lookahead >= max_prefetch_row_groups_ || + reserved_prefetch_bytes_ >= prefetch_budget_) { + break; } - active_count++; - if (!trg.IsPartiallyMatched()) { - fully_matched_row_groups.push_back(trg.GetRowGroupIndex()); + } + if (!pending_prefetch_plan_) { + auto plan = PlanRowGroupPrefetch(target_row_groups_[next_prefetch_row_group_idx_]); + if (!plan.ok() && !is_current) { + // An error in a future group must not interrupt the current group. + break; } + PAIMON_ASSIGN_OR_RAISE(pending_prefetch_plan_, std::move(plan)); } - - bool has_partially_matched = fully_matched_row_groups.size() != active_count; - - WaitForPendingPreBuffer(); - - // TODO(Yonghao Fang): Neither Paimon nor Arrow manage the size and lifecycle of prebuffered - // caches. So when a lot of row is needed, there is possibility of OOM due to too much - // prebuffering. Also, DispatchPreBuffer will drop previous prebuffered ranges by - // GetRecordBatchReader, which cause IO wastes. - - // Create standard reader for fully-matched row groups. - if (!fully_matched_row_groups.empty()) { - PAIMON_RETURN_NOT_OK_FROM_ARROW(file_reader_->GetRecordBatchReader( - fully_matched_row_groups, column_indices, &batch_reader_)); - } else { - batch_reader_.reset(); + const int64_t bytes = pending_prefetch_plan_->bytes; + if (!is_current && (bytes == 0 || bytes > prefetch_budget_ - reserved_prefetch_bytes_)) { + break; } - - // When page-filtered RGs exist, issue a single PreBuffer covering both kinds. - // Otherwise GetRecordBatchReader already issued PreBuffer internally. - if (has_partially_matched) { - PAIMON_ASSIGN_OR_RAISE(std::vector<::arrow::io::ReadRange> all_ranges, - CollectPreBufferRanges(column_indices, first_active_idx)); - DispatchPreBuffer(std::move(all_ranges)); + if (bytes > 0) { + auto cache = parquet_reader->MakePreBufferCache(io_context, options); + prefetched_row_groups_.push_back({next_prefetch_row_group_idx_, bytes, cache}); + reserved_prefetch_bytes_ += bytes; + // A range cache miss or I/O error can be served by the underlying file. + [[maybe_unused]] auto status = cache->Cache(std::move(pending_prefetch_plan_->ranges)); } + pending_prefetch_plan_.reset(); + next_prefetch_row_group_idx_ = NextReadableRowGroup(next_prefetch_row_group_idx_ + 1); + } + return Status::OK(); +} - // Reset read state to the first row group that will be read. - if (first_active_idx >= target_row_groups_.size()) { - next_row_to_read_ = num_rows_; - } else { - next_row_to_read_ = - all_row_group_ranges_[target_row_groups_[first_active_idx].GetRowGroupIndex()] - .first; - } - previous_first_row_ = std::numeric_limits::max(); - current_row_group_idx_ = first_active_idx; - reader_initialized_ = true; +Status FileReaderWrapper::OpenCurrentRowGroup() { + auto* parquet_reader = file_reader_->parquet_reader(); + const auto& target = target_row_groups_[current_row_group_idx_]; + const bool page_filtered = target.IsPartiallyMatched(); + if (!prefetched_row_groups_.empty() && + prefetched_row_groups_.front().target_index == current_row_group_idx_) { + parquet_reader->SetPreBufferCache(prefetched_row_groups_.front().cache); + } else if (page_filtered && !target_column_indices_.empty()) { + // Positional I/O lets the decoder skip unselected page bodies. + parquet_reader->SetPreBufferCache(parquet_reader->MakePreBufferCache( + ::arrow::io::IOContext(pool_.get()), file_reader_->properties().cache_options())); + } + + const int32_t row_group_index = target.GetRowGroupIndex(); + if (!page_filtered) { + PAIMON_RETURN_NOT_OK_FROM_ARROW(file_reader_->GetRecordBatchReader( + {row_group_index}, target_column_indices_, &batch_reader_)); return Status::OK(); } + const int64_t max_chunk_size = + batch_size_ > 0 ? batch_size_ : std::numeric_limits::max(); + PAIMON_ASSIGN_OR_RAISE( + batch_reader_, PageFilteredRowGroupReader::ReadFilteredRowGroup( + target, target_column_indices_, max_chunk_size, + GetRowGroupPageIndexReader(row_group_index), pool_, file_reader_.get())); + return Status::OK(); +} + +Status FileReaderWrapper::PrepareForReading(const std::vector& target_row_groups, + const std::vector& column_indices) { + try { + PAIMON_RETURN_NOT_OK(PrepareForReadingLazy(target_row_groups, column_indices)); + InitializeReadPosition(); + return FillPrefetchWindow(); + } PAIMON_PARQUET_CATCH_AND_RETURN_STATUS("FileReaderWrapper::PrepareForReading") } Status FileReaderWrapper::ApplyReadRanges( const std::vector>& read_ranges) { // A read-range change invalidates any seek recorded before initialization. - pending_start_idx_.reset(); - if (read_ranges.empty()) { - for (auto& trg : target_row_groups_) { - trg.SetExcludedByReadRange(true); - } - reader_initialized_ = false; - return Status::OK(); - } - // Build a set of row group indices whose range matches one of the read ranges. - std::set matching_rg_indices; - for (const auto& read_range : read_ranges) { - for (size_t i = 0; i < all_row_group_ranges_.size(); i++) { - if (all_row_group_ranges_[i] == read_range) { - matching_rg_indices.insert(static_cast(i)); - } - } - } - // Mark each target row group as excluded or not based on the matching set. - for (auto& trg : target_row_groups_) { - trg.SetExcludedByReadRange(matching_rg_indices.count(trg.GetRowGroupIndex()) == 0); + pending_seek_row_group_idx_.reset(); + ResetPrefetchWindow(); + const std::set> selected_ranges(read_ranges.begin(), + read_ranges.end()); + for (auto& target : target_row_groups_) { + const auto& row_group_range = all_row_group_ranges_[target.GetRowGroupIndex()]; + target.SetExcludedByReadRange(selected_ranges.count(row_group_range) == 0); } reader_initialized_ = false; return Status::OK(); diff --git a/src/paimon/format/parquet/file_reader_wrapper.h b/src/paimon/format/parquet/file_reader_wrapper.h index 971aac7c0..791127700 100644 --- a/src/paimon/format/parquet/file_reader_wrapper.h +++ b/src/paimon/format/parquet/file_reader_wrapper.h @@ -19,6 +19,7 @@ #pragma once #include +#include #include #include #include @@ -52,21 +53,18 @@ class Predicate; namespace paimon::parquet { -// The FileReaderWrapper is a decorator class designed to support seek functionality, as well as the -// methods GetPreviousBatchFirstRowNumber and GetNextRowToRead. +/// Reads Parquet batches in file row order and tracks their positions across the prefetch window. class FileReaderWrapper { public: ~FileReaderWrapper(); static Result> Create( std::unique_ptr<::parquet::arrow::FileReader>&& reader, int64_t batch_size, - bool enable_offset_index_cache, std::shared_ptr pool); + bool enable_offset_index_cache, int64_t prefetch_budget, int64_t prefetch_row_groups, + std::shared_ptr pool); - /// Seek to the specified row number. - /// @param row_number The row to seek to (must be at a row group boundary). - /// When the reader is not yet initialized (before the first Next()), the reader - /// construction is deferred to PrepareForReading to avoid building a batch reader - /// that would be immediately discarded. + /// Seek to the first readable row group at or after the given file row. + /// @param row_number File row. A row inside a readable group is invalid. Status SeekToRow(uint64_t row_number); /// Read the next batch of rows. @@ -120,14 +118,11 @@ class FileReaderWrapper { Status PrepareForReadingLazy(const std::vector& target_row_groups, const std::vector& column_indices); - /// Prepare for immediate reading of the specified row groups and columns. - /// Initializes the reader and starts pre-buffering I/O. + /// Start prefetching the first window. Decoding begins on the first Next(). Status PrepareForReading(const std::vector& target_row_groups, const std::vector& column_indices); - /// Apply read ranges to the current target_row_groups_, keeping only those - /// whose row-group range is equal to one of the given read ranges. - /// Resets reader state so that the next Next() call will re-initialize. + /// Select exact row-group ranges for the next scan. Status ApplyReadRanges(const std::vector>& read_ranges); /// Get the page index reader for the file. @@ -147,49 +142,44 @@ class FileReaderWrapper { std::shared_ptr<::parquet::RowGroupPageIndexReader> GetRowGroupPageIndexReader( int32_t row_group_index); - /// Compute the (offset, length) byte ranges required by the current target row groups - /// and columns. Unlike the arrow-internal PreBuffer path, this covers row groups that - /// are excluded by read-range dispatch as well, because the shared prefetch cache must - /// serve data consumed by all sub-readers. Relies only on file metadata, so it is safe - /// to call before the lazy reader initialization. + /// Compute the (offset, length) ranges for the shared cache, including row groups + /// dispatched to other sub-readers. This can run before the first Next(). Result>> GetPreBufferRanges(); private: FileReaderWrapper(std::unique_ptr<::parquet::arrow::FileReader>&& file_reader, const std::vector>& all_row_group_ranges, - uint64_t num_rows, int64_t batch_size, - std::shared_ptr<::arrow::MemoryPool> pool); + uint64_t num_rows, int64_t batch_size, int64_t prefetch_budget, + int64_t prefetch_row_groups, std::shared_ptr<::arrow::MemoryPool> pool); + + struct PrefetchPlan { + std::vector<::arrow::io::ReadRange> ranges; + int64_t bytes; + }; + + struct PrefetchedRowGroup { + uint64_t target_index; + int64_t bytes; + std::shared_ptr<::arrow::io::internal::ReadRangeCache> cache; + }; + + Status FillPrefetchWindow(); + Result PlanRowGroupPrefetch(const TargetRowGroup& target); + void RetirePrefetchedRowGroupsBefore(uint64_t index); + void ResetPrefetchWindow(); + void ResetRowGroupReader(); + void InitializeReadPosition(); + Status OpenCurrentRowGroup(); + void SetCurrentRowGroup(uint64_t index); + uint64_t NextReadableRowGroup(uint64_t index) const; - /// Wait for all pending PreBuffer operations to complete. - void WaitForPendingPreBuffer(); - - /// Advance current_row_group_idx_ to the next row group and update next_row_to_read_. void AdvanceToNextRowGroup(); - /// Read next batch from a page-filtered row group. Returns nullptr when the RG is exhausted. Result> NextPageFiltered(); - /// Read next batch from the fully-matched batch_reader_. Returns nullptr when exhausted. Result> NextFullyMatched(); - /// Collect all byte ranges that need pre-buffering (page-filtered + fully-matched), - /// skipping row groups excluded by ApplyReadRanges and row groups before start_idx - /// (already skipped by a deferred seek). - Result> CollectPreBufferRanges( - const std::vector& column_indices, uint64_t start_idx); - - /// Core byte-range collection shared by CollectPreBufferRanges and GetPreBufferRanges. - /// When skip_read_range_excluded is true, row groups excluded by ApplyReadRanges are - /// skipped (arrow-internal PreBuffer for this reader); when false, they are included - /// (shared prefetch cache covering all sub-readers). Ranges before start_idx are - /// never collected. Metadata and page index lookups throw on malformed files or IO - /// failures, so the exceptions are converted to a Status here. - Result> DoCollectPreBufferRanges( - const std::vector& column_indices, bool skip_read_range_excluded, - uint64_t start_idx); - - /// Dispatch a single PreBufferRanges call with merged ranges. - void DispatchPreBuffer(std::vector<::arrow::io::ReadRange> ranges); + Result> CollectRowGroupRanges(const TargetRowGroup& target); std::unique_ptr<::parquet::arrow::FileReader> file_reader_; std::unique_ptr batch_reader_; @@ -199,30 +189,23 @@ class FileReaderWrapper { std::shared_ptr<::arrow::MemoryPool> pool_; int64_t batch_size_; // 0 means no limit + const int64_t prefetch_budget_; + const int64_t max_prefetch_row_groups_; const uint64_t num_rows_; uint64_t next_row_to_read_ = std::numeric_limits::max(); uint64_t previous_first_row_ = std::numeric_limits::max(); uint64_t current_row_group_idx_ = 0; bool reader_initialized_ = false; - // Target index recorded by SeekToRow when the reader was still uninitialized; - // consumed by PrepareForReading so the deferred initialization starts at the seeked - // position instead of rebuilding readers twice. - std::optional pending_start_idx_; - - // Streaming reader for the currently-active page-filtered row group. Created lazily - // on the first Next() call into a page-filtered RG, drained batch-by-batch, then reset - // when ReadNext returns nullptr (end of that RG). - std::unique_ptr current_page_filtered_reader_; - int64_t filtered_global_offset_ = 0; // Cumulative filtered-row offset within RG - RowRanges current_filtered_row_ranges_; // RowRanges for the active page-filtered RG - uint64_t current_filtered_rg_start_ = 0; // Absolute row-group start row number - - // Target row groups with row ranges for none page-level filtering and page-level filtering + std::optional pending_seek_row_group_idx_; + + int64_t filtered_row_offset_ = 0; std::vector target_row_groups_; - // Track pre-buffered ranges so we can wait on destruction - std::vector<::arrow::io::ReadRange> prebuffered_ranges_; + std::deque prefetched_row_groups_; + int64_t reserved_prefetch_bytes_ = 0; + uint64_t next_prefetch_row_group_idx_ = 0; + std::optional pending_prefetch_plan_; bool enable_offset_index_cache_ = false; diff --git a/src/paimon/format/parquet/file_reader_wrapper_test.cpp b/src/paimon/format/parquet/file_reader_wrapper_test.cpp index 9ef953fa7..52f686180 100644 --- a/src/paimon/format/parquet/file_reader_wrapper_test.cpp +++ b/src/paimon/format/parquet/file_reader_wrapper_test.cpp @@ -18,8 +18,10 @@ #include "paimon/format/parquet/file_reader_wrapper.h" +#include #include #include +#include #include #include #include @@ -34,6 +36,7 @@ #include "arrow/c/abi.h" #include "arrow/c/bridge.h" #include "arrow/io/caching.h" +#include "arrow/io/file.h" #include "arrow/memory_pool.h" #include "fmt/format.h" #include "gtest/gtest.h" @@ -51,8 +54,10 @@ #include "paimon/predicate/literal.h" #include "paimon/predicate/predicate_builder.h" #include "paimon/record_batch.h" +#include "paimon/testing/utils/gated_async_input_stream.h" #include "paimon/testing/utils/testharness.h" #include "parquet/arrow/reader.h" +#include "parquet/arrow/writer.h" #include "parquet/file_reader.h" #include "parquet/metadata.h" #include "parquet/page_index.h" @@ -84,17 +89,16 @@ class ReadTrackingInputStream : public InputStream { } Result Read(char* buffer, int64_t size, int64_t offset) override { - RecordPositionalRead(offset, size); + RecordPositionalRead(size); return input_->Read(buffer, size, offset); } void ReadAsync(char* buffer, int64_t size, int64_t offset, std::function&& callback) override { - RecordPositionalRead(offset, size); + RecordPositionalRead(size); { std::lock_guard lock(mutex_); if (++async_read_calls_ == 1 && fail_first_async_read_) { - // Exercise the synchronous exception path in Parquet prebuffering. throw std::runtime_error("injected prebuffer read failure"); } } @@ -124,8 +128,7 @@ class ReadTrackingInputStream : public InputStream { } private: - void RecordPositionalRead(int64_t offset, int64_t size) { - (void)offset; + void RecordPositionalRead(int64_t size) { std::lock_guard lock(mutex_); positional_read_bytes_ += size; } @@ -213,10 +216,14 @@ class FileReaderWrapperTest : public ::testing::Test { Result> PrepareReaderWrapperOnStream( std::shared_ptr in, int64_t wrapper_batch_size = 0, - bool enable_offset_index_cache = false) { + bool enable_offset_index_cache = false, + int64_t prefetch_budget = DEFAULT_PARQUET_READ_CACHE_OPTION_WINDOW_SIZE_LIMIT, + std::shared_ptr input_pool = nullptr, + arrow::io::CacheOptions cache_options = arrow::io::CacheOptions::Defaults(), + int64_t prefetch_row_groups = DEFAULT_PARQUET_READ_CACHE_OPTION_PREFETCH_ROW_GROUPS) { PAIMON_ASSIGN_OR_RAISE(int64_t file_length, in->Length()); - auto input_stream = - std::make_unique(std::move(in), file_length, arrow_pool_); + auto input_stream = std::make_unique( + std::move(in), file_length, input_pool ? std::move(input_pool) : arrow_pool_); ::parquet::arrow::FileReaderBuilder file_reader_builder; ::parquet::ReaderProperties reader_properties; reader_properties.enable_buffered_stream(); @@ -224,16 +231,17 @@ class FileReaderWrapperTest : public ::testing::Test { file_reader_builder.Open(std::move(input_stream), reader_properties)); ::parquet::ArrowReaderProperties arrow_reader_props; - arrow_reader_props.set_pre_buffer(true); + arrow_reader_props.set_pre_buffer(false); arrow_reader_props.set_batch_size(static_cast(batch_size_)); arrow_reader_props.set_use_threads(true); - arrow_reader_props.set_cache_options(arrow::io::CacheOptions::Defaults()); + arrow_reader_props.set_cache_options(cache_options); std::unique_ptr<::parquet::arrow::FileReader> file_reader; PAIMON_RETURN_NOT_OK_FROM_ARROW(file_reader_builder.memory_pool(arrow_pool_.get()) ->properties(arrow_reader_props) ->Build(&file_reader)); return FileReaderWrapper::Create(std::move(file_reader), wrapper_batch_size, - enable_offset_index_cache, arrow_pool_); + enable_offset_index_cache, prefetch_budget, + prefetch_row_groups, arrow_pool_); } void PrepareParquetFile(const std::string& file_path, int32_t row_count, @@ -296,6 +304,8 @@ TEST_F(FileReaderWrapperTest, NullFileReader) { ASSERT_NOK_WITH_MSG(FileReaderWrapper::Create(nullptr, /*batch_size=*/0, /*enable_offset_index_cache=*/false, + /*prefetch_budget=*/0, + /*prefetch_row_groups=*/0, /*pool=*/arrow_pool_), "file reader wrapper create failed. file reader is nullptr"); } @@ -337,28 +347,436 @@ TEST_F(FileReaderWrapperTest, PredicateReadsOnlyItsPageIndexesAndKeepsPayloadRea ASSERT_FALSE(end); } -TEST_F(FileReaderWrapperTest, PreBufferExceptionFallsBackToReadableData) { - std::string file_path = PathUtil::JoinPath(dir_->Str(), "prebuffer-failure.parquet"); +TEST_F(FileReaderWrapperTest, FailedPrefetchFallsBackToOnDemandReads) { + const std::string file_path = PathUtil::JoinPath(dir_->Str(), "prebuffer-failure.parquet"); PrepareParquetFile(file_path, /*row_count=*/200, /*enable_page_index=*/true); - ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs_->Open(file_path)); - auto failing_input = - std::make_shared(input, /*fail_first_async_read=*/true); - ASSERT_OK_AND_ASSIGN(auto reader, PrepareReaderWrapperOnStream(failing_input)); - ASSERT_EQ(0, failing_input->GetAsyncReadCalls()); - RowRanges ranges(RowRanges::Range(20, 29)); - ASSERT_OK(reader->PrepareForReading( - {TargetRowGroup(/*rg_index=*/0, /*is_partially_matched=*/true, ranges)}, {0, 1, 2})); - ASSERT_EQ(1, failing_input->GetAsyncReadCalls()); + for (bool page_filtered : {false, true}) { + SCOPED_TRACE(page_filtered); + for (bool fail_on_submit : {false, true}) { + SCOPED_TRACE(fail_on_submit); + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs_->Open(file_path)); + auto gated = std::make_shared(input); + auto tracking = std::make_shared(gated, fail_on_submit); + ASSERT_OK_AND_ASSIGN(auto reader, PrepareReaderWrapperOnStream(tracking)); + const int32_t first_row = page_filtered ? 20 : 0; + const int32_t row_count = page_filtered ? 10 : 200; + const RowRanges ranges = + page_filtered ? RowRanges(RowRanges::Range(20, 29)) : RowRanges(); + ASSERT_EQ(0, tracking->GetAsyncReadCalls()); + Status prepare = + reader->PrepareForReading({TargetRowGroup(0, page_filtered, ranges)}, {0, 1, 2}); + if (fail_on_submit) { + gated->ReleaseAll(); + } else { + gated->FailAll(Status::IOError("injected asynchronous prefetch read failure")); + } + ASSERT_OK(prepare); + ASSERT_GT(tracking->GetAsyncReadCalls(), 0); + ASSERT_EQ(tracking->GetAsyncReadCalls() - (fail_on_submit ? 1 : 0), + gated->AsyncReadCount()); + + ASSERT_OK_AND_ASSIGN(auto batch, reader->Next()); + ASSERT_TRUE(batch); + ASSERT_OK_AND_ASSIGN(uint64_t first_row_read, reader->GetPreviousBatchFirstRowNumber()); + ASSERT_EQ(first_row, first_row_read); + auto expected = PrepareArray(PrepareArrowSchema().second, row_count, first_row); + auto expected_batch = arrow::RecordBatch::FromStructArray(expected); + ASSERT_TRUE(expected_batch.ok()); + ASSERT_TRUE(batch->Equals(*expected_batch.ValueOrDie())); + ASSERT_OK_AND_ASSIGN(auto end, reader->Next()); + ASSERT_FALSE(end); + } + } +} - ASSERT_OK_AND_ASSIGN(auto batch, reader->Next()); - ASSERT_TRUE(batch); - auto expected = PrepareArray(PrepareArrowSchema().second, /*record_batch_size=*/10, - /*offset=*/20); - auto expected_batch = arrow::RecordBatch::FromStructArray(expected); - ASSERT_TRUE(expected_batch.ok()); - ASSERT_TRUE(batch->Equals(*expected_batch.ValueOrDie())); +TEST_F(FileReaderWrapperTest, BoundsProjectedInputAsRowGroupCountGrows) { + constexpr int32_t kRowsPerGroup = 32; + constexpr int64_t kBudget = 900 * 1024; + constexpr int32_t kPayloadSize = 12 * 1024; + const std::string padding(kPayloadSize, 'x'); + batch_size_ = 4; + for (int32_t groups : {6, 30}) { + SCOPED_TRACE(groups); + const int32_t rows = groups * kRowsPerGroup; + arrow::StringBuilder strings; + arrow::Int32Builder ids; + for (int32_t row = 0; row < rows; ++row) { + ASSERT_TRUE(strings.Append(fmt::format("{}{:04}", padding, row)).ok()); + ASSERT_TRUE(ids.Append(row).ok()); + } + auto schema = arrow::schema( + {arrow::field("payload", arrow::utf8()), arrow::field("id", arrow::int32())}); + auto data = + arrow::Table::Make(schema, {strings.Finish().ValueOrDie(), ids.Finish().ValueOrDie()}); + auto path = PathUtil::JoinPath(dir_->Str(), fmt::format("wide-{}.parquet", groups)); + auto out = arrow::io::FileOutputStream::Open(path).ValueOrDie(); + auto properties = ::parquet::WriterProperties::Builder() + .disable_dictionary() + ->disable_statistics() + ->build(); + ASSERT_TRUE( + ::parquet::arrow::WriteTable(*data, arrow_pool_.get(), out, kRowsPerGroup, properties) + .ok()); + ASSERT_TRUE(out->Close().ok()); + + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs_->Open(path)); + auto tracking = std::make_shared(input); + auto input_pool = std::make_shared(arrow::default_memory_pool()); + ASSERT_OK_AND_ASSIGN(auto reader, PrepareReaderWrapperOnStream(tracking, batch_size_, false, + kBudget, input_pool)); + std::vector targets; + for (int32_t group = 0; group < groups; ++group) { + targets.emplace_back(group, false, RowRanges()); + } + ASSERT_EQ(groups, reader->GetNumberOfRowGroups()); + ASSERT_OK(reader->PrepareForReadingLazy(targets, {0})); + ASSERT_OK_AND_ASSIGN(auto ranges, reader->GetPreBufferRanges()); + int64_t projected_bytes = 0; + for (const auto& range : ranges) { + projected_bytes += range.second; + } + ASSERT_GT(projected_bytes, 2 * kBudget); + + int64_t input_bytes_at_open = input_pool->bytes_allocated(); + int64_t bytes_before_scan = tracking->GetPositionalReadBytes(); + using Clock = std::chrono::steady_clock; + Clock::duration scan_time{}; + auto read_batch = [&]() { + auto start = Clock::now(); + auto result = reader->Next(); + scan_time += Clock::now() - start; + return result; + }; + ASSERT_OK_AND_ASSIGN(auto first, read_batch()); + ASSERT_NE(nullptr, first); + auto first_batch_time = scan_time; + ASSERT_EQ(2, tracking->GetAsyncReadCalls()); + std::shared_ptr batch = first; + int64_t rows_read = 0; + while (batch) { + ASSERT_EQ(1, batch->num_columns()); + ASSERT_OK_AND_ASSIGN(uint64_t first_row, reader->GetPreviousBatchFirstRowNumber()); + ASSERT_EQ(rows_read, first_row); + ASSERT_TRUE(batch->column(0)->Equals( + data->column(0)->chunk(0)->Slice(rows_read, batch->num_rows()))); + rows_read += batch->num_rows(); + ASSERT_OK_AND_ASSIGN(batch, read_batch()); + } + ASSERT_EQ(rows, rows_read); + ASSERT_EQ(groups, tracking->GetAsyncReadCalls()); + const int64_t physical_bytes = tracking->GetPositionalReadBytes() - bytes_before_scan; + ASSERT_EQ(projected_bytes, physical_bytes); + ASSERT_EQ(input_bytes_at_open, input_pool->bytes_allocated()); + ASSERT_LE(input_pool->max_memory(), kBudget); + ASSERT_OK(reader->Close()); + reader.reset(); + ASSERT_EQ(0, input_pool->bytes_allocated()); + ASSERT_TRUE(first->column(0)->Equals(data->column(0)->chunk(0)->Slice(0, batch_size_))); + + RecordProperty( + fmt::format("first_batch_us_{}_groups", groups), + std::to_string( + std::chrono::duration_cast(first_batch_time).count())); + RecordProperty(fmt::format("scan_mib_per_second_{}_groups", groups), + fmt::format("{:.2f}", physical_bytes / (1024.0 * 1024.0) / + std::chrono::duration(scan_time).count())); + RecordProperty(fmt::format("physical_bytes_{}_groups", groups), + std::to_string(physical_bytes)); + RecordProperty(fmt::format("peak_input_bytes_{}_groups", groups), + std::to_string(input_pool->max_memory())); + } +} + +TEST_F(FileReaderWrapperTest, SeeksAndClosesAcrossPrefetchWindows) { + std::string file_path = PathUtil::JoinPath(dir_->Str(), "seek-prefetch.parquet"); + PrepareParquetFile(file_path, 9000, true); + const std::vector targets{ + TargetRowGroup(0, false, RowRanges()), TargetRowGroup(3, false, RowRanges()), + TargetRowGroup(5, true, RowRanges(RowRanges::Range(20, 29))), + TargetRowGroup(7, false, RowRanges()), TargetRowGroup(8, false, RowRanges())}; + constexpr int64_t kBudget = 24 * 1024; + for (bool lazy : {false, true}) { + SCOPED_TRACE(lazy); + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs_->Open(file_path)); + auto tracking = std::make_shared(input); + auto cache_options = arrow::io::CacheOptions::Defaults(); + cache_options.lazy = lazy; + ASSERT_OK_AND_ASSIGN(auto reader, + PrepareReaderWrapperOnStream(tracking, /*wrapper_batch_size=*/4, false, + kBudget, nullptr, cache_options)); + ASSERT_OK(reader->PrepareForReadingLazy(targets, {0})); + ASSERT_OK(reader->ApplyReadRanges({{0, 1000}, {5000, 6000}, {7000, 8000}, {8000, 9000}})); + ASSERT_OK_AND_ASSIGN(auto first, reader->Next()); + ASSERT_NE(nullptr, first); + ASSERT_EQ(0, reader->GetPreviousBatchFirstRowNumber().value()); + const int64_t initial_reads = lazy ? 1 : 2; + ASSERT_EQ(initial_reads, tracking->GetAsyncReadCalls()); + + ASSERT_OK(reader->SeekToRow(0)); + ASSERT_OK_AND_ASSIGN(auto active, reader->Next()); + ASSERT_NE(nullptr, active); + ASSERT_TRUE(active->Equals(*first)); + ASSERT_EQ(initial_reads, tracking->GetAsyncReadCalls()); + + ASSERT_OK(reader->SeekToRow(3000)); + ASSERT_EQ(5000, reader->GetNextRowToRead()); + ASSERT_OK_AND_ASSIGN(auto filtered, reader->Next()); + ASSERT_NE(nullptr, filtered); + ASSERT_EQ(5020, reader->GetPreviousBatchFirstRowNumber().value()); + ASSERT_EQ(4, filtered->num_rows()); + ASSERT_EQ(initial_reads + 1, tracking->GetAsyncReadCalls()); + + ASSERT_OK(reader->SeekToRow(8000)); + ASSERT_OK_AND_ASSIGN(auto last, reader->Next()); + ASSERT_NE(nullptr, last); + ASSERT_EQ(8000, reader->GetPreviousBatchFirstRowNumber().value()); + ASSERT_EQ(initial_reads + 2, tracking->GetAsyncReadCalls()); + + ASSERT_OK(reader->SeekToRow(5000)); + ASSERT_OK_AND_ASSIGN(auto filtered_again, reader->Next()); + ASSERT_NE(nullptr, filtered_again); + ASSERT_TRUE(filtered_again->Equals(*filtered)); + ASSERT_EQ(5020, reader->GetPreviousBatchFirstRowNumber().value()); + ASSERT_EQ(lazy ? 4 : 6, tracking->GetAsyncReadCalls()); + + ASSERT_OK(reader->SeekToRow(0)); + ASSERT_OK_AND_ASSIGN(auto restarted, reader->Next()); + ASSERT_NE(nullptr, restarted); + ASSERT_TRUE(restarted->Equals(*first)); + ASSERT_EQ(0, reader->GetPreviousBatchFirstRowNumber().value()); + const int64_t calls = tracking->GetAsyncReadCalls(); + ASSERT_OK(reader->Close()); + ASSERT_EQ(calls, tracking->GetAsyncReadCalls()); + ASSERT_OK_AND_ASSIGN(auto end, reader->Next()); + ASSERT_FALSE(end); + ASSERT_EQ("str_5020", + checked_cast(*filtered->column(0)).GetString(0)); + } +} + +TEST_F(FileReaderWrapperTest, PrefetchesOversizedCurrentRowGroupWithoutLookahead) { + std::string file_path = PathUtil::JoinPath(dir_->Str(), "oversized-prefetch.parquet"); + PrepareParquetFile(file_path, 4000, true); + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs_->Open(file_path)); + auto tracking = std::make_shared(input); + constexpr int64_t kBudget = 1024; + ASSERT_OK_AND_ASSIGN(auto reader, + PrepareReaderWrapperOnStream(tracking, batch_size_, false, kBudget)); + ASSERT_OK(reader->PrepareForReadingLazy( + {TargetRowGroup(0, false, RowRanges()), + TargetRowGroup(1, true, RowRanges(RowRanges::Range(20, 299))), + TargetRowGroup(2, true, RowRanges(RowRanges::Range(0, 9))), + TargetRowGroup(3, true, RowRanges(RowRanges::Range(0, 9)))}, + {0})); + const std::vector> expected_batches{ + {0, 512}, {512, 488}, {1020, 280}, {2000, 10}, {3000, 10}}; + int64_t async_calls_after_rg0 = 0; + int64_t async_calls_after_rg1 = 0; + int64_t async_calls_after_rg2 = 0; + for (size_t i = 0; i < expected_batches.size(); ++i) { + const auto& [first_row, rows] = expected_batches[i]; + SCOPED_TRACE(first_row); + ASSERT_OK_AND_ASSIGN(auto batch, reader->Next()); + ASSERT_NE(nullptr, batch); + ASSERT_EQ(rows, batch->num_rows()); + ASSERT_EQ(first_row, reader->GetPreviousBatchFirstRowNumber().value()); + if (i == 0) { + async_calls_after_rg0 = tracking->GetAsyncReadCalls(); + ASSERT_EQ(1, async_calls_after_rg0); + } else if (i == 1) { + ASSERT_EQ(async_calls_after_rg0, tracking->GetAsyncReadCalls()); + } else if (i == 2) { + async_calls_after_rg1 = tracking->GetAsyncReadCalls(); + ASSERT_GT(async_calls_after_rg1, async_calls_after_rg0); + } else if (i == 3) { + async_calls_after_rg2 = tracking->GetAsyncReadCalls(); + ASSERT_EQ(async_calls_after_rg1 + 2, async_calls_after_rg2); + } else if (i == 4) { + ASSERT_EQ(async_calls_after_rg2, tracking->GetAsyncReadCalls()); + } + const auto& strings = checked_cast(*batch->column(0)); + for (int64_t row = 0; row < rows; ++row) { + ASSERT_EQ(fmt::format("str_{}", first_row + row), strings.GetString(row)); + } + } ASSERT_OK_AND_ASSIGN(auto end, reader->Next()); ASSERT_FALSE(end); + + ASSERT_OK_AND_ASSIGN(std::shared_ptr seek_input, fs_->Open(file_path)); + auto seek_tracking = std::make_shared(seek_input); + ASSERT_OK_AND_ASSIGN(auto seek_reader, + PrepareReaderWrapperOnStream(seek_tracking, batch_size_, false, kBudget)); + ASSERT_OK( + seek_reader->PrepareForReading({TargetRowGroup(0, true, RowRanges(RowRanges::Range(0, 9))), + TargetRowGroup(1, false, RowRanges())}, + {0})); + ASSERT_EQ(1, seek_tracking->GetAsyncReadCalls()); + ASSERT_OK(seek_reader->SeekToRow(1000)); + ASSERT_OK_AND_ASSIGN(auto oversized_batch, seek_reader->Next()); + ASSERT_NE(nullptr, oversized_batch); + ASSERT_EQ(512, oversized_batch->num_rows()); + ASSERT_EQ(1000, seek_reader->GetPreviousBatchFirstRowNumber().value()); + ASSERT_EQ(2, seek_tracking->GetAsyncReadCalls()); +} + +TEST_F(FileReaderWrapperTest, PrefetchRowGroupsControlsLookahead) { + std::string file_path = PathUtil::JoinPath(dir_->Str(), "lookahead-prefetch.parquet"); + PrepareParquetFile(file_path, 6000); + const std::vector targets{ + TargetRowGroup(0, false, RowRanges()), TargetRowGroup(1, false, RowRanges()), + TargetRowGroup(2, false, RowRanges()), TargetRowGroup(3, false, RowRanges()), + TargetRowGroup(4, false, RowRanges()), TargetRowGroup(5, false, RowRanges())}; + + { + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs_->Open(file_path)); + ASSERT_NOK_WITH_MSG( + PrepareReaderWrapperOnStream(input, batch_size_, false, + DEFAULT_PARQUET_READ_CACHE_OPTION_WINDOW_SIZE_LIMIT, + nullptr, arrow::io::CacheOptions::Defaults(), + /*prefetch_row_groups=*/-1), + "FileReaderWrapper requires explicit, bounded pre-buffering"); + } + + { + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs_->Open(file_path)); + auto tracking = std::make_shared(input); + ASSERT_OK_AND_ASSIGN(auto reader, PrepareReaderWrapperOnStream( + tracking, batch_size_, false, /*prefetch_budget=*/0, + nullptr, arrow::io::CacheOptions::Defaults(), + /*prefetch_row_groups=*/2)); + ASSERT_OK(reader->PrepareForReading(targets, {0})); + ASSERT_EQ(0, tracking->GetAsyncReadCalls()); + int64_t total_rows = 0; + while (true) { + ASSERT_OK_AND_ASSIGN(auto batch, reader->Next()); + if (!batch) { + break; + } + total_rows += batch->num_rows(); + } + ASSERT_EQ(6000, total_rows); + ASSERT_EQ(0, tracking->GetAsyncReadCalls()); + } + + for (int64_t lookahead : {int64_t{0}, int64_t{1}, int64_t{3}}) { + SCOPED_TRACE(lookahead); + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs_->Open(file_path)); + auto tracking = std::make_shared(input); + ASSERT_OK_AND_ASSIGN( + auto reader, + PrepareReaderWrapperOnStream(tracking, batch_size_, false, + DEFAULT_PARQUET_READ_CACHE_OPTION_WINDOW_SIZE_LIMIT, + nullptr, arrow::io::CacheOptions::Defaults(), lookahead)); + ASSERT_OK(reader->PrepareForReading(targets, {0})); + ASSERT_EQ(1 + lookahead, tracking->GetAsyncReadCalls()); + + int64_t total_rows = 0; + while (true) { + ASSERT_OK_AND_ASSIGN(auto batch, reader->Next()); + if (!batch) { + break; + } + ASSERT_EQ(static_cast(total_rows), + reader->GetPreviousBatchFirstRowNumber().value()); + total_rows += batch->num_rows(); + } + ASSERT_EQ(6000, total_rows); + ASSERT_EQ(6, tracking->GetAsyncReadCalls()); + } + + { + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs_->Open(file_path)); + auto tracking = std::make_shared(input); + ASSERT_OK_AND_ASSIGN(auto probe, PrepareReaderWrapper(file_path)); + ASSERT_OK(probe->PrepareForReadingLazy(targets, {0})); + ASSERT_OK_AND_ASSIGN(auto ranges, probe->GetPreBufferRanges()); + ASSERT_EQ(6, ranges.size()); + const auto two_group_budget = static_cast(ranges[0].second + ranges[1].second); + ASSERT_OK_AND_ASSIGN(auto reader, PrepareReaderWrapperOnStream( + tracking, batch_size_, false, two_group_budget, + nullptr, arrow::io::CacheOptions::Defaults(), + /*prefetch_row_groups=*/5)); + ASSERT_OK(reader->PrepareForReading(targets, {0})); + ASSERT_EQ(2, tracking->GetAsyncReadCalls()); + } +} + +TEST_F(FileReaderWrapperTest, IncludesInFlightReadsAndCoalescedGapsInPrefetchBudget) { + constexpr int64_t kArrowBufferAlignment = 64; + std::string path = PathUtil::JoinPath(dir_->Str(), "prefetch-gap.parquet"); + PrepareParquetFile(path, 2000); + const std::vector targets{TargetRowGroup(0, false, RowRanges()), + TargetRowGroup(1, false, RowRanges())}; + const std::vector columns{0, 2}; + ASSERT_OK_AND_ASSIGN(auto metadata_reader, PrepareReaderWrapper(path)); + ASSERT_OK(metadata_reader->PrepareForReadingLazy(targets, columns)); + ASSERT_OK_AND_ASSIGN(auto ranges, metadata_reader->GetPreBufferRanges()); + ASSERT_EQ(4, ranges.size()); + const int64_t projected_bytes = ranges[0].second + ranges[1].second; + const uint64_t first_chunk_end = ranges[0].first + ranges[0].second; + ASSERT_GT(ranges[1].first, first_chunk_end); + const int64_t gap = ranges[1].first - first_chunk_end; + auto cache_options = arrow::io::CacheOptions::Defaults(); + ASSERT_LE(gap, cache_options.hole_size_limit); + + for (int64_t budget : {int64_t{1}, projected_bytes, projected_bytes + gap}) { + SCOPED_TRACE(budget); + const int64_t expected_bytes = + budget == projected_bytes ? projected_bytes : projected_bytes + gap; + const int32_t expected_reads = budget == projected_bytes ? 2 : 1; + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs_->Open(path)); + auto tracking = std::make_shared(input); + auto gated = std::make_shared(tracking); + auto input_pool = std::make_shared(arrow::default_memory_pool()); + ASSERT_OK_AND_ASSIGN(auto reader, PrepareReaderWrapperOnStream(gated, batch_size_, false, + budget, input_pool)); + const int64_t before_prefetch = tracking->GetPositionalReadBytes(); + const int64_t memory_before_prefetch = input_pool->bytes_allocated(); + Status prepare = reader->PrepareForReading(targets, columns); + const int32_t submitted_reads = gated->AsyncReadCount(); + const int64_t before_completion = tracking->GetPositionalReadBytes(); + const int64_t in_flight_bytes = input_pool->bytes_allocated() - memory_before_prefetch; + gated->ReleaseAllKeepingCallbacks(); + ASSERT_OK(prepare); + ASSERT_EQ(before_prefetch, before_completion); + ASSERT_EQ(expected_reads, submitted_reads); + ASSERT_GE(in_flight_bytes, expected_bytes); + ASSERT_LT(in_flight_bytes, expected_bytes + submitted_reads * kArrowBufferAlignment); + ASSERT_EQ(expected_bytes, tracking->GetPositionalReadBytes() - before_prefetch); + ASSERT_OK(reader->Close()); + reader.reset(); + EXPECT_EQ(0, input_pool->bytes_allocated()); + gated->DropCompletedCallbacks(); + } +} + +TEST_F(FileReaderWrapperTest, CloseWaitsForInFlightReadsAfterPrefetchError) { + std::string path = PathUtil::JoinPath(dir_->Str(), "close-pending.parquet"); + PrepareParquetFile(path, 1000); + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs_->Open(path)); + auto gated = std::make_shared(input); + auto tracking = + std::make_shared(gated, /*fail_first_async_read=*/true); + auto cache_options = arrow::io::CacheOptions::Defaults(); + cache_options.hole_size_limit = 0; + cache_options.range_size_limit = 1; + ASSERT_OK_AND_ASSIGN( + auto reader, PrepareReaderWrapperOnStream(tracking, batch_size_, false, 64 * 1024, nullptr, + cache_options)); + Status prepare = reader->PrepareForReading({TargetRowGroup(0, false, RowRanges())}, {0, 2}); + std::promise close_started; + auto close = std::async(std::launch::async, [&]() { + close_started.set_value(); + return reader->Close(); + }); + close_started.get_future().wait(); + auto close_state = close.wait_for(std::chrono::milliseconds(20)); + gated->ReleaseAll(); + ASSERT_OK(close.get()); + ASSERT_OK(prepare); + ASSERT_EQ(2, tracking->GetAsyncReadCalls()); + ASSERT_EQ(1, gated->AsyncReadCount()); + ASSERT_EQ(std::future_status::timeout, close_state); } TEST_F(FileReaderWrapperTest, ReusesParsedOffsetIndexesWithinFileReader) { @@ -440,11 +858,6 @@ TEST_F(FileReaderWrapperTest, Simple) { ASSERT_EQ(5500, reader_wrapper->GetPreviousBatchFirstRowNumber().value()); } -/// The prefetch framework always issues SeekToRow right after SetReadRanges, while the -/// wrapper is still uninitialized (before the first Next()). That seek must not build -/// the arrow batch reader eagerly: building it once in SeekToRow and again in -/// PrepareForReading makes the arrow reader request every column chunk twice (2x read -/// amplification). The deferred construction must also honor the seeked start position. TEST_F(FileReaderWrapperTest, SeekBeforeInitIssuesNoReadsAndStartsAtSeekPosition) { std::string file_path = PathUtil::JoinPath(dir_->Str(), "seek_before_init.parquet"); PrepareParquetFile(file_path, /*row_count=*/5500); @@ -456,18 +869,12 @@ TEST_F(FileReaderWrapperTest, SeekBeforeInitIssuesNoReadsAndStartsAtSeekPosition PrepareReaderWrapperOnStream(std::move(tracking_stream))); ASSERT_EQ(6, reader_wrapper->GetNumberOfRowGroups()); - // Baseline: only metadata reads happened so far (footer etc. during Open/Build). int64_t baseline_read_bytes = tracking->GetPositionalReadBytes(); - // Seek to the start of RG2 while still uninitialized. This must only record the - // position, not build a batch reader that would eagerly read column chunks. ASSERT_OK(reader_wrapper->SeekToRow(2000)); ASSERT_EQ(2000, reader_wrapper->GetNextRowToRead()); - ASSERT_EQ(baseline_read_bytes, tracking->GetPositionalReadBytes()) - << "SeekToRow before initialization issued eager column chunk reads; the deferred " - "PrepareForReader would build a second reader and read everything twice"; + ASSERT_EQ(baseline_read_bytes, tracking->GetPositionalReadBytes()); - // The first Next() performs the single deferred initialization at the seeked position. int64_t total_rows = 0; bool checked_first_batch = false; while (true) { @@ -481,7 +888,6 @@ TEST_F(FileReaderWrapperTest, SeekBeforeInitIssuesNoReadsAndStartsAtSeekPosition } total_rows += batch->num_rows(); } - // RG2..RG5 cover rows [2000, 5500). ASSERT_EQ(3500, total_rows); ASSERT_EQ(5500, reader_wrapper->GetNextRowToRead()); } @@ -626,22 +1032,20 @@ TEST_F(FileReaderWrapperTest, PageFilteredRespectsBatchSize) { /// row group start for the whole row group makes callers believe the reader has not moved. TEST_F(FileReaderWrapperTest, PageFilteredAdvancesNextRowToRead) { std::string file_path = PathUtil::JoinPath(dir_->Str(), "page_next_row.parquet"); - // 2000 rows produces 2 row groups (max_row_group_length=1000) with page index enabled. - PrepareParquetFile(file_path, /*row_count=*/2000, /*enable_page_index=*/true); + PrepareParquetFile(file_path, /*row_count=*/3000, /*enable_page_index=*/true); + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs_->Open(file_path)); + auto input_pool = std::make_shared(arrow::default_memory_pool()); ASSERT_OK_AND_ASSIGN(auto reader_wrapper, - PrepareReaderWrapper(file_path, /*wrapper_batch_size=*/7)); - ASSERT_EQ(2, reader_wrapper->GetNumberOfRowGroups()); - - // RowRanges are RG-local. RG0 keeps two non-contiguous stretches so that a batch can span the - // gap between them; RG1 keeps its first 20 rows. + PrepareReaderWrapperOnStream( + input, /*wrapper_batch_size=*/7, /*enable_offset_index_cache=*/false, + DEFAULT_PARQUET_READ_CACHE_OPTION_WINDOW_SIZE_LIMIT, input_pool)); RowRanges rg0_ranges({RowRanges::Range(10, 49), RowRanges::Range(100, 149)}); - RowRanges rg1_ranges(RowRanges::Range(0, 19)); + RowRanges rg2_ranges(RowRanges::Range(0, 19)); ASSERT_OK(reader_wrapper->PrepareForReading( {TargetRowGroup(/*rg_index=*/0, /*is_partially_matched=*/true, /*ranges=*/rg0_ranges), - TargetRowGroup(/*rg_index=*/1, /*is_partially_matched=*/true, /*ranges=*/rg1_ranges)}, + TargetRowGroup(/*rg_index=*/2, /*is_partially_matched=*/true, /*ranges=*/rg2_ranges)}, /*column_indices=*/{0, 1, 2})); - // Absolute row numbers the reader is expected to produce, in order. std::vector expected_rows; for (uint64_t row = 10; row <= 49; ++row) { expected_rows.push_back(row); @@ -649,10 +1053,11 @@ TEST_F(FileReaderWrapperTest, PageFilteredAdvancesNextRowToRead) { for (uint64_t row = 100; row <= 149; ++row) { expected_rows.push_back(row); } - for (uint64_t row = 1000; row <= 1019; ++row) { + for (uint64_t row = 2000; row <= 2019; ++row) { expected_rows.push_back(row); } + const int64_t input_bytes_with_both_groups = input_pool->bytes_allocated(); size_t consumed = 0; while (true) { ASSERT_OK_AND_ASSIGN(std::shared_ptr record_batch, @@ -665,11 +1070,12 @@ TEST_F(FileReaderWrapperTest, PageFilteredAdvancesNextRowToRead) { reader_wrapper->GetPreviousBatchFirstRowNumber().value()); consumed += record_batch->num_rows(); ASSERT_LE(consumed, expected_rows.size()); - // RG0 ends exactly where RG1 starts, so the row group boundary is also covered by - // expected_rows; only the very last batch leaves the cursor at the file end. uint64_t expected_next_row = - consumed < expected_rows.size() ? expected_rows[consumed] : 2000; + consumed < expected_rows.size() ? expected_rows[consumed] : 3000; ASSERT_EQ(expected_next_row, reader_wrapper->GetNextRowToRead()); + if (expected_next_row == 2000) { + ASSERT_LT(input_pool->bytes_allocated(), input_bytes_with_both_groups); + } } ASSERT_EQ(expected_rows.size(), consumed); } @@ -892,15 +1298,17 @@ class CompactThriftFooter { } } - // Enter the body of the first element of the list at the cursor; the element - // must be a struct. - bool EnterFirstListElement() { + bool EnterListStruct(uint64_t index) { uint64_t header = 0; if (!ReadByte(&header)) return false; uint64_t size = (header >> 4) & 0x0F; if ((header & 0x0F) != kStruct) return false; if (size == 15 && !ReadVarint(&size)) return false; - return size > 0; // Cursor is now at the first element's struct body. + if (index >= size) return false; + for (uint64_t i = 0; i < index; ++i) { + if (!SkipValue(kStruct)) return false; + } + return true; } static constexpr uint8_t kI64 = 6; @@ -1032,12 +1440,9 @@ class CompactThriftFooter { } // namespace -// A corrupt footer may carry negative column chunk offsets. GetPreBufferRanges must -// reject them instead of casting them into huge uint64_t ranges that would blow up -// the downstream range coalescing. -TEST_F(FileReaderWrapperTest, GetPreBufferRangesRejectsNegativeMetadataOffset) { +TEST_F(FileReaderWrapperTest, RejectsInvalidPrefetchRangesWhenNeeded) { std::string file_path = PathUtil::JoinPath(dir_->Str(), "test.parquet"); - PrepareParquetFile(file_path, /*row_count=*/100); + PrepareParquetFile(file_path, /*row_count=*/1100); std::ifstream file(file_path, std::ios::binary); std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); @@ -1054,13 +1459,11 @@ TEST_F(FileReaderWrapperTest, GetPreBufferRangesRejectsNegativeMetadataOffset) { ASSERT_LT(static_cast(footer_length) + 8, content.size()); size_t footer_start = tail - 8 - footer_length; - // Walk to FileMetaData.row_groups[0].columns[0].meta_data.data_page_offset and - // flip the sign of its zigzag varint (positive -> negative, byte length kept). CompactThriftFooter footer(&content, footer_start); ASSERT_TRUE(footer.SeekField(/*FileMetaData.row_groups=*/4, CompactThriftFooter::kList)); - ASSERT_TRUE(footer.EnterFirstListElement()); + ASSERT_TRUE(footer.EnterListStruct(1)); ASSERT_TRUE(footer.SeekField(/*RowGroup.columns=*/1, CompactThriftFooter::kList)); - ASSERT_TRUE(footer.EnterFirstListElement()); + ASSERT_TRUE(footer.EnterListStruct(0)); ASSERT_TRUE(footer.SeekField(/*ColumnChunk.meta_data=*/3, CompactThriftFooter::kStruct)); ASSERT_TRUE(footer.SeekField(/*ColumnMetaData.data_page_offset=*/9, CompactThriftFooter::kI64)); size_t offset_pos = footer.pos(); @@ -1072,12 +1475,17 @@ TEST_F(FileReaderWrapperTest, GetPreBufferRangesRejectsNegativeMetadataOffset) { corrupt_file.write(content.data(), static_cast(content.size())); corrupt_file.close(); - ASSERT_OK_AND_ASSIGN(auto reader_wrapper, PrepareReaderWrapper(corrupt_path)); - ASSERT_OK(reader_wrapper->PrepareForReadingLazy( - {TargetRowGroup(/*rg_index=*/0, /*is_partially_matched=*/false, - /*ranges=*/RowRanges())}, - /*column_indices=*/{0, 1, 2})); - ASSERT_NOK_WITH_MSG(reader_wrapper->GetPreBufferRanges(), "pre-buffer range offset"); + ASSERT_OK_AND_ASSIGN(auto reader, PrepareReaderWrapper(corrupt_path)); + ASSERT_NOK_WITH_MSG(reader->GetPreBufferRanges(), "pre-buffer range offset"); + int64_t rows_read = 0; + while (rows_read < 1000) { + ASSERT_OK_AND_ASSIGN(auto batch, reader->Next()); + ASSERT_NE(nullptr, batch); + ASSERT_EQ(rows_read, reader->GetPreviousBatchFirstRowNumber().value()); + rows_read += batch->num_rows(); + } + ASSERT_EQ(1000, rows_read); + ASSERT_NOK_WITH_MSG(reader->Next(), "pre-buffer range offset"); } } // namespace paimon::parquet::test diff --git a/src/paimon/format/parquet/page_filtered_row_group_reader.cpp b/src/paimon/format/parquet/page_filtered_row_group_reader.cpp index 8c8fcf2e7..9f94bf6c8 100644 --- a/src/paimon/format/parquet/page_filtered_row_group_reader.cpp +++ b/src/paimon/format/parquet/page_filtered_row_group_reader.cpp @@ -29,10 +29,8 @@ #include "arrow/array.h" #include "arrow/builder.h" #include "arrow/chunked_array.h" -#include "arrow/io/caching.h" #include "arrow/io/interfaces.h" #include "arrow/table.h" -#include "arrow/util/future.h" #include "fmt/format.h" #include "paimon/common/utils/arrow/arrow_utils.h" #include "paimon/common/utils/arrow/status_utils.h" @@ -241,30 +239,6 @@ RowRanges PageFilteredRowGroupReader::ComputeCompressedRowRanges( return compressed; } -Status PageFilteredRowGroupReader::WaitForPreBuffer( - int32_t row_group_index, const std::vector& column_indices, - const ::arrow::io::CacheOptions& cache_options, bool pre_buffered, - const std::vector<::arrow::io::ReadRange>& page_ranges, - std::shared_ptr<::arrow::MemoryPool> pool, ::parquet::ParquetFileReader* parquet_reader) { - std::vector rg_vec = {row_group_index}; - std::vector col_vec(column_indices.begin(), column_indices.end()); - if (!pre_buffered) { - ::arrow::io::IOContext io_ctx(pool.get()); - parquet_reader->PreBuffer(rg_vec, col_vec, io_ctx, cache_options); - } - if (!page_ranges.empty()) { - auto status = parquet_reader->WhenBufferedRanges(page_ranges).status(); - if (!status.ok()) { - ::arrow::io::IOContext io_ctx(pool.get()); - parquet_reader->PreBuffer(rg_vec, col_vec, io_ctx, cache_options); - PAIMON_RETURN_NOT_OK_FROM_ARROW(parquet_reader->WhenBuffered(rg_vec, col_vec).status()); - } - } else { - PAIMON_RETURN_NOT_OK_FROM_ARROW(parquet_reader->WhenBuffered(rg_vec, col_vec).status()); - } - return Status::OK(); -} - /// Retains the decoder and selected-row cursor of every leaf, including leaves whose page /// plans use different compressed row coordinates. Only the current output window is decoded. class PageFilteredRowGroupReader::FilteredRecordBatchReader : public arrow::RecordBatchReader { @@ -554,8 +528,7 @@ PageFilteredRowGroupReader::FilteredRecordBatchReader::CreateFieldReader( Result> PageFilteredRowGroupReader::ReadFilteredRowGroup( const TargetRowGroup& target_row_group, const std::vector& column_indices, - const ::arrow::io::CacheOptions& cache_options, bool pre_buffered, - const std::vector<::arrow::io::ReadRange>& page_ranges, int64_t max_chunksize, + int64_t max_chunksize, const std::shared_ptr<::parquet::RowGroupPageIndexReader>& row_group_page_index_reader, std::shared_ptr<::arrow::MemoryPool> pool, ::parquet::arrow::FileReader* arrow_file_reader) { if (max_chunksize <= 0) { @@ -563,11 +536,6 @@ Result> PageFilteredRowGroupReader::Re } const auto& row_ranges = target_row_group.GetRowRanges(); const int32_t row_group_index = target_row_group.GetRowGroupIndex(); - if (!row_ranges.IsEmpty()) { - PAIMON_RETURN_NOT_OK(WaitForPreBuffer(row_group_index, column_indices, cache_options, - pre_buffered, page_ranges, pool, - arrow_file_reader->parquet_reader())); - } return FilteredRecordBatchReader::Create(row_ranges, row_group_index, column_indices, max_chunksize, row_group_page_index_reader, pool, arrow_file_reader); diff --git a/src/paimon/format/parquet/page_filtered_row_group_reader.h b/src/paimon/format/parquet/page_filtered_row_group_reader.h index 1d6a998ca..94c6e8028 100644 --- a/src/paimon/format/parquet/page_filtered_row_group_reader.h +++ b/src/paimon/format/parquet/page_filtered_row_group_reader.h @@ -25,7 +25,7 @@ #include #include -#include "arrow/io/caching.h" +#include "arrow/io/interfaces.h" #include "arrow/memory_pool.h" #include "arrow/record_batch.h" #include "arrow/type.h" @@ -50,10 +50,6 @@ class PageFilteredRowGroupReader { /// Read a row group with page-level filtering. /// @param target_row_group Target row group with index and row ranges /// @param column_indices Leaf column indices to read - /// @param cache_options Cache options for PreBuffer - /// @param pre_buffered If true, assumes PreBuffer was already called externally - /// and only waits via WhenBuffered (no redundant PreBuffer). - /// @param page_ranges If non-empty, wait via WhenBufferedRanges instead of WhenBuffered /// @param max_chunksize Positive per-batch row cap for the returned reader. /// @param row_group_page_index_reader Reusable page-index reader for the target row group /// @param pool Memory pool @@ -61,8 +57,7 @@ class PageFilteredRowGroupReader { /// @return A RecordBatchReader streaming the filtered rows. static Result> ReadFilteredRowGroup( const TargetRowGroup& target_row_group, const std::vector& column_indices, - const ::arrow::io::CacheOptions& cache_options, bool pre_buffered, - const std::vector<::arrow::io::ReadRange>& page_ranges, int64_t max_chunksize, + int64_t max_chunksize, const std::shared_ptr<::parquet::RowGroupPageIndexReader>& row_group_page_index_reader, std::shared_ptr<::arrow::MemoryPool> pool, ::parquet::arrow::FileReader* arrow_file_reader); @@ -88,15 +83,6 @@ class PageFilteredRowGroupReader { const std::vector<::parquet::PageLocation>& page_locations, int32_t page_idx, int64_t row_group_row_count); - /// Wait for pre-buffered data to become available before reading. - static Status WaitForPreBuffer(int32_t row_group_index, - const std::vector& column_indices, - const ::arrow::io::CacheOptions& cache_options, - bool pre_buffered, - const std::vector<::arrow::io::ReadRange>& page_ranges, - std::shared_ptr<::arrow::MemoryPool> pool, - ::parquet::ParquetFileReader* parquet_reader); - /// Build a direct data page read plan for a column based on RowRanges + OffsetIndex. /// The returned first data page offset and all page offsets are relative to the /// beginning of the column chunk stream used by Arrow's PageReader. diff --git a/src/paimon/format/parquet/page_filtered_row_group_reader_test.cpp b/src/paimon/format/parquet/page_filtered_row_group_reader_test.cpp index a26e27b9f..167d5ef74 100644 --- a/src/paimon/format/parquet/page_filtered_row_group_reader_test.cpp +++ b/src/paimon/format/parquet/page_filtered_row_group_reader_test.cpp @@ -227,7 +227,7 @@ class ReadAtTrackingInputStream : public InputStream { void ReadAsync(char* buffer, int64_t size, int64_t offset, std::function&& callback) override { - RecordPositionalRead(offset, size); + RecordPositionalRead(offset, size, /*asynchronous=*/true); input_->ReadAsync(buffer, size, offset, std::move(callback)); } @@ -243,9 +243,10 @@ class ReadAtTrackingInputStream : public InputStream { return input_->Close(); } - void ClearReadAtRanges() { + void ClearReads() { std::lock_guard lock(mutex_); read_at_ranges_.clear(); + issued_async_reads_ = false; } std::vector GetReadAtRanges() const { @@ -253,15 +254,22 @@ class ReadAtTrackingInputStream : public InputStream { return read_at_ranges_; } + bool IssuedAsyncReads() const { + std::lock_guard lock(mutex_); + return issued_async_reads_; + } + private: - void RecordPositionalRead(int64_t offset, int64_t size) { + void RecordPositionalRead(int64_t offset, int64_t size, bool asynchronous = false) { std::lock_guard lock(mutex_); read_at_ranges_.push_back({offset, size}); + issued_async_reads_ = issued_async_reads_ || asynchronous; } std::shared_ptr input_; mutable std::mutex mutex_; std::vector read_at_ranges_; + bool issued_async_reads_ = false; }; /// Test fixture for page-level filtering. @@ -354,16 +362,19 @@ class PageFilteredRowGroupReaderTest : public ::testing::Test { } /// Read back a Parquet file with a predicate, a bitmap, and page index filter enabled. - void ReadWithPredicateAndBitmapImpl( - const std::string& file_name, const std::shared_ptr& read_schema, - const std::shared_ptr& predicate, const RoaringBitmap32& bitmap, - std::shared_ptr* out, - const std::map options = {}, int32_t batch_size = 1024, - std::vector* read_at_ranges = nullptr) { + void ReadWithPredicateAndBitmapImpl(const std::string& file_name, + const std::shared_ptr& read_schema, + const std::shared_ptr& predicate, + const RoaringBitmap32& bitmap, + std::shared_ptr* out, + const std::map options = {}, + int32_t batch_size = 1024, + std::vector* read_at_ranges = nullptr, + bool* issued_async_reads = nullptr) { ASSERT_OK_AND_ASSIGN(std::shared_ptr in, fs_->Open(file_name)); ASSERT_OK_AND_ASSIGN(int64_t length, in->Length()); std::shared_ptr tracking_in; - if (read_at_ranges != nullptr) { + if (read_at_ranges != nullptr || issued_async_reads != nullptr) { tracking_in = std::make_shared(in); in = tracking_in; } @@ -380,13 +391,16 @@ class PageFilteredRowGroupReaderTest : public ::testing::Test { if (tracking_in) { // Ignore footer and schema metadata reads. The test only checks I/O issued while // consuming data pages. - tracking_in->ClearReadAtRanges(); + tracking_in->ClearReads(); } ASSERT_OK_AND_ASSIGN( *out, paimon::test::ReadResultCollector::CollectResult(std::move(batch_reader))); - if (tracking_in) { + if (read_at_ranges != nullptr) { *read_at_ranges = tracking_in->GetReadAtRanges(); } + if (issued_async_reads != nullptr) { + *issued_async_reads = tracking_in->IssuedAsyncReads(); + } } protected: @@ -1023,8 +1037,6 @@ TEST_F(PageFilteredRowGroupReaderTest, StreamingAlignsMisalignedChunksAcrossDeco const RowRanges ranges( {RowRanges::Range(2, 5), RowRanges::Range(10, 15), RowRanges::Range(19, 23)}); TargetRowGroup target(0, true, ranges); - const auto page_ranges = PageFilteredRowGroupReader::ComputePageRanges( - target, {0, 1}, indexes, file_reader->parquet_reader()); std::vector> decoded_windows(2); auto chunked_reader = std::make_unique<::testing::StrictMock>(); @@ -1044,10 +1056,10 @@ TEST_F(PageFilteredRowGroupReaderTest, StreamingAlignsMisalignedChunksAcrossDeco &decoded_windows[field_index]); return arrow::Status::OK(); }); - ASSERT_OK_AND_ASSIGN(std::unique_ptr batches, - PageFilteredRowGroupReader::ReadFilteredRowGroup( - target, {0, 1}, arrow::io::CacheOptions::Defaults(), false, - page_ranges, kBatchSize, indexes, arrow_pool_, chunked_reader.get())); + ASSERT_OK_AND_ASSIGN( + std::unique_ptr batches, + PageFilteredRowGroupReader::ReadFilteredRowGroup(target, {0, 1}, kBatchSize, indexes, + arrow_pool_, chunked_reader.get())); ASSERT_TRUE(batches->schema()->Equals(*arrow::schema(data->type()->fields()))); ASSERT_TRUE(decoded_windows[0].empty()); ASSERT_TRUE(decoded_windows[1].empty()); @@ -1103,10 +1115,6 @@ TEST_F(PageFilteredRowGroupReaderTest, StreamingAlignsMisalignedChunksAcrossDeco ASSERT_EQ(expected_rows.size(), selected_row); } -/// Test: end-to-end page-filtered read produces correct results when using page-level PreBuffer. -/// -/// This exercises the full path: ComputePageRanges → PreBufferRanges → CachedInputStream → -/// ReadFilteredRowGroup with page_ranges. TEST_F(PageFilteredRowGroupReaderTest, EndToEndPageLevelPreBuffer) { std::string file_name = dir_->Str() + "/e2e_page_prebuffer.parquet"; auto data = MakeSequentialIntData(100); @@ -1552,11 +1560,6 @@ TEST_F(PageFilteredRowGroupReaderTest, BitmapAllPagesSomeRowGroups) { } } -/// Test: OffsetIndex lets the reader jump directly to selected data pages. -/// -/// The bitmap selects rows from page 1 and page 8. Synchronous positional reads issued while -/// consuming the row group must not cover any unselected page header. Before direct page jumps, -/// SerializedPageReader sequentially Peeked every page header and this assertion failed. TEST_F(PageFilteredRowGroupReaderTest, DirectOffsetIndexJumpDoesNotReadUnselectedPageHeaders) { std::string file_name = dir_->Str() + "/direct_offset_index_jump.parquet"; auto data = MakeSequentialIntData(100); @@ -1584,6 +1587,12 @@ TEST_F(PageFilteredRowGroupReaderTest, DirectOffsetIndexJumpDoesNotReadUnselecte ASSERT_EQ(page_idx * 10, page_locations[page_idx].first_row_index); } + const int64_t data_start = page_locations.front().offset; + const auto& last_page = page_locations.back(); + const int64_t data_end = last_page.offset + last_page.compressed_page_size; + const int64_t expected_data_bytes = + page_locations[1].compressed_page_size + page_locations[8].compressed_page_size; + RoaringBitmap32 bitmap; bitmap.Add(15); // page 1 bitmap.Add(85); // page 8 @@ -1593,24 +1602,37 @@ TEST_F(PageFilteredRowGroupReaderTest, DirectOffsetIndexJumpDoesNotReadUnselecte options[PARQUET_READ_CACHE_OPTION_HOLE_SIZE_LIMIT] = "0"; auto read_schema = arrow::schema({arrow::field("val", arrow::int32())}); - std::shared_ptr result; - std::vector read_at_ranges; - ReadWithPredicateAndBitmapImpl(file_name, read_schema, /*predicate=*/nullptr, bitmap, &result, - options, 1, &read_at_ranges); - - ASSERT_TRUE(result); - ASSERT_EQ(2, result->length()); - ASSERT_EQ(2, result->num_chunks()); - auto flat = arrow::Concatenate(result->chunks()).ValueOrDie(); - auto struct_arr = std::dynamic_pointer_cast(flat); - ASSERT_TRUE(struct_arr); - auto val_arr = std::dynamic_pointer_cast(struct_arr->field(0)); - ASSERT_TRUE(val_arr); - ASSERT_EQ(15, val_arr->Value(0)); - ASSERT_EQ(85, val_arr->Value(1)); + for (int64_t budget : + {DEFAULT_PARQUET_READ_CACHE_OPTION_WINDOW_SIZE_LIMIT, int64_t{0}, int64_t{1}}) { + SCOPED_TRACE(budget); + if (budget != DEFAULT_PARQUET_READ_CACHE_OPTION_WINDOW_SIZE_LIMIT) { + options[PARQUET_READ_CACHE_OPTION_WINDOW_SIZE_LIMIT] = std::to_string(budget); + } + std::shared_ptr result; + std::vector read_at_ranges; + bool issued_async_reads = false; + ReadWithPredicateAndBitmapImpl(file_name, read_schema, /*predicate=*/nullptr, bitmap, + &result, options, 1, &read_at_ranges, &issued_async_reads); - AssertSelectedPagesRead(page_locations, /*selected_pages=*/{1, 8}, read_at_ranges); - AssertUnselectedPageHeadersNotRead(page_locations, /*selected_pages=*/{1, 8}, read_at_ranges); + ASSERT_TRUE(result); + ASSERT_EQ(2, result->length()); + ASSERT_EQ(2, result->num_chunks()); + auto flat = arrow::Concatenate(result->chunks()).ValueOrDie(); + ASSERT_TRUE(flat->RangeEquals(0, 1, 15, *data)) << flat->ToString(); + ASSERT_TRUE(flat->RangeEquals(1, 2, 85, *data)) << flat->ToString(); + + AssertSelectedPagesRead(page_locations, /*selected_pages=*/{1, 8}, read_at_ranges); + AssertUnselectedPageHeadersNotRead(page_locations, /*selected_pages=*/{1, 8}, + read_at_ranges); + int64_t data_bytes_read = 0; + for (const auto& range : read_at_ranges) { + data_bytes_read += + std::max(0, std::min(range.offset + range.length, data_end) - + std::max(range.offset, data_start)); + } + EXPECT_EQ(expected_data_bytes, data_bytes_read); + EXPECT_EQ(budget > 0, issued_async_reads); + } } /// Dictionary pages are column-local. Each leaf must load its own dictionary before the @@ -1880,14 +1902,12 @@ TEST_F(PageFilteredRowGroupReaderTest, DictionaryEmptySelectionDoesNotReadPages) arrow_file_reader->parquet_reader()); ASSERT_TRUE(page_ranges.empty()); - tracking_input->ClearReadAtRanges(); - ASSERT_OK_AND_ASSIGN( - std::unique_ptr result_reader, - PageFilteredRowGroupReader::ReadFilteredRowGroup( - empty_target, /*column_indices=*/{0}, arrow::io::CacheOptions::Defaults(), - /*pre_buffered=*/false, /*page_ranges=*/{}, /*max_chunksize=*/1024, - /*row_group_page_index_reader=*/row_group_page_index, arrow_pool_, - arrow_file_reader.get())); + tracking_input->ClearReads(); + ASSERT_OK_AND_ASSIGN(std::unique_ptr result_reader, + PageFilteredRowGroupReader::ReadFilteredRowGroup( + empty_target, /*column_indices=*/{0}, /*max_chunksize=*/1024, + /*row_group_page_index_reader=*/row_group_page_index, arrow_pool_, + arrow_file_reader.get())); ASSERT_TRUE(result_reader->schema()->Equals( *arrow::schema({arrow::field("val", arrow::dictionary(arrow::int32(), arrow::utf8()))}))); std::shared_ptr batch; @@ -2044,10 +2064,10 @@ TEST_F(PageFilteredRowGroupReaderTest, InvalidOffsetIndexFallsBackWithoutChangin ASSERT_EQ(size, ranges[0].length); AssertSelectedPagesRead(valid_index->page_locations(), {1, 8}, ranges); AssertUnselectedPageHeadersNotRead(valid_index->page_locations(), {1, 8}, ranges); - ASSERT_OK_AND_ASSIGN(std::unique_ptr batches, - PageFilteredRowGroupReader::ReadFilteredRowGroup( - target, {0, 1}, arrow::io::CacheOptions::Defaults(), false, ranges, - /*max_chunksize=*/3, page_index, arrow_pool_, reader.get())); + ASSERT_OK_AND_ASSIGN( + std::unique_ptr batches, + PageFilteredRowGroupReader::ReadFilteredRowGroup( + target, {0, 1}, /*max_chunksize=*/3, page_index, arrow_pool_, reader.get())); ASSERT_TRUE(batches->schema()->Equals(*arrow::schema(data->type()->fields()))); size_t selected_count = 0; while (true) { @@ -2946,19 +2966,15 @@ TEST_F(PageFilteredRowGroupReaderTest, StreamingPreservesDictionaryValuesAcrossS auto indexes = file_reader->parquet_reader()->GetPageIndexReader()->RowGroup(0); RowRanges ranges({RowRanges::Range(2, 16), RowRanges::Range(32, 46), RowRanges::Range(52, 58)}); TargetRowGroup target(0, true, ranges); - const auto page_ranges = PageFilteredRowGroupReader::ComputePageRanges( - target, {0, 1}, indexes, file_reader->parquet_reader()); for (int64_t batch_size : {-1, 0}) { auto result = PageFilteredRowGroupReader::ReadFilteredRowGroup( - target, {0, 1}, arrow::io::CacheOptions::Defaults(), false, page_ranges, batch_size, - indexes, arrow_pool_, file_reader.get()); + target, {0, 1}, batch_size, indexes, arrow_pool_, file_reader.get()); ASSERT_FALSE(result.ok()); ASSERT_TRUE(result.status().IsInvalid()); } ASSERT_OK_AND_ASSIGN(std::unique_ptr batches, PageFilteredRowGroupReader::ReadFilteredRowGroup( - target, {0, 1}, arrow::io::CacheOptions::Defaults(), false, - page_ranges, kBatchSize, indexes, arrow_pool_, file_reader.get())); + target, {0, 1}, kBatchSize, indexes, arrow_pool_, file_reader.get())); ASSERT_EQ(arrow::Type::DICTIONARY, batches->schema()->field(1)->type()->id()); std::vector> retained_batches; std::vector actual_rows; @@ -3033,12 +3049,10 @@ TEST_F(PageFilteredRowGroupReaderTest, StreamingBoundsDecodedMemoryAndPreservesR ASSERT_TRUE(::parquet::arrow::OpenFile(stream, read_pool.get(), &file_reader).ok()); auto indexes = file_reader->parquet_reader()->GetPageIndexReader()->RowGroup(0); TargetRowGroup target(0, true, ranges); - const auto page_ranges = PageFilteredRowGroupReader::ComputePageRanges( - target, {0, 1}, indexes, file_reader->parquet_reader()); - ASSERT_OK_AND_ASSIGN(std::unique_ptr batches, - PageFilteredRowGroupReader::ReadFilteredRowGroup( - target, {0, 1}, arrow::io::CacheOptions::Defaults(), false, - page_ranges, kBatchSize, indexes, read_pool, file_reader.get())); + ASSERT_OK_AND_ASSIGN( + std::unique_ptr batches, + PageFilteredRowGroupReader::ReadFilteredRowGroup(target, {0, 1}, kBatchSize, indexes, + read_pool, file_reader.get())); ASSERT_TRUE(batches->schema()->Equals(*arrow::schema(data->type()->fields()))); std::shared_ptr first; @@ -3125,12 +3139,9 @@ TEST_F(PageFilteredRowGroupReaderTest, StreamingDefersLaterPageDecodeErrors) { ASSERT_TRUE(::parquet::arrow::OpenFile(corrupted, arrow_pool_.get(), &file_reader).ok()); auto indexes = file_reader->parquet_reader()->GetPageIndexReader()->RowGroup(0); TargetRowGroup target(0, true, RowRanges::CreateSingle(100)); - const auto ranges = PageFilteredRowGroupReader::ComputePageRanges( - target, {0, 1}, indexes, file_reader->parquet_reader()); ASSERT_OK_AND_ASSIGN(std::unique_ptr batches, PageFilteredRowGroupReader::ReadFilteredRowGroup( - target, {0, 1}, arrow::io::CacheOptions::Defaults(), false, ranges, 5, - indexes, arrow_pool_, file_reader.get())); + target, {0, 1}, 5, indexes, arrow_pool_, file_reader.get())); int64_t rows = 0; arrow::Status status; std::shared_ptr first; diff --git a/src/paimon/format/parquet/parquet_file_batch_reader.cpp b/src/paimon/format/parquet/parquet_file_batch_reader.cpp index d8d5d5d3e..5fed79d11 100644 --- a/src/paimon/format/parquet/parquet_file_batch_reader.cpp +++ b/src/paimon/format/parquet/parquet_file_batch_reader.cpp @@ -48,6 +48,7 @@ #include "paimon/common/utils/arrow/mem_utils.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/checked_cast.h" +#include "paimon/common/utils/math.h" #include "paimon/common/utils/options_utils.h" #include "paimon/common/utils/scope_guard.h" #include "paimon/common/utils/string_utils.h" @@ -296,6 +297,23 @@ Result> ParquetFileBatchReader::Create( PAIMON_ASSIGN_OR_RAISE(::parquet::ArrowReaderProperties arrow_reader_properties, CreateArrowReaderProperties(pool, options, batch_size, hints)); + PAIMON_ASSIGN_OR_RAISE(int64_t prefetch_budget, + OptionsUtils::GetValueFromMap( + options, PARQUET_READ_CACHE_OPTION_WINDOW_SIZE_LIMIT, + DEFAULT_PARQUET_READ_CACHE_OPTION_WINDOW_SIZE_LIMIT)); + PAIMON_RETURN_NOT_OK( + ValidateValueNonNegative(prefetch_budget, PARQUET_READ_CACHE_OPTION_WINDOW_SIZE_LIMIT)); + PAIMON_ASSIGN_OR_RAISE(int64_t prefetch_row_groups, + OptionsUtils::GetValueFromMap( + options, PARQUET_READ_CACHE_OPTION_PREFETCH_ROW_GROUPS, + DEFAULT_PARQUET_READ_CACHE_OPTION_PREFETCH_ROW_GROUPS)); + PAIMON_RETURN_NOT_OK(ValidateValueNonNegative( + prefetch_row_groups, PARQUET_READ_CACHE_OPTION_PREFETCH_ROW_GROUPS)); + if (!arrow_reader_properties.pre_buffer()) { + prefetch_budget = 0; + } + // Keep Arrow from pre-buffering outside the wrapper's window. + arrow_reader_properties.set_pre_buffer(false); ::parquet::arrow::FileReaderBuilder file_reader_builder; PAIMON_RETURN_NOT_OK_FROM_ARROW( @@ -322,7 +340,8 @@ Result> ParquetFileBatchReader::Create( PAIMON_ASSIGN_OR_RAISE( std::unique_ptr reader, FileReaderWrapper::Create(std::move(file_reader), static_cast(batch_size), - enable_offset_index_cache, pool)); + enable_offset_index_cache, prefetch_budget, + prefetch_row_groups, pool)); // Arrow silently ignores set_read_dictionary for leaves it cannot read as dictionaries, // so take the columns it really emits that way from the schema it just derived. std::set dictionary_fields; diff --git a/src/paimon/format/parquet/parquet_file_batch_reader_test.cpp b/src/paimon/format/parquet/parquet_file_batch_reader_test.cpp index bdbbe9936..3e0feefa0 100644 --- a/src/paimon/format/parquet/parquet_file_batch_reader_test.cpp +++ b/src/paimon/format/parquet/parquet_file_batch_reader_test.cpp @@ -1329,6 +1329,89 @@ TEST_F(ParquetFileBatchReaderTest, TestPreBufferReadHints) { } } +TEST_F(ParquetFileBatchReaderTest, TestPrefetchWindowOptions) { + struct AsyncReadCountingInputStream : public InputStream { + explicit AsyncReadCountingInputStream(std::shared_ptr inner) + : inner_(std::move(inner)) {} + Status Seek(int64_t offset, SeekOrigin origin) override { + return inner_->Seek(offset, origin); + } + Result GetPos() const override { + return inner_->GetPos(); + } + Result Read(char* buffer, int64_t size) override { + return inner_->Read(buffer, size); + } + Result Read(char* buffer, int64_t size, int64_t offset) override { + return inner_->Read(buffer, size, offset); + } + void ReadAsync(char* buffer, int64_t size, int64_t offset, + std::function&& callback) override { + async_reads_.fetch_add(1); + inner_->ReadAsync(buffer, size, offset, std::move(callback)); + } + Status Close() override { + return inner_->Close(); + } + Result GetUri() const override { + return inner_->GetUri(); + } + Result Length() const override { + return inner_->Length(); + } + int32_t AsyncReads() const { + return async_reads_.load(); + } + std::shared_ptr inner_; + std::atomic async_reads_{0}; + }; + + WriteArray(file_path_, struct_array_, schema_, /*write_batch_size=*/1, + /*enable_dictionary=*/false, /*max_row_group_length=*/1); + { + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs_->Open(file_path_)); + ParquetReaderBuilder builder({{PARQUET_READ_CACHE_OPTION_WINDOW_SIZE_LIMIT, "-1"}}, + batch_size_); + builder.WithMemoryPool(GetDefaultPool()); + ASSERT_NOK_WITH_MSG(builder.Build(input), + "parquet.read.cache-option.window-size-limit -1 is less than 0"); + } + { + ASSERT_OK_AND_ASSIGN(std::shared_ptr input, fs_->Open(file_path_)); + ParquetReaderBuilder builder({{PARQUET_READ_CACHE_OPTION_PREFETCH_ROW_GROUPS, "-1"}}, + batch_size_); + builder.WithMemoryPool(GetDefaultPool()); + ASSERT_NOK_WITH_MSG(builder.Build(input), + "parquet.read.cache-option.prefetch-row-groups -1 is less than 0"); + } + const std::vector, int32_t>> cases = { + {{{PARQUET_READ_CACHE_OPTION_WINDOW_SIZE_LIMIT, "0"}}, 0}, + {{{PARQUET_READ_CACHE_OPTION_PREFETCH_ROW_GROUPS, "0"}}, 1}, + {{}, 2}, + {{{PARQUET_READ_CACHE_OPTION_PREFETCH_ROW_GROUPS, "2"}}, 3}, + }; + for (const auto& [opts, expected_first_batch_async_reads] : cases) { + ASSERT_OK_AND_ASSIGN(std::shared_ptr raw_input, fs_->Open(file_path_)); + auto counting_input = std::make_shared(raw_input); + ParquetReaderBuilder builder(opts, /*batch_size=*/1); + builder.WithMemoryPool(GetDefaultPool()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, + builder.Build(counting_input)); + ASSERT_OK_AND_ASSIGN(BatchReader::ReadBatch first_batch, reader->NextBatch()); + ASSERT_FALSE(BatchReader::IsEofBatch(first_batch)); + ASSERT_EQ(expected_first_batch_async_reads, counting_input->AsyncReads()); + int64_t total_rows = first_batch.first->length; + ArrowArrayRelease(first_batch.first.get()); + ArrowSchemaRelease(first_batch.second.get()); + ASSERT_OK_AND_ASSIGN(std::shared_ptr rest, + paimon::test::ReadResultCollector::CollectResult(reader.get())); + if (rest) { + total_rows += rest->length(); + } + ASSERT_EQ(struct_array_->length(), total_rows); + } +} + TEST_F(ParquetFileBatchReaderTest, TestBitmapRowGroupPushDownWithMultiRowGroups) { arrow::FieldVector fields = {arrow::field("f0", arrow::int32())}; auto arrow_type = arrow::struct_(fields); diff --git a/src/paimon/format/parquet/parquet_format_defs.h b/src/paimon/format/parquet/parquet_format_defs.h index f45603fc5..535e49df3 100644 --- a/src/paimon/format/parquet/parquet_format_defs.h +++ b/src/paimon/format/parquet/parquet_format_defs.h @@ -72,6 +72,17 @@ static inline const char PARQUET_READ_CACHE_OPTION_HOLE_SIZE_LIMIT[] = "parquet.read.cache-option.hole-size-limit"; static inline const char PARQUET_READ_CACHE_OPTION_RANGE_SIZE_LIMIT[] = "parquet.read.cache-option.range-size-limit"; +// Soft byte budget for projected Parquet data buffered or in flight per reader. When positive, at +// least the current row group is prefetched even if it exceeds this budget; subsequent row groups +// are prefetched only while within budget. Zero disables the prefetch window. +static inline const char PARQUET_READ_CACHE_OPTION_WINDOW_SIZE_LIMIT[] = + "parquet.read.cache-option.window-size-limit"; +static constexpr int64_t DEFAULT_PARQUET_READ_CACHE_OPTION_WINDOW_SIZE_LIMIT = 128 * 1024 * 1024; +// Maximum number of subsequent row groups to prefetch beyond the current row group. +// Zero disables lookahead beyond the current row group. +static inline const char PARQUET_READ_CACHE_OPTION_PREFETCH_ROW_GROUPS[] = + "parquet.read.cache-option.prefetch-row-groups"; +static constexpr int64_t DEFAULT_PARQUET_READ_CACHE_OPTION_PREFETCH_ROW_GROUPS = 1; // Strategy for refining row ranges using the selection bitmap produced by pushed-down // predicates. Two options: // * "coalesce" (default): build row-level ranges from the bitmap, then merge nearby