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 66722e30 perf(parquet/internal/encoding): preallocate dictionaries
bounded by page data (#1473)
66722e30 is described below
commit 66722e30df98ddd6f7bb46023fa13287b84308f6
Author: Matt Topol <[email protected]>
AuthorDate: Fri Nov 6 12:15:00 2026 -0500
perf(parquet/internal/encoding): preallocate dictionaries bounded by page
data (#1473)
### Rationale for this change
Since #1011, reading dictionary-encoded columns allocates more than in
v18.7.0. `dictConverter.ensure` decodes into a temporary slice and
appends it to the dictionary each time a batch reaches a higher index,
so a large dictionary is reallocated many times. #1011's bounds checks
are correct; this restores a single up-front allocation without trusting
the declared dictionary length.
The analysis and the core fix are from @zoobst in #1446. This PR ports
their patch to current main.
### What changes are included in this PR?
- `ensure` decodes straight into the dictionary's spare capacity,
growing geometrically when it needs more room.
- `NewDictConverter` bounds the dictionary by the number of values the
page's bytes can hold (page bytes / minimum PLAIN value size) as well as
by the declared length.
- The dictionary is allocated up front, but never with more memory than
the page itself, since slice-backed values such as `ByteArray` cost a
slice header per entry.
- An index the page's bytes can't reach is rejected before the
dictionary grows, so a header that overstates its length can't force a
large allocation. On main, such an index allocates up to the index
before the short page is detected.
- Indexes are still checked against the declared length, and a short
dictionary is still reported as an error.
Reading the same 1M-row file (float64, int64 and binary columns, Snappy)
through `pqarrow.ReadTable`:
| Distinct values | v18.7.0 | main | this PR |
| --- | ---: | ---: | ---: |
| 10k | 121.3 MiB | 122.7 MiB | 121.0 MiB |
| 100k | 136.1 MiB | 147.8 MiB | 135.9 MiB |
Read time was unchanged or slightly faster.
### Are these changes tested?
Yes.
### Are there any user-facing changes?
Lower memory use when reading dictionary-encoded columns, and corrupt
dictionary pages that overstate their length fail without a large
allocation. There is no API change.
Closes #1446.
---
parquet/internal/encoding/decoder.go | 6 ++
.../internal/encoding/dictionary_converter_test.go | 41 +++++++++++-
parquet/internal/encoding/typed_encoder.go | 73 +++++++++++++++++++---
3 files changed, 111 insertions(+), 9 deletions(-)
diff --git a/parquet/internal/encoding/decoder.go
b/parquet/internal/encoding/decoder.go
index a6f7931d..1ee888d2 100644
--- a/parquet/internal/encoding/decoder.go
+++ b/parquet/internal/encoding/decoder.go
@@ -99,6 +99,12 @@ func (d *decoder) SetData(nvals int, data []byte) error {
// ValuesLeft returns the number of remaining values that can be decoded
func (d *decoder) ValuesLeft() int { return d.nvals }
+// dataLen returns the number of encoded bytes left to decode.
+func (d *decoder) dataLen() int { return len(d.data) }
+
+// fixedLen returns the value width for a FixedLenByteArray column, or -1.
+func (d *decoder) fixedLen() int { return d.typeLen }
+
// Encoding returns the encoding type used by this decoder to decode the bytes.
func (d *decoder) Encoding() parquet.Encoding { return
parquet.Encoding(d.encoding) }
diff --git a/parquet/internal/encoding/dictionary_converter_test.go
b/parquet/internal/encoding/dictionary_converter_test.go
index 9e318d90..7c1ecca1 100644
--- a/parquet/internal/encoding/dictionary_converter_test.go
+++ b/parquet/internal/encoding/dictionary_converter_test.go
@@ -17,7 +17,9 @@
package encoding
import (
+ "runtime"
"testing"
+ "unsafe"
"github.com/apache/arrow-go/v18/arrow/memory"
"github.com/apache/arrow-go/v18/parquet"
@@ -30,11 +32,46 @@ func TestDictionaryConverterBoundsGrowthByValuesLeft(t
*testing.T) {
require.NoError(t, decoder.SetData(1, []byte{42, 0, 0, 0}))
converter := NewDictConverter[int32](decoder).(*dictConverter[int32])
- require.Zero(t, cap(converter.dict))
require.Equal(t, 1, converter.dictLen)
+ require.LessOrEqual(t, cap(converter.dict), 1)
require.Error(t, converter.ensure(utils.IndexType(1<<30)))
- require.Zero(t, cap(converter.dict))
+ require.LessOrEqual(t, cap(converter.dict), 1)
require.NoError(t, converter.ensure(0))
require.Equal(t, []int32{42}, converter.dict)
}
+
+func TestDictionaryConverterBoundsGrowthByData(t *testing.T) {
+ decoder := NewDecoder(parquet.Types.Int32, parquet.Encodings.Plain,
nil, memory.DefaultAllocator)
+ require.NoError(t, decoder.SetData(1<<30, []byte{42, 0, 0, 0}))
+ converter := NewDictConverter[int32](decoder).(*dictConverter[int32])
+
+ require.LessOrEqual(t, cap(converter.dict), 1)
+ // an index the page's 4 bytes can't reach is rejected before the
+ // dictionary grows toward it
+ var before, after runtime.MemStats
+ runtime.ReadMemStats(&before)
+ require.Error(t, converter.ensure(utils.IndexType(1<<24)))
+ runtime.ReadMemStats(&after)
+ require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(1<<20))
+ require.LessOrEqual(t, cap(converter.dict), 1)
+
+ require.NoError(t, converter.ensure(0))
+ require.Equal(t, []int32{42}, converter.dict)
+ require.Error(t, converter.ensure(1))
+ require.LessOrEqual(t, cap(converter.dict), 1)
+}
+
+func TestDictionaryConverterPreallocNoLargerThanPage(t *testing.T) {
+ // 4096 zero-length values: each is just a 4-byte length prefix, but
+ // would cost a slice header in the dictionary
+ const n = 4096
+ data := make([]byte, 4*n)
+ decoder := NewDecoder(parquet.Types.ByteArray, parquet.Encodings.Plain,
nil, memory.DefaultAllocator)
+ require.NoError(t, decoder.SetData(n, data))
+ converter :=
NewDictConverter[parquet.ByteArray](decoder).(*dictConverter[parquet.ByteArray])
+
+ require.LessOrEqual(t,
cap(converter.dict)*int(unsafe.Sizeof(parquet.ByteArray(nil))), len(data))
+ require.NoError(t, converter.ensure(n-1))
+ require.Len(t, converter.dict, n)
+}
diff --git a/parquet/internal/encoding/typed_encoder.go
b/parquet/internal/encoding/typed_encoder.go
index b4861e08..ed75f45f 100644
--- a/parquet/internal/encoding/typed_encoder.go
+++ b/parquet/internal/encoding/typed_encoder.go
@@ -341,8 +341,11 @@ func (d *typedDictDecoder[T]) DecodeSpaced(out []T,
nullCount int, validBits []b
type dictConverter[T parquet.ColumnTypes] struct {
valueDecoder Decoder[T]
dictLen int
- dict []T
- zeroVal T
+ // maxLen is the most values the dictionary page's bytes can hold,
+ // never more than dictLen.
+ maxLen int
+ dict []T
+ zeroVal T
}
func (dc *dictConverter[T]) ensure(idx utils.IndexType) error {
@@ -350,15 +353,29 @@ func (dc *dictConverter[T]) ensure(idx utils.IndexType)
error {
return fmt.Errorf("parquet: dictionary index %d is out of
range", idx)
}
if len(dc.dict) <= int(idx) {
- val := make([]T, int(idx)+1-len(dc.dict))
- n, err := dc.valueDecoder.Decode(val)
+ // Reject an index the page's bytes cannot reach before
allocating,
+ // so a header that overstates its length can't force a large
+ // allocation.
+ if int(idx) >= dc.maxLen {
+ return errors.New("parquet: dictionary contains fewer
values than declared")
+ }
+ need := int(idx) + 1
+ if cap(dc.dict) < need {
+ // Grow geometrically so indexes that climb a few at a
time
+ // don't reallocate the dictionary on every batch.
+ grown := make([]T, len(dc.dict), min(max(need,
2*cap(dc.dict)), dc.maxLen))
+ copy(grown, dc.dict)
+ dc.dict = grown
+ }
+ cur := len(dc.dict)
+ n, err := dc.valueDecoder.Decode(dc.dict[cur:need])
if err != nil {
return err
}
- if n != len(val) {
+ if n != need-cur {
return errors.New("parquet: dictionary contains fewer
values than declared")
}
- dc.dict = append(dc.dict, val[:n]...)
+ dc.dict = dc.dict[:need]
}
return nil
}
@@ -753,7 +770,49 @@ func (enc *DictFixedLenByteArrayEncoder) Type()
parquet.Type {
// NewDictConverter creates a dict converter of the appropriate type, using
the passed in
// decoder as the decoder to decode the dictionary index.
func NewDictConverter[T parquet.ColumnTypes](dict TypedDecoder)
utils.DictionaryConverter[T] {
- return &dictConverter[T]{valueDecoder: dict.(Decoder[T]), dictLen:
dict.ValuesLeft()}
+ dc := &dictConverter[T]{valueDecoder: dict.(Decoder[T]), dictLen:
dict.ValuesLeft()}
+ dc.maxLen = dc.dictLen
+ // The declared length alone is not trusted, since a corrupt header can
+ // claim far more values than the page contains. Bound it by what the
+ // page's bytes can hold. Allocate up front, but never more memory than
+ // the page itself: slice-backed values cost a slice header per entry,
+ // far more than an empty encoded value, so beyond that ensure grows the
+ // dictionary only when an index needs it.
+ if d, ok := dict.(interface {
+ dataLen() int
+ fixedLen() int
+ }); ok {
+ if n, ok := maxPlainValues[T](d.dataLen(), d.fixedLen()); ok {
+ dc.maxLen = min(dc.dictLen, n)
+ dc.dict = make([]T, 0, min(dc.maxLen,
d.dataLen()/int(unsafe.Sizeof(dc.zeroVal))))
+ }
+ }
+ return dc
+}
+
+// maxPlainValues returns the most PLAIN-encoded values of T that dataLen
+// bytes can hold, and false when there is no useful bound.
+func maxPlainValues[T parquet.ColumnTypes](dataLen, fixedLen int) (int, bool) {
+ var size int
+ var zero T
+ switch any(zero).(type) {
+ case bool:
+ return dataLen * 8, true // bit-packed
+ case int32, float32:
+ size = 4
+ case int64, float64:
+ size = 8
+ case parquet.Int96:
+ size = 12
+ case parquet.ByteArray:
+ size = 4 // the length prefix
+ case parquet.FixedLenByteArray:
+ size = fixedLen
+ }
+ if size <= 0 {
+ return 0, false
+ }
+ return dataLen / size, true
}
var (