From c9f9dfc9564eceb0716d5f57c48b8cdf72900e65 Mon Sep 17 00:00:00 2001 From: Gang Wu Date: Mon, 30 Nov 2026 23:37:58 +0800 Subject: [PATCH] ORC-2239: [C++] Prefetch stripe I/O before RowReader::next() Expose tryPrefetchIO() so callers can submit reads for the next selected stripe at a stripe boundary. Reuse the existing stripe preparation and defer column reader construction until next(). Generated-by: OpenAI Codex (GPT-6) --- c++/include/orc/Reader.hh | 9 ++ c++/src/Reader.cc | 61 +++++++++++- c++/src/Reader.hh | 11 ++- c++/test/TestReader.cc | 192 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 267 insertions(+), 6 deletions(-) diff --git a/c++/include/orc/Reader.hh b/c++/include/orc/Reader.hh index 4ae989ec58..0bed9f71c7 100644 --- a/c++/include/orc/Reader.hh +++ b/c++/include/orc/Reader.hh @@ -753,6 +753,15 @@ namespace orc { */ virtual std::unique_ptr createRowBatch(uint64_t size) const = 0; + /** + * Submit data reads for the next selected stripe at a stripe boundary. + * Call before the first next() or after consuming the previous batch. + * Has no effect within an initialized stripe, after EOF, when prefetching + * is disabled, or when the current stripe has already been prepared. + * Preparing a stripe can read metadata synchronously. + */ + void tryPrefetchIO(); + /** * Read the next row batch from the current position. * Caller must look at numElements in the row batch to determine how diff --git a/c++/src/Reader.cc b/c++/src/Reader.cc index 4c16b737fb..fea4c888e2 100644 --- a/c++/src/Reader.cc +++ b/c++/src/Reader.cc @@ -1232,16 +1232,16 @@ namespace orc { } } - void RowReaderImpl::startNextStripe() { + void RowReaderImpl::prepareNextStripe() { reader_.reset(); // ColumnReaders use lots of memory; free old memory first rowIndexes_.clear(); bloomFilterIndex_.clear(); sharedDictionaries_.clear(); // Clear dictionaries from previous stripe // evaluate file statistics if it exists - if (sargsApplier_ && - !sargsApplier_->evaluateFileStatistics(*footer_, numRowGroupsInStripeRange_)) { - // skip the entire file + if (currentStripe_ >= lastStripe_ || + (sargsApplier_ && + !sargsApplier_->evaluateFileStatistics(*footer_, numRowGroupsInStripeRange_))) { markEndOfFile(); return; } @@ -1360,7 +1360,51 @@ namespace orc { } } } + } else { + markEndOfFile(); + } + } + + void RowReaderImpl::tryPrefetchIO() { + if (!enableAsyncPrefetch_ || prefetchedStripe_ || isCurrentStripeInited() || + currentStripe_ >= lastStripe_) { + return; + } + + const auto firstCandidate = currentStripe_; + const auto previousRow = previousRow_; + prepareNextStripe(); + prefetchedStripe_ = PrefetchedStripe{firstCandidate, currentStripe_}; + previousRow_ = previousRow; + } + void RowReaderImpl::startNextStripe() { + bool reusePrefetchedStripe = prefetchedStripe_ && + currentStripe_ >= prefetchedStripe_->firstCandidate && + currentStripe_ <= prefetchedStripe_->selected; + if (reusePrefetchedStripe) { + // Predicate pushdown already rejected the earlier candidates in this range. + if (currentStripe_ < prefetchedStripe_->selected) { + currentStripe_ = prefetchedStripe_->selected; + currentRowInStripe_ = 0; + } + if (currentStripe_ < lastStripe_ && sargsApplier_ && + !sargsApplier_->hasSelectedFrom(currentRowInStripe_)) { + // A seek can start past the last selected row group in the prefetched stripe. + ++currentStripe_; + currentRowInStripe_ = 0; + reusePrefetchedStripe = false; + } + } + prefetchedStripe_.reset(); + if (!reusePrefetchedStripe) { + prepareNextStripe(); + } else if (currentStripe_ < lastStripe_) { + // An intervening seek to EOF may have cleared the row count. + rowsInCurrentStripe_ = currentStripeInfo_.number_of_rows(); + } + + if (currentStripe_ < lastStripe_) { // get writer timezone info from stripe footer to help understand timestamp values. const Timezone& writerTimezone = currentStripeFooter_.has_writer_timezone() @@ -1396,7 +1440,7 @@ namespace orc { markEndOfFile(); return false; } - if (currentRowInStripe_ == 0) { + if (!isCurrentStripeInited()) { startNextStripe(); } uint64_t rowsToRead = @@ -1861,6 +1905,13 @@ namespace orc { // PASS } + void RowReader::tryPrefetchIO() { + // Keep the RowReader vtable unchanged. + if (auto* impl = dynamic_cast(this)) { + impl->tryPrefetchIO(); + } + } + Reader::~Reader() { // PASS } diff --git a/c++/src/Reader.hh b/c++/src/Reader.hh index 289e467930..78d775ca2a 100644 --- a/c++/src/Reader.hh +++ b/c++/src/Reader.hh @@ -29,6 +29,7 @@ #include "io/Cache.hh" #include "sargs/SargsApplier.hh" +#include #include namespace orc { @@ -171,6 +172,11 @@ namespace orc { proto::StripeInformation currentStripeInfo_; proto::StripeFooter currentStripeFooter_; std::unique_ptr reader_; + struct PrefetchedStripe { + uint64_t firstCandidate; + uint64_t selected; + }; + std::optional prefetchedStripe_; // stripe indices that whose entire I/O ranges have been fully cached. std::unordered_set fullyCachedStripes_; @@ -178,6 +184,7 @@ namespace orc { bool useTightNumericVector_; bool throwOnSchemaEvolutionOverflow_; // internal methods + void prepareNextStripe(); void startNextStripe(); inline void markEndOfFile(); @@ -217,7 +224,7 @@ namespace orc { // whether the current stripe is initialized inline bool isCurrentStripeInited() const { - return currentStripe_ == processingStripe_; + return reader_ && currentStripe_ == processingStripe_; } /** @@ -248,6 +255,8 @@ namespace orc { std::unique_ptr createRowBatch(uint64_t size) const override; + void tryPrefetchIO(); + bool next(ColumnVectorBatch& data) override; CompressionKind getCompression() const; diff --git a/c++/test/TestReader.cc b/c++/test/TestReader.cc index ee4762a876..26c82758aa 100644 --- a/c++/test/TestReader.cc +++ b/c++/test/TestReader.cc @@ -1138,6 +1138,198 @@ namespace orc { } }; + class DeferredIOCountingInputStream final : public IOCountingInputStream { + public: + using IOCountingInputStream::IOCountingInputStream; + + std::vector submittedReads; + uint64_t asyncReadsCompleted = 0; + + std::future readAsync(void* buf, uint64_t length, uint64_t offset) override { + submittedReads.emplace_back(offset, length); + return std::async(std::launch::deferred, [this, buf, length, offset] { + read(buf, length, offset); + ++asyncReadsCompleted; + }); + } + }; + + TEST(TestAsyncPrefetch, testTryPrefetchIOBeforeNext) { + MemoryOutputStream memStream(DEFAULT_MEM_STREAM_SIZE); + std::ignore = writeSampleData(memStream); + for (bool seekBeforeNext : {false, true}) { + SCOPED_TRACE(seekBeforeNext); + auto input = std::make_unique( + std::make_unique(memStream.getData(), memStream.getLength())); + auto* counting = input.get(); + auto reader = createReader(std::move(input), {}); + ASSERT_GE(reader->getNumberOfStripes(), 2UL); + const auto stripe = reader->getStripe(1); + const auto firstRow = reader->getStripe(0)->getNumberOfRows(); + auto rowReader = reader->createRowReader(RowReaderOptions{} + .range(stripe->getOffset(), stripe->getLength()) + .includeTypes({1}) + .setEnableAsyncPrefetch(true) + .setSmallStripeLookAheadLimit(0)); + + rowReader->tryPrefetchIO(); + const auto submitted = counting->submittedReads.size(); + ASSERT_GT(submitted, 0UL); + EXPECT_EQ(counting->asyncReadsCompleted, 0UL); + rowReader->tryPrefetchIO(); + EXPECT_EQ(counting->submittedReads.size(), submitted); + + if (seekBeforeNext) { + rowReader->seekToRow(firstRow); + // Seeking may load row indexes in addition to the already-prefetched data. + for (size_t i = submitted; i < counting->submittedReads.size(); ++i) { + const auto& range = counting->submittedReads[i]; + EXPECT_LE(range.offset + range.length, stripe->getOffset() + stripe->getIndexLength()); + } + } + const auto submittedBeforeNext = counting->submittedReads.size(); + auto batch = rowReader->createRowBatch(stripe->getNumberOfRows()); + ASSERT_TRUE(rowReader->next(*batch)); + ASSERT_EQ(batch->numElements, stripe->getNumberOfRows()); + const auto& ids = + static_cast(*static_cast(*batch).fields[0]); + for (uint64_t row = 0; row < batch->numElements; ++row) { + EXPECT_EQ(ids.data[row], static_cast(firstRow + row)); + } + EXPECT_FALSE(rowReader->next(*batch)); + EXPECT_EQ(counting->submittedReads.size(), submittedBeforeNext); + + const auto readsAtEof = counting->getReadCount(); + rowReader->tryPrefetchIO(); + EXPECT_EQ(counting->submittedReads.size(), submittedBeforeNext); + EXPECT_EQ(counting->getReadCount(), readsAtEof); + } + } + + TEST(TestAsyncPrefetch, testTryPrefetchIOAcrossStripes) { + MemoryOutputStream memStream(DEFAULT_MEM_STREAM_SIZE); + const auto totalRows = writeSampleData(memStream); + for (const auto& [enabled, lookAhead] : + {std::pair{false, 0UL}, std::pair{true, 0UL}, std::pair{true, 2UL}}) { + SCOPED_TRACE(enabled); + SCOPED_TRACE(lookAhead); + auto input = std::make_unique( + std::make_unique(memStream.getData(), memStream.getLength())); + auto* counting = input.get(); + auto reader = createReader(std::move(input), {}); + ASSERT_GE(reader->getNumberOfStripes(), 2UL); + auto rowReader = reader->createRowReader(RowReaderOptions{} + .includeTypes({1}) + .setEnableAsyncPrefetch(enabled) + .setSmallStripeLookAheadLimit(lookAhead)); + auto firstBatch = rowReader->createRowBatch(1); + uint64_t firstRow = 0; + for (uint64_t stripe = 0; stripe < reader->getNumberOfStripes(); ++stripe) { + SCOPED_TRACE(stripe); + const auto before = counting->submittedReads.size(); + const auto readsBefore = counting->getReadCount(); + rowReader->tryPrefetchIO(); + const auto after = counting->submittedReads.size(); + if (enabled) { + if (lookAhead == 0 || stripe == 0) { + EXPECT_GT(after, before); + } + // The previous stripe can have prefetched this stripe's footer. + EXPECT_LE(counting->asyncReadsCompleted, before); + } else { + EXPECT_EQ(after, before); + EXPECT_EQ(counting->getReadCount(), readsBefore); + } + rowReader->tryPrefetchIO(); + EXPECT_EQ(counting->submittedReads.size(), after); + + ASSERT_TRUE(rowReader->next(*firstBatch)); + ASSERT_EQ(firstBatch->numElements, 1UL); + EXPECT_EQ(rowReader->getRowNumber(), firstRow); + EXPECT_EQ(counting->submittedReads.size(), after); + + const auto rowsInStripe = reader->getStripe(stripe)->getNumberOfRows(); + ASSERT_GT(rowsInStripe, 1UL); + const auto readsInsideStripe = counting->getReadCount(); + rowReader->tryPrefetchIO(); + EXPECT_EQ(counting->submittedReads.size(), after); + EXPECT_EQ(counting->getReadCount(), readsInsideStripe); + + auto remaining = rowReader->createRowBatch(rowsInStripe - 1); + ASSERT_TRUE(rowReader->next(*remaining)); + ASSERT_EQ(remaining->numElements, rowsInStripe - 1); + EXPECT_EQ(rowReader->getRowNumber(), firstRow + 1); + firstRow += rowsInStripe; + } + EXPECT_EQ(firstRow, totalRows); + EXPECT_FALSE(rowReader->next(*firstBatch)); + } + } + + TEST(TestAsyncPrefetch, testSeekAfterPrefetchWithPredicate) { + MemoryOutputStream memStream(DEFAULT_MEM_STREAM_SIZE); + std::ignore = writeSampleData(memStream); + auto reader = createReader( + std::make_unique(memStream.getData(), memStream.getLength()), {}); + ASSERT_GE(reader->getNumberOfStripes(), 2UL); + const auto firstSelectedRow = reader->getStripe(0)->getNumberOfRows(); + auto sarg = SearchArgumentFactory::newBuilder() + ->startNot() + .lessThan("id", PredicateDataType::LONG, + Literal(static_cast(firstSelectedRow))) + .end() + .build(); + auto rowReader = reader->createRowReader(RowReaderOptions{} + .includeTypes({1}) + .searchArgument(std::move(sarg)) + .setEnableAsyncPrefetch(true)); + + rowReader->tryPrefetchIO(); + rowReader->seekToRow(0); + auto batch = rowReader->createRowBatch(10); + ASSERT_TRUE(rowReader->next(*batch)); + EXPECT_EQ(rowReader->getRowNumber(), firstSelectedRow); + } + + TEST(TestAsyncPrefetch, testSeekBeforePrefetchedStripeCandidates) { + MemoryOutputStream memStream(DEFAULT_MEM_STREAM_SIZE); + const auto totalRows = writeSampleData(memStream); + auto input = std::make_unique( + std::make_unique(memStream.getData(), memStream.getLength())); + auto* counting = input.get(); + auto reader = createReader(std::move(input), {}); + ASSERT_GE(reader->getNumberOfStripes(), 3UL); + const auto firstStripeRows = reader->getStripe(0)->getNumberOfRows(); + const auto skippedStripeRows = reader->getStripe(1)->getNumberOfRows(); + const auto thirdStripeFirstRow = firstStripeRows + skippedStripeRows; + auto sarg = + SearchArgumentFactory::newBuilder() + ->startOr() + .lessThan("id", PredicateDataType::LONG, Literal(static_cast(firstStripeRows))) + .startNot() + .lessThan("id", PredicateDataType::LONG, + Literal(static_cast(thirdStripeFirstRow))) + .end() + .end() + .build(); + auto rowReader = reader->createRowReader(RowReaderOptions{} + .includeTypes({1}) + .searchArgument(std::move(sarg)) + .setEnableAsyncPrefetch(true) + .setSmallStripeLookAheadLimit(0)); + auto batch = rowReader->createRowBatch(firstStripeRows); + ASSERT_TRUE(rowReader->next(*batch)); + ASSERT_EQ(batch->numElements, firstStripeRows); + const auto submitted = counting->submittedReads.size(); + rowReader->tryPrefetchIO(); + ASSERT_GT(counting->submittedReads.size(), submitted); + + rowReader->seekToRow(0); + ASSERT_TRUE(rowReader->next(*batch)); + EXPECT_EQ(rowReader->getRowNumber(), 0UL); + EXPECT_EQ(batch->numElements + readAllRows(*rowReader), totalRows - skippedStripeRows); + } + TEST(TestSmallStripeLookAhead, testIOCountWithDifferentLimits) { MemoryOutputStream memStream(DEFAULT_MEM_STREAM_SIZE); uint64_t totalRows = writeSampleData(memStream, /*stripeSize*/ 1024, /*rowsPerStripe*/ 200);