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 f4d84226 fix(parquet/file): reuse decoded dictionary on seek and
report invalid dictionary offsets (#1647)
f4d84226 is described below
commit f4d8422610eae444ba9351712795d211b3b9e665
Author: Harrison Crosse <[email protected]>
AuthorDate: Fri Nov 20 16:17:48 2026 -0500
fix(parquet/file): reuse decoded dictionary on seek and report invalid
dictionary offsets (#1647)
### Rationale for this change
Follows up on #1588. Without an offset index, seeking a chunk whose
dictionary page sits at `data_page_offset` reads and decompresses the
dictionary twice. When `dictionary_page_offset` exceeds `data_page_offset`,
`GetDictionaryPage` reports a generic page header error instead of naming the
offsets.
### What changes are included in this PR?
`serializedPageReader` now caches the decoded dictionary page metadata
alongside `dictPageBuffer` so `GetDictionaryPage` reuses the already decoded
buffer instead of reading it again from the stream, clearing the cache on
`Reset` and before resizing `dictPageBuffer`.
`GetDictionaryPage` now checks `span < 0` explicitly and returns an error
naming `dictionary_page_offset` and `data_page_offset`.
### Are these changes tested?
Yes. I added tests verifying that seeking reads the dictionary once, that a
failed subsequent dictionary decode invalidates the cache, and that invalid
offset ordering reports both offsets.
### Are there any user-facing changes?
Yes. Invalid dictionary offset ordering now produces an error naming both
offsets. There is no API change.
---
parquet/file/column_reader_test.go | 6 +-
parquet/file/page_reader.go | 113 ++++++++++++++++--------------
parquet/file/page_reader_internal_test.go | 52 +++++++++++++-
3 files changed, 117 insertions(+), 54 deletions(-)
diff --git a/parquet/file/column_reader_test.go
b/parquet/file/column_reader_test.go
index 21a13c13..ac22fc5a 100644
--- a/parquet/file/column_reader_test.go
+++ b/parquet/file/column_reader_test.go
@@ -1313,10 +1313,14 @@ func TestGetDictionaryPageOffsetPastDataPageOffset(t
*testing.T) {
defer fr.Close()
for col := range fr.MetaData().Schema.NumColumns() {
+ cc, err := fr.MetaData().RowGroup(0).ColumnChunk(col)
+ require.NoError(t, err)
+
pr, err := fr.RowGroup(0).GetColumnPageReader(col)
require.NoError(t, err)
_, err = pr.GetDictionaryPage()
- require.Error(t, err)
+ require.ErrorContains(t, err, fmt.Sprintf("dictionary page
offset %d is past data page offset %d",
+ cc.DictionaryPageOffset(), cc.DataPageOffset()))
require.NoError(t, pr.Close())
}
}
diff --git a/parquet/file/page_reader.go b/parquet/file/page_reader.go
index 6f61190a..18d72bb4 100644
--- a/parquet/file/page_reader.go
+++ b/parquet/file/page_reader.go
@@ -406,6 +406,13 @@ func (d *DictionaryPage) Release() {
// IsSorted returns whether the dictionary itself is sorted
func (d *DictionaryPage) IsSorted() bool { return d.sorted }
+type cachedDictPage struct {
+ valid bool
+ nvals int32
+ encoding format.Encoding
+ sorted bool
+}
+
type serializedPageReader struct {
r parquet.BufferedReader
chunk *metadata.ColumnChunkMetaData
@@ -442,6 +449,7 @@ type serializedPageReader struct {
decompressBuffer *memory.Buffer
dataPageBuffer *memory.Buffer
dictPageBuffer *memory.Buffer
+ cachedDict cachedDictPage
err error
}
@@ -537,6 +545,7 @@ func (p *serializedPageReader) Reset(r
parquet.BufferedReader, nrows int64, comp
}
p.rowsSeen, p.pageOrd, p.nrows = 0, 0, nrows
p.curPageHdr, p.curPage, p.err = nil, nil, nil
+ p.cachedDict = cachedDictPage{}
p.r = r
p.columnCanStream = false
@@ -755,7 +764,48 @@ func (p *serializedPageReader) dictionaryAtDataOffset()
bool {
return p.dataOffset <= p.baseOffset && (p.chunkStartsWithDict ||
p.cryptoCtx.MetaDecryptor == nil)
}
+func (p *serializedPageReader) dictionaryPage() *DictionaryPage {
+ return &DictionaryPage{
+ page: page{
+ buf:
memory.NewBufferBytes(p.dictPageBuffer.Bytes()),
+ typ: format.PageType_DICTIONARY_PAGE,
+ nvals: p.cachedDict.nvals,
+ encoding: p.cachedDict.encoding,
+ },
+ sorted: p.cachedDict.sorted,
+ }
+}
+
+func (p *serializedPageReader) decodeDictPage(rd io.Reader, dictHeader
*format.DictionaryPageHeader, lenCompressed, lenUncompressed int) error {
+ if dictHeader.GetNumValues() < 0 {
+ return errors.New("parquet: invalid page header (negative
number of values)")
+ }
+
+ // A failure below would leave the cache pointing at the resized buffer.
+ p.cachedDict = cachedDictPage{}
+ p.dictPageBuffer.ResizeNoShrink(lenUncompressed)
+ data, err := p.decompress(rd, lenCompressed, p.dictPageBuffer.Bytes())
+ if err != nil {
+ return err
+ }
+ if len(data) != lenUncompressed {
+ return fmt.Errorf("parquet: metadata said %d bytes uncompressed
dictionary page, got %d bytes", lenUncompressed, len(data))
+ }
+
+ p.cachedDict = cachedDictPage{
+ valid: true,
+ nvals: dictHeader.GetNumValues(),
+ encoding: dictHeader.GetEncoding(),
+ sorted: dictHeader.IsSetIsSorted() &&
dictHeader.GetIsSorted(),
+ }
+ return nil
+}
+
func (p *serializedPageReader) GetDictionaryPage() (*DictionaryPage, error) {
+ if p.cachedDict.valid {
+ return p.dictionaryPage(), nil
+ }
+
probe := p.dictOffset == 0 && p.dictionaryAtDataOffset()
if p.dictOffset > 0 || probe {
// This reads the dictionary page from the start of the chunk,
independent of
@@ -766,12 +816,15 @@ func (p *serializedPageReader) GetDictionaryPage()
(*DictionaryPage, error) {
defer func() { p.cryptoCtx.StartDecryptWithDictionaryPage =
atDictionary }()
span := p.dataOffset - p.baseOffset
+ if span < 0 {
+ return nil, fmt.Errorf("parquet: dictionary page offset
%d is past data page offset %d", p.dictOffset, p.dataOffset)
+ }
readBufSize := int(min(span, int64(p.r.BufferSize())))
// The dictionary page starts the stream, and the data offset
marks its end
- // only when it is past the dictionary offset. Otherwise the
length is
- // unknown, as it is when no dictionary offset is recorded.
Buffer only a
- // page header, since the stream of a default reader holds the
whole chunk.
- if span <= 0 {
+ // when it is past the dictionary offset. When they are equal,
or no
+ // dictionary offset is recorded, the length is unknown. Buffer
only a page
+ // header, since the stream of a default reader holds the whole
chunk.
+ if span == 0 {
span = math.MaxInt64
readBufSize = min(p.r.BufferSize(),
defaultPageHeaderSize)
}
@@ -801,30 +854,10 @@ func (p *serializedPageReader) GetDictionaryPage()
(*DictionaryPage, error) {
return nil, err
}
- if dictHeader.GetNumValues() < 0 {
- return nil, errors.New("parquet: invalid page header
(negative number of values)")
- }
-
- p.dictPageBuffer.ResizeNoShrink(lenUncompressed)
- buf := memory.NewBufferBytes(p.dictPageBuffer.Bytes())
-
- data, err := p.decompress(rd, lenCompressed, buf.Bytes())
- if err != nil {
+ if err := p.decodeDictPage(rd, dictHeader, lenCompressed,
lenUncompressed); err != nil {
return nil, err
}
- if len(data) != lenUncompressed {
- return nil, fmt.Errorf("parquet: metadata said %d bytes
uncompressed dictionary page, got %d bytes", lenUncompressed, len(data))
- }
-
- return &DictionaryPage{
- page: page{
- buf: buf,
- typ: hdr.Type,
- nvals: dictHeader.GetNumValues(),
- encoding: dictHeader.GetEncoding(),
- },
- sorted: dictHeader.IsSetIsSorted() &&
dictHeader.GetIsSorted(),
- }, nil
+ return p.dictionaryPage(), nil
}
return nil, nil
@@ -1066,35 +1099,11 @@ func (p *serializedPageReader) Next() bool {
switch p.curPageHdr.GetType() {
case format.PageType_DICTIONARY_PAGE:
p.cryptoCtx.StartDecryptWithDictionaryPage = false
- dictHeader := p.curPageHdr.GetDictionaryPageHeader()
- if dictHeader.GetNumValues() < 0 {
- p.err = errors.New("parquet: invalid page
header (negative number of values)")
- return false
- }
-
- p.dictPageBuffer.ResizeNoShrink(lenUncompressed)
- buf := memory.NewBufferBytes(p.dictPageBuffer.Bytes())
-
- data, err := p.decompress(p.r, lenCompressed,
buf.Bytes())
- if err != nil {
+ if err := p.decodeDictPage(p.r,
p.curPageHdr.GetDictionaryPageHeader(), lenCompressed, lenUncompressed); err !=
nil {
p.err = err
return false
}
- if len(data) != lenUncompressed {
- p.err = fmt.Errorf("parquet: metadata said %d
bytes uncompressed dictionary page, got %d bytes", lenUncompressed, len(data))
- return false
- }
-
- // make dictionary page
- p.curPage = &DictionaryPage{
- page: page{
- buf: buf,
- typ: p.curPageHdr.Type,
- nvals: dictHeader.GetNumValues(),
- encoding: dictHeader.GetEncoding(),
- },
- sorted: dictHeader.IsSetIsSorted() &&
dictHeader.GetIsSorted(),
- }
+ p.curPage = p.dictionaryPage()
case format.PageType_DATA_PAGE:
p.pageOrd++
diff --git a/parquet/file/page_reader_internal_test.go
b/parquet/file/page_reader_internal_test.go
index d3e24bd9..ebda94b0 100644
--- a/parquet/file/page_reader_internal_test.go
+++ b/parquet/file/page_reader_internal_test.go
@@ -346,8 +346,14 @@ func unencryptedChunkReader(t *testing.T, nrows int64,
chunk []byte) (*serialize
}
func serializePage(t *testing.T, pg pageSpec) []byte {
+ return serializePageWithSizes(t, pg, int32(len(pg.body)),
int32(len(pg.body)))
+}
+
+// serializePageWithSizes writes a page whose header declares sizes that need
not
+// match its body, as a corrupt file may.
+func serializePageWithSizes(t *testing.T, pg pageSpec, compressed,
uncompressed int32) []byte {
t.Helper()
- pg.hdr.CompressedPageSize, pg.hdr.UncompressedPageSize =
int32(len(pg.body)), int32(len(pg.body))
+ pg.hdr.CompressedPageSize, pg.hdr.UncompressedPageSize = compressed,
uncompressed
hdrBytes, err :=
thrift.NewThriftSerializer().Write(context.Background(), pg.hdr)
require.NoError(t, err)
return append(hdrBytes, pg.body...)
@@ -395,3 +401,47 @@ func
TestGetDictionaryPageWithoutRecordedOffsetReadsOnlyTheDictionary(t *testing
require.EqualValues(t, dictValues, got.NumValues())
require.Less(t, *read, 2*len(dict), "read %d of %d chunk bytes for a %d
byte dictionary page", *read, len(chunk), len(dict))
}
+
+func TestSeekToRowDictionaryAtDataPageOffsetReadsDictionaryOnce(t *testing.T) {
+ // RLE_DICTIONARY indices 0,1,1,0,0,0,1,0 at bit width 1
+ indices := []byte{1, 3, 0x46}
+ chunk := append(
+ serializePage(t, dictPageSpec(10, 20)),
+ serializePage(t, dataPageSpec(8,
format.Encoding_RLE_DICTIONARY, indices))...,
+ )
+
+ p, outerRead := unencryptedChunkReader(t, 8, chunk)
+ cr := requiredInt32Column(t, p)
+ t.Cleanup(func() { require.NoError(t, cr.Close()) })
+
+ require.NoError(t, cr.SeekToRow(0))
+ vals := make([]int32, 8)
+ _, n, err := cr.ReadBatch(8, vals, nil, nil)
+ require.NoError(t, err)
+ require.Equal(t, []int32{10, 20, 20, 10, 10, 10, 20, 10}, vals[:n])
+ require.Zero(t, *outerRead, "dictionary page was re-read from the chunk
stream after seek already decoded it")
+}
+
+// A dictionary page that fails to decode must invalidate the cached
dictionary,
+// or a later GetDictionaryPage reports the resized dictionary buffer under the
+// header of the page that did decode.
+func TestNextFailedDictionaryPageInvalidatesCachedDictionary(t *testing.T) {
+ first := serializePage(t, dictPageSpec(10, 20))
+ // The second page claims 16 uncompressed bytes but carries 8, which
the reader
+ // rejects after resizing and partly overwriting the dictionary buffer.
+ second := dictPageSpec(4, 5)
+ chunk := append(first, serializePageWithSizes(t, second,
int32(len(second.body)), 16)...)
+
+ p, _ := unencryptedChunkReader(t, 8, chunk)
+ require.True(t, p.Next())
+
+ require.False(t, p.Next())
+ require.ErrorContains(t, p.err, "uncompressed dictionary page")
+
+ // The cache is repopulated by re-reading the chunk, not from the
buffer that the
+ // failed page resized.
+ dict, err := p.GetDictionaryPage()
+ require.NoError(t, err)
+ require.EqualValues(t, 2, dict.NumValues())
+ require.Equal(t, []byte{10, 0, 0, 0, 20, 0, 0, 0}, dict.Data())
+}