Skip to content
6 changes: 6 additions & 0 deletions cpp/src/arrow/array/builder_binary.h
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,12 @@ class BaseBinaryBuilder
return Status::OK();
}

/// Get the builder to keep track of the offsets.
TypedBufferBuilder<offset_type>* offsets_builder() { return &offsets_builder_; }
/// Get the builder to keep track of the value binary data.
TypedBufferBuilder<uint8_t>* value_data_builder() { return &value_data_builder_; }
using ArrayBuilder::UnsafeAppendToBitmap;

void Reset() override {
ArrayBuilder::Reset();
offsets_builder_.Reset();
Expand Down
81 changes: 79 additions & 2 deletions cpp/src/parquet/decoder.cc
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,8 @@ struct ArrowBinaryHelper<ByteArrayType> {
return acc_->builder->AppendNull();
}

bool CanFit(int64_t length) const { return length <= chunk_space_remaining_; }

private:
Status PushChunk() {
ARROW_ASSIGN_OR_RAISE(auto chunk, acc_->builder->Finish());
Expand All @@ -504,8 +506,6 @@ struct ArrowBinaryHelper<ByteArrayType> {
return Status::OK();
}

bool CanFit(int64_t length) const { return length <= chunk_space_remaining_; }

Accumulator* acc_;
int64_t entries_remaining_;
int64_t chunk_space_remaining_;
Expand Down Expand Up @@ -1675,13 +1675,90 @@ class DeltaLengthByteArrayDecoder : public DecoderImpl,
num_valid_values_ = num_length;
}

Status DecodeArrowDenseFastPath(
int num_values, int null_count, const uint8_t* valid_bits,
int64_t valid_bits_offset, typename EncodingTraits<ByteArrayType>::Accumulator* out,
int* out_num_values) {
int num_non_null_values = num_values - null_count;
if (num_non_null_values > num_valid_values_) {
throw ParquetException("Expected to decode ", num_non_null_values,
" values, but can decode decoded ", num_valid_values_,
" values.");
}
const int32_t* length_ptr = buffered_length_->data_as<int32_t>() + length_idx_;
int bytes_offset = len_ - decoder_->bytes_left();
const uint8_t* data_ptr = data_ + bytes_offset;
const int64_t initial_offset = out->builder->value_data_length();
auto* offsets_builder = out->builder->offsets_builder();
auto* value_data_builder = out->builder->value_data_builder();
// Phase1: get total length of binary data and append to value_data_builder
int64_t accum_length = 0;
for (int i = 0; i < num_non_null_values; ++i) {
if (ARROW_PREDICT_FALSE(length_ptr[i] < 0)) {
return Status::Invalid("negative string delta length");
}
accum_length += length_ptr[i];
}
{
// Actually these checks would not happen since DecodeArrowDenseFastPath
// would be called only when helper.CanFit(decoder_->bytes_left()),
// so, accum_length <= decoder_->bytes_left() << chunk_space_remaining_
// <= std::numeric_limits<int32_t>::max().
if (ARROW_PREDICT_FALSE(accum_length > std::numeric_limits<int32_t>::max())) {
return Status::Invalid("excess expansion in DELTA_BYTE_ARRAY");
}
if (ARROW_PREDICT_FALSE(decoder_->bytes_left() < accum_length)) {
return Status::Invalid("Binary data is too short");
}
}
RETURN_NOT_OK(out->builder->ValidateOverflow(accum_length));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But what happens if accum_length > chunk_space_remaining_. Would it just fail? It should probably append a new chunk.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would never happens, chunk_space_remaining_ >= decoder_->bytes_left() >= accum_length, so this would not happens

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But why is chunk_space_remaining_ >= decoder_->bytes_left()?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, this is because we know that CanFit(decoder_->bytes_left()), right? Adding a comment might help...

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added here: c21878c

// Append the binary data
ARROW_RETURN_NOT_OK(value_data_builder->Append(data_ptr, accum_length));
// Phase2: append offsets
RETURN_NOT_OK(offsets_builder->Reserve(num_values));
{
accum_length = 0;
int length_idx = 0;
RETURN_NOT_OK(VisitNullBitmapInline(
valid_bits, valid_bits_offset, num_values, null_count,
[&]() {
offsets_builder->UnsafeAppend(
static_cast<int32_t>(initial_offset + accum_length));
accum_length += length_ptr[length_idx];
++length_idx;
return Status::OK();
},
[&]() {
offsets_builder->UnsafeAppend(
static_cast<int32_t>(initial_offset + accum_length));
return Status::OK();
}));
}
// Phase3: Append nulls
out->builder->UnsafeAppendToBitmap(valid_bits, valid_bits_offset, num_values);
// Phase4: update the encoder internal status.
if (ARROW_PREDICT_FALSE(!decoder_->Advance(8 * accum_length))) {
ParquetException::EofException();
}
length_idx_ += num_non_null_values;
this->num_values_ -= num_non_null_values;
num_valid_values_ -= num_non_null_values;
*out_num_values = num_values - null_count;
return Status::OK();
}

Status DecodeArrowDense(int num_values, int null_count, const uint8_t* valid_bits,
int64_t valid_bits_offset,
typename EncodingTraits<ByteArrayType>::Accumulator* out,
int* out_num_values) {
ArrowBinaryHelper<ByteArrayType> helper(out, num_values);
RETURN_NOT_OK(helper.Prepare());

if (helper.CanFit(decoder_->bytes_left())) {
return DecodeArrowDenseFastPath(num_values, null_count, valid_bits,
valid_bits_offset, out, out_num_values);
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder why we need the slow path below at all. Instead, we could just expose chunk_space_remaining_ and PushChunk, and use them to build the output chunk by chunk as necessary.

@mapleFU mapleFU Mar 27, 2025 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Emmm I don't know what does this mean, when Page's buffer is larger than a chunk can handle, we need find "maximum buffer we can pushinto", and segment the arrow array to multiple sub-chunks, then switch to next batch in this case?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, basically something like this:

    int64_t start = 0;
    while (start < num_non_null_values) {
      // Find the number of values that we can write in this chunk
      int64_t chunk_data_length = 0;
      for (int64_t end = start; end < num_non_null_values; ++end) {
        const int64_t length = length_ptr[end];
        if (ARROW_PREDICT_FALSE(length < 0)) {
          return Status::Invalid("negative string delta length");
        }
        if (chunk_data_length + length > out->chunk_space_remaining()) {
          break;
        }
        chunk_data_length += length;
      }
      // Write chunk [start, end)
      ...
      out->PushChunk();
      start = end;
    }

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this should also find out that, given a num_non_null_values, what's the number of num_values in this range?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahem... that's a good point. Ideally we would need something like VisitNullBitmapInline, but that would stop after a certain number of non-null values...

@mapleFU mapleFU Mar 27, 2025 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, seems this requires a underlying "loop" abstraction which could hint "next-value", "end", "break"...This also requires handling the all-nulls values. So I prefer using this fast-path firstly.

This abstraction might be like:

struct Stride {
  int32_t num_non_null_values;
  int32_t num_values;
  int32_t binary_length;
};

Stride nextStride(int32_t max_length) {
  if (decoder_->bytes_left() <= out->chunk_space_remaining()) {
    // accumulate value lengths until max_length
    // ...
    return Stride {...};
  }
  VisitNullBitmapInline(...); // find out the fitable stride
  return Stride{..};
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So should I move forward with some slow stride checking or leave it a fastpath here? @pitrou

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah! Well, I was underestimating the complexity of the clean solution, so leaving it as a fast path sounds fine.

@pitrou pitrou Apr 3, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The remaining problem, though, is that the fallback isn't tested?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The remaining problem, though, is that the fallback isn't tested?

I think fallback is tested but I'll check this, it's a bit hard to reserve so large memory for testing though

std::vector<ByteArray> values(num_values - null_count);
const int num_valid_values = Decode(values.data(), num_values - null_count);
if (ARROW_PREDICT_FALSE(num_values - null_count != num_valid_values)) {
Expand Down
31 changes: 31 additions & 0 deletions cpp/src/parquet/encoding_benchmark.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1267,6 +1267,27 @@ class BM_ArrowBinaryPlain : public BenchmarkDecodeArrowByteArray {
}
};

class BM_ArrowBinaryDeltaLength : public BenchmarkDecodeArrowByteArray {
public:
void DoEncodeArrow() override {
auto encoder = MakeTypedEncoder<ByteArrayType>(Encoding::DELTA_LENGTH_BYTE_ARRAY);
encoder->Put(*input_array_);
buffer_ = encoder->FlushValues();
}

void DoEncodeLowLevel() override {
auto encoder = MakeTypedEncoder<ByteArrayType>(Encoding::DELTA_LENGTH_BYTE_ARRAY);
encoder->Put(values_.data(), num_values_);
buffer_ = encoder->FlushValues();
}

std::unique_ptr<ByteArrayDecoder> InitializeDecoder() override {
auto decoder = MakeTypedDecoder<ByteArrayType>(Encoding::DELTA_LENGTH_BYTE_ARRAY);
decoder->SetData(num_values_, buffer_->data(), static_cast<int>(buffer_->size()));
return decoder;
}
};

BENCHMARK_DEFINE_F(BM_ArrowBinaryPlain, EncodeArrow)
(benchmark::State& state) { EncodeArrowBenchmark(state); }
BENCHMARK_REGISTER_F(BM_ArrowBinaryPlain, EncodeArrow)->Range(1 << 18, 1 << 20);
Expand All @@ -1284,6 +1305,16 @@ BENCHMARK_DEFINE_F(BM_ArrowBinaryPlain, DecodeArrowNonNull_Dense)
BENCHMARK_REGISTER_F(BM_ArrowBinaryPlain, DecodeArrowNonNull_Dense)
->Range(MIN_RANGE, MAX_RANGE);

BENCHMARK_DEFINE_F(BM_ArrowBinaryDeltaLength, DecodeArrow_Dense)
(benchmark::State& state) { DecodeArrowDenseBenchmark(state); }
BENCHMARK_REGISTER_F(BM_ArrowBinaryDeltaLength, DecodeArrow_Dense)
->Range(MIN_RANGE, MAX_RANGE);

BENCHMARK_DEFINE_F(BM_ArrowBinaryDeltaLength, DecodeArrowNotNull_Dense)
(benchmark::State& state) { DecodeArrowNonNullDenseBenchmark(state); }
BENCHMARK_REGISTER_F(BM_ArrowBinaryDeltaLength, DecodeArrowNotNull_Dense)
->Range(MIN_RANGE, MAX_RANGE);

BENCHMARK_DEFINE_F(BM_ArrowBinaryPlain, DecodeArrow_Dict)
(benchmark::State& state) { DecodeArrowDictBenchmark(state); }
BENCHMARK_REGISTER_F(BM_ArrowBinaryPlain, DecodeArrow_Dict)->Range(MIN_RANGE, MAX_RANGE);
Expand Down