hcrosse commented on code in PR #2822: URL: https://github.com/apache/iceberg-go/pull/2822#discussion_r4810514530
########## table/arrow_scanner_morsel.go: ########## @@ -0,0 +1,525 @@ +// 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 table + +import ( + "context" + "fmt" + "iter" + "sync" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/compute/exprs" + "github.com/apache/iceberg-go" + iceinternal "github.com/apache/iceberg-go/internal" + "github.com/apache/iceberg-go/table/dv" + tblutils "github.com/apache/iceberg-go/table/internal" + "github.com/apache/iceberg-go/table/internal/substrait" +) + +func anyParquetTask(tasks []FileScanTask) bool { + for _, t := range tasks { + if t.File != nil && t.File.FileFormat() == iceberg.ParquetFile { + return true + } + } + + return false +} + +func (as *arrowScan) buildParquetRowGroupTester( + task FileScanTask, + fileSchema *iceberg.Schema, + pruningFilter iceberg.BooleanExpression, + rdr tblutils.FileReader, + plans *compiledFileFilterPlans, +) (*tblutils.ParquetRowGroupTester, error) { + var tester *tblutils.ParquetRowGroupTester + if plans != nil && plans.pruning != nil { + tester = &tblutils.ParquetRowGroupTester{ + StatsFn: plans.pruning.statsEvaluator(), + StatsFieldIDs: plans.pruning.statsFieldIDs, + BloomPreds: plans.pruning.bloomPreds, + DictionaryPreds: plans.pruning.dictionaryPreds, + } + } else { + logicalSchema := as.filterSchema + if logicalSchema == nil { + logicalSchema = as.projectedSchema + } + + hasMissingDefault, err := pruningFilterHasMissingInitialDefault( + pruningFilter, logicalSchema, fileSchema) + if err != nil { + return nil, err + } + if hasMissingDefault { + // TranslateColumnNames treats fields missing from the physical file + // as null, which is unsafe when an added field has a non-null initial-default. + pruningFilter = iceberg.AlwaysTrue{} + } + + pruningFilter, err = stripExtractPredicates(pruningFilter) + if err != nil { + return nil, err + } + + filePruningFilter, err := iceberg.TranslateColumnNames(pruningFilter, fileSchema) + if err != nil { + return nil, err + } + + filePruningFilter, err = iceberg.BindExpr(fileSchema, filePruningFilter, as.caseSensitive) + if err != nil { + return nil, err + } + statsFieldIDs, err := iceberg.ExtractFieldIDs(filePruningFilter) + if err != nil { + return nil, err + } + + statsFn, err := newParquetRowGroupStatsEvaluator(fileSchema, filePruningFilter, false) + if err != nil { + return nil, err + } + + bloomPreds, err := newBloomFilterPredicates(filePruningFilter) + if err != nil { + return nil, err + } + + dictionaryPreds, err := newDictionaryPredicates(filePruningFilter) + if err != nil { + return nil, err + } + + tester = &tblutils.ParquetRowGroupTester{ + StatsFn: statsFn, + StatsFieldIDs: statsFieldIDs, + BloomPreds: bloomPreds, + DictionaryPreds: dictionaryPreds, + } + } + + // Leave byte range unset on complete tasks so malformed or legacy + // row-group offsets cannot drop data. + if task.Start != 0 || + (task.Length != 0 && task.Length != task.File.FileSizeBytes()) { + tester.RangeSet = true + tester.Start, tester.Length = adjustParquetTaskRange(task, rdr.SourceFileSize()) + tester.PlanningSplitOffsets = iceinternal.BorrowedDataFileSplitOffsets(task.File) + } + + return tester, nil +} + +type morselWorkKind uint8 + +const ( + morselWorkDone morselWorkKind = iota + morselWorkTask + morselWorkRowGroup +) + +type morselWork struct { + kind morselWorkKind + task tblutils.Enumerated[FileScanTask] + prepared *preparedParquetTask + rg tblutils.SelectedRowGroup +} + +type preparedParquetTask struct { + pipeline *preparedTaskPipeline + colIndices []int + selected []tblutils.SelectedRowGroup + // nextRG is guarded by morselScheduler.mu. + nextRG int +} + +type morselScheduler struct { + mu sync.Mutex + tasks []FileScanTask + nextTask int + preparing int + activeFiles []*preparedParquetTask + wake chan struct{} +} + +func newMorselScheduler(tasks []FileScanTask) *morselScheduler { + return &morselScheduler{ + tasks: tasks, + wake: make(chan struct{}), + } +} + +func (s *morselScheduler) broadcastLocked() { + close(s.wake) + s.wake = make(chan struct{}) +} + +func (s *morselScheduler) nextWork(ctx context.Context) morselWork { + for { + if ctx.Err() != nil { + return morselWork{kind: morselWorkDone} + } + + s.mu.Lock() + if len(s.activeFiles) > 0 { + pf := s.activeFiles[0] + rg := pf.selected[pf.nextRG] + pf.nextRG++ + if pf.nextRG >= len(pf.selected) { + s.activeFiles[0] = nil + s.activeFiles = s.activeFiles[1:] + if len(s.activeFiles) == 0 { + s.activeFiles = nil + } + } + s.mu.Unlock() + + return morselWork{kind: morselWorkRowGroup, prepared: pf, rg: rg} + } + + if s.nextTask < len(s.tasks) { + idx := s.nextTask + s.nextTask++ + t := s.tasks[idx] + if t.File != nil && t.File.FileFormat() == iceberg.ParquetFile { + s.preparing++ + } + s.mu.Unlock() + + return morselWork{ + kind: morselWorkTask, + task: tblutils.Enumerated[FileScanTask]{ + Value: t, + Index: idx, + Last: idx == len(s.tasks)-1, + }, + } + } + + if s.preparing == 0 { + s.mu.Unlock() + + return morselWork{kind: morselWorkDone} + } + + wake := s.wake + s.mu.Unlock() + + select { + case <-ctx.Done(): + return morselWork{kind: morselWorkDone} + case <-wake: + } + } +} + +func (s *morselScheduler) finishPrepare(pf *preparedParquetTask) { + s.mu.Lock() + s.preparing-- + if pf != nil && pf.nextRG < len(pf.selected) { + s.activeFiles = append(s.activeFiles, pf) + } + s.broadcastLocked() + s.mu.Unlock() +} + +func (as *arrowScan) openParquetMorselReader( + ctx context.Context, + file iceberg.DataFile, + invariants *arrowScanInvariants, +) (tblutils.RowGroupFileReader, error) { + rdr, err := as.openFileReaderWithDictionaries(ctx, file, invariants) + if err != nil { + return nil, err + } + + rgRdr, ok := rdr.(tblutils.RowGroupFileReader) + if !ok { + _ = rdr.Close() + + return nil, fmt.Errorf("%w: parquet reader does not support row-group selection", iceberg.ErrNotImplemented) + } + + return rgRdr, nil +} + +func (as *arrowScan) prepareParquetTask( + ctx context.Context, + task tblutils.Enumerated[FileScanTask], + positionalDeleteBitmap *dv.RoaringPositionBitmap, + dvBitmap *dv.RoaringPositionBitmap, + eqDeleteSets []*equalityDeleteSet, + invariants *arrowScanInvariants, +) (pf *preparedParquetTask, rgRdr tblutils.RowGroupFileReader, err error) { + rowFilter, err := as.rowFilterForTask(task.Value) + if err != nil { + return nil, nil, err + } + + iceSchema, colIndices, rdr, err := as.prepareToRead(ctx, task.Value.File, invariants, eqDeleteSets) + if err != nil { + return nil, nil, err + } + + keepReader := false + defer func() { + if !keepReader { + iceinternal.CheckedClose(rdr, &err) + } + }() + + rgRdr, ok := rdr.(tblutils.RowGroupFileReader) + if !ok { + return nil, nil, fmt.Errorf("%w: parquet reader does not support row-group selection", iceberg.ErrNotImplemented) + } + + prep, err := as.prepareTaskPipeline(task, iceSchema, rowFilter, + positionalDeleteBitmap, dvBitmap, eqDeleteSets, eqDeleteSets, invariants) + if err != nil { + return nil, nil, err + } + if prep.dropFile { + return nil, nil, nil + } + + pruningFilter := prep.rowFilter + if prep.pruningFilter != nil { + pruningFilter = prep.pruningFilter + } + if pruningFilter == nil { + pruningFilter = iceberg.AlwaysTrue{} + } + + tester, err := as.buildParquetRowGroupTester(task.Value, iceSchema, pruningFilter, rdr, prep.filterPlans) + if err != nil { + return nil, nil, err + } + + selected, err := rgRdr.SelectRowGroups(colIndices, tester) + if err != nil { + return nil, nil, err + } + if len(selected) == 0 { + return nil, nil, nil + } + + pf = &preparedParquetTask{ + pipeline: prep, + colIndices: colIndices, + selected: selected, + // The preparing worker keeps selected[0] on its open reader. + nextRG: 1, + } + + keepReader = true + + return pf, rgRdr, nil +} + +func (as *arrowScan) readParquetMorsel( + ctx context.Context, + pf *preparedParquetTask, + rg tblutils.SelectedRowGroup, + rdr tblutils.RowGroupFileReader, + sink *recordSink, + invariants *arrowScanInvariants, +) error { + var posSource *rowPositionSource + if pf.pipeline.needsPosSource(false) { + posSource = &rowPositionSource{ + spans: []tblutils.RowGroupSpan{{FirstRowPos: rg.FirstRowPos, NumRows: rg.NumRows}}, + } + } + + pipeline, err := pf.pipeline.buildPipeline(ctx, as, posSource, invariants, nil) + if err != nil { + return err + } + + recRdr, err := rdr.GetRowGroupRecords(ctx, pf.colIndices, []int{rg.Index}) + if err != nil { + return err + } + defer recRdr.Release() + + return as.streamUnorderedRecords(ctx, pf.pipeline.task, recRdr, pipeline, sink) +} + +func (as *arrowScan) recordBatchesUnorderedMorselized( + ctx context.Context, + tasks []FileScanTask, + positionDeleteLoader *lazyPositionDeleteLoader, + dvLoader *lazyDeletionVectorLoader, + equalityDeleteLoader *lazyEqualityDeleteLoader, + invariants *arrowScanInvariants, + cleanup func(), +) iter.Seq2[arrow.RecordBatch, error] { + return func(yield func(arrow.RecordBatch, error) bool) { + extSet := substrait.NewExtensionSet() + // Disable nested per-column pqarrow parallelism so concurrent column + // decoders stay bounded by numWorkers rather than numWorkers x columns. + scanCtx, cancel := context.WithCancelCause( + tblutils.WithParquetParallelColumns(exprs.WithExtensionIDSet(ctx, extSet), false), Review Comment: Thanks for catching that and sharing the benchmark. I removed the scan-wide context override (which also disabled parallel column reads on delete files) and moved the choice to per-row-group reads, keeping `Props.Parallel` enabled whenever a file has fewer selected row groups than scan workers and disabling it once a file has enough row groups to fill the worker pool. On 6 interleaved runs at `c=4` on Apple M4 Max (262,144 rows, half int64 and half string, Zstd): - 1x1 RG, 16 col: 24.0 ms vs 24.2 ms base (parity with base) - 1x2 RG, 16 col: 19.5 ms vs 24.6 ms base (-20.7%) - 1x4 RG, 16 col: 24.2 ms vs 26.9 ms base (-10.1%) - 1x16 RG, 16 col: 29.6 ms vs 35.3 ms base (-16.2%) - 8x2 RG, 16 col: 26.4 ms vs 24.6 ms base at `c=4`, and 23.1 ms vs 23.9 ms at `c=14` Keeping column decoding serial once `len(selected) >= numWorkers` avoids the peak RSS jump from running parallel columns across every worker at once (239 MiB vs 306 MiB on 16-RG 16-col and 561 MiB vs 770 MiB on 16-RG 64-col at `c=4`), while keeping single-row-group and low-row-group wide files fast. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
