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 faac56cf fix(parquet/file): seek encrypted chunks that have a 
dictionary page (#1594)
faac56cf is described below

commit faac56cfd1fa7eb259dda19240dcc03056b29ea2
Author: Harrison Crosse <[email protected]>
AuthorDate: Wed Nov 18 13:30:39 2026 -0500

    fix(parquet/file): seek encrypted chunks that have a dictionary page (#1594)
    
    ### Rationale for this change
    
    `SeekToRow` uses the wrong page header AAD on encrypted dictionary columns.
    
    I reproduced this on v18.9.0 and main, with Go 1.26.10 on macOS arm64.
    
    ### What changes are included in this PR?
    
    `SeekToPageWithRow` clears `StartDecryptWithDictionaryPage` when it skips 
the dictionary page. `GetDictionaryPage`, which the column reader calls next, 
sets the flag for its header read and restores it.
    
    When the dictionary page is at `data_page_offset`, because 
`dictionary_page_offset` equals it or is 0, a seek without an offset index 
returns there after an earlier read cleared the flag. Seeking restores the 
flag's initial value. `dictionaryAtDataOffset`, added in #1588, also returns 
true for encrypted chunks whose metadata declares a dictionary page, so seeking 
skips it as for plaintext chunks.
    
    ### Are these changes tested?
    
    - `TestSeekToRowEncryptedDictionary` seeks with and without an offset index.
    - `TestGetDictionaryPageOnEncryptedChunk` reads the dictionary before and 
after `Next` does.
    - `TestReseekOnEncryptedChunkWithSharedPageOffset` reseeks after a read, 
with and without a dictionary offset.
    - `TestRecordReaderSeekToRowEncryptedDictionary` covers `pqarrow`.
    - `TestSeekToRowEncryptedTestData` seeks in an Arrow C++ file.
    
    All five fail on main and pass with this change.
    
    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. Seeking encrypted dictionary columns succeeds. There is no API change.
    
    Closes #1593
---
 parquet/encryption_read_config_test.go    |  32 +++++++
 parquet/file/column_reader_test.go        | 143 ++++++++++++++++++++++++++++++
 parquet/file/page_reader.go               |  27 ++++--
 parquet/file/page_reader_internal_test.go |  35 +++++++-
 parquet/pqarrow/file_reader_test.go       |  64 +++++++++++++
 5 files changed, 294 insertions(+), 7 deletions(-)

diff --git a/parquet/encryption_read_config_test.go 
b/parquet/encryption_read_config_test.go
index 9b1fcffa..e60f437f 100644
--- a/parquet/encryption_read_config_test.go
+++ b/parquet/encryption_read_config_test.go
@@ -622,6 +622,38 @@ func (d *TestDecryptionSuite) TestDecryption() {
        }
 }
 
+// uniform_encryption.parquet.encrypted was written by Arrow C++, with a
+// dictionary page and an offset index in each chunk.
+func TestSeekToRowEncryptedTestData(t *testing.T) {
+       props := parquet.NewReaderProperties(memory.DefaultAllocator)
+       props.FileDecryptProps = 
parquet.NewFileDecryptionProperties(parquet.WithFooterKey(FooterEncryptionKey))
+       rdr, err := file.OpenParquetFile(path.Join(getDataDir(), 
"uniform_encryption.parquet.encrypted"), false, file.WithReadProps(props))
+       require.NoError(t, err)
+       defer rdr.Close()
+
+       const col, nrows, row = 1, 50, 24
+       chunk, err := rdr.MetaData().RowGroup(0).ColumnChunk(col)
+       require.NoError(t, err)
+       require.Equal(t, parquet.Types.Int32, chunk.Type())
+       require.True(t, chunk.HasDictionaryPage())
+
+       read := func(seekTo, n int) []int32 {
+               cr, err := rdr.RowGroup(0).Column(col)
+               require.NoError(t, err)
+               defer cr.Close()
+               ir := cr.(*file.Int32ColumnChunkReader)
+               if seekTo > 0 {
+                       require.NoError(t, ir.SeekToRow(int64(seekTo)))
+               }
+               vals := make([]int32, n)
+               got, _, err := ir.ReadBatch(int64(n), vals, nil, nil)
+               require.NoError(t, err)
+               require.EqualValues(t, n, got)
+               return vals
+       }
+       require.Equal(t, read(0, nrows)[row:], read(row, nrows-row))
+}
+
 // javaKeyRetriever unwraps keys the way parquet-mr's KeyToolkit does for a 
file written
 // with external key material and double wrapping: the KMS master key unwraps 
a key
 // encryption key (KEK), and the KEK unwraps the data key.
diff --git a/parquet/file/column_reader_test.go 
b/parquet/file/column_reader_test.go
index 42124ea8..c964f8c6 100644
--- a/parquet/file/column_reader_test.go
+++ b/parquet/file/column_reader_test.go
@@ -1319,6 +1319,149 @@ func TestGetDictionaryPageOffsetPastDataPageOffset(t 
*testing.T) {
        }
 }
 
