diff --git a/cpp/src/parquet/column_reader.cc b/cpp/src/parquet/column_reader.cc index ce1a918e13e..7290aee5c62 100644 --- a/cpp/src/parquet/column_reader.cc +++ b/cpp/src/parquet/column_reader.cc @@ -634,83 +634,6 @@ std::unique_ptr PageReader::Open(std::shared_ptr s namespace { -/*************************** - * SkippableTypedDecoder * - ***************************/ - -/// Wrapper around a `TypedDecoder` pointer to skip values. -/// -/// Use a scratch buffer to decode values into that buffer. -/// This was migrated here from a historical implementation. -/// Ideally all decoders would implement a `Skip` functionality that would at best -/// avoid decoding, and at worst, decode without intermediary allocation. -/// -/// @todo GH-50453 -template -class SkippableTypedDecoder { - public: - using Decoder = TypedDecoder; - using T = typename Decoder::T; - - /// Size in bytes of a single value. - static constexpr int64_t kValueByteSize = type_traits::value_byte_size; - /// Batch size for reading and throwing away values during skip. - static constexpr int64_t kScratchValueCount = 1024; - /// Size in bytes of the scratch batch. - static constexpr int64_t kScratchByteSize = kScratchValueCount * kValueByteSize; - - explicit SkippableTypedDecoder(::arrow::MemoryPool* pool = nullptr) : pool_(pool) {} - - explicit SkippableTypedDecoder(Decoder* decoder) : decoder_(decoder) {} - - void SetDecoder(Decoder* decoder) { decoder_ = decoder; } - - const Decoder* get() const { return decoder_; } - - Decoder* get() { return decoder_; } - - const Decoder* operator->() const { return decoder_; } - - Decoder* operator->() { return decoder_; } - - explicit operator bool() const { return decoder_ != nullptr; } - - /// Skip the number of values in the decoder. - /// - /// Initialize reusable buffer to decode the values into before throwing them away. - int64_t Skip(int64_t num_values) { - EnsureScratch(); - - int64_t total_read = 0; - int iter_read = 0; - do { - static_assert(kScratchValueCount <= std::numeric_limits::max()); - const int batch_size = - static_cast(std::min(kScratchValueCount, num_values - total_read)); - - iter_read = get()->Decode(scratch_->mutable_data_as(), batch_size); - total_read += iter_read; - } while (iter_read > 0 && total_read < num_values); - - return total_read; - } - - private: - /// Scratch space to skip decode values that need skipping. - /// We actually do not need the whole shared_ptr machinery but it was historically - /// chosen for ease of use with ``AllocateBuffer`` and migrated here. - std::shared_ptr scratch_ = nullptr; - Decoder* decoder_ = nullptr; - ::arrow::MemoryPool* pool_ = nullptr; - - void EnsureScratch() { - if (this->scratch_ == nullptr) { - this->scratch_ = AllocateBuffer(pool_, kScratchByteSize); - } - ARROW_DCHECK_NE(this->scratch_, nullptr); - } -}; - /********************* * ValueSinkCursor * *********************/ @@ -1146,8 +1069,7 @@ class ColumnChunkReader { ColumnChunkReader(const ColumnDescriptor* descr, ::arrow::MemoryPool* pool, DefLevelDecoder def_levels_decoder, RepLevelDecoder rep_levels_decoder) - : current_decoder_(pool), - def_levels_decoder_(std::move(def_levels_decoder)), + : def_levels_decoder_(std::move(def_levels_decoder)), rep_levels_decoder_(std::move(rep_levels_decoder)), descr_(descr), pool_(pool) {} @@ -1155,7 +1077,7 @@ class ColumnChunkReader { void SetPageReader(std::unique_ptr reader) { current_page_ = nullptr; pager_ = std::move(reader); - current_decoder_.SetDecoder(nullptr); + current_decoder_ = nullptr; decoders_.clear(); new_dictionary_ = nullptr; current_encoding_ = Encoding::UNKNOWN; @@ -1201,7 +1123,7 @@ class ColumnChunkReader { /// Return the current decoder as a dict decoder if page is dictionary encoded DictDecoder* current_dict_decoder() { - return dynamic_cast*>(this->current_decoder_.get()); + return dynamic_cast*>(this->current_decoder_); } /// Return the dictionary decoder if a dictionary page was read since the last call. @@ -1221,7 +1143,7 @@ class ColumnChunkReader { int64_t Skip(int64_t num_values_to_skip); protected: - SkippableTypedDecoder current_decoder_; + TypedDecoder* current_decoder_ = nullptr; DefLevelDecoder def_levels_decoder_; RepLevelDecoder rep_levels_decoder_; const ColumnDescriptor* descr_; @@ -1367,7 +1289,7 @@ void ColumnChunkReader::ConfigureDictionary(const DictionaryPage* page) ParquetException::NYI("only plain dictionary encoding has been implemented"); } - current_decoder_.SetDecoder(decoders_[encoding].get()); + current_decoder_ = decoders_[encoding].get(); ARROW_DCHECK(current_decoder_); } @@ -1410,7 +1332,7 @@ void ColumnChunkReader::InitializeDataDecoder(const DataPage& page, auto it = decoders_.find(static_cast(encoding)); if (it != decoders_.end()) { ARROW_DCHECK(it->second.get() != nullptr); - current_decoder_.SetDecoder(it->second.get()); + current_decoder_ = it->second.get(); } else { switch (encoding) { case Encoding::PLAIN: @@ -1421,7 +1343,7 @@ void ColumnChunkReader::InitializeDataDecoder(const DataPage& page, case Encoding::DELTA_BYTE_ARRAY: case Encoding::DELTA_LENGTH_BYTE_ARRAY: { auto decoder = MakeTypedDecoder(encoding, descr_, pool_); - current_decoder_.SetDecoder(decoder.get()); + current_decoder_ = decoder.get(); decoders_[static_cast(encoding)] = std::move(decoder); break; } @@ -1472,7 +1394,7 @@ int64_t ColumnChunkReader::Skip(int64_t num_values_to_skip) { const int32_t non_null = AdvanceLevels(batch_size); // Skip the corresponding data values. - this->current_decoder_.Skip(non_null); + this->current_decoder_->Skip(non_null); this->MarkValuesAsConsumed(batch_size); values_to_skip -= batch_size; @@ -1978,9 +1900,7 @@ int64_t TypedRecordReader::SkipRecordsInBufferNonRepeated(int64_t num_re const int32_t skipped_records = narrow_min(num_records, remaining_records); const int64_t remaining_levels_pos = levels_position_ + skipped_records; - // We skipped the levels by incrementing 'levels_position_'. For values - // we do not have a buffer, so we need to read them and throw them away. - // First we need to figure out how many present/not-null values there are. + // Only present values advance the data decoder. const auto values_to_read = static_cast( CountLevels(def_levels() + levels_position_, remaining_levels_pos - levels_position_, this->max_def_level())); @@ -1989,8 +1909,6 @@ int64_t TypedRecordReader::SkipRecordsInBufferNonRepeated(int64_t num_re // these levels anymore. We will remove these values from the buffer. def_levels_.Erase(levels_position_, remaining_levels_pos); - // For values, we do not have them in buffer, so we will read them and - // throw them away. SkipValuesInPage(values_to_read); // Mark the levels as read in the underlying column reader. @@ -2077,10 +1995,10 @@ int64_t TypedRecordReader::SkipRecordsRepeated(int64_t num_records) { template void TypedRecordReader::SkipValuesInPage(int64_t num_values) { - const int64_t values_read = this->current_decoder_.Skip(num_values); + const int64_t values_read = this->current_decoder_->Skip(clamp_to(num_values)); if (values_read < num_values) { std::stringstream ss; - ss << "Could not read and throw away " << num_values << " values"; + ss << "Could not skip " << num_values << " values"; throw ParquetException(ss.str()); } } @@ -2207,7 +2125,7 @@ int64_t TypedRecordReader::ReadRepeatedRecordsInBuffer(int64_t num_recor int64_t records_read = DelimitRecords(num_records, values_to_read); if (valid_bits_.is_void()) { // not nullable or read_dense_for_nullable // This is only reading in the current page so this fits in an int32. - value_sink_.ReadValuesDense(*this->current_decoder_.get(), + value_sink_.ReadValuesDense(*this->current_decoder_, clamp_to(*values_to_read)); // null_count is always 0 for required. ARROW_DCHECK_EQ(*null_count, 0); @@ -2256,7 +2174,7 @@ void TypedRecordReader::ReadDenseForOptionalInBuffer( CountLevels(def_levels + start_levels_position, levels_position_ - start_levels_position, this->max_def_level()); // This is only reading in the current page so this fits in an int32. - value_sink_.ReadValuesDense(*this->current_decoder_.get(), + value_sink_.ReadValuesDense(*this->current_decoder_, clamp_to(*values_to_read)); } @@ -2274,7 +2192,7 @@ void TypedRecordReader::ReadSpacedForOptionalOrRepeatedInBuffer( *null_count = result.null_count; // This is only reading in the current page so this fits in an int32. - value_sink_.ReadValuesSpaced(*this->current_decoder_.get(), + value_sink_.ReadValuesSpaced(*this->current_decoder_, clamp_to(result.values_read), clamp_to(*null_count), /* valid_bits= */ valid_bits_.data(), @@ -2311,7 +2229,7 @@ int64_t TypedRecordReader::ReadRecordDataInBuffer(int64_t num_records) { ARROW_DCHECK(!nullable_values()); values_to_read = num_records; // This is only reading in the current page so this fits in an int32. - value_sink_.ReadValuesDense(*this->current_decoder_.get(), + value_sink_.ReadValuesDense(*this->current_decoder_, clamp_to(values_to_read)); records_read = num_records; // We don't need to update null_count, since it is 0. @@ -2484,7 +2402,7 @@ int64_t RequiredTypedRecordReader::ReadRecords(int64_t num_records) { const int32_t batch_size = narrow_min(num_records - records_read, this->available_values_current_page()); - value_sink_.ReadValuesDense(*this->current_decoder_.get(), batch_size); + value_sink_.ReadValuesDense(*this->current_decoder_, batch_size); this->MarkValuesAsConsumed(batch_size); records_read += batch_size; @@ -2639,14 +2557,14 @@ int64_t FlatOptionalTypedRecordReader::ReadRecords(int64_t num_records) if (read_dense_for_nullable()) { const auto result = this->def_levels_decoder_.CountUpTo(1, batch_size); CheckValidLevelCount(result.processed_count == batch_size); - value_sink_.ReadValuesDense(*this->current_decoder_.get(), result.matching_count); + value_sink_.ReadValuesDense(*this->current_decoder_, result.matching_count); records_read += result.processed_count; this->MarkValuesAsConsumed(result.processed_count); } else { const auto old_valid_bits_start = valid_bits_.values_count(); const auto null_count = valid_bits_.ReadFromDecoder(this->def_levels_decoder_, batch_size); - value_sink_.ReadValuesSpaced(*this->current_decoder_.get(), batch_size, null_count, + value_sink_.ReadValuesSpaced(*this->current_decoder_, batch_size, null_count, /* valid_bits= */ valid_bits_.data(), /* valid_bits_offset= */ old_valid_bits_start); if constexpr (VS::kCanDiscardValidity) { diff --git a/cpp/src/parquet/decoder.cc b/cpp/src/parquet/decoder.cc index 076a44cfc0b..8d55c10b7ef 100644 --- a/cpp/src/parquet/decoder.cc +++ b/cpp/src/parquet/decoder.cc @@ -358,6 +358,21 @@ class PlainDecoder : public TypedDecoderImpl { int Decode(T* buffer, int max_values) override; + int Skip(int max_values) override { + if constexpr (std::is_same_v) { + return TypedDecoder::Skip(max_values); + } else { + const int count = std::min(max_values, this->num_values_); + if (count <= 0) return 0; + const int64_t bytes = static_cast(count) * this->type_length_; + if (bytes > this->len_) ParquetException::EofException(); + this->data_ += bytes; + this->len_ -= static_cast(bytes); + this->num_values_ -= count; + return count; + } + } + int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset, typename EncodingTraits::Accumulator* builder) override; @@ -539,6 +554,14 @@ class PlainBooleanDecoder : public TypedDecoderImpl, public Boolean explicit PlainBooleanDecoder(const ColumnDescriptor* descr); void SetData(int num_values, const uint8_t* data, int len) override; + int Skip(int max_values) override { + const int count = std::min(max_values, num_values_); + if (count <= 0) return 0; + if (!bit_reader_->Advance(count)) ParquetException::EofException(); + num_values_ -= count; + return count; + } + // Two flavors of bool decoding int Decode(uint8_t* buffer, int max_values) override; int Decode(bool* buffer, int max_values) override; @@ -1812,6 +1835,13 @@ class DeltaLengthByteArrayDecoder : public TypedDecoderImpl { return max_values; } + int Skip(int max_values) override { + if (max_values <= 0) return 0; + const int32_t* lengths; + const uint8_t* data; + return NextBatch(max_values, &lengths, &data); + } + // Advance over up to `max_values` values and expose them as a view: the // per-value lengths, and a pointer to the start of their (contiguous) data. // Returns the number of values available. @@ -2442,6 +2472,13 @@ class ByteStreamSplitDecoderBase : public TypedDecoderImpl { stride_ = this->num_values_; } + int Skip(int max_values) final { + const int count = std::min(max_values, this->num_values_); + if (count <= 0) return 0; + Advance(count); + return count; + } + int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset, typename EncodingTraits::DictAccumulator* builder) override { @@ -2484,13 +2521,18 @@ class ByteStreamSplitDecoderBase : public TypedDecoderImpl { if (ARROW_PREDICT_TRUE(values_to_decode > 0)) { ::arrow::util::internal::ByteStreamSplitDecode( this->data_, this->type_length_, values_to_decode, stride_, out_buffer); - this->data_ += values_to_decode; - this->num_values_ -= values_to_decode; - this->len_ -= this->type_length_ * values_to_decode; + Advance(values_to_decode); } return values_to_decode; } + void Advance(int count) { + // Move within the first byte stream. The distance between streams stays constant. + this->data_ += count; + this->num_values_ -= count; + this->len_ -= this->type_length_ * count; + } + uint8_t* EnsureDecodeBuffer(int64_t min_values) { const int64_t size = this->type_length_ * min_values; if (!decode_buffer_ || decode_buffer_->size() < size) { diff --git a/cpp/src/parquet/encoding.h b/cpp/src/parquet/encoding.h index 157d67264c5..c66d495e1b3 100644 --- a/cpp/src/parquet/encoding.h +++ b/cpp/src/parquet/encoding.h @@ -17,6 +17,7 @@ #pragma once +#include #include #include #include @@ -278,6 +279,21 @@ class TypedDecoder : virtual public Decoder { /// at the end of the current data page. virtual int Decode(T* buffer, int max_values) = 0; + /// \brief Skip up to max_values physical (non-null) values in this data page. + /// + /// Returns the number skipped. The next Decode starts at the first unskipped value. + virtual int Skip(int max_values) { + constexpr int kBatchSize = 1024 / sizeof(T); + T scratch[kBatchSize]; + int skipped = 0; + while (skipped < max_values) { + const int count = Decode(scratch, std::min(kBatchSize, max_values - skipped)); + if (count == 0) break; + skipped += count; + } + return skipped; + } + /// \brief Decode the values in this data page but leave spaces for null entries. /// /// \param[in] buffer destination for decoded values diff --git a/cpp/src/parquet/encoding_test.cc b/cpp/src/parquet/encoding_test.cc index f378812d8c6..be60032d4e8 100644 --- a/cpp/src/parquet/encoding_test.cc +++ b/cpp/src/parquet/encoding_test.cc @@ -257,6 +257,29 @@ class TestEncodingBase : public ::testing::Test { virtual void CheckRoundtrip() = 0; + void CheckSkip(Encoding::type encoding) { + InitData(2053, 1); + auto encoder = + MakeTypedEncoder(encoding, /*use_dictionary=*/false, descr_.get()); + encoder->Put(draws_, num_values_); + auto encoded = encoder->FlushValues(); + auto decoder = MakeTypedDecoder(encoding, descr_.get()); + decoder->SetData(num_values_, encoded->data(), static_cast(encoded->size())); + + int pos = 0; + for (int skip : {0, 7, 1031}) { + ASSERT_EQ(skip, decoder->Skip(skip)); + pos += skip; + ASSERT_EQ(num_values_ - pos, decoder->values_left()); + ASSERT_EQ(3, decoder->Decode(decode_buf_, 3)); + ASSERT_NO_FATAL_FAILURE(VerifyResults(decode_buf_, draws_ + pos, 3)); + pos += 3; + } + ASSERT_EQ(num_values_ - pos, decoder->Skip(std::numeric_limits::max())); + ASSERT_EQ(0, decoder->Skip(1)); + ASSERT_EQ(0, decoder->values_left()); + } + virtual void CheckRoundtripSpaced(const uint8_t* valid_bits, int64_t valid_bits_offset) {} @@ -368,6 +391,10 @@ class TestPlainEncoding : public TestEncodingBase { TYPED_TEST_SUITE(TestPlainEncoding, ParquetTypes); +TYPED_TEST(TestPlainEncoding, InterleaveSkipAndDecode) { + this->CheckSkip(Encoding::PLAIN); +} + TYPED_TEST(TestPlainEncoding, BasicRoundTrip) { ASSERT_NO_FATAL_FAILURE(this->Execute(10000, 1)); @@ -1673,6 +1700,10 @@ using ByteStreamSplitTypes = ::testing::Types; TYPED_TEST_SUITE(TestByteStreamSplitEncoding, ByteStreamSplitTypes); +TYPED_TEST(TestByteStreamSplitEncoding, InterleaveSkipAndDecode) { + this->CheckSkip(Encoding::BYTE_STREAM_SPLIT); +} + TYPED_TEST(TestByteStreamSplitEncoding, BasicRoundTrip) { for (int values = 0; values < 32; ++values) { ASSERT_NO_FATAL_FAILURE(this->Execute(values, 1)); @@ -2252,6 +2283,10 @@ class TestDeltaLengthByteArrayEncoding : public TestEncodingBase { typedef ::testing::Types TestDeltaLengthByteArrayEncodingTypes; TYPED_TEST_SUITE(TestDeltaLengthByteArrayEncoding, TestDeltaLengthByteArrayEncodingTypes); +TYPED_TEST(TestDeltaLengthByteArrayEncoding, InterleaveSkipAndDecode) { + this->CheckSkip(Encoding::DELTA_LENGTH_BYTE_ARRAY); +} + TYPED_TEST(TestDeltaLengthByteArrayEncoding, BasicRoundTrip) { ASSERT_NO_FATAL_FAILURE(this->Execute(0, 0)); ASSERT_NO_FATAL_FAILURE(this->Execute(2000, 200)); @@ -2519,6 +2554,10 @@ class TestDeltaByteArrayEncoding : public TestDeltaLengthByteArrayEncoding using TestDeltaByteArrayEncodingTypes = ::testing::Types; TYPED_TEST_SUITE(TestDeltaByteArrayEncoding, TestDeltaByteArrayEncodingTypes); +TYPED_TEST(TestDeltaByteArrayEncoding, InterleaveSkipAndDecode) { + this->CheckSkip(Encoding::DELTA_BYTE_ARRAY); +} + TYPED_TEST(TestDeltaByteArrayEncoding, BasicRoundTrip) { ASSERT_NO_FATAL_FAILURE(this->Execute(0, /*repeats=*/0)); ASSERT_NO_FATAL_FAILURE(this->Execute(250, 5));