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 aba35416 perf(parquet/pqarrow): read selected row ranges (#1632)
aba35416 is described below

commit aba35416f463a99758ecbaee56d0f908fb63da32
Author: Vu <[email protected]>
AuthorDate: Thu Nov 19 23:52:10 2026 +0100

    perf(parquet/pqarrow): read selected row ranges (#1632)
    
    ### Rationale for this change
    
    Callers that already know which rows they want can seek to the beginning of 
each range. A normal batch can extend past the end of that range, so the caller 
still decodes rows it will discard. This comes up when reading payload columns 
for a selective query. Related to #38.
    
    ### What changes are included in this PR?
    
    Add `GetRecordReaderWithRowRanges` for sorted, non-overlapping, half-open 
ranges relative to the selected row groups.
    
    ### Implementation
    
    - Seek across gaps and cap each batch at its range boundary. Projections 
with repeated columns read through gaps sequentially to preserve row alignment 
on files affected by #1522. This workaround can be removed after #1608 merges.
    - Coalesce adjacent ranges and use the regular reader path for a selection 
that covers every row.
    
    #### Benchmark
    
    With page indexes and 1% of rows selected, the range reader took **1.06 
ms**, down from **2.03 ms** with manual `SeekToRow` and batch slicing (**48% 
lower latency**). It read **66% fewer bytes** from the source and allocated 
**57% fewer bytes**. Full decode followed by selection took **22.78 ms**.
    
    ##### Latency
    
    | Page index | Rows kept | Decode then select (ms) | Seek then slice (ms) | 
Row ranges (ms) | Change vs. seek then slice |
    | --- | ---: | ---: | ---: | ---: | ---: |
    | Yes | 1% | 22.78 | 2.03 | **1.06** | −47.8% |
    | Yes | 10% | 22.26 | 3.01 | **2.57** | −14.7% |
    | Yes | 100% | 22.70 | 21.60 | 22.22 | +2.9% |
    | No | 1% | 22.45 | 4.70 | **3.63** | −22.8% |
    | No | 10% | 22.09 | 5.97 | **5.55** | −7.0% |
    | No | 100% | 22.70 | 21.88 | 22.62 | +3.4% |
    
    The 100% cases exercise the ordinary reader path through the range API. Its 
source-byte counts match full decode. The manual baseline stops when it has 
collected the last requested row, and the other two paths iterate to EOF.
    
    ##### Source reads and allocations
    
    | Page index | Rows kept | Decode then select (MiB read) | Seek then slice 
(MiB read) | Row ranges (MiB read) |
    | --- | ---: | ---: | ---: | ---: |
    | Yes | 1% | 33.01 | 2.26 | **0.76** |
    | Yes | 10% | 33.01 | 4.26 | **3.76** |
    | Yes | 100% | 33.01 | 33.01 | 33.01 |
    | No | 1% | 33.07 | 18.79 | **17.29** |
    | No | 10% | 33.07 | 20.80 | **20.30** |
    | No | 100% | 33.07 | 33.07 | 33.07 |
    
    | Page index | Rows kept | Decode then select (MiB allocated) | Seek then 
slice (MiB allocated) | Row ranges (MiB allocated) |
    | --- | ---: | ---: | ---: | ---: |
    | Yes | 1% | 71.62 | 6.63 | **2.86** |
    | Yes | 10% | 71.62 | 10.96 | **8.83** |
    | Yes | 100% | 71.62 | 71.62 | 71.61 |
    | No | 1% | 71.72 | 6.76 | **2.99** |
    | No | 10% | 71.73 | 11.10 | **8.97** |
    | No | 100% | 71.72 | 71.72 | 71.72 |
    
    ##### Setup
    
    The fixture is a Snappy Parquet file with 262,144 rows in four row groups, 
an `int64` ID, a 128-byte fixed-width payload, and a 128 KiB data-page target. 
The 1% and 10% cases keep one contiguous range starting halfway through each 
row group. All paths use 4,096-row batches and check the selected row count and 
checksum.
    
    Figures are medians per operation from 12 fresh processes per method with 
rotating method order. Runs used one pinned efficiency core on an Intel Core 
i9-12900HK, Linux amd64, and Go 1.26.10. The file is in memory and fixture 
construction is outside the timer. Bytes read count reads from the benchmark 
source. MiB allocated is cumulative Go allocation volume per operation.
    
    To reproduce the process order on Linux, set `cpu` to a core on your 
machine and run the following with Bash.
    
    ```bash
    cpu=19
    out=$(mktemp -d)
    go test -c -o "$out/pqarrow.test" ./parquet/pqarrow
    methods=(decode-then-select seek-then-slice row-ranges)
    
    for ((round=0; round<12; round++)); do
      for ((step=0; step<3; step++)); do
        method=${methods[(round + step) % 3]}
        
filter="^BenchmarkRecordReaderRowRanges$/^indexed=(true|false)$/^selected=(1|10|100)%$/^method=$method$"
        taskset -c "$cpu" env GOMAXPROCS=1 GOGC=100 "$out/pqarrow.test" \
          -test.run '^$' -test.bench "$filter" -test.benchmem 
-test.benchtime=200ms \
          >> "$out/$method.txt"
      done
    done
    
    benchstat -ignore /method "$out/decode-then-select.txt" 
"$out/seek-then-slice.txt" "$out/row-ranges.txt"
    ```
    
    ### Are there any user-facing changes?
    
    - The new reader accepts `[]pqarrow.RowRange`, and `SeekToRow` indexes into 
the selected rows. Batches stop at range boundaries, so an isolated single-row 
range produces a one-row batch.
    - With `GetRecordReader`, a successful seek after EOF lets reading resume.
    - With `GetRecordReader`, each occurrence of a requested row group counts 
toward valid seek offsets. Repeating row groups can make offsets past the 
file's physical row count valid.
---
 parquet/pqarrow/file_reader.go           |  64 +++++++--
 parquet/pqarrow/row_ranges.go            | 170 ++++++++++++++++++++++++
 parquet/pqarrow/row_ranges_bench_test.go | 217 +++++++++++++++++++++++++++++++
 parquet/pqarrow/row_ranges_test.go       | 146 +++++++++++++++++++++
 4 files changed, 586 insertions(+), 11 deletions(-)

diff --git a/parquet/pqarrow/file_reader.go b/parquet/pqarrow/file_reader.go
index abd1a58d..830d2e03 100644
--- a/parquet/pqarrow/file_reader.go
+++ b/parquet/pqarrow/file_reader.go
@@ -548,13 +548,15 @@ type RecordReader interface {
        array.RecordReader
        arrio.Reader
        // SeekToRow will shift the record reader so that subsequent calls to 
Read
-       // or Next will begin from the specified row.
+       // or Next will begin from the specified row. A successful seek clears
+       // the end-of-stream state so that reading can resume after EOF.
        //
        // If the record reader was constructed with a request for a subset of 
row
        // groups, then rows are counted across the requested row groups, not 
the
        // entire file. This prevents reading row groups that were requested to 
be
        // skipped, and allows treating the subset of row groups as a single 
collection
-       // of rows.
+       // of rows. A reader constructed with GetRecordReaderWithRowRanges 
counts
+       // only rows in the selected ranges.
        //
        // If the file contains Offset indexes for a given column, then it will 
be
        // utilized to skip pages as needed to find the requested row. 
Otherwise page
@@ -567,6 +569,10 @@ type RecordReader interface {
 //
 // For both cases, if you pass nil for column indexes or rowgroups it will 
default to reading all of them.
 func (fr *FileReader) GetRecordReader(ctx context.Context, colIndices, 
rowGroups []int) (RecordReader, error) {
+       return fr.getRecordReader(ctx, colIndices, rowGroups, nil)
+}
+
+func (fr *FileReader) getRecordReader(ctx context.Context, colIndices, 
rowGroups []int, ranges []RowRange) (RecordReader, error) {
        if err := fr.checkRowGroups(rowGroups); err != nil {
                return nil, err
        }
@@ -589,6 +595,27 @@ func (fr *FileReader) GetRecordReader(ctx context.Context, 
colIndices, rowGroups
                }
        }
 
+       nrows := int64(0)
+       for _, rg := range rowGroups {
+               nrows += fr.rdr.MetaData().RowGroup(rg).NumRows()
+       }
+
+       selection, err := newRowRangeSelection(ranges, nrows)
+       if err != nil {
+               return nil, err
+       }
+       if selection != nil {
+               if len(selection.ranges) == 0 {
+                       rowGroups = []int{}
+               }
+               for _, col := range colIndices {
+                       if 
fr.rdr.MetaData().Schema.Column(col).MaxRepetitionLevel() > 0 {
+                               selection.hasRepeatedColumns = true
+                               break
+                       }
+               }
+       }
+
        // TODO(mtopol): add optimizations to pre-buffer data from the file
 
        readers, sc, err := fr.GetFieldReaders(ctx, colIndices, rowGroups)
@@ -600,11 +627,6 @@ func (fr *FileReader) GetRecordReader(ctx context.Context, 
colIndices, rowGroups
                return nil, errors.New("no leaf column readers matched col 
indices")
        }
 
-       nrows := int64(0)
-       for _, rg := range rowGroups {
-               nrows += fr.rdr.MetaData().RowGroup(rg).NumRows()
-       }
-
        var batchSize int64
        if fr.Props.BatchSize <= 0 {
                batchSize = nrows
@@ -618,6 +640,7 @@ func (fr *FileReader) GetRecordReader(ctx context.Context, 
colIndices, rowGroups
                sc:           sc,
                fieldReaders: readers,
                mem:          fr.mem,
+               selection:    selection,
        }
        rr.refCount.Add(1)
        return rr, nil
@@ -802,8 +825,8 @@ func (c *columnIterator) FindChunkForRow(rowIdx int64) 
(file.PageReader, int64,
                return nil, 0, nil
        }
 
-       if rowIdx < 0 || rowIdx > c.rdr.NumRows() {
-               return nil, 0, fmt.Errorf("invalid row index %d, file only has 
%d rows", rowIdx, c.rdr.NumRows())
+       if rowIdx < 0 {
+               return nil, 0, fmt.Errorf("%w: negative row index %d", 
arrow.ErrInvalid, rowIdx)
        }
 
        idx := int64(0)
@@ -856,11 +879,23 @@ type recordReader struct {
        cur          arrow.RecordBatch
        err          error
        mem          memory.Allocator
+       selection    *rowRangeSelection
 
        refCount atomic.Int64
 }
 
 func (r *recordReader) SeekToRow(row int64) error {
+       if r.selection != nil {
+               return r.seekToSelectedRow(row)
+       }
+       if err := r.seekToInputRow(row); err != nil {
+               return err
+       }
+       r.err = nil
+       return nil
+}
+
+func (r *recordReader) seekToInputRow(row int64) error {
        if r.cur != nil {
                r.cur.Release()
                r.cur = nil
@@ -910,11 +945,11 @@ func (r *recordReader) Release() {
 
 func (r *recordReader) Schema() *arrow.Schema { return r.sc }
 
-func (r *recordReader) next() bool {
+func (r *recordReader) readBatch(batchSize int64) bool {
        cols := make([]arrow.Array, len(r.sc.Fields()))
        defer releaseArrays(cols)
        readField := func(idx int, rdr *ColumnReader) error {
-               data, err := rdr.NextBatch(r.batchSize)
+               data, err := rdr.NextBatch(batchSize)
                if err != nil {
                        return err
                }
@@ -1014,6 +1049,13 @@ func (r *recordReader) Next() bool {
        return r.next()
 }
 
+func (r *recordReader) next() bool {
+       if r.selection != nil {
+               return r.nextSelectedBatch()
+       }
+       return r.readBatch(r.batchSize)
+}
+
 func (r *recordReader) RecordBatch() arrow.RecordBatch { return r.cur }
 
 // Deprecated: Use [RecordBatch] instead.
diff --git a/parquet/pqarrow/row_ranges.go b/parquet/pqarrow/row_ranges.go
new file mode 100644
index 00000000..4643fa9f
--- /dev/null
+++ b/parquet/pqarrow/row_ranges.go
@@ -0,0 +1,170 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package pqarrow
+
+import (
+       "context"
+       "fmt"
+       "io"
+
+       "github.com/apache/arrow-go/v18/arrow"
+)
+
+// RowRange is a half-open interval of rows, including Start and excluding End.
+type RowRange struct {
+       Start, End int64
+}
+
+// GetRecordReaderWithRowRanges reads only the requested row ranges from the
+// selected row groups and columns. Row offsets are relative to the requested
+// row groups in their supplied order. Ranges must be non-empty, sorted by
+// start, and non-overlapping.
+//
+// As with GetRecordReader, nil colIndices or rowGroups selects all columns or
+// row groups, respectively. Nil ranges selects all rows and an empty, non-nil
+// slice selects no rows.
+//
+// Adjacent ranges are coalesced. Batches stop at range boundaries even if they
+// are shorter than the configured batch size. An isolated single-row range
+// produces a one-row batch.
+//
+// For projections containing repeated columns, gaps are read sequentially to
+// preserve row alignment across page boundaries.
+func (fr *FileReader) GetRecordReaderWithRowRanges(ctx context.Context, 
colIndices, rowGroups []int, ranges []RowRange) (RecordReader, error) {
+       return fr.getRecordReader(ctx, colIndices, rowGroups, ranges)
+}
+
+type rowRangeSelection struct {
+       ranges             []RowRange
+       index              int
+       nextRow            int64
+       hasRepeatedColumns bool
+}
+
+func newRowRangeSelection(ranges []RowRange, numRows int64) 
(*rowRangeSelection, error) {
+       if ranges == nil {
+               return nil, nil
+       }
+       var merged []RowRange
+       for i, rows := range ranges {
+               if rows.Start < 0 || rows.End <= rows.Start || rows.End > 
numRows {
+                       return nil, fmt.Errorf("%w: row range %d [%d, %d) 
exceeds %d rows or is empty", arrow.ErrInvalid, i, rows.Start, rows.End, 
numRows)
+               }
+               if i > 0 {
+                       previous := &merged[len(merged)-1]
+                       if rows.Start < previous.End {
+                               return nil, fmt.Errorf("%w: row range %d 
overlaps or precedes a previous range", arrow.ErrInvalid, i)
+                       }
+                       if rows.Start == previous.End {
+                               previous.End = rows.End
+                               continue
+                       }
+               }
+               merged = append(merged, rows)
+       }
+       if len(merged) == 1 && merged[0] == (RowRange{0, numRows}) {
+               return nil, nil
+       }
+       return &rowRangeSelection{ranges: merged}, nil
+}
+
+func (r *recordReader) seekToSelectedRow(row int64) error {
+       if row < 0 {
+               return fmt.Errorf("%w: negative row index %d", arrow.ErrIndex, 
row)
+       }
+       remaining := row
+       for i, rows := range r.selection.ranges {
+               length := rows.End - rows.Start
+               if remaining < length {
+                       inputRow := rows.Start + remaining
+                       if err := r.seekToRangeRow(inputRow); err != nil {
+                               r.err = err
+                               return err
+                       }
+                       r.selection.index = i
+                       r.selection.nextRow = inputRow
+                       r.err = nil
+                       return nil
+               }
+               remaining -= length
+       }
+       return fmt.Errorf("%w: row index %d exceeds %d selected rows", 
arrow.ErrIndex, row, row-remaining)
+}
+
+func (r *recordReader) seekToRangeRow(row int64) error {
+       if !r.selection.hasRepeatedColumns {
+               return r.seekToInputRow(row)
+       }
+       if err := r.seekToInputRow(0); err != nil {
+               return err
+       }
+       return r.readThroughGap(row)
+}
+
+// Arbitrary seeks into repeated Data Page V1 columns without offset indexes
+// can lose row alignment (GH-1522). Read through gaps in repeated projections.
+// Remove this workaround once https://github.com/apache/arrow-go/pull/1608 
lands.
+func (r *recordReader) readThroughGap(rows int64) error {
+       for rows > 0 {
+               if !r.readBatch(min(r.batchSize, rows)) {
+                       if r.err == io.EOF {
+                               return io.ErrUnexpectedEOF
+                       }
+                       return r.err
+               }
+               rows -= r.cur.NumRows()
+               r.cur.Release()
+               r.cur = nil
+       }
+       return nil
+}
+
+func (r *recordReader) nextSelectedBatch() bool {
+       if r.err != nil {
+               return false
+       }
+       s := r.selection
+       if s.index == len(s.ranges) {
+               r.err = io.EOF
+               return false
+       }
+       rows := s.ranges[s.index]
+       if s.nextRow < rows.Start {
+               var err error
+               if s.hasRepeatedColumns {
+                       err = r.readThroughGap(rows.Start - s.nextRow)
+               } else {
+                       err = r.seekToInputRow(rows.Start)
+               }
+               if err != nil {
+                       r.err = err
+                       return false
+               }
+               s.nextRow = rows.Start
+       }
+       if !r.readBatch(min(r.batchSize, rows.End-s.nextRow)) {
+               if r.err == io.EOF {
+                       r.err = io.ErrUnexpectedEOF
+               }
+               return false
+       }
+       s.nextRow += r.cur.NumRows()
+       if s.nextRow == rows.End {
+               s.index++
+       }
+       return true
+}
diff --git a/parquet/pqarrow/row_ranges_bench_test.go 
b/parquet/pqarrow/row_ranges_bench_test.go
new file mode 100644
index 00000000..ad3f5c3d
--- /dev/null
+++ b/parquet/pqarrow/row_ranges_bench_test.go
@@ -0,0 +1,217 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package pqarrow_test
+
+import (
+       "bytes"
+       "fmt"
+       "math/rand/v2"
+       "testing"
+
+       "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/array"
+       "github.com/apache/arrow-go/v18/arrow/memory"
+       "github.com/apache/arrow-go/v18/parquet"
+       "github.com/apache/arrow-go/v18/parquet/compress"
+       "github.com/apache/arrow-go/v18/parquet/file"
+       "github.com/apache/arrow-go/v18/parquet/pqarrow"
+)
+
+func BenchmarkRecordReaderRowRanges(b *testing.B) {
+       const (
+               groupRows = 64 * 1024
+               groups    = 4
+               rows      = groupRows * groups
+       )
+       mem := memory.DefaultAllocator
+       tbl := makeRowRangeBenchmarkTable(mem, rows)
+       defer tbl.Release()
+
+       for _, indexed := range []bool{true, false} {
+               b.Run(fmt.Sprintf("indexed=%t", indexed), func(b *testing.B) {
+                       var buf bytes.Buffer
+                       props := parquet.NewWriterProperties(
+                               parquet.WithPageIndexEnabled(indexed), 
parquet.WithCompression(compress.Codecs.Snappy),
+                               parquet.WithDictionaryDefault(false), 
parquet.WithDataPageSize(128*1024),
+                       )
+                       if err := pqarrow.WriteTable(tbl, &buf, groupRows, 
props, pqarrow.DefaultWriterProps()); err != nil {
+                               b.Fatal(err)
+                       }
+
+                       for _, percent := range []int64{1, 10, 100} {
+                               b.Run(fmt.Sprintf("selected=%d%%", percent), 
func(b *testing.B) {
+                                       var ranges []pqarrow.RowRange
+                                       if percent == 100 {
+                                               ranges = 
[]pqarrow.RowRange{{Start: 0, End: rows}}
+                                       } else {
+                                               for group := range 
int64(groups) {
+                                                       start := 
group*groupRows + groupRows/2
+                                                       ranges = append(ranges, 
pqarrow.RowRange{Start: start, End: start + groupRows*percent/100})
+                                               }
+                                       }
+                                       var want rowRangeBenchmarkResult
+                                       for _, selected := range ranges {
+                                               for id := selected.Start; id < 
selected.End; id++ {
+                                                       want.rows++
+                                                       want.checksum += id + 
int64(byte(id)) + int64(byte(id>>8))
+                                               }
+                                       }
+
+                                       for _, method := range 
[]string{"decode-then-select", "seek-then-slice", "row-ranges"} {
+                                               b.Run("method="+method, func(b 
*testing.B) {
+                                                       b.ReportAllocs()
+                                                       var sourceBytes int64
+                                                       for b.Loop() {
+                                                               source := 
&rowRangeBenchmarkSource{Reader: bytes.NewReader(buf.Bytes())}
+                                                               got := 
readRowRangeBenchmark(b, source, mem, ranges, method)
+                                                               if got != want {
+                                                                       
b.Fatalf("read %+v, want %+v", got, want)
+                                                               }
+                                                               sourceBytes += 
source.bytesRead
+                                                       }
+                                                       
b.ReportMetric(float64(sourceBytes)/float64(b.N), "read-B/op")
+                                               })
+                                       }
+                               })
+                       }
+               })
+       }
+}
+
+type rowRangeBenchmarkSource struct {
+       *bytes.Reader
+       bytesRead int64
+}
+
+func (r *rowRangeBenchmarkSource) Read(p []byte) (int, error) {
+       n, err := r.Reader.Read(p)
+       r.bytesRead += int64(n)
+       return n, err
+}
+
+func (r *rowRangeBenchmarkSource) ReadAt(p []byte, offset int64) (int, error) {
+       n, err := r.Reader.ReadAt(p, offset)
+       r.bytesRead += int64(n)
+       return n, err
+}
+
+type rowRangeBenchmarkResult struct {
+       rows, checksum int64
+}
+
+func readRowRangeBenchmark(b *testing.B, source *rowRangeBenchmarkSource, mem 
memory.Allocator,
+       ranges []pqarrow.RowRange, method string) rowRangeBenchmarkResult {
+       props := parquet.NewReaderProperties(mem)
+       props.BufferedStreamEnabled = true
+       pf, err := file.NewParquetReader(source, file.WithReadProps(props))
+       if err != nil {
+               b.Fatal(err)
+       }
+       defer pf.Close()
+       reader, err := pqarrow.NewFileReader(pf, 
pqarrow.ArrowReadProperties{BatchSize: 4096}, mem)
+       if err != nil {
+               b.Fatal(err)
+       }
+       var records pqarrow.RecordReader
+       if method == "row-ranges" {
+               records, err = reader.GetRecordReaderWithRowRanges(b.Context(), 
nil, nil, ranges)
+       } else {
+               records, err = reader.GetRecordReader(b.Context(), nil, nil)
+       }
+       if err != nil {
+               b.Fatal(err)
+       }
+       defer records.Release()
+
+       var result rowRangeBenchmarkResult
+       if method == "seek-then-slice" {
+               for _, selected := range ranges {
+                       if err := records.SeekToRow(selected.Start); err != nil 
{
+                               b.Fatal(err)
+                       }
+                       for remaining := selected.End - selected.Start; 
remaining > 0; {
+                               if !records.Next() {
+                                       b.Fatalf("premature end of range: %v", 
records.Err())
+                               }
+                               batch := records.RecordBatch()
+                               length := min(remaining, batch.NumRows())
+                               result.append(batch, 0, length)
+                               remaining -= length
+                       }
+               }
+               return result
+       }
+
+       var batchStart int64
+       var index int
+       for records.Next() {
+               batch := records.RecordBatch()
+               if method == "row-ranges" {
+                       result.append(batch, 0, batch.NumRows())
+                       continue
+               }
+               batchEnd := batchStart + batch.NumRows()
+               for index < len(ranges) && ranges[index].Start < batchEnd {
+                       selected := ranges[index]
+                       result.append(batch, max(batchStart, 
selected.Start)-batchStart, min(batchEnd, selected.End)-batchStart)
+                       if selected.End > batchEnd {
+                               break
+                       }
+                       index++
+               }
+               batchStart = batchEnd
+       }
+       if err := records.Err(); err != nil {
+               b.Fatal(err)
+       }
+       return result
+}
+
+func (r *rowRangeBenchmarkResult) append(batch arrow.RecordBatch, start, end 
int64) {
+       ids := batch.Column(0).(*array.Int64)
+       payload := batch.Column(1).(*array.FixedSizeBinary)
+       for i := start; i < end; i++ {
+               value := payload.Value(int(i))
+               r.checksum += ids.Value(int(i)) + int64(value[0]) + 
int64(value[len(value)-1])
+       }
+       r.rows += end - start
+}
+
+func makeRowRangeBenchmarkTable(mem memory.Allocator, rows int) arrow.Table {
+       const payloadSize = 128
+       payloadType := &arrow.FixedSizeBinaryType{ByteWidth: payloadSize}
+       schema := arrow.NewSchema([]arrow.Field{
+               {Name: "id", Type: arrow.PrimitiveTypes.Int64}, {Name: 
"payload", Type: payloadType},
+       }, nil)
+       builder := array.NewRecordBuilder(mem, schema)
+       defer builder.Release()
+       builder.Reserve(rows)
+       ids := builder.Field(0).(*array.Int64Builder)
+       payload := builder.Field(1).(*array.FixedSizeBinaryBuilder)
+       random := rand.NewChaCha8([32]byte{1})
+       var value [payloadSize]byte
+       for row := range rows {
+               ids.Append(int64(row))
+               random.Read(value[:])
+               value[0] = byte(row)
+               value[len(value)-1] = byte(row >> 8)
+               payload.Append(value[:])
+       }
+       batch := builder.NewRecordBatch()
+       defer batch.Release()
+       return array.NewTableFromRecords(schema, []arrow.RecordBatch{batch})
+}
diff --git a/parquet/pqarrow/row_ranges_test.go 
b/parquet/pqarrow/row_ranges_test.go
new file mode 100644
index 00000000..9f934eed
--- /dev/null
+++ b/parquet/pqarrow/row_ranges_test.go
@@ -0,0 +1,146 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package pqarrow_test
+
+import (
+       "bytes"
+       "fmt"
+       "io"
+       "testing"
+
+       "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/array"
+       "github.com/apache/arrow-go/v18/arrow/memory"
+       "github.com/apache/arrow-go/v18/parquet"
+       "github.com/apache/arrow-go/v18/parquet/file"
+       "github.com/apache/arrow-go/v18/parquet/pqarrow"
+       "github.com/stretchr/testify/require"
+)
+
+func TestRecordReaderRowRanges(t *testing.T) {
+       for _, indexed := range []bool{false, true} {
+               for _, parallel := range []bool{false, true} {
+                       t.Run(fmt.Sprintf("indexed=%t/parallel=%t", indexed, 
parallel), func(t *testing.T) {
+                               mem := 
memory.NewCheckedAllocator(memory.DefaultAllocator)
+                               defer mem.AssertSize(t, 0)
+                               schema := arrow.NewSchema([]arrow.Field{
+                                       {Name: "id", Type: 
arrow.PrimitiveTypes.Int64},
+                                       {Name: "values", Type: 
arrow.ListOf(arrow.PrimitiveTypes.Int32), Nullable: true},
+                               }, nil)
+                               data := 
`[{"id":0,"values":[1,2,3]},{"id":1,"values":[]},{"id":2,"values":null},
+                                       
{"id":3,"values":[4]},{"id":4,"values":[5,6]},{"id":5,"values":null},
+                                       
{"id":6,"values":[7,null,8]},{"id":7,"values":[]},{"id":8,"values":[9]},
+                                       
{"id":9,"values":[10,11,12]},{"id":10,"values":[13]},{"id":11,"values":null}]`
+                               tbl, err := array.TableFromJSON(mem, schema, 
[]string{data})
+                               require.NoError(t, err)
+                               defer tbl.Release()
+
+                               var buf bytes.Buffer
+                               props := 
parquet.NewWriterProperties(parquet.WithAllocator(mem), 
parquet.WithPageIndexEnabled(indexed),
+                                       parquet.WithDataPageSize(1), 
parquet.WithBatchSize(1), parquet.WithDictionaryDefault(false))
+                               require.NoError(t, pqarrow.WriteTable(tbl, 
&buf, 3, props, pqarrow.DefaultWriterProps()))
+                               pf, err := 
file.NewParquetReader(bytes.NewReader(buf.Bytes()), 
file.WithReadProps(parquet.NewReaderProperties(mem)))
+                               require.NoError(t, err)
+                               defer pf.Close()
+                               reader, err := pqarrow.NewFileReader(pf, 
pqarrow.ArrowReadProperties{BatchSize: 2, Parallel: parallel}, mem)
+                               require.NoError(t, err)
+
+                               ranges := []pqarrow.RowRange{{Start: 1, End: 
2}, {Start: 3, End: 5}, {Start: 5, End: 8}}
+                               rr, err := 
reader.GetRecordReaderWithRowRanges(t.Context(), nil, []int{3, 1, 2}, ranges)
+                               require.NoError(t, err)
+                               defer rr.Release()
+                               ranges[0] = pqarrow.RowRange{Start: 0, End: 1}
+
+                               var rows []int64
+                               var sizes []int64
+                               for rr.Next() {
+                                       batch := rr.RecordBatch()
+                                       sizes = append(sizes, batch.NumRows())
+                                       for index, id := range 
batch.Column(0).(*array.Int64).Int64Values() {
+                                               rows = append(rows, id)
+                                               require.Equal(t, 
tbl.Column(1).Data().Chunk(0).ValueStr(int(id)), 
batch.Column(1).ValueStr(index))
+                                       }
+                               }
+                               require.NoError(t, rr.Err())
+                               require.Equal(t, []int64{10, 3, 4, 5, 6, 7}, 
rows)
+                               require.Equal(t, []int64{1, 2, 2, 1}, sizes)
+                               _, err = rr.Read()
+                               require.ErrorIs(t, err, io.EOF)
+
+                               require.ErrorIs(t, rr.SeekToRow(6), 
arrow.ErrIndex)
+                               require.ErrorIs(t, rr.SeekToRow(-1), 
arrow.ErrIndex)
+                               require.NoError(t, rr.SeekToRow(2))
+                               batch, err := rr.Read()
+                               require.NoError(t, err)
+                               require.Equal(t, []int64{4, 5}, 
batch.Column(0).(*array.Int64).Int64Values())
+                               require.True(t, rr.Next())
+                               require.Equal(t, []int64{6, 7}, 
rr.RecordBatch().Column(0).(*array.Int64).Int64Values())
+                               require.False(t, rr.Next())
+                               require.NoError(t, rr.Err())
+                       })
+               }
+       }
+}
+
+func TestRecordReaderRowRangeValidation(t *testing.T) {
+       mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
+       defer mem.AssertSize(t, 0)
+       tbl := makeWideInt32Table(mem, 2, 8)
+       defer tbl.Release()
+       var buf bytes.Buffer
+       require.NoError(t, pqarrow.WriteTable(tbl, &buf, 4, nil, 
pqarrow.DefaultWriterProps()))
+       pf, err := file.NewParquetReader(bytes.NewReader(buf.Bytes()), 
file.WithReadProps(parquet.NewReaderProperties(mem)))
+       require.NoError(t, err)
+       defer pf.Close()
+       reader, err := pqarrow.NewFileReader(pf, 
pqarrow.ArrowReadProperties{BatchSize: 2}, mem)
+       require.NoError(t, err)
+
+       for _, ranges := range [][]pqarrow.RowRange{
+               {{Start: -1, End: 1}}, {{Start: 2, End: 2}}, {{Start: 3, End: 
2}}, {{Start: 3, End: 5}},
+               {{Start: 0, End: 3}, {Start: 2, End: 4}}, {{Start: 2, End: 4}, 
{Start: 0, End: 1}},
+       } {
+               _, err := reader.GetRecordReaderWithRowRanges(t.Context(), 
[]int{0}, []int{1}, ranges)
+               require.ErrorIs(t, err, arrow.ErrInvalid)
+       }
+
+       for _, test := range []struct {
+               ranges []pqarrow.RowRange
+               groups []int
+               want   []int32
+       }{
+               {[]pqarrow.RowRange{}, []int{1}, nil},
+               {nil, []int{1}, []int32{4, 5, 6, 7}},
+               {[]pqarrow.RowRange{{Start: 0, End: 2}, {Start: 2, End: 4}}, 
[]int{1}, []int32{4, 5, 6, 7}},
+               {[]pqarrow.RowRange{{Start: 9, End: 11}}, []int{0, 0, 0}, 
[]int32{1, 2}},
+       } {
+               rr, err := reader.GetRecordReaderWithRowRanges(t.Context(), 
[]int{0}, test.groups, test.ranges)
+               require.NoError(t, err)
+               defer rr.Release()
+               require.Equal(t, 1, rr.Schema().NumFields())
+               var got []int32
+               for rr.Next() {
+                       got = append(got, 
rr.RecordBatch().Column(0).(*array.Int32).Int32Values()...)
+               }
+               require.NoError(t, rr.Err())
+               require.Equal(t, test.want, got)
+               if len(test.want) > 0 {
+                       require.NoError(t, rr.SeekToRow(0))
+                       require.True(t, rr.Next())
+                       require.Equal(t, test.want[0], 
rr.RecordBatch().Column(0).(*array.Int32).Value(0))
+               }
+       }
+}

Reply via email to