+const (
+       encSeekRowGroups = 2
+       encSeekRows      = 1500
+       encSeekKey       = "0123456789012345"
+)
+
+func encryptedDictionaryFile(t *testing.T, pageIndex bool) []byte {
+       t.Helper()
+       sc := schema.MustGroup(schema.NewGroupNode("schema", 
parquet.Repetitions.Required, schema.FieldList{
+               schema.NewInt64Node("x", parquet.Repetitions.Required, -1),
+       }, -1))
+
+       var out bytes.Buffer
+       w, err := file.NewParquetWriterWithError(&out, sc, 
file.WithWriterProps(parquet.NewWriterProperties(
+               
parquet.WithEncryptionProperties(parquet.NewFileEncryptionProperties(encSeekKey)),
+               parquet.WithDictionaryDefault(true),
+               parquet.WithDictionaryCostFallbackFor("x", false),
+               parquet.WithDictionaryPageSizeLimit(1<<20),
+               parquet.WithDataPageSize(400),
+               parquet.WithBatchSize(16),
+               parquet.WithPageIndexEnabled(pageIndex))))
+       require.NoError(t, err)
+       for rg := range encSeekRowGroups {
+               rgw, err := w.AppendRowGroupChecked()
+               require.NoError(t, err)
+               cw, err := rgw.NextColumn()
+               require.NoError(t, err)
+               vals := make([]int64, encSeekRows)
+               for i := range vals {
+                       vals[i] = int64((i*31 + rg) % 97)
+               }
+               _, err = cw.(*file.Int64ColumnChunkWriter).WriteBatch(vals, 
nil, nil)
+               require.NoError(t, err)
+               require.NoError(t, cw.Close())
+               require.NoError(t, rgw.Close())
+       }
+       require.NoError(t, w.Close())
+       return out.Bytes()
+}
+
+func openEncryptedFile(t *testing.T, data []byte) *file.Reader {
+       t.Helper()
+       props := parquet.NewReaderProperties(memory.DefaultAllocator)
+       props.FileDecryptProps = 
parquet.NewFileDecryptionProperties(parquet.WithFooterKey(encSeekKey))
+       rdr, err := file.NewParquetReader(bytes.NewReader(data), 
file.WithReadProps(props))
+       require.NoError(t, err)
+       t.Cleanup(func() { require.NoError(t, rdr.Close()) })
+       return rdr
+}
+
+// dataPageRows returns the number of values in each data page of column 0, and
+// whether the chunk starts with a dictionary page.
+func dataPageRows(t *testing.T, rg *file.RowGroupReader) (rows []int64, 
dictionary bool) {
+       t.Helper()
+       pr, err := rg.GetColumnPageReader(0)
+       require.NoError(t, err)
+       defer pr.Close()
+       for pr.Next() {
+               switch pg := pr.Page().(type) {
+               case *file.DictionaryPage:
+                       dictionary = true
+               case file.DataPage:
+                       rows = append(rows, int64(pg.NumValues()))
+               }
+       }
+       require.NoError(t, pr.Err())
+       return rows, dictionary
+}
+
+func TestSeekToRowEncryptedDictionary(t *testing.T) {
+       const row = 700
+       for _, pageIndex := range []bool{false, true} {
+               t.Run(fmt.Sprintf("offset index %v", pageIndex), func(t 
*testing.T) {
+                       rdr := openEncryptedFile(t, encryptedDictionaryFile(t, 
pageIndex))
+                       rg := rdr.RowGroup(encSeekRowGroups - 1)
+
+                       chunk, err := rdr.MetaData().RowGroup(encSeekRowGroups 
- 1).ColumnChunk(0)
+                       require.NoError(t, err)
+                       require.Equal(t, pageIndex, 
chunk.GetOffsetIndexLocation() != nil)
+                       rows, dictionary := dataPageRows(t, rg)
+                       require.True(t, dictionary)
+                       require.Greater(t, len(rows), 4)
+                       require.Less(t, rows[0], int64(row))
+
+                       open := func() *file.Int64ColumnChunkReader {
+                               cr, err := rg.Column(0)
+                               require.NoError(t, err)
+                               t.Cleanup(func() { require.NoError(t, 
cr.Close()) })
+                               return cr.(*file.Int64ColumnChunkReader)
+                       }
+                       want := readRows[int64](t, open(), encSeekRows, 0)
+
+                       cr := open()
+                       require.NoError(t, cr.SeekToRow(row))
+                       require.Equal(t, want[row:row+300], readRows[int64](t, 
cr, 300, 0))
+               })
+       }
+}
+
+func TestGetDictionaryPageOnEncryptedChunk(t *testing.T) {
+       rdr := openEncryptedFile(t, encryptedDictionaryFile(t, false))
+       rg := rdr.RowGroup(encSeekRowGroups - 1)
+       wantRows, _ := dataPageRows(t, rg)
+
+       scan := func(t *testing.T, pr file.PageReader) {
+               var rows []int64
+               for pr.Next() {
+                       rows = append(rows, 
int64(pr.Page().(file.DataPage).NumValues()))
+               }
+               require.NoError(t, pr.Err())
+               require.Equal(t, wantRows, rows)
+       }
+
+       t.Run("before the first page", func(t *testing.T) {
+               pr, err := rg.GetColumnPageReader(0)
+               require.NoError(t, err)
+               defer pr.Close()
+
+               dict, err := pr.GetDictionaryPage()
+               require.NoError(t, err)
+               require.NotNil(t, dict)
+
+               require.True(t, pr.Next(), "reading after GetDictionaryPage: 
%v", pr.Err())
+               require.IsType(t, &file.DictionaryPage{}, pr.Page())
+               scan(t, pr)
+       })
+
+       t.Run("after the dictionary page was read", func(t *testing.T) {
+               pr, err := rg.GetColumnPageReader(0)
+               require.NoError(t, err)
+               defer pr.Close()
+
+               require.True(t, pr.Next(), pr.Err())
+               want := pr.Page().(*file.DictionaryPage).NumValues()
+
+               dict, err := pr.GetDictionaryPage()
+               require.NoError(t, err)
+               require.NotNil(t, dict)
+               require.Equal(t, want, dict.NumValues())
+               scan(t, pr)
+       })
+}
+
 // 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 b54e793b..36a5211d 100644
--- a/parquet/file/page_reader.go
+++ b/parquet/file/page_reader.go
@@ -433,6 +433,10 @@ type serializedPageReader struct {
        dataPageAad       string
        dataPageHeaderAad string
 
+       // The initial value of cryptoCtx.StartDecryptWithDictionaryPage, which 
the
+       // reader clears once it is past the dictionary page.
+       chunkStartsWithDict bool
+
        baseOffset, dataOffset, dictOffset int64
 
        decompressBuffer *memory.Buffer
@@ -477,6 +481,7 @@ func (p *serializedPageReader) init(compressType 
compress.Compression, ctx *Cryp
 
        if ctx != nil {
                p.cryptoCtx = *ctx
+               p.chunkStartsWithDict = ctx.StartDecryptWithDictionaryPage
                p.initDecryption()
        }
 
@@ -520,6 +525,7 @@ func NewPageReader(r parquet.BufferedReader, nrows int64, 
compressType compress.
        rdr.decompressBuffer.ResizeNoShrink(defaultPageHeaderSize)
        if ctx != nil {
                rdr.cryptoCtx = *ctx
+               rdr.chunkStartsWithDict = ctx.StartDecryptWithDictionaryPage
                rdr.initDecryption()
        }
        return rdr, nil
@@ -540,9 +546,11 @@ func (p *serializedPageReader) Reset(r 
parquet.BufferedReader, nrows int64, comp
        }
        if ctx != nil {
                p.cryptoCtx = *ctx
+               p.chunkStartsWithDict = ctx.StartDecryptWithDictionaryPage
                p.initDecryption()
        } else {
                p.cryptoCtx = CryptoContext{}
+               p.chunkStartsWithDict = false
                p.dataPageAad = ""
                p.dataPageHeaderAad = ""
        }
@@ -740,16 +748,23 @@ func extractStats(dataHeader dataheader) (pageStats 
metadata.EncodedStatistics)
 
 // 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.
+// the same offset as the data offset. Encrypted chunks whose metadata declares
+// no dictionary page 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
+       return p.dataOffset <= p.baseOffset && (p.chunkStartsWithDict || 
p.cryptoCtx.MetaDecryptor == nil)
 }
 
 func (p *serializedPageReader) GetDictionaryPage() (*DictionaryPage, error) {
        probe := p.dictOffset == 0 && p.dictionaryAtDataOffset()
        if p.dictOffset > 0 || probe {
+               // This reads the dictionary page from the start of the chunk, 
independent of
+               // p.r, so it needs the dictionary AAD. Restore the flag so it 
still describes
+               // the next page of p.r.
+               atDictionary := p.cryptoCtx.StartDecryptWithDictionaryPage
+               p.cryptoCtx.StartDecryptWithDictionaryPage = true
+               defer func() { p.cryptoCtx.StartDecryptWithDictionaryPage = 
atDictionary }()
+
                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
@@ -777,7 +792,6 @@ func (p *serializedPageReader) GetDictionaryPage() 
(*DictionaryPage, error) {
                        return nil, errors.New("parquet: invalid dictionary 
page header")
                }
 
-               p.cryptoCtx.StartDecryptWithDictionaryPage = true
                if p.cryptoCtx.DataDecryptor != nil {
                        p.updateDecryption(p.cryptoCtx.DataDecryptor, 
encryption.DictPageModule, p.dataPageAad)
                }
@@ -787,7 +801,6 @@ func (p *serializedPageReader) GetDictionaryPage() 
(*DictionaryPage, error) {
                        return nil, err
                }
 
-               p.cryptoCtx.StartDecryptWithDictionaryPage = false
                if dictHeader.GetNumValues() < 0 {
                        return nil, errors.New("parquet: invalid page header 
(negative number of values)")
                }
@@ -905,6 +918,7 @@ func (p *serializedPageReader) SeekToPageWithRow(rowIdx 
int64) error {
 
                p.rowsSeen = 0
                p.pageOrd = 0
+               p.cryptoCtx.StartDecryptWithDictionaryPage = p.dataOffset <= 
p.baseOffset && p.chunkStartsWithDict
 
                skipDict := p.dictionaryAtDataOffset()
                for p.Next() && (p.rowsSeen < rowIdx || (skipDict && 
p.curPageHdr.GetType() == format.PageType_DICTIONARY_PAGE)) {
@@ -927,6 +941,7 @@ func (p *serializedPageReader) SeekToPageWithRow(rowIdx 
int64) error {
 
        p.r.Reset(section)
        p.rowsSeen, p.pageOrd = pages[index].FirstRowIndex, int16(index)
+       p.cryptoCtx.StartDecryptWithDictionaryPage = false
        p.Next()
        return p.err
 }
diff --git a/parquet/file/page_reader_internal_test.go 
b/parquet/file/page_reader_internal_test.go
index 24ac96cd..8baf8f90 100644
--- a/parquet/file/page_reader_internal_test.go
+++ b/parquet/file/page_reader_internal_test.go
@@ -233,7 +233,7 @@ func TestEncryptedChunkWithoutDictionaryIsNotProbed(t 
*testing.T) {
 }
 
 // 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.
+// loads the dictionary before decoding the first data page.
 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}
@@ -247,6 +247,39 @@ func 
TestSeekToRowZeroOnEncryptedChunkStartingWithDictionaryPage(t *testing.T) {
        require.Equal(t, []int32{10, 20, 20, 10, 10, 10, 20, 10}, vals[:n])
 }
 
+// A seek goes back to the dictionary page, whose header takes the dictionary 
AAD
+// again, whether or not the chunk records a dictionary page offset.
+func TestReseekOnEncryptedChunkWithSharedPageOffset(t *testing.T) {
+       // RLE_DICTIONARY indices 0,1,1,0,0,0,1,0 at bit width 1
+       indices := []byte{1, 3, 0x46}
+       want := []int32{10, 20, 20, 10, 10, 10, 20, 10}
+
+       for _, tc := range []struct {
+               name                               string
+               baseOffset, dataOffset, dictOffset int64
+       }{
+               {"SharedPageOffset", 1, 1, 1},
+               {"NoDictionaryOffset", 0, 0, 0},
+       } {
+               t.Run(tc.name, func(t *testing.T) {
+                       p := encryptedChunk(t, true, 8, dictPageSpec(10, 20), 
dataPageSpec(8, format.Encoding_RLE_DICTIONARY, indices))
+                       p.baseOffset, p.dataOffset, p.dictOffset = 
tc.baseOffset, tc.dataOffset, tc.dictOffset
+                       cr := requiredInt32Column(t, p)
+                       t.Cleanup(func() { require.NoError(t, cr.Close()) })
+
+                       vals := make([]int32, 8)
+                       _, n, err := cr.ReadBatch(8, vals, nil, nil)
+                       require.NoError(t, err)
+                       require.Equal(t, want, vals[:n])
+
+                       require.NoError(t, cr.SeekToRow(0))
+                       _, n, err = cr.ReadBatch(8, vals, nil, nil)
+                       require.NoError(t, err)
+                       require.Equal(t, want, vals[:n])
+               })
+       }
+}
+
 type countingReader struct {
        utils.Reader
        read *int
diff --git a/parquet/pqarrow/file_reader_test.go 
b/parquet/pqarrow/file_reader_test.go
index 57627d62..6bdf827f 100644
--- a/parquet/pqarrow/file_reader_test.go
+++ b/parquet/pqarrow/file_reader_test.go
@@ -708,6 +708,70 @@ func TestRecordReaderSeekToRowDictionaryAtDataPageOffset(t 
*testing.T) {
        require.Truef(t, array.RecordEqual(want, got), "expected: %s\ngot: %s", 
want, got)
 }
 
+// A record reader builds a new page reader for each seek, which starts at the
+// dictionary page of an encrypted chunk.
+func TestRecordReaderSeekToRowEncryptedDictionary(t *testing.T) {
+       const (
+               footerKey = "0123456789012345"
+               rowGroups = 2
+               rowsPerRG = 1500
+               row       = 2200
+       )
+       mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
+       defer mem.AssertSize(t, 0)
+
+       bldr := array.NewInt64Builder(mem)
+       defer bldr.Release()
+       for i := range rowGroups * rowsPerRG {
+               bldr.Append(int64((i*31 + i/rowsPerRG) % 97))
+       }
+       arr := bldr.NewArray()
+       defer arr.Release()
+       sc := arrow.NewSchema([]arrow.Field{{Name: "x", Type: 
arrow.PrimitiveTypes.Int64}}, nil)
+       tbl := array.NewTableFromSlice(sc, [][]arrow.Array{{arr}})
+       defer tbl.Release()
+
+       var buf bytes.Buffer
+       require.NoError(t, pqarrow.WriteTable(tbl, &buf, rowsPerRG, 
parquet.NewWriterProperties(
+               
parquet.WithEncryptionProperties(parquet.NewFileEncryptionProperties(footerKey)),
+               parquet.WithDictionaryDefault(true),
+               parquet.WithDictionaryCostFallbackFor("x", false),
+               parquet.WithDictionaryPageSizeLimit(1<<20),
+               parquet.WithDataPageSize(400),
+               parquet.WithBatchSize(16)),
+               pqarrow.NewArrowWriterProperties(pqarrow.WithAllocator(mem))))
+
+       props := parquet.NewReaderProperties(mem)
+       props.FileDecryptProps = 
parquet.NewFileDecryptionProperties(parquet.WithFooterKey(footerKey))
+       pf, err := file.NewParquetReader(bytes.NewReader(buf.Bytes()), 
file.WithReadProps(props))
+       require.NoError(t, err)
+       defer pf.Close()
+       chunk, err := pf.MetaData().RowGroup(rowGroups - 1).ColumnChunk(0)
+       require.NoError(t, err)
+       require.True(t, chunk.HasDictionaryPage())
+
+       fr, err := pqarrow.NewFileReader(pf, 
pqarrow.ArrowReadProperties{BatchSize: 100}, mem)
+       require.NoError(t, err)
+       seq, err := fr.ReadTable(context.Background())
+       require.NoError(t, err)
+       defer seq.Release()
+       var want []int64
+       for _, c := range seq.Column(0).Data().Chunks() {
+               want = append(want, c.(*array.Int64).Int64Values()...)
+       }
+       require.Len(t, want, rowGroups*rowsPerRG)
+
+       rr, err := fr.GetRecordReader(context.Background(), []int{0}, nil)
+       require.NoError(t, err)
+       defer rr.Release()
+       require.NoError(t, rr.SeekToRow(row))
+       rec, err := rr.Read()
+       require.NoError(t, err)
+       got := rec.Column(0).(*array.Int64).Int64Values()
+       require.NotEmpty(t, got)
+       require.Equal(t, want[row:row+len(got)], got)
+}
+
 func TestRecordReaderSeekToRowRepeated(t *testing.T) {
        sc := arrow.NewSchema([]arrow.Field{{Name: "x", Type: 
arrow.ListOf(arrow.PrimitiveTypes.Int32), Nullable: true}}, nil)
 

Reply via email to