From 0d7f0507fe2583f54f9e9af9218c1787133bb0c5 Mon Sep 17 00:00:00 2001 From: ArrayRecord Team Date: Fri, 20 Nov 2026 05:50:14 -0800 Subject: [PATCH] Pass the chunk length to `NewReader()` when reading chunks. Chunk reads create a child reader with `NewReader(offset)` and read the chunk with `MaskedReader`. They now use `NewReader(offset, length_hint)` with the length being read, so that `riegeli::GcsReader` sends one request for exactly this range instead of an open-ended request which is cancelled after the chunk is read. Sources which do not use the hint, e.g. `FileReader`, `FdReader`, and `StringReader`, read as before. With `index_storage_option:offloaded`, each chunk offset lookup reads the footer chunk with `DefaultChunkReader`. Its length, measured when the footer is read by `Initialize()`, is passed too, so these lookups no longer send an open-ended request each which is cancelled before the footer padding and postscript are read. PiperOrigin-RevId: 1026412932 --- cpp/BUILD | 2 + cpp/array_record_reader.cc | 39 +++- cpp/array_record_reader_test.cc | 376 ++++++++++++++++++++++++++++++++ 3 files changed, 406 insertions(+), 11 deletions(-) diff --git a/cpp/BUILD b/cpp/BUILD index 977d77b..db27ab6 100644 --- a/cpp/BUILD +++ b/cpp/BUILD @@ -295,9 +295,11 @@ cc_test( ":layout_cc_proto", ":test_utils", ":thread_pool", + "@abseil-cpp//absl/base:core_headers", "@abseil-cpp//absl/functional:function_ref", "@abseil-cpp//absl/status", "@abseil-cpp//absl/strings", + "@abseil-cpp//absl/synchronization", "@googletest//:gtest_main", "@riegeli//riegeli/base:initializer", "@riegeli//riegeli/base:types", diff --git a/cpp/array_record_reader.cc b/cpp/array_record_reader.cc index 524bed1..bb7a183 100644 --- a/cpp/array_record_reader.cc +++ b/cpp/array_record_reader.cc @@ -120,15 +120,21 @@ class ArrayChunkOffset : public ChunkOffset { class OffloadedChunkOffset : public ChunkOffset { public: + // `footer_chunk_length` is the distance from `footer_offset` to the end of + // the footer chunk, as reported by `riegeli::DefaultChunkReader::pos()`. OffloadedChunkOffset(ArrayRecordReaderBase* base_reader, - uint64_t footer_offset, uint64_t num_chunks) + uint64_t footer_offset, uint64_t footer_chunk_length, + uint64_t num_chunks) : base_reader_(base_reader), footer_offset_(footer_offset), + footer_chunk_length_(footer_chunk_length), num_chunks_(num_chunks) {} uint64_t operator[](size_t idx) const override { auto backing_reader = base_reader_->get_backing_reader(); - auto reader = backing_reader->NewReader(footer_offset_); + // `riegeli::DefaultChunkReader` reads up to the end of the footer chunk. + auto reader = + backing_reader->NewReader(footer_offset_, footer_chunk_length_); auto chunk_reader = riegeli::DefaultChunkReader<>(reader.get()); Chunk chunk; ChunkDecoder footer_decoder; @@ -150,6 +156,7 @@ class OffloadedChunkOffset : public ChunkOffset { private: ArrayRecordReaderBase* base_reader_; uint64_t footer_offset_; + uint64_t footer_chunk_length_; uint64_t num_chunks_; }; @@ -275,13 +282,17 @@ ArrayRecordReaderBase& ArrayRecordReaderBase::operator=( // evaluated variables for random access are all initialized. Therefore it's // safe to access the reader from multiple threads later on, even though the // methods wasn't const. -ChunkDecoder ReadChunk(Reader& reader, size_t pos, size_t len) { +// +// If `chunk_length` is not `nullptr`, it is set to the distance from `pos` to +// the end of the chunk read. +ChunkDecoder ReadChunk(Reader& reader, size_t pos, size_t len, + uint64_t* chunk_length = nullptr) { ChunkDecoder decoder; if (!reader.ok()) { decoder.Fail(reader.status()); return decoder; } - MaskedReader masked_reader(reader.NewReader(pos), len); + MaskedReader masked_reader(reader.NewReader(pos, len), len); if (!masked_reader.ok()) { decoder.Fail(masked_reader.status()); return decoder; @@ -292,6 +303,7 @@ ChunkDecoder ReadChunk(Reader& reader, size_t pos, size_t len) { decoder.Fail(chunk_reader.status()); return decoder; } + if (chunk_length != nullptr) *chunk_length = chunk_reader.pos() - pos; decoder.Decode(chunk); return decoder; } @@ -332,6 +344,7 @@ void ArrayRecordReaderBase::Initialize() { AR_ENDO_TASK("Reading ArrayRecord footer"); RiegeliFooterMetadata footer_metadata; ChunkDecoder footer_decoder; + uint64_t footer_chunk_length = 0; { AR_ENDO_SCOPE("Reading postscript and footer chunk"); if (!reader->SupportsRandomAccess()) { @@ -390,7 +403,8 @@ void ArrayRecordReaderBase::Initialize() { ReadChunk((prefetch_length > 0 && footer_offset >= prefetch_offset) ? prefetched_reader : *reader, - footer_offset, size - kRiegeliBlockSize - footer_offset); + footer_offset, size - kRiegeliBlockSize - footer_offset, + &footer_chunk_length); if (!footer_decoder.ReadRecord(footer_metadata)) { Fail(Annotate(footer_decoder.status(), @@ -446,7 +460,7 @@ void ArrayRecordReaderBase::Initialize() { } break; case Options::IndexStorageOption::kOffloaded: state_->chunk_offsets = std::make_unique( - this, state_->footer_offset, num_chunks); + this, state_->footer_offset, footer_chunk_length, num_chunks); break; } @@ -511,7 +525,8 @@ absl::Status ArrayRecordReaderBase::ParallelReadRecords( { AR_ENDO_SCOPE("MaskedReader"); masked_reader = MaskedReader( - reader->NewReader((*state_->chunk_offsets)[chunk_idx_start]), + reader->NewReader((*state_->chunk_offsets)[chunk_idx_start], + buf_len), buf_len); } for (uint64_t chunk_idx = chunk_idx_start; chunk_idx <= last_chunk_idx; @@ -590,7 +605,8 @@ absl::Status ArrayRecordReaderBase::ParallelReadRecordsInRange( { AR_ENDO_SCOPE("MaskedReader"); masked_reader = MaskedReader( - reader->NewReader((*state_->chunk_offsets)[chunk_idx_start]), + reader->NewReader((*state_->chunk_offsets)[chunk_idx_start], + buf_len), buf_len); } for (uint64_t chunk_idx = chunk_idx_start; chunk_idx <= last_chunk_idx; @@ -712,7 +728,8 @@ absl::Status ArrayRecordReaderBase::ParallelReadRecordsWithIndices( { AR_ENDO_SCOPE("MaskedReader"); masked_reader = MaskedReader( - reader->NewReader((*state_->chunk_offsets)[buffer_chunks[0]]), + reader->NewReader((*state_->chunk_offsets)[buffer_chunks[0]], + buf_len), buf_len); } for (auto chunk_idx : buffer_chunks) { @@ -892,8 +909,8 @@ bool ArrayRecordReaderBase::ReadAheadFromBuffer(uint64_t buffer_idx) { MaskedReader masked_reader(riegeli::kClosed); { AR_ENDO_SCOPE("MaskedReader"); - masked_reader = - MaskedReader(reader->NewReader(chunk_offsets.front()), buffer_len); + masked_reader = MaskedReader( + reader->NewReader(chunk_offsets.front(), buffer_len), buffer_len); } if (!masked_reader.ok()) { for (auto& decoder : decoders) { diff --git a/cpp/array_record_reader_test.cc b/cpp/array_record_reader_test.cc index 1a932ad..8560f34 100644 --- a/cpp/array_record_reader_test.cc +++ b/cpp/array_record_reader_test.cc @@ -26,10 +26,13 @@ limitations under the License. #include #include +#include "gmock/gmock.h" #include "gtest/gtest.h" +#include "absl/base/thread_annotations.h" #include "absl/functional/function_ref.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" +#include "absl/synchronization/mutex.h" #include "cpp/array_record_writer.h" #include "cpp/common.h" #include "cpp/layout.pb.h" @@ -787,5 +790,378 @@ TEST(ArrayRecordReaderTest, FooterEndsAtExactBlockBoundaryWithoutPadding) { } } +// Records the ranges hinted to `NewReader()`, possibly from multiple threads. +class HintLog { + public: + using Hint = std::pair; + + void Record(riegeli::Position pos, size_t length) { + absl::MutexLock lock(mutex_); + hints_.emplace_back(pos, length); + } + + // Returns the ranges recorded since the previous call. + std::vector Take() { + absl::MutexLock lock(mutex_); + return std::exchange(hints_, {}); + } + + private: + absl::Mutex mutex_; + std::vector hints_ ABSL_GUARDED_BY(mutex_); +}; + +// Reads from a string, and records the ranges hinted to `NewReader()`. +class LengthHintRecordingReader : public riegeli::Reader { + public: + LengthHintRecordingReader(absl::string_view data, HintLog* log, + riegeli::Position initial_pos = 0) + : data_(data), log_(log) { + set_limit_pos(initial_pos); + } + + bool SupportsRandomAccess() override { return true; } + bool SupportsNewReader() override { return true; } + + protected: + bool PullSlow(size_t min_length, size_t recommended_length) override { + if (limit_pos() == data_.size()) return false; + set_buffer(data_.data() + pos(), data_.size() - pos()); + set_limit_pos(data_.size()); + return available() >= min_length; + } + + bool SeekSlow(riegeli::Position new_pos) override { + set_buffer(); + set_limit_pos(std::min(new_pos, data_.size())); + return new_pos <= data_.size(); + } + + std::optional SizeImpl() override { return data_.size(); } + + std::unique_ptr NewReaderImpl( + riegeli::Position initial_pos) override { + ADD_FAILURE() << "NewReader(" << initial_pos << ") without a length hint"; + return std::make_unique( + data_, log_, std::min(initial_pos, data_.size())); + } + + std::unique_ptr NewReaderWithLengthHintImpl( + riegeli::Position initial_pos, riegeli::Position length_hint) override { + log_->Record(initial_pos, length_hint); + // Reading past the hinted range fails, so that a hint which is too short + // is detected. + const riegeli::Position start = + std::min(initial_pos, data_.size()); + const size_t end = + start + std::min(length_hint, data_.size() - start); + return std::make_unique(data_.substr(0, end), + log_, start); + } + + private: + absl::string_view data_; + HintLog* log_; +}; + +class ChunkLengthDeclarationTest : public testing::Test { + protected: + using Hint = HintLog::Hint; + + void SetUp() override { + auto writer = ArrayRecordWriter( + riegeli::Maker(&encoded_), + ArrayRecordWriterBase::Options().set_group_size(1).set_uncompressed(), + nullptr); + for (int i = 0; i < kNumRecords; ++i) { + ASSERT_TRUE(writer.WriteRecord(Record(i))); + } + ASSERT_TRUE(writer.Close()); + + // With a group size of 1, each record is in its own chunk. + auto reference = + ArrayRecordReader(riegeli::Maker(encoded_), + ArrayRecordReaderBase::Options(), nullptr); + ASSERT_TRUE(reference.ok()) << reference.status(); + for (int i = 0; i < kNumRecords; ++i) { + chunks_.emplace_back( + reference.ChunkStartOffset(i), + reference.ChunkEndOffset(i) - reference.ChunkStartOffset(i)); + } + footer_offset_ = reference.ChunkEndOffset(kNumRecords - 1); + ASSERT_TRUE(reference.Close()) << reference.status(); + + riegeli::StringReader<> src(encoded_); + ASSERT_TRUE(src.Seek(footer_offset_)) << src.status(); + riegeli::DefaultChunkReader<> footer_reader(&src); + riegeli::Chunk footer; + ASSERT_TRUE(footer_reader.ReadChunk(footer)) << footer_reader.status(); + footer_chunk_ = Hint(footer_offset_, footer_reader.pos() - footer_offset_); + } + + static std::string Record(uint64_t i) { + return std::string(1000, static_cast('a' + i % 26)); + } + + // Each chunk group consists of a single chunk. + static ArrayRecordReaderBase::Options ReaderOptions() { + return ArrayRecordReaderBase::Options().set_readahead_buffer_size(1); + } + + auto OpenReader(const ArrayRecordReaderBase::Options& options, + ARThreadPool* pool) { + return ArrayRecordReader( + riegeli::Maker(encoded_, &log_), options, + pool); + } + + Hint Postscript() const { + return Hint(encoded_.size() - kBlockSize, kBlockSize); + } + + // The range between the footer and the postscript. + Hint FooterBlocks() const { + return Hint(footer_offset_, encoded_.size() - kBlockSize - footer_offset_); + } + + static constexpr int kNumRecords = 10; + static constexpr size_t kBlockSize = size_t{1} << 16; + std::string encoded_; + std::vector chunks_; + riegeli::Position footer_offset_ = 0; + Hint footer_chunk_; + HintLog log_; +}; + +TEST_F(ChunkLengthDeclarationTest, InitializeWithoutFooterPrefetch) { + auto reader = OpenReader(ReaderOptions().set_footer_prefetch_bytes(0), + /*pool=*/nullptr); + ASSERT_TRUE(reader.ok()) << reader.status(); + // Declaring the postscript, which ends the file, bounds nothing but costs + // nothing either. + EXPECT_THAT(log_.Take(), testing::ElementsAre(Postscript(), FooterBlocks())); + EXPECT_TRUE(reader.Close()) << reader.status(); +} + +TEST_F(ChunkLengthDeclarationTest, InitializeWithFooterPrefetch) { + // The prefetched tail is read with a single read call, and the postscript + // and footer are then read from memory. + auto reader = OpenReader(ReaderOptions(), /*pool=*/nullptr); + ASSERT_TRUE(reader.ok()) << reader.status(); + EXPECT_THAT(log_.Take(), testing::IsEmpty()); + EXPECT_TRUE(reader.Close()) << reader.status(); +} + +TEST_F(ChunkLengthDeclarationTest, ParallelReadRecords) { + auto reader = OpenReader(ReaderOptions(), ArrayRecordGlobalPool()); + ASSERT_TRUE(reader.ok()) << reader.status(); + log_.Take(); + EXPECT_TRUE( + reader + .ParallelReadRecords([&](uint64_t index, absl::string_view record) { + EXPECT_EQ(record, Record(index)); + return absl::OkStatus(); + }) + .ok()); + EXPECT_THAT(log_.Take(), testing::UnorderedElementsAreArray(chunks_)); + EXPECT_TRUE(reader.Close()) << reader.status(); +} + +TEST_F(ChunkLengthDeclarationTest, ParallelReadRecordsInRange) { + auto reader = OpenReader(ReaderOptions(), ArrayRecordGlobalPool()); + ASSERT_TRUE(reader.ok()) << reader.status(); + log_.Take(); + EXPECT_TRUE(reader + .ParallelReadRecordsInRange( + 2, 5, + [&](uint64_t index, absl::string_view record) { + EXPECT_EQ(record, Record(index)); + return absl::OkStatus(); + }) + .ok()); + EXPECT_THAT(log_.Take(), testing::UnorderedElementsAre(chunks_[2], chunks_[3], + chunks_[4])); + EXPECT_TRUE(reader.Close()) << reader.status(); +} + +TEST_F(ChunkLengthDeclarationTest, ParallelReadRecordsWithIndices) { + auto reader = OpenReader(ReaderOptions(), ArrayRecordGlobalPool()); + ASSERT_TRUE(reader.ok()) << reader.status(); + log_.Take(); + const std::vector indices = {7, 1}; + EXPECT_TRUE(reader + .ParallelReadRecordsWithIndices( + indices, + [&](uint64_t indices_index, absl::string_view record) { + EXPECT_EQ(record, Record(indices[indices_index])); + return absl::OkStatus(); + }) + .ok()); + EXPECT_THAT(log_.Take(), + testing::UnorderedElementsAre(chunks_[1], chunks_[7])); + EXPECT_TRUE(reader.Close()) << reader.status(); +} + +TEST_F(ChunkLengthDeclarationTest, ReadRecordWithReadahead) { + auto reader = OpenReader(ReaderOptions(), ArrayRecordGlobalPool()); + ASSERT_TRUE(reader.ok()) << reader.status(); + log_.Take(); + for (int i = 0; i < kNumRecords; ++i) { + absl::string_view record; + ASSERT_TRUE(reader.ReadRecord(&record)) << reader.status(); + EXPECT_EQ(record, Record(i)); + } + EXPECT_THAT(log_.Take(), testing::UnorderedElementsAreArray(chunks_)); + EXPECT_TRUE(reader.Close()) << reader.status(); +} + +TEST_F(ChunkLengthDeclarationTest, ReadRecordWithoutReadahead) { + auto reader = OpenReader(ReaderOptions(), /*pool=*/nullptr); + ASSERT_TRUE(reader.ok()) << reader.status(); + log_.Take(); + ASSERT_TRUE(reader.SeekRecord(5)); + absl::string_view record; + ASSERT_TRUE(reader.ReadRecord(&record)) << reader.status(); + EXPECT_EQ(record, Record(5)); + EXPECT_THAT(log_.Take(), testing::ElementsAre(chunks_[5])); + EXPECT_TRUE(reader.Close()) << reader.status(); +} + +TEST_F(ChunkLengthDeclarationTest, OffloadedIndexDeclaresFooterChunk) { + // The footer chunk is followed by padding to the postscript. + ASSERT_LT(footer_chunk_.first + footer_chunk_.second, + encoded_.size() - kBlockSize); + auto reader = + OpenReader(ReaderOptions() + .set_index_storage_option(IndexStorageOption::kOffloaded) + .set_footer_prefetch_bytes(0), + /*pool=*/nullptr); + ASSERT_TRUE(reader.ok()) << reader.status(); + const std::vector initialize_hints = log_.Take(); + ASSERT_GE(initialize_hints.size(), 2u); + EXPECT_EQ(initialize_hints[0], Postscript()); + EXPECT_EQ(initialize_hints[1], FooterBlocks()); + for (size_t i = 2; i < initialize_hints.size(); ++i) { + EXPECT_EQ(initialize_hints[i], footer_chunk_) << "at hint " << i; + } + + ASSERT_TRUE(reader.SeekRecord(5)); + absl::string_view record; + ASSERT_TRUE(reader.ReadRecord(&record)) << reader.status(); + EXPECT_EQ(record, Record(5)); + // Looking up the start and the end of the chunk reads the footer twice. + EXPECT_THAT(log_.Take(), + testing::ElementsAre(footer_chunk_, footer_chunk_, chunks_[5])); + EXPECT_TRUE(reader.Close()) << reader.status(); +} + +TEST_F(ChunkLengthDeclarationTest, + InitializeWhenFooterIsNotPrefetchedDeclaresFooterBlocks) { + // Only the postscript block is prefetched, and the footer is read from the + // source. + auto reader = + OpenReader(ReaderOptions().set_footer_prefetch_bytes(kBlockSize), + /*pool=*/nullptr); + ASSERT_TRUE(reader.ok()) << reader.status(); + EXPECT_THAT(log_.Take(), testing::ElementsAre(FooterBlocks())); + EXPECT_TRUE(reader.Close()) << reader.status(); +} + +TEST_F(ChunkLengthDeclarationTest, ChunkGroupsDeclareCombinedRanges) { + const size_t three_chunks_length = + chunks_[2].first + chunks_[2].second - chunks_[0].first; + auto group = [&](size_t first, size_t last) { + return Hint( + chunks_[first].first, + chunks_[last].first + chunks_[last].second - chunks_[first].first); + }; + auto reader = + OpenReader(ReaderOptions().set_readahead_buffer_size(three_chunks_length), + ArrayRecordGlobalPool()); + ASSERT_TRUE(reader.ok()) << reader.status(); + log_.Take(); + EXPECT_TRUE( + reader + .ParallelReadRecords([&](uint64_t index, absl::string_view record) { + EXPECT_EQ(record, Record(index)); + return absl::OkStatus(); + }) + .ok()); + EXPECT_THAT(log_.Take(), + testing::UnorderedElementsAre(group(0, 2), group(3, 5), + group(6, 8), group(9, 9))); + EXPECT_TRUE(reader.Close()) << reader.status(); +} + +TEST(ChunkLengthDeclarationLargeTest, ChunksSpanningBlockBoundaries) { + std::string encoded; + const std::string large_record(100000, 'x'); + { + auto writer = ArrayRecordWriter( + riegeli::Maker(&encoded), + ArrayRecordWriterBase::Options().set_group_size(1).set_uncompressed(), + nullptr); + for (int i = 0; i < 3; ++i) ASSERT_TRUE(writer.WriteRecord(large_record)); + ASSERT_TRUE(writer.Close()); + } + // Each record is in its own chunk, which is longer than a block and thus + // includes block headers. + using Hint = HintLog::Hint; + std::vector chunks; + Hint footer_chunk; + { + auto reference = + ArrayRecordReader(riegeli::Maker(encoded), + ArrayRecordReaderBase::Options(), nullptr); + ASSERT_TRUE(reference.ok()) << reference.status(); + for (int i = 0; i < 3; ++i) { + chunks.emplace_back( + reference.ChunkStartOffset(i), + reference.ChunkEndOffset(i) - reference.ChunkStartOffset(i)); + EXPECT_GT(chunks.back().second, size_t{1} << 16); + } + const riegeli::Position footer_offset = reference.ChunkEndOffset(2); + ASSERT_TRUE(reference.Close()) << reference.status(); + + riegeli::StringReader<> src(encoded); + ASSERT_TRUE(src.Seek(footer_offset)) << src.status(); + riegeli::DefaultChunkReader<> footer_reader(&src); + riegeli::Chunk footer; + ASSERT_TRUE(footer_reader.ReadChunk(footer)) << footer_reader.status(); + footer_chunk = Hint(footer_offset, footer_reader.pos() - footer_offset); + } + for (const IndexStorageOption index_storage_option : + {IndexStorageOption::kInMemory, IndexStorageOption::kOffloaded}) { + HintLog log; + auto reader = ArrayRecordReader( + riegeli::Maker(encoded, &log), + ArrayRecordReaderBase::Options() + .set_readahead_buffer_size(1) + .set_index_storage_option(index_storage_option) + .set_footer_prefetch_bytes(0), + /*pool=*/nullptr); + ASSERT_TRUE(reader.ok()) << reader.status(); + log.Take(); + for (uint64_t i : {1, 0, 2}) { + ASSERT_TRUE(reader.SeekRecord(i)); + absl::string_view record; + ASSERT_TRUE(reader.ReadRecord(&record)) << reader.status(); + EXPECT_EQ(record, large_record); + } + if (index_storage_option == IndexStorageOption::kInMemory) { + EXPECT_THAT(log.Take(), + testing::ElementsAre(chunks[1], chunks[0], chunks[2])); + } else { + // Looking up the start and the end of a chunk reads the footer twice, + // except that the end of the last chunk is the footer offset. + EXPECT_THAT(log.Take(), + testing::ElementsAre(footer_chunk, footer_chunk, chunks[1], + footer_chunk, footer_chunk, chunks[0], + footer_chunk, chunks[2])); + } + EXPECT_TRUE(reader.Close()) << reader.status(); + } +} + } // namespace } // namespace array_record