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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 77 additions & 74 deletions cmake_modules/arrow.diff
Original file line number Diff line number Diff line change
Expand Up @@ -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<ReadRange> 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<ReadRange> 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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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<const char*>(peek_buffer_->data()),
+ static_cast<size_t>(peek_buffer_->size()));
+ }
+
+ ::arrow::Result<int64_t> 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<size_t>(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<size_t>(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<size_t>(buf->size()));
+ position_ += buf->size();
+ return buf->size();
+ return buffer->size();
+ }
+
+ ::arrow::Result<std::shared_ptr<::arrow::Buffer>> Read(int64_t nbytes) override {
Expand All @@ -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();
Expand All @@ -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<CachedInputStream>(
+ 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<int>& row_groups,
@@ -911,6 +1019,21 @@ void ParquetFileReader::PreBuffer(const std::vector<int>& 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<SerializedFile*>(contents_.get());
+ file->PreBufferRanges(ranges, ctx, options);
+ const ::arrow::io::CacheOptions& options) const {
+ const auto* file =
+ ::arrow::internal::checked_cast<const SerializedFile*>(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<SerializedFile*>(contents_.get());
+ return file->WhenBufferedRanges(ranges);
+ file->SetPreBufferCache(std::move(cache));
+}
+
// ----------------------------------------------------------------------
Expand All @@ -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<int>& row_groups,
const std::vector<int>& 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
Expand Down
47 changes: 33 additions & 14 deletions docs/source/user_guide/prefetch.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
===
Expand Down
35 changes: 24 additions & 11 deletions src/paimon/common/utils/arrow/arrow_input_stream_adapter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include "paimon/common/utils/arrow/arrow_input_stream_adapter.h"

#include <cstdint>
#include <exception>
#include <functional>
#include <utility>

Expand Down Expand Up @@ -147,18 +148,30 @@ arrow::Future<std::shared_ptr<arrow::Buffer>> ArrowInputStreamAdapter::ReadAsync
std::shared_ptr<arrow::Buffer> buffer = std::move(buffer_result).ValueUnsafe();
buffer = KeepMemoryPoolAlive(std::move(buffer), pool_);
std::shared_ptr<std::atomic<uint64_t>> storage_read_bytes = storage_read_bytes_;
input_stream_->ReadAsync(
reinterpret_cast<char*>(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<uint64_t>(nbytes));
char* data = reinterpret_cast<char*>(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<uint64_t>(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;
}

Expand Down
Loading
Loading