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 64638af4 perf(parquet/file): use dense decoding for batches without 
nulls (#1447)
64638af4 is described below

commit 64638af4d9910d0364fbd8d26ffc61377aee7658
Author: Harrison Crosse <[email protected]>
AuthorDate: Thu Nov 5 16:11:42 2026 -0500

    perf(parquet/file): use dense decoding for batches without nulls (#1447)
    
    ### Rationale for this change
    
    Optional columns take the spaced decode path even when a batch has no
    nulls. With `SetReadDict` enabled, that includes building a per-value
    validity slice before appending dictionary indices.
    
    I measured 2M synthetic 24-byte strings in one dictionary-encoded row
    group, with `SetReadDict` enabled, over 10 interleaved rounds on one
    8-vCPU AMD EPYC Linux amd64 VM running Go 1.26.10.
    
    These are median times for optional columns with no nulls, comparing
    main at `22c9f26d` with this change.
    
    | Distinct values | Rows/batch | Main → fix, ns/row | Reduction |
    | --- | ---: | ---: | ---: |
    | 1k | 8,192 | 10.19 → 6.53 | 36% |
    | 1k | 65,536 | 8.51 → 4.70 | 45% |
    | 100k | 8,192 | 180.4 → 174.5 | 3% |
    | 100k | 65,536 | 36.31 → 32.78 | 10% |
    
    benchstat gives `p<0.001` for three rows and `p=0.004` for 100k at 8,192
    rows per batch. In that case most of the time goes to copying the
    dictionary into every batch, which
    https://github.com/apache/arrow-go/pull/1444 addresses. Required columns
    stayed within noise. A version of this change without the count checks
    ran at the same speed.
    
    I added `BenchmarkReadOptionalDictionaryColumn` to
    `parquet/pqarrow/dictionary_reader_bench_test.go`. It shares its loop
    and `writeDictionaryStringColumn` with `BenchmarkReadDictionaryColumn`.
    Against main at `eea284eb`, it ran 17% to 30% faster at 100 and 10,000
    distinct values, with no clear change at 100,000.
    `BenchmarkReadDictionaryColumn`, which reads a required column, was
    unchanged. Existing benchmark names are unchanged.
    
    ### What changes are included in this PR?
    
    Batches with no nulls now use dense decoding. `DefLevelsToBitmap` still
    writes their validity bits first, and batches with nulls keep spaced
    decoding.
    
    Each `ReadValuesDense` implementation also checks the decoded count.
    `byteArrayDictRecordReader.ReadValuesSpaced`, used with `SetReadDict`,
    now checks the count from `DecodeIndicesSpaced` too. Both return
    `parquet: number of values / definition levels read did not match` when
    the decoder yields fewer values than requested. Other spaced readers
    already reject short counts inside their decoders. Valid pages keep
    their existing behavior.
    
    ### Are these changes tested?
    
    I added three tests.
    
    - `TestReadRecordsDenseForBatchesWithoutNulls` reads pages with nulls,
    without nulls, then with nulls in one call. It checks the path for each
    page, the values and the validity bits.
    - `TestReadRecordsRejectsShortPage` changes a `DELTA_BINARY_PACKED`
    header to claim two values instead of four. It checks that `ReadRecords`
    returns an error for optional and required columns.
    - `TestReadRecordsRejectsShortDictionaryPageWithNulls` shortens the RLE
    run of dictionary indices in a page with one null. It checks that
    `ReadRecords` returns an error.
    
    On main, the path test, the short-page test for required columns and the
    short dictionary page test fail.
    
    On Linux, `go test -tags assert,test ./parquet/...` passes with the same
    per-package results as main. With `-race`, `./parquet/file/` and
    `./parquet/pqarrow/` pass. `gofmt`, `golangci-lint` and the Release
    Audit Tool pass.
    
    I have not tested short pages for every encoding, `noasm`, arm64 or
    32-bit builds, or real-world files. I benchmarked only
    dictionary-encoded strings with `SetReadDict` enabled, and not columns
    that contain nulls.
    
    ### Are there any user-facing changes?
    
    Optional columns with no nulls read faster in these benchmarks. There is
    no API change.
    
    Required columns, and dictionary columns read with `SetReadDict` in
    batches with nulls, now return an error when a page's decoder yields
    fewer values than requested. On main they returned no error. Optional
    batches that now take the dense path keep count validation, although the
    message can differ slightly from the decoder's own.
    
    Closes https://github.com/apache/arrow-go/issues/1445.
---
 parquet/file/record_reader.go                   |  49 ++++----
 parquet/file/record_reader_internal_test.go     | 141 ++++++++++++++++++++++++
 parquet/pqarrow/dictionary_reader_bench_test.go |  16 ++-
 3 files changed, 181 insertions(+), 25 deletions(-)

diff --git a/parquet/file/record_reader.go b/parquet/file/record_reader.go
index 213883f7..73381758 100644
--- a/parquet/file/record_reader.go
+++ b/parquet/file/record_reader.go
@@ -329,35 +329,43 @@ func (pr *primitiveRecordReader) ReserveValues(extra 
int64, hasNullable bool) er
 }
 
 func (pr *primitiveRecordReader) ReadValuesDense(toRead int64) (err error) {
+       var n int
        switch cr := pr.ColumnChunkReader.(type) {
        case *BooleanColumnChunkReader:
-               _, err = 
cr.curDecoder.(encoding.BooleanBitmapDecoder).DecodeToBitmap(
+               n, err = 
cr.curDecoder.(encoding.BooleanBitmapDecoder).DecodeToBitmap(
                        pr.values.Bytes(), pr.valuesWritten, int(toRead))
        case *Int32ColumnChunkReader:
                values := 
arrow.Int32Traits.CastFromBytes(pr.values.Bytes())[int(pr.valuesWritten):]
-               _, err = 
cr.curDecoder.(encoding.Int32Decoder).Decode(values[:toRead])
+               n, err = 
cr.curDecoder.(encoding.Int32Decoder).Decode(values[:toRead])
        case *Int64ColumnChunkReader:
                values := 
arrow.Int64Traits.CastFromBytes(pr.values.Bytes())[int(pr.valuesWritten):]
-               _, err = 
cr.curDecoder.(encoding.Int64Decoder).Decode(values[:toRead])
+               n, err = 
cr.curDecoder.(encoding.Int64Decoder).Decode(values[:toRead])
        case *Int96ColumnChunkReader:
                values := 
parquet.Int96Traits.CastFromBytes(pr.values.Bytes())[int(pr.valuesWritten):]
-               _, err = 
cr.curDecoder.(encoding.Int96Decoder).Decode(values[:toRead])
+               n, err = 
cr.curDecoder.(encoding.Int96Decoder).Decode(values[:toRead])
        case *ByteArrayColumnChunkReader:
                values := 
parquet.ByteArrayTraits.CastFromBytes(pr.values.Bytes())[int(pr.valuesWritten):]
-               _, err = 
cr.curDecoder.(encoding.ByteArrayDecoder).Decode(values[:toRead])
+               n, err = 
cr.curDecoder.(encoding.ByteArrayDecoder).Decode(values[:toRead])
        case *FixedLenByteArrayColumnChunkReader:
                values := 
parquet.FixedLenByteArrayTraits.CastFromBytes(pr.values.Bytes())[int(pr.valuesWritten):]
-               _, err = 
cr.curDecoder.(encoding.FixedLenByteArrayDecoder).Decode(values[:toRead])
+               n, err = 
cr.curDecoder.(encoding.FixedLenByteArrayDecoder).Decode(values[:toRead])
        case *Float32ColumnChunkReader:
                values := 
arrow.Float32Traits.CastFromBytes(pr.values.Bytes())[int(pr.valuesWritten):]
-               _, err = 
cr.curDecoder.(encoding.Float32Decoder).Decode(values[:toRead])
+               n, err = 
cr.curDecoder.(encoding.Float32Decoder).Decode(values[:toRead])
        case *Float64ColumnChunkReader:
                values := 
arrow.Float64Traits.CastFromBytes(pr.values.Bytes())[int(pr.valuesWritten):]
-               _, err = 
cr.curDecoder.(encoding.Float64Decoder).Decode(values[:toRead])
+               n, err = 
cr.curDecoder.(encoding.Float64Decoder).Decode(values[:toRead])
        default:
                panic("invalid type for record reader")
        }
-       return
+       return checkDecoded(n, err, toRead)
+}
+
+func checkDecoded(n int, err error, want int64) error {
+       if err == nil && int64(n) != want {
+               return errors.New("parquet: number of values / definition 
levels read did not match")
+       }
+       return err
 }
 
 func (pr *primitiveRecordReader) ReadValuesSpaced(valuesWithNulls, nullCount 
int64) (err error) {
@@ -679,9 +687,11 @@ func (rr *recordReader) ReadRecordData(numRecords int64) 
(int64, error) {
                DefLevelsToBitmap(rr.DefLevels()[startPos:int(rr.levelsPos)], 
rr.leafInfo, &validityIO)
                valuesToRead = validityIO.Read - validityIO.NullCount
                nullCount = validityIO.NullCount
-               err = rr.ReadValuesSpaced(validityIO.Read, nullCount)
-       } else {
+       }
+       if nullCount == 0 {
                err = rr.ReadValuesDense(valuesToRead)
+       } else {
+               err = rr.ReadValuesSpaced(valuesToRead+nullCount, nullCount)
        }
        if err != nil {
                return 0, err
@@ -832,8 +842,8 @@ func (fr *flbaRecordReader) ReadValuesDense(toRead int64) 
error {
        values := fr.valueBuf[:toRead]
        dec := 
fr.ColumnChunkReader.(*FixedLenByteArrayColumnChunkReader).curDecoder.(encoding.FixedLenByteArrayDecoder)
 
-       _, err := dec.Decode(values)
-       if err != nil {
+       n, err := dec.Decode(values)
+       if err = checkDecoded(n, err, toRead); err != nil {
                return err
        }
 
@@ -967,8 +977,8 @@ func (br *byteArrayRecordReader) ReadValuesDense(toRead 
int64) error {
        values := br.valueBuf[:toRead]
        dec := 
br.ColumnChunkReader.(*ByteArrayColumnChunkReader).curDecoder.(encoding.ByteArrayDecoder)
 
-       _, err := dec.Decode(values)
-       if err != nil {
+       n, err := dec.Decode(values)
+       if err = checkDecoded(n, err, toRead); err != nil {
                return err
        }
 
@@ -1108,8 +1118,8 @@ func (bd *byteArrayDictRecordReader) 
ReadValuesDense(toRead int64) error {
                }
 
                rdr := bd.ColumnChunkReader.(*ByteArrayColumnChunkReader)
-               _, err := 
rdr.curDecoder.(*encoding.DictByteArrayDecoder).DecodeIndices(int(toRead), 
bd.bldr)
-               return err
+               n, err := 
rdr.curDecoder.(*encoding.DictByteArrayDecoder).DecodeIndices(int(toRead), 
bd.bldr)
+               return checkDecoded(n, err, toRead)
        }
        return bd.byteArrayRecordReader.ReadValuesDense(toRead)
 }
@@ -1125,9 +1135,8 @@ func (bd *byteArrayDictRecordReader) 
ReadValuesSpaced(valuesWithNulls, nullCount
                }
 
                rdr := bd.ColumnChunkReader.(*ByteArrayColumnChunkReader)
-               _, err := 
rdr.curDecoder.(*encoding.DictByteArrayDecoder).DecodeIndicesSpaced(int(valuesWithNulls),
 int(nullCount), validBits, offset, bd.bldr)
-               return err
-
+               n, err := 
rdr.curDecoder.(*encoding.DictByteArrayDecoder).DecodeIndicesSpaced(int(valuesWithNulls),
 int(nullCount), validBits, offset, bd.bldr)
+               return checkDecoded(n, err, valuesWithNulls)
        }
 
        return bd.byteArrayRecordReader.ReadValuesSpaced(valuesWithNulls, 
int64(nullCount))
diff --git a/parquet/file/record_reader_internal_test.go 
b/parquet/file/record_reader_internal_test.go
index e9285edd..889aeccf 100644
--- a/parquet/file/record_reader_internal_test.go
+++ b/parquet/file/record_reader_internal_test.go
@@ -17,9 +17,12 @@
 package file
 
 import (
+       "bytes"
+       "slices"
        "testing"
 
        "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/bitutil"
        "github.com/apache/arrow-go/v18/arrow/memory"
        "github.com/apache/arrow-go/v18/parquet"
        "github.com/apache/arrow-go/v18/parquet/schema"
@@ -44,3 +47,141 @@ func 
TestDelimitRecordsRejectsNonzeroInitialRepetitionLevel(t *testing.T) {
        require.Zero(t, values)
        require.Zero(t, rr.levelsPos)
 }
+
+type valuePathRecorder struct {
+       recordReaderImpl
+       paths []string
+}
+
+func (p *valuePathRecorder) ReadValuesDense(toRead int64) error {
+       p.paths = append(p.paths, "dense")
+       return p.recordReaderImpl.ReadValuesDense(toRead)
+}
+
+func (p *valuePathRecorder) ReadValuesSpaced(valuesWithNulls, nullCount int64) 
error {
+       p.paths = append(p.paths, "spaced")
+       return p.recordReaderImpl.ReadValuesSpaced(valuesWithNulls, nullCount)
+}
+
+func writeInt32Column(t *testing.T, rep parquet.Repetition, values []int32, 
defLevels []int16, opts ...parquet.WriterProperty) []byte {
+       t.Helper()
+       root := schema.MustGroup(schema.NewGroupNode("schema", 
parquet.Repetitions.Required, schema.FieldList{
+               schema.NewInt32Node("values", rep, -1),
+       }, -1))
+       var buf bytes.Buffer
+       w := NewParquetWriter(&buf, root, 
WithWriterProps(parquet.NewWriterProperties(opts...)))
+       rgw := w.AppendRowGroup()
+       cw, err := rgw.NextColumn()
+       require.NoError(t, err)
+       _, err = cw.(*Int32ColumnChunkWriter).WriteBatch(values, defLevels, nil)
+       require.NoError(t, err)
+       require.NoError(t, cw.Close())
+       require.NoError(t, rgw.Close())
+       require.NoError(t, w.Close())
+       return buf.Bytes()
+}
+
+func newInt32RecordReader(t *testing.T, data []byte) *recordReader {
+       t.Helper()
+       pf, err := NewParquetReader(bytes.NewReader(data))
+       require.NoError(t, err)
+       t.Cleanup(func() { pf.Close() })
+       descr := pf.MetaData().Schema.Column(0)
+       rr := newRecordReader(descr, LevelInfo{DefLevel: 
descr.MaxDefinitionLevel()}, memory.DefaultAllocator, nil).(*recordReader)
+       t.Cleanup(rr.Release)
+       pr, err := pf.RowGroup(0).GetColumnPageReader(0)
+       require.NoError(t, err)
+       rr.SetPageReader(pr)
+       return rr
+}
+
+func TestReadRecordsDenseForBatchesWithoutNulls(t *testing.T) {
+       // Pages of four levels each: with nulls, without nulls, with nulls.
+       defLevels := []int16{1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1}
+       values := []int32{1, 2, 3, 4, 5, 6, 7, 8, 9}
+       data := writeInt32Column(t, parquet.Repetitions.Optional, values, 
defLevels,
+               parquet.WithBatchSize(4), parquet.WithDataPageSize(1))
+       rr := newInt32RecordReader(t, data)
+       rec := &valuePathRecorder{recordReaderImpl: rr.recordReaderImpl}
+       rr.recordReaderImpl = rec
+
+       n, err := rr.ReadRecords(int64(len(defLevels)))
+       require.NoError(t, err)
+       require.EqualValues(t, len(defLevels), n)
+       require.Equal(t, []string{"spaced", "dense", "spaced"}, rec.paths)
+
+       got := arrow.Int32Traits.CastFromBytes(rr.Values())
+       valid := rr.GetValidBits()
+       next := values
+       for i, def := range defLevels {
+               require.Equalf(t, def == 1, bitutil.BitIsSet(valid, i), 
"validity of row %d", i)
+               if def == 1 {
+                       require.Equalf(t, next[0], got[i], "value of row %d", i)
+                       next = next[1:]
+               }
+       }
+}
+
+func TestReadRecordsRejectsShortPage(t *testing.T) {
+       values := []int32{10, 20, 30, 40}
+       tests := []struct {
+               name      string
+               rep       parquet.Repetition
+               defLevels []int16
+       }{
+               {"optional", parquet.Repetitions.Optional, []int16{1, 1, 1, 1}},
+               {"required", parquet.Repetitions.Required, nil},
+       }
+       for _, tt := range tests {
+               t.Run(tt.name, func(t *testing.T) {
+                       data := writeInt32Column(t, tt.rep, values, 
tt.defLevels,
+                               parquet.WithDictionaryDefault(false), 
parquet.WithEncoding(parquet.Encodings.DeltaBinaryPacked))
+                       // DELTA_BINARY_PACKED header: block size 128, 4 
miniblocks, 4 values, first value 10.
+                       header := []byte{0x80, 0x01, 0x04, 0x04, 0x14}
+                       require.Equal(t, 1, bytes.Count(data, header))
+                       data[bytes.Index(data, header)+3] = 2
+
+                       _, err := newInt32RecordReader(t, 
data).ReadRecords(int64(len(values)))
+                       require.ErrorContains(t, err, "number of values / 
definition levels read did not match")
+               })
+       }
+}
+
+func TestReadRecordsRejectsShortDictionaryPageWithNulls(t *testing.T) {
+       defLevels := []int16{1, 1, 1, 1, 1, 1, 1, 1, 1, 0}
+       values := slices.Repeat([]parquet.ByteArray{parquet.ByteArray("x")}, 9)
+       root := schema.MustGroup(schema.NewGroupNode("schema", 
parquet.Repetitions.Required, schema.FieldList{
+               schema.NewByteArrayNode("values", parquet.Repetitions.Optional, 
-1),
+       }, -1))
+       var buf bytes.Buffer
+       w := NewParquetWriter(&buf, root, 
WithWriterProps(parquet.NewWriterProperties(parquet.WithDictionaryCostFallbackFor("values",
 false))))
+       rgw := w.AppendRowGroup()
+       cw, err := rgw.NextColumn()
+       require.NoError(t, err)
+       _, err = cw.(*ByteArrayColumnChunkWriter).WriteBatch(values, defLevels, 
nil)
+       require.NoError(t, err)
+       require.NoError(t, cw.Close())
+       require.NoError(t, rgw.Close())
+       require.NoError(t, w.Close())
+       data := buf.Bytes()
+
+       // Dictionary indices: bit width 1, then one RLE run of nine zeros, 
shortened to eight.
+       indices := []byte{0x01, 0x12, 0x00}
+       require.Equal(t, 1, bytes.Count(data, indices))
+       data[bytes.Index(data, indices)+1] = 0x10
+
+       pf, err := NewParquetReader(bytes.NewReader(data))
+       require.NoError(t, err)
+       defer pf.Close()
+       descr := pf.MetaData().Schema.Column(0)
+       rr := newByteArrayDictRecordReader(descr, LevelInfo{DefLevel: 1, 
NullSlotUsage: 1},
+               &arrow.DictionaryType{IndexType: arrow.PrimitiveTypes.Int32, 
ValueType: arrow.BinaryTypes.Binary},
+               memory.DefaultAllocator, nil).(*binaryRecordReader)
+       defer rr.Release()
+       pr, err := pf.RowGroup(0).GetColumnPageReader(0)
+       require.NoError(t, err)
+       rr.SetPageReader(pr)
+
+       _, err = rr.ReadRecords(int64(len(defLevels)))
+       require.ErrorContains(t, err, "number of values / definition levels 
read did not match")
+}
diff --git a/parquet/pqarrow/dictionary_reader_bench_test.go 
b/parquet/pqarrow/dictionary_reader_bench_test.go
index 8a6109f1..9ab19f03 100644
--- a/parquet/pqarrow/dictionary_reader_bench_test.go
+++ b/parquet/pqarrow/dictionary_reader_bench_test.go
@@ -30,12 +30,17 @@ import (
        "github.com/apache/arrow-go/v18/parquet/pqarrow"
 )
 
-func BenchmarkReadDictionaryColumn(b *testing.B) {
+func BenchmarkReadDictionaryColumn(b *testing.B) { 
benchmarkReadDictionaryColumn(b, false) }
+
+// BenchmarkReadOptionalDictionaryColumn reads an optional column that holds 
no nulls.
+func BenchmarkReadOptionalDictionaryColumn(b *testing.B) { 
benchmarkReadDictionaryColumn(b, true) }
+
+func benchmarkReadDictionaryColumn(b *testing.B, nullable bool) {
        const rows = 1 << 18
 
        for _, distinct := range []int{100, 10_000, 100_000} {
                b.Run(fmt.Sprintf("distinct=%d", distinct), func(b *testing.B) {
-                       parquetData := writeDictionaryStringColumn(b, 
memory.DefaultAllocator, rows, distinct)
+                       parquetData := writeDictionaryStringColumn(b, 
memory.DefaultAllocator, rows, distinct, nullable)
 
                        for _, batchSize := range []int64{8192, 65536} {
                                b.Run(fmt.Sprintf("batch=%d", batchSize), 
func(b *testing.B) {
@@ -54,10 +59,11 @@ func BenchmarkReadDictionaryColumn(b *testing.B) {
 
 // writeDictionaryStringColumn writes rows 25-byte strings with the given 
number
 // of distinct values to one row group whose data pages are all dictionary
-// encoded.
-func writeDictionaryStringColumn(tb testing.TB, mem memory.Allocator, rows, 
distinct int) []byte {
+// encoded. The column holds no nulls; nullable makes it optional rather than
+// required.
+func writeDictionaryStringColumn(tb testing.TB, mem memory.Allocator, rows, 
distinct int, nullable bool) []byte {
        tb.Helper()
-       schema := arrow.NewSchema([]arrow.Field{{Name: "s", Type: 
arrow.BinaryTypes.String}}, nil)
+       schema := arrow.NewSchema([]arrow.Field{{Name: "s", Type: 
arrow.BinaryTypes.String, Nullable: nullable}}, nil)
 
        bldr := array.NewStringBuilder(mem)
        defer bldr.Release()

Reply via email to