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 8d21bdb4 fix(parquet/file): find the dictionary page when seeking 
chunks that place it at the data page offset (#1588)
8d21bdb4 is described below

commit 8d21bdb4a971871749fc938c324a1c3a7414792f
Author: Harrison Crosse <[email protected]>
AuthorDate: Mon Nov 16 18:27:14 2026 -0500

    fix(parquet/file): find the dictionary page when seeking chunks that place 
it at the data page offset (#1588)
    
    ### Rationale for this change
    
    `SeekToRow` fails when the dictionary page sits at `data_page_offset`
    and `dictionary_page_offset` is absent or equal to it. Unreleased
    parquet-mr 1.12.0 snapshots and 1.12.0-rc0 between
    [PARQUET-1850](https://issues.apache.org/jira/browse/PARQUET-1850) and
    [PARQUET-1977](https://issues.apache.org/jira/browse/PARQUET-1977) wrote
    equal offsets.
    
    I reproduced this on v18.8.0 and main, with Go 1.26.10 on macOS arm64.
    
    ### What changes are included in this PR?
    
    When the dictionary page's length is unknown, `GetDictionaryPage` reads
    the chunk's first page, buffering only a header. Without a recorded
    offset, it ignores other page types.
    
    Without an offset index, seeking skips the dictionary page, which fixes
    `SeekToRow(0)` after a read.
    
    `GetDictionaryPage` returns an error instead of panicking on
    parquet-testing's `column_chunk_key_value_metadata.parquet`, whose
    `data_page_offset` precedes `dictionary_page_offset`.
    
    Encrypted chunks without a recorded dictionary offset are not probed,
    since a page header's AAD depends on its type.
    
    ### Are these changes tested?
    
    `TestSeekToRowDictionaryAtDataPageOffset`,
    `TestSeekToRowDictionaryPageOffsetEqualsDataPageOffset`,
    `TestGetDictionaryPageOffsetPastDataPageOffset`,
    `TestRecordReaderSeekToRowDictionaryAtDataPageOffset` and
    `TestGetDictionaryPageWithoutRecordedOffsetReadsOnlyTheDictionary` fail
    on main and pass with this change.
    
    `TestEncryptedChunkWithoutDictionaryIsNotProbed`,
    `TestSeekToRowZeroOnEncryptedChunkStartingWithDictionaryPage` and
    `TestGetDictionaryPageWithoutRecordedOffset` pass on main and guard
    unchanged behavior.
    
    Full `go test -race -tags assert,test ./parquet/...` and `golangci-lint`
    2.13.2 passed on linux/amd64 with pinned test data, and focused tests
    passed on macOS arm64.
    
    ### Are there any user-facing changes?
    
    Yes. `SeekToRow` finds dictionary pages at `data_page_offset`. There is
    no API change.
    
    Closes https://github.com/apache/arrow-go/issues/1566.
---
 parquet/file/column_reader_test.go        | 203 ++++++++++++++++++++++++++++++
 parquet/file/page_reader.go               |  37 +++++-
 parquet/file/page_reader_internal_test.go | 192 ++++++++++++++++++++++++++++
 parquet/pqarrow/file_reader_test.go       |  38 ++++++
 4 files changed, 464 insertions(+), 6 deletions(-)

diff --git a/parquet/file/column_reader_test.go 
b/parquet/file/column_reader_test.go
index 7581ed05..9d3023d9 100644
--- a/parquet/file/column_reader_test.go
+++ b/parquet/file/column_reader_test.go
@@ -18,6 +18,7 @@ package file_test
 
 import (
        "bytes"
+       "encoding/binary"
        "fmt"
        "math"
        "math/rand"
@@ -36,7 +37,9 @@ import (
        "github.com/apache/arrow-go/v18/parquet/compress"
        "github.com/apache/arrow-go/v18/parquet/file"
        "github.com/apache/arrow-go/v18/parquet/internal/encoding"
+       format "github.com/apache/arrow-go/v18/parquet/internal/gen-go/parquet"
        "github.com/apache/arrow-go/v18/parquet/internal/testutils"
+       "github.com/apache/arrow-go/v18/parquet/internal/thrift"
        "github.com/apache/arrow-go/v18/parquet/pqarrow"
        "github.com/apache/arrow-go/v18/parquet/schema"
        "github.com/stretchr/testify/assert"
@@ -856,6 +859,206 @@ func TestFullSeekRow(t *testing.T) {
        }
 }
 
+type seekBatchReader[T any] interface {
+       ReadBatch(int64, []T, []int16, []int16) (int64, int, error)
+}
+
+// readRows reads n flat values, returning nil entries for nulls.
+func readRows[T any](t *testing.T, r seekBatchReader[T], n int, maxDef int16) 
[]*T {
+       t.Helper()
+       vals := make([]T, n)
+       defs := make([]int16, n)
+       got, nvals, err := r.ReadBatch(int64(n), vals, defs, nil)
+       require.NoError(t, err)
+       require.EqualValues(t, n, got)
+
+       out := make([]*T, n)
+       next := 0
+       for i := range out {
+               if maxDef == 0 || defs[i] == maxDef {
+                       out[i] = &vals[next]
+                       next++
+               }
+       }
+       require.Equal(t, nvals, next)
+       return out
+}
+
+// Both files hold dictionary encoded columns whose chunks have no
+// dictionary_page_offset, so the dictionary page sits at data_page_offset.
+func TestSeekToRowDictionaryAtDataPageOffset(t *testing.T) {
+       dir := os.Getenv("PARQUET_TEST_DATA")
+       if dir == "" {
+               dir = "../../parquet-testing/data"
+               t.Log("PARQUET_TEST_DATA not set, using 
../../parquet-testing/data")
+       }
+       require.DirExists(t, dir)
+
+       t.Run("offset index", func(t *testing.T) {
+               fr, err := file.OpenParquetFile(filepath.Join(dir, 
"alltypes_tiny_pages.parquet"), false)
+               require.NoError(t, err)
+               defer fr.Close()
+               rg := fr.RowGroup(0)
+
+               const col, nrows = 2, 100
+               maxDef := fr.MetaData().Schema.Column(col).MaxDefinitionLevel()
+               open := func() *file.Int32ColumnChunkReader {
+                       cr, err := rg.Column(col)
+                       require.NoError(t, err)
+                       return cr.(*file.Int32ColumnChunkReader)
+               }
+               want := readRows[int32](t, open(), nrows, maxDef)
+
+               // Reading past the seek target crosses data pages, which only 
works if the
+               // dictionary load left the page stream where it was.
+               cr := open()
+               require.NoError(t, cr.SeekToRow(0))
+               require.Equal(t, want, readRows[int32](t, cr, nrows, maxDef))
+       })
+
+       t.Run("no offset index", func(t *testing.T) {
+               fr, err := file.OpenParquetFile(filepath.Join(dir, 
"datapage_v2.snappy.parquet"), false)
+               require.NoError(t, err)
+               defer fr.Close()
+               rg := fr.RowGroup(0)
+
+               const col, nrows = 2, 5
+               maxDef := fr.MetaData().Schema.Column(col).MaxDefinitionLevel()
+               open := func() *file.Float64ColumnChunkReader {
+                       cr, err := rg.Column(col)
+                       require.NoError(t, err)
+                       return cr.(*file.Float64ColumnChunkReader)
+               }
+               want := readRows[float64](t, open(), nrows, maxDef)
+
+               t.Run("fresh reader", func(t *testing.T) {
+                       cr := open()
+                       require.NoError(t, cr.SeekToRow(4))
+                       require.Equal(t, want[4:], readRows[float64](t, cr, 1, 
maxDef))
+               })
+
+               t.Run("reseek after read", func(t *testing.T) {
+                       cr := open()
+                       readRows[float64](t, cr, nrows, maxDef)
+                       require.NoError(t, cr.SeekToRow(0))
+                       require.Equal(t, want, readRows[float64](t, cr, nrows, 
maxDef))
+               })
+       })
+}
+
+func sharedOffsetFile(t *testing.T, values []int32, pageIndex bool) []byte {
+       t.Helper()
+       sc := schema.MustGroup(schema.NewGroupNode("schema", 
parquet.Repetitions.Required, schema.FieldList{
+               schema.NewInt32Node("x", parquet.Repetitions.Required, -1),
+       }, -1))
+       var out bytes.Buffer
+       w, err := file.NewParquetWriterWithError(&out, sc, 
file.WithWriterProps(parquet.NewWriterProperties(
+               parquet.WithDictionaryDefault(true),
+               parquet.WithDictionaryPageSizeLimit(1<<20),
+               parquet.WithDictionaryCostFallbackFor("x", false),
+               parquet.WithDataPageSize(256),
+               parquet.WithBatchSize(50),
+               parquet.WithPageIndexEnabled(pageIndex))))
+       require.NoError(t, err)
+       rg := w.AppendRowGroup()
+       cw, err := rg.NextColumn()
+       require.NoError(t, err)
+       _, err = cw.(*file.Int32ColumnChunkWriter).WriteBatch(values, nil, nil)
+       require.NoError(t, err)
+       require.NoError(t, cw.Close())
+       require.NoError(t, rg.Close())
+       require.NoError(t, w.Close())
+
+       data := out.Bytes()
+       footerStart := len(data) - 8 - 
int(binary.LittleEndian.Uint32(data[len(data)-8:]))
+       md := format.NewFileMetaData()
+       _, err = thrift.DeserializeThrift(md, data[footerStart:len(data)-8])
+       require.NoError(t, err)
+       chunk := md.RowGroups[0].Columns[0].MetaData
+       require.True(t, chunk.IsSetDictionaryPageOffset())
+       require.Greater(t, chunk.DataPageOffset, 
chunk.GetDictionaryPageOffset())
+       chunk.DataPageOffset = chunk.GetDictionaryPageOffset()
+
+       var footer bytes.Buffer
+       _, err = thrift.NewThriftSerializer().Serialize(md, &footer, nil)
+       require.NoError(t, err)
+       var footerLen [4]byte
+       binary.LittleEndian.PutUint32(footerLen[:], uint32(footer.Len()))
+       return append(append(append(bytes.Clone(data[:footerStart]), 
footer.Bytes()...), footerLen[:]...), "PAR1"...)
+}
+
+// Unreleased parquet-mr builds between PARQUET-1850 and PARQUET-1977 wrote
+// chunks whose data_page_offset equals dictionary_page_offset, so the
+// dictionary page sits at both offsets and a seek has to read it from there.
+func TestSeekToRowDictionaryPageOffsetEqualsDataPageOffset(t *testing.T) {
+       const nrows = 2000
+       values := make([]int32, nrows)
+       for i := range values {
+               values[i] = int32((i * 37) % 1000)
+       }
+
+       for _, pageIndex := range []bool{false, true} {
+               t.Run(fmt.Sprintf("offset index %v", pageIndex), func(t 
*testing.T) {
+                       rdr, err := 
file.NewParquetReader(bytes.NewReader(sharedOffsetFile(t, values, pageIndex)))
+                       require.NoError(t, err)
+                       t.Cleanup(func() { require.NoError(t, rdr.Close()) })
+                       open := func() *file.Int32ColumnChunkReader {
+                               cr, err := rdr.RowGroup(0).Column(0)
+                               require.NoError(t, err)
+                               t.Cleanup(func() { require.NoError(t, 
cr.Close()) })
+                               return cr.(*file.Int32ColumnChunkReader)
+                       }
+                       read := func(cr *file.Int32ColumnChunkReader, n int) 
[]int32 {
+                               got := make([]int32, n)
+                               read, _, err := cr.ReadBatch(int64(n), got, 
nil, nil)
+                               require.NoError(t, err)
+                               require.EqualValues(t, n, read)
+                               return got
+                       }
+
+                       require.Equal(t, values, read(open(), nrows))
+
+                       const row = 150
+                       cr := open()
+                       require.NoError(t, cr.SeekToRow(row))
+                       require.Equal(t, values[row:row+250], read(cr, 250))
+
+                       if pageIndex {
+                               return
+                       }
+                       t.Run("seek to row 0 after a read", func(t *testing.T) {
+                               cr := open()
+                               read(cr, 10)
+                               require.NoError(t, cr.SeekToRow(0))
+                               require.Equal(t, values[:100], read(cr, 100))
+                       })
+               })
+       }
+}
+
+// The dictionary page offset of each column chunk in this file is past its
+// data page offset of 0.
+func TestGetDictionaryPageOffsetPastDataPageOffset(t *testing.T) {
+       dir := os.Getenv("PARQUET_TEST_DATA")
+       if dir == "" {
+               dir = "../../parquet-testing/data"
+               t.Log("PARQUET_TEST_DATA not set, using 
../../parquet-testing/data")
+       }
+       require.DirExists(t, dir)
+
+       fr, err := file.OpenParquetFile(filepath.Join(dir, 
"column_chunk_key_value_metadata.parquet"), false)
+       require.NoError(t, err)
+       defer fr.Close()
+
+       for col := range fr.MetaData().Schema.NumColumns() {
+               pr, err := fr.RowGroup(0).GetColumnPageReader(col)
+               require.NoError(t, err)
+               _, err = pr.GetDictionaryPage()
+               require.Error(t, err)
+               require.NoError(t, pr.Close())
+       }
+}
+
 // Reject ALP before non-floating-point decoder traits can panic.
 func TestALPOnIntegerColumnIsRejected(t *testing.T) {
        mem := memory.NewCheckedAllocator(memory.NewGoAllocator())
diff --git a/parquet/file/page_reader.go b/parquet/file/page_reader.go
index 66c33968..b54e793b 100644
--- a/parquet/file/page_reader.go
+++ b/parquet/file/page_reader.go
@@ -21,6 +21,7 @@ import (
        "errors"
        "fmt"
        "io"
+       "math"
        "math/bits"
        "sort"
        "sync"
@@ -737,17 +738,40 @@ func extractStats(dataHeader dataheader) (pageStats 
metadata.EncodedStatistics)
        return
 }
 
+// dictionaryAtDataOffset reports whether the page at data_page_offset may be a
+// dictionary page, which is so when the chunk records no dictionary offset or
+// the same offset as the data offset. Encrypted chunks are excluded because 
the
+// AAD of a page header depends on the page type, which is unknown before the
+// header is read.
+func (p *serializedPageReader) dictionaryAtDataOffset() bool {
+       return p.dataOffset <= p.baseOffset && p.cryptoCtx.MetaDecryptor == nil
+}
+
 func (p *serializedPageReader) GetDictionaryPage() (*DictionaryPage, error) {
-       if p.dictOffset > 0 {
+       probe := p.dictOffset == 0 && p.dictionaryAtDataOffset()
+       if p.dictOffset > 0 || probe {
+               span := p.dataOffset - p.baseOffset
+               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 {
+                       span = math.MaxInt64
+                       readBufSize = min(p.r.BufferSize(), 
defaultPageHeaderSize)
+               }
                hdr := format.NewPageHeader()
-               readBufSize := min(int(p.dataOffset-p.baseOffset), 
p.r.BufferSize())
-               rd := utils.NewBufferedReader(
-                       io.NewSectionReader(p.r.Outer(), 
p.dictOffset-p.baseOffset, p.dataOffset-p.baseOffset),
-                       readBufSize)
+               rd := utils.NewBufferedReader(io.NewSectionReader(p.r.Outer(), 
0, span), readBufSize)
                if err := p.readPageHeader(rd, hdr); err != nil {
+                       if probe && errors.Is(err, io.EOF) {
+                               return nil, nil
+                       }
                        return nil, err
                }
 
+               if probe && hdr.GetType() != format.PageType_DICTIONARY_PAGE {
+                       return nil, nil
+               }
                dictHeader := hdr.GetDictionaryPageHeader()
                if dictHeader == nil {
                        return nil, errors.New("parquet: invalid dictionary 
page header")
@@ -882,7 +906,8 @@ func (p *serializedPageReader) SeekToPageWithRow(rowIdx 
int64) error {
                p.rowsSeen = 0
                p.pageOrd = 0
 
-               for p.Next() && p.rowsSeen < rowIdx {
+               skipDict := p.dictionaryAtDataOffset()
+               for p.Next() && (p.rowsSeen < rowIdx || (skipDict && 
p.curPageHdr.GetType() == format.PageType_DICTIONARY_PAGE)) {
                }
                return p.err
        }
diff --git a/parquet/file/page_reader_internal_test.go 
b/parquet/file/page_reader_internal_test.go
index 0f83b7f8..24ac96cd 100644
--- a/parquet/file/page_reader_internal_test.go
+++ b/parquet/file/page_reader_internal_test.go
@@ -25,10 +25,13 @@ import (
        "testing"
 
        "github.com/apache/arrow-go/v18/arrow/memory"
+       "github.com/apache/arrow-go/v18/internal/utils"
        "github.com/apache/arrow-go/v18/parquet"
+       "github.com/apache/arrow-go/v18/parquet/compress"
        "github.com/apache/arrow-go/v18/parquet/internal/encryption"
        format "github.com/apache/arrow-go/v18/parquet/internal/gen-go/parquet"
        "github.com/apache/arrow-go/v18/parquet/internal/thrift"
+       "github.com/apache/arrow-go/v18/parquet/schema"
        "github.com/stretchr/testify/require"
 )
 
@@ -133,3 +136,192 @@ func TestReadEncryptedPageHeaderWithTrailingPadding(t 
*testing.T) {
        require.NoError(t, err)
        require.Equal(t, "page data!", string(rest))
 }
+
+type pageSpec struct {
+       hdr  *format.PageHeader
+       body []byte
+}
+
+// encryptedChunk encrypts pages with the AADs a writer uses, numbering data
+// pages from 0, and returns a page reader over them.
+func encryptedChunk(t *testing.T, startWithDictionaryPage bool, nrows int64, 
pages ...pageSpec) *serializedPageReader {
+       t.Helper()
+       const key = "0123456789012345"
+       encProps := parquet.NewFileEncryptionProperties(key)
+       enc := encryption.NewFileEncryptor(encProps, 
memory.DefaultAllocator).GetFooterEncryptor()
+
+       var stream bytes.Buffer
+       var ord int16
+       for _, pg := range pages {
+               hdrModule, bodyModule, pageOrd := 
encryption.DataPageHeaderModule, encryption.DataPageModule, ord
+               if pg.hdr.Type == format.PageType_DICTIONARY_PAGE {
+                       hdrModule, bodyModule, pageOrd = 
encryption.DictPageHeaderModule, encryption.DictPageModule, -1
+               } else {
+                       ord++
+               }
+
+               var body bytes.Buffer
+               enc.UpdateAad(encryption.CreateModuleAad(encProps.FileAad(), 
bodyModule, 0, 0, pageOrd))
+               enc.Encrypt(&body, pg.body)
+               pg.hdr.CompressedPageSize, pg.hdr.UncompressedPageSize = 
int32(body.Len()), int32(len(pg.body))
+               hdrBytes, err := 
thrift.NewThriftSerializer().Write(context.Background(), pg.hdr)
+               require.NoError(t, err)
+
+               enc.UpdateAad(encryption.CreateModuleAad(encProps.FileAad(), 
hdrModule, 0, 0, pageOrd))
+               enc.Encrypt(&stream, hdrBytes)
+               stream.Write(body.Bytes())
+       }
+
+       fdec := 
encryption.NewFileDecryptor(parquet.NewFileDecryptionProperties(parquet.WithFooterKey(key)),
+               encProps.FileAad(), parquet.AesGcm, "", memory.DefaultAllocator)
+       rd, err := parquet.NewReaderProperties(memory.DefaultAllocator).
+               GetStream(bytes.NewReader(stream.Bytes()), 0, 
int64(stream.Len()))
+       require.NoError(t, err)
+
+       p, err := NewPageReader(rd, nrows, compress.Codecs.Uncompressed, 
memory.DefaultAllocator, &CryptoContext{
+               StartDecryptWithDictionaryPage: startWithDictionaryPage,
+               MetaDecryptor:                  
fdec.GetFooterDecryptorForColumnMeta(""),
+               DataDecryptor:                  
fdec.GetFooterDecryptorForColumnData(""),
+       })
+       require.NoError(t, err)
+       return p.(*serializedPageReader)
+}
+
+func dictPageSpec(values ...int32) pageSpec {
+       hdr := format.NewPageHeader()
+       hdr.Type = format.PageType_DICTIONARY_PAGE
+       hdr.DictionaryPageHeader = format.NewDictionaryPageHeader()
+       hdr.DictionaryPageHeader.NumValues = int32(len(values))
+       hdr.DictionaryPageHeader.Encoding = format.Encoding_PLAIN
+       body := make([]byte, 4*len(values))
+       for i, v := range values {
+               binary.LittleEndian.PutUint32(body[4*i:], uint32(v))
+       }
+       return pageSpec{hdr, body}
+}
+
+func dataPageSpec(numValues int32, enc format.Encoding, body []byte) pageSpec {
+       hdr := format.NewPageHeader()
+       hdr.Type = format.PageType_DATA_PAGE
+       hdr.DataPageHeader = format.NewDataPageHeader()
+       hdr.DataPageHeader.NumValues = numValues
+       hdr.DataPageHeader.Encoding = enc
+       return pageSpec{hdr, body}
+}
+
+func requiredInt32Column(t *testing.T, p PageReader) *Int32ColumnChunkReader {
+       t.Helper()
+       sc := schema.NewColumn(schema.NewInt32Node("a", 
parquet.Repetitions.Required, -1), 0, 0)
+       return NewColumnReader(sc, p, memory.DefaultAllocator, 
nil).(*Int32ColumnChunkReader)
+}
+
+// Pages of an encrypted chunk are decrypted with AADs that name their ordinal,
+// so a probe of the first page after other pages were read would fail to
+// authenticate.
+func TestEncryptedChunkWithoutDictionaryIsNotProbed(t *testing.T) {
+       p := encryptedChunk(t, false, 3, dataPageSpec(3, format.Encoding_PLAIN, 
[]byte{1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0}))
+       cr := requiredInt32Column(t, p)
+
+       vals := make([]int32, 3)
+       _, n, err := cr.ReadBatch(3, vals, nil, nil)
+       require.NoError(t, err)
+       require.Equal(t, []int32{1, 2, 3}, vals[:n])
+
+       dict, err := p.GetDictionaryPage()
+       require.NoError(t, err)
+       require.Nil(t, dict)
+}
+
+// A seek to row 0 of an encrypted chunk with no dictionary page offset still
+// hands the dictionary page to the column reader, because no probe can supply 
it.
+func TestSeekToRowZeroOnEncryptedChunkStartingWithDictionaryPage(t *testing.T) 
{
+       // RLE_DICTIONARY indices 0,1,1,0,0,0,1,0 at bit width 1
+       indices := []byte{1, 3, 0x46}
+       p := encryptedChunk(t, true, 8, dictPageSpec(10, 20), dataPageSpec(8, 
format.Encoding_RLE_DICTIONARY, indices))
+       cr := requiredInt32Column(t, p)
+
+       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])
+}
+
+type countingReader struct {
+       utils.Reader
+       read *int
+}
+
+func (c countingReader) ReadAt(b []byte, off int64) (int, error) {
+       n, err := c.Reader.ReadAt(b, off)
+       *c.read += n
+       return n, err
+}
+
+type countingBufferedReader struct {
+       parquet.BufferedReader
+       outer countingReader
+}
+
+func (c countingBufferedReader) Outer() utils.Reader { return c.outer }
+
+func unencryptedChunkReader(t *testing.T, nrows int64, chunk []byte) 
(*serializedPageReader, *int) {
+       t.Helper()
+       read := new(int)
+       br := utils.NewByteReader(chunk)
+       p, err := NewPageReader(countingBufferedReader{br, countingReader{br, 
read}}, nrows,
+               compress.Codecs.Uncompressed, memory.DefaultAllocator, nil)
+       require.NoError(t, err)
+       return p.(*serializedPageReader), read
+}
+
+func serializePage(t *testing.T, pg pageSpec) []byte {
+       t.Helper()
+       pg.hdr.CompressedPageSize, pg.hdr.UncompressedPageSize = 
int32(len(pg.body)), int32(len(pg.body))
+       hdrBytes, err := 
thrift.NewThriftSerializer().Write(context.Background(), pg.hdr)
+       require.NoError(t, err)
+       return append(hdrBytes, pg.body...)
+}
+
+func TestGetDictionaryPageWithoutRecordedOffset(t *testing.T) {
+       malformed := dataPageSpec(1, format.Encoding_PLAIN, make([]byte, 8))
+       malformed.hdr.DictionaryPageHeader = format.NewDictionaryPageHeader()
+       malformed.hdr.DictionaryPageHeader.NumValues = 2
+       malformed.hdr.DictionaryPageHeader.Encoding = format.Encoding_PLAIN
+
+       tests := []struct {
+               name  string
+               chunk []byte
+       }{
+               {"empty chunk", nil},
+               {"first page is a data page", serializePage(t, dataPageSpec(1, 
format.Encoding_PLAIN, make([]byte, 4)))},
+               {"data page carrying a dictionary header", serializePage(t, 
malformed)},
+       }
+       for _, tt := range tests {
+               t.Run(tt.name, func(t *testing.T) {
+                       p, _ := unencryptedChunkReader(t, 1, tt.chunk)
+                       dict, err := p.GetDictionaryPage()
+                       require.NoError(t, err)
+                       require.Nil(t, dict)
+               })
+       }
+}
+
+// The probe must not buffer the chunk, since the stream of a default reader
+// holds the whole chunk and a buffer that large is allocated and filled per 
seek.
+func TestGetDictionaryPageWithoutRecordedOffsetReadsOnlyTheDictionary(t 
*testing.T) {
+       const dictValues, bodyBytes = 16 * 1024, 1 << 20
+       values := make([]int32, dictValues)
+       for i := range values {
+               values[i] = int32(i)
+       }
+       dict := serializePage(t, dictPageSpec(values...))
+       chunk := append(dict, serializePage(t, dataPageSpec(1, 
format.Encoding_PLAIN, make([]byte, bodyBytes)))...)
+
+       p, read := unencryptedChunkReader(t, 1, chunk)
+       got, err := p.GetDictionaryPage()
+       require.NoError(t, err)
+       require.NotNil(t, got)
+       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))
+}
diff --git a/parquet/pqarrow/file_reader_test.go 
b/parquet/pqarrow/file_reader_test.go
index a8760610..4bbf9cd7 100644
--- a/parquet/pqarrow/file_reader_test.go
+++ b/parquet/pqarrow/file_reader_test.go
@@ -670,6 +670,44 @@ func TestRecordReaderSeekToRowMultiRowGroup(t *testing.T) {
        assert.Truef(t, array.RecordEqual(first, rec), "expected: %s\ngot: %s", 
first, rec)
 }
 
+// string_col in alltypes_tiny_pages is dictionary encoded and its chunk has no
+// dictionary_page_offset.
+func TestRecordReaderSeekToRowDictionaryAtDataPageOffset(t *testing.T) {
+       mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
+       defer mem.AssertSize(t, 0)
+
+       pf, err := file.OpenParquetFile(path.Join(getDataDir(), 
"alltypes_tiny_pages.parquet"), false,
+               file.WithReadProps(parquet.NewReaderProperties(mem)))
+       require.NoError(t, err)
+       defer pf.Close()
+
+       fr, err := pqarrow.NewFileReader(pf, 
pqarrow.ArrowReadProperties{BatchSize: 100}, mem)
+       require.NoError(t, err)
+
+       const stringCol, batch = 9, 36
+       newReader := func() pqarrow.RecordReader {
+               rr, err := fr.GetRecordReader(context.Background(), 
[]int{stringCol}, nil)
+               require.NoError(t, err)
+               return rr
+       }
+
+       seq := newReader()
+       defer seq.Release()
+       for range batch {
+               _, err := seq.Read()
+               require.NoError(t, err)
+       }
+       want, err := seq.Read()
+       require.NoError(t, err)
+
+       rr := newReader()
+       defer rr.Release()
+       require.NoError(t, rr.SeekToRow(batch*100))
+       got, err := rr.Read()
+       require.NoError(t, err)
+       require.Truef(t, array.RecordEqual(want, got), "expected: %s\ngot: %s", 
want, got)
+}
+
 func TestFileReaderWriterMetadata(t *testing.T) {
        mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
        defer mem.AssertSize(t, 0)

Reply via email to