This is an automated email from the ASF dual-hosted git repository.
zeroshade pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-go.git
The following commit(s) were added to refs/heads/main by this push:
new 226bcc86 perf(parquet): decode binary dictionary pages in batches
(#1652)
226bcc86 is described below
commit 226bcc867c3590c5c13d0a2709838fa6760f2767
Author: kurtoskalac <[email protected]>
AuthorDate: Tue Nov 24 17:00:08 2026 +0100
perf(parquet): decode binary dictionary pages in batches (#1652)
### Why
Projected reads of dictionary-encoded strings build a temporary slice
header for every decoded value. On a 262,144-row projection, read time
went from 9.81 to 6.84 ms with Zstd and from 9.60 to 6.63 ms with
Snappy.
Medians from ten single-core runs on Go 1.26.8 against `f1ab644`.
### What
Build dense binary arrays from bounded batches of dictionary indices.
### Implementation
Validate indices before appending and grow the output buffer as needed.
Batch appends for plain binary pages as well.
---------
Signed-off-by: Kurtorkalacs <[email protected]>
Co-authored-by: Minh Vu <[email protected]>
Co-authored-by: Kurtorkalacs
<[email protected]>
---
parquet/file/record_reader.go | 26 ++++-
parquet/internal/encoding/byte_array_decoder.go | 83 ++++++++++++++++
.../internal/encoding/decoder_benchmark_test.go | 59 ++++++++++++
.../pqarrow/read_repeated_strings_bench_test.go | 105 +++++++++++++++++++++
4 files changed, 269 insertions(+), 4 deletions(-)
diff --git a/parquet/file/record_reader.go b/parquet/file/record_reader.go
index 898ee67a..88a28d91 100644
--- a/parquet/file/record_reader.go
+++ b/parquet/file/record_reader.go
@@ -21,6 +21,7 @@ import (
"fmt"
"sync"
"sync/atomic"
+ "unsafe"
"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/array"
@@ -976,13 +977,23 @@ func (br *byteArrayRecordReader) Release() {
}
func (br *byteArrayRecordReader) ReadValuesDense(toRead int64) error {
+ dec :=
br.ColumnChunkReader.(*ByteArrayColumnChunkReader).curDecoder.(encoding.ByteArrayDecoder)
+ if dict, ok := dec.(*encoding.DictByteArrayDecoder); ok {
+ if bldr, ok := br.bldr.(*array.BinaryBuilder); ok {
+ n, err := dict.DecodeToBinaryBuilder(bldr, int(toRead))
+ if err := checkDecoded(n, err, toRead); err != nil {
+ return err
+ }
+ br.ResetValues()
+ return nil
+ }
+ }
+
if int64(cap(br.valueBuf)) < toRead {
br.valueBuf = make([]parquet.ByteArray, 0, toRead)
}
values := br.valueBuf[:toRead]
- dec :=
br.ColumnChunkReader.(*ByteArrayColumnChunkReader).curDecoder.(encoding.ByteArrayDecoder)
-
n, err := dec.Decode(values)
if err = checkDecoded(n, err, toRead); err != nil {
return err
@@ -990,9 +1001,16 @@ func (br *byteArrayRecordReader) ReadValuesDense(toRead
int64) error {
switch bldr := br.bldr.(type) {
case *array.BinaryBuilder:
- for _, val := range values {
- bldr.Append(val)
+ requiredBytes := uint64(bldr.DataLen())
+ for _, value := range values {
+ requiredBytes += uint64(len(value))
+ }
+ if err := encoding.ReserveBinaryData(bldr, requiredBytes); err
!= nil {
+ return err
}
+ // ByteArray and []byte have the same representation.
AppendValues
+ // copies the payloads while the decoded page is still live.
+
bldr.AppendValues(unsafe.Slice((*[]byte)(unsafe.SliceData(values)),
len(values)), nil)
case *array.BinaryDictionaryBuilder:
for _, val := range values {
if err := bldr.Append(val); err != nil {
diff --git a/parquet/internal/encoding/byte_array_decoder.go
b/parquet/internal/encoding/byte_array_decoder.go
index 5089a4f7..c83a22fc 100644
--- a/parquet/internal/encoding/byte_array_decoder.go
+++ b/parquet/internal/encoding/byte_array_decoder.go
@@ -20,9 +20,12 @@ import (
"encoding/binary"
"errors"
"fmt"
+ "io"
+ "math"
"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/array"
+ "github.com/apache/arrow-go/v18/arrow/bitutil"
"github.com/apache/arrow-go/v18/arrow/memory"
"github.com/apache/arrow-go/v18/internal/utils"
"github.com/apache/arrow-go/v18/parquet"
@@ -188,6 +191,86 @@ func (pbad *PlainByteArrayDecoder) DecodeSpaced(out
[]parquet.ByteArray, nullCou
return spacedExpand(out, nullCount, validBits, validBitsOffset), nil
}
+// ReserveBinaryData checks the Arrow offset limit before growing the data
+// buffer for a payload of required bytes, including bytes already appended.
+func ReserveBinaryData(bldr *array.BinaryBuilder, required uint64) error {
+ limit := uint64(math.MaxInt)
+ if bldr.Type().Layout().Buffers[1].ByteWidth == arrow.Int32SizeBytes {
+ limit = min(limit, math.MaxInt32)
+ }
+ if required > limit {
+ return fmt.Errorf("%w: binary payload exceeds Arrow offset
capacity", arrow.ErrInvalid)
+ }
+ if size := int(required); size > bldr.DataCap() {
+ capacity := size
+ if required <= limit/2 {
+ capacity = bitutil.NextPowerOf2(size)
+ }
+ bldr.ReserveData(capacity - bldr.DataLen())
+ }
+
+ return nil
+}
+
+// DecodeToBinaryBuilder appends count dictionary values in bounded batches.
+// On error it restores the builder to its starting length.
+func (d *DictByteArrayDecoder) DecodeToBinaryBuilder(bldr
*array.BinaryBuilder, count int) (_ int, err error) {
+ if count == 0 {
+ return 0, nil
+ }
+ if count > d.nvals {
+ return 0, io.ErrUnexpectedEOF
+ }
+
+ dict := d.dictValueDecoder.(*dictConverter[parquet.ByteArray])
+ var indices [1024]uint64
+ var values [len(indices)][]byte
+
+ start := bldr.Len()
+ defer func() {
+ if err != nil && bldr.Len() > start {
+ bldr.Resize(start)
+ }
+ }()
+ bldr.Reserve(count)
+ written := 0
+ for written < count {
+ batch := min(count-written, len(indices))
+ n, err := d.idxDecoder.GetBatch(indices[:batch])
+ d.nvals -= n
+ if err != nil {
+ return 0, err
+ }
+ if n != batch {
+ return 0, io.ErrUnexpectedEOF
+ }
+
+ var maxIndex uint64
+ for _, index := range indices[:n] {
+ maxIndex = max(maxIndex, index)
+ }
+ if maxIndex > math.MaxInt32 {
+ return 0, fmt.Errorf("parquet: dictionary index %d is
out of range", maxIndex)
+ }
+ if err := dict.ensure(pqutils.IndexType(maxIndex)); err != nil {
+ return 0, err
+ }
+
+ size := uint64(bldr.DataLen())
+ for i, index := range indices[:n] {
+ value := dict.dict[index]
+ values[i] = value
+ size += uint64(len(value))
+ }
+ if err := ReserveBinaryData(bldr, size); err != nil {
+ return 0, err
+ }
+ bldr.AppendValues(values[:n], nil)
+ written += n
+ }
+ return written, nil
+}
+
func (d *DictByteArrayDecoder) InsertDictionary(bldr array.Builder) error {
conv := d.dictValueDecoder.(*dictConverter[parquet.ByteArray])
dictLength := conv.dictLen
diff --git a/parquet/internal/encoding/decoder_benchmark_test.go
b/parquet/internal/encoding/decoder_benchmark_test.go
index 6b9e0a14..e221ac76 100644
--- a/parquet/internal/encoding/decoder_benchmark_test.go
+++ b/parquet/internal/encoding/decoder_benchmark_test.go
@@ -18,6 +18,7 @@ package encoding_test
import (
"fmt"
+ "math"
"testing"
"github.com/apache/arrow-go/v18/arrow"
@@ -26,6 +27,7 @@ import (
"github.com/apache/arrow-go/v18/arrow/memory"
"github.com/apache/arrow-go/v18/parquet"
"github.com/apache/arrow-go/v18/parquet/internal/encoding"
+ "github.com/apache/arrow-go/v18/parquet/schema"
"github.com/stretchr/testify/require"
)
@@ -93,6 +95,63 @@ func TestDictByteArrayDecoderDecodeIndices(t *testing.T) {
require.Equal(t, len(values), n)
}
+func TestDictByteArrayDecoderDecodeToBinaryBuilder(t *testing.T) {
+ mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer mem.AssertSize(t, 0)
+
+ column := schema.NewColumn(schema.NewByteArrayNode("value",
parquet.Repetitions.Required, -1), 0, 0)
+ dictionary := encoding.NewDecoder(parquet.Types.ByteArray,
parquet.Encodings.Plain, column, mem)
+ require.NoError(t, dictionary.SetData(2, []byte{3, 0, 0, 0, 'o', 'n',
'e', 0, 0, 0, 0}))
+ decoder := encoding.NewDictDecoder(parquet.Types.ByteArray, column,
mem).(*encoding.DictByteArrayDecoder)
+ decoder.SetDict(dictionary)
+
+ builder := array.NewBinaryBuilder(mem, arrow.BinaryTypes.Binary)
+ defer builder.Release()
+ builder.Append([]byte("prefix"))
+
+ indices := make([]uint64, 2051)
+ for i := range indices {
+ indices[i] = uint64(i % 2)
+ }
+ require.NoError(t, decoder.SetData(len(indices),
encodeDictionaryIndexPage(t, indices, 1)))
+ for _, batch := range []int{2049, 2} {
+ n, err := decoder.DecodeToBinaryBuilder(builder, batch)
+ require.NoError(t, err)
+ require.Equal(t, batch, n)
+ }
+ result := builder.NewBinaryArray()
+ defer result.Release()
+ require.Equal(t, len(indices)+1, result.Len())
+ require.Equal(t, "prefix", result.ValueString(0))
+ for i, index := range indices {
+ require.False(t, result.IsNull(i+1))
+ require.Equal(t, []string{"one", ""}[index],
result.ValueString(i+1))
+ }
+
+ builder.Append([]byte("keep"))
+ builder.AppendNull()
+ indices[1400] = 2
+ require.NoError(t, decoder.SetData(len(indices),
encodeDictionaryIndexPage(t, indices, 2)))
+ n, err := decoder.DecodeToBinaryBuilder(builder, len(indices))
+ require.ErrorContains(t, err, "out of range")
+ require.Zero(t, n)
+ require.Equal(t, 2, builder.Len())
+ require.Equal(t, len("keep"), builder.DataLen())
+ builder.Append([]byte("next"))
+ restored := builder.NewBinaryArray()
+ defer restored.Release()
+ require.Equal(t, "keep", restored.ValueString(0))
+ require.True(t, restored.IsNull(1))
+ require.Equal(t, "next", restored.ValueString(2))
+}
+
+func TestReserveBinaryDataRejectsOffsetOverflow(t *testing.T) {
+ builder := array.NewBinaryBuilder(memory.DefaultAllocator,
arrow.BinaryTypes.String)
+ defer builder.Release()
+ require.ErrorIs(t, encoding.ReserveBinaryData(builder,
uint64(math.MaxInt32)+1), arrow.ErrInvalid)
+ require.Zero(t, builder.DataCap())
+}
+
func TestDictByteArrayDecoderDecodeIndicesSpaced(t *testing.T) {
mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
defer mem.AssertSize(t, 0)
diff --git a/parquet/pqarrow/read_repeated_strings_bench_test.go
b/parquet/pqarrow/read_repeated_strings_bench_test.go
new file mode 100644
index 00000000..d7e6cd84
--- /dev/null
+++ b/parquet/pqarrow/read_repeated_strings_bench_test.go
@@ -0,0 +1,105 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package pqarrow_test
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "testing"
+
+ "github.com/apache/arrow-go/v18/arrow"
+ "github.com/apache/arrow-go/v18/arrow/array"
+ "github.com/apache/arrow-go/v18/arrow/memory"
+ "github.com/apache/arrow-go/v18/parquet"
+ "github.com/apache/arrow-go/v18/parquet/compress"
+ "github.com/apache/arrow-go/v18/parquet/file"
+ "github.com/apache/arrow-go/v18/parquet/pqarrow"
+)
+
+func BenchmarkReadRepeatedStrings(b *testing.B) {
+ const rows = 1 << 18
+ mem := memory.DefaultAllocator
+ schema := arrow.NewSchema([]arrow.Field{
+ {Name: "id", Type: arrow.PrimitiveTypes.Int64},
+ {Name: "value", Type: arrow.BinaryTypes.String},
+ }, nil)
+ ids := array.NewInt64Builder(mem)
+ ids.Reserve(rows)
+ builder := array.NewStringBuilder(mem)
+ labels := make([]string, 256)
+ for i := range labels {
+ labels[i] = fmt.Sprintf("region-%03d", i)
+ }
+ builder.Reserve(rows)
+ state := uint32(1)
+ for i := range rows {
+ state = state*1664525 + 1013904223
+ builder.Append(labels[state>>24])
+ ids.UnsafeAppend(int64(i))
+ }
+ values := builder.NewArray()
+ builder.Release()
+ defer values.Release()
+ idValues := ids.NewArray()
+ ids.Release()
+ defer idValues.Release()
+ batch := array.NewRecordBatch(schema, []arrow.Array{idValues, values},
rows)
+ defer batch.Release()
+ table := array.NewTableFromRecords(schema, []arrow.RecordBatch{batch})
+ defer table.Release()
+
+ for _, codec := range []compress.Compression{compress.Codecs.Zstd,
compress.Codecs.Snappy} {
+ b.Run(codec.String(), func(b *testing.B) {
+ var output bytes.Buffer
+ props :=
parquet.NewWriterProperties(parquet.WithCompression(codec))
+ if err := pqarrow.WriteTable(table, &output, rows,
props, pqarrow.DefaultWriterProps()); err != nil {
+ b.Fatal(err)
+ }
+ readProps := pqarrow.ArrowReadProperties{BatchSize: 32
* 1024}
+ ctx := context.Background()
+ b.ReportAllocs()
+ b.SetBytes(rows * int64(len(labels[0])))
+ for b.Loop() {
+ f, err :=
file.NewParquetReader(bytes.NewReader(output.Bytes()))
+ if err != nil {
+ b.Fatal(err)
+ }
+ reader, err := pqarrow.NewFileReader(f,
readProps, mem)
+ if err != nil {
+ _ = f.Close()
+ b.Fatal(err)
+ }
+ records, err := reader.GetRecordReader(ctx,
[]int{1}, nil)
+ if err != nil {
+ _ = f.Close()
+ b.Fatal(err)
+ }
+ read := int64(0)
+ for records.Next() {
+ read += records.RecordBatch().NumRows()
+ }
+ err = records.Err()
+ records.Release()
+ closeErr := f.Close()
+ if err != nil || closeErr != nil || read !=
rows {
+ b.Fatalf("read %d of %d rows: %v,
close: %v", read, rows, err, closeErr)
+ }
+ }
+ })
+ }
+}