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
9 changes: 9 additions & 0 deletions c++/include/orc/Reader.hh
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,15 @@ namespace orc {
*/
virtual std::unique_ptr<ColumnVectorBatch> 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
Expand Down
61 changes: 56 additions & 5 deletions c++/src/Reader.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -1396,7 +1440,7 @@ namespace orc {
markEndOfFile();
return false;
}
if (currentRowInStripe_ == 0) {
if (!isCurrentStripeInited()) {
startNextStripe();
}
uint64_t rowsToRead =
Expand Down Expand Up @@ -1861,6 +1905,13 @@ namespace orc {
// PASS
}

void RowReader::tryPrefetchIO() {
// Keep the RowReader vtable unchanged.
if (auto* impl = dynamic_cast<RowReaderImpl*>(this)) {
impl->tryPrefetchIO();
}
}

Reader::~Reader() {
// PASS
}
Expand Down
11 changes: 10 additions & 1 deletion c++/src/Reader.hh
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
#include "io/Cache.hh"
#include "sargs/SargsApplier.hh"

#include <optional>
#include <unordered_set>

namespace orc {
Expand Down Expand Up @@ -171,13 +172,19 @@ namespace orc {
proto::StripeInformation currentStripeInfo_;
proto::StripeFooter currentStripeFooter_;
std::unique_ptr<ColumnReader> reader_;
struct PrefetchedStripe {
uint64_t firstCandidate;
uint64_t selected;
};
std::optional<PrefetchedStripe> prefetchedStripe_;
// stripe indices that whose entire I/O ranges have been fully cached.
std::unordered_set<uint64_t> fullyCachedStripes_;

bool enableEncodedBlock_;
bool useTightNumericVector_;
bool throwOnSchemaEvolutionOverflow_;
// internal methods
void prepareNextStripe();
void startNextStripe();
inline void markEndOfFile();

Expand Down Expand Up @@ -217,7 +224,7 @@ namespace orc {

// whether the current stripe is initialized
inline bool isCurrentStripeInited() const {
return currentStripe_ == processingStripe_;
return reader_ && currentStripe_ == processingStripe_;
}

/**
Expand Down Expand Up @@ -248,6 +255,8 @@ namespace orc {

std::unique_ptr<ColumnVectorBatch> createRowBatch(uint64_t size) const override;

void tryPrefetchIO();

bool next(ColumnVectorBatch& data) override;

CompressionKind getCompression() const;
Expand Down
192 changes: 192 additions & 0 deletions c++/test/TestReader.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1138,6 +1138,198 @@ namespace orc {
}
};

class DeferredIOCountingInputStream final : public IOCountingInputStream {
public:
using IOCountingInputStream::IOCountingInputStream;

std::vector<ReadRange> submittedReads;
uint64_t asyncReadsCompleted = 0;

std::future<void> 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<DeferredIOCountingInputStream>(
std::make_unique<MemoryInputStream>(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<LongVectorBatch&>(*static_cast<StructVectorBatch&>(*batch).fields[0]);
for (uint64_t row = 0; row < batch->numElements; ++row) {
EXPECT_EQ(ids.data[row], static_cast<int64_t>(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<DeferredIOCountingInputStream>(
std::make_unique<MemoryInputStream>(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<MemoryInputStream>(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<int64_t>(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<DeferredIOCountingInputStream>(
std::make_unique<MemoryInputStream>(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<int64_t>(firstStripeRows)))
.startNot()
.lessThan("id", PredicateDataType::LONG,
Literal(static_cast<int64_t>(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);
Expand Down
Loading