You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by "fallintoplace (via GitHub)" <gi...@apache.org> on 2026/10/07 11:54:24 UTC
[PR] perf(table): parallelize scan task finalization [iceberg-go]
fallintoplace opened a new pull request, #2149:
URL: https://github.com/apache/iceberg-go/pull/2149
**What**
- Parallelize scan-task finalization after manifest planning.
**Why**
- Residual evaluation, delete accounting and Parquet splitting currently run serially for every planned file.
**Implementation**
- Process contiguous task ranges with bounded workers and local metrics.
- Keep small plans serial. Preserve task order and the first task-order error.
- Share the residual evaluator cache safely. Reuse the input task slice for unsplit plans.
- Add correctness checks and a scaling benchmark.
**Benchmark**
Finalization only, Apple M1 Pro, darwin/arm64, Go 1.26.3, `GOMAXPROCS=8`. Median of 3 runs, 300ms each.
100K files for plain/residual cases; 20K files with 32 offsets each for splitting. Columns show ms/op by worker count.
| Case | 1 worker | 2 workers | 4 workers | 8 workers |
| --- | ---: | ---: | ---: | ---: |
| plain | 3.93 | 2.07 | 1.50 | 1.02 |
| identity_residual | 20.07 | 12.53 | 11.22 | 14.16 |
| split_offsets | 22.52 | 23.11 | 21.44 | 17.69 |
This is worker scaling within the new implementation, not a full `PlanFiles` before/after comparison.
```sh
go test ./table -run '^$' -bench '^BenchmarkFinalizePlannedTasks$' -benchmem -benchtime=300ms -count=3 -cpu=8
```
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] perf(table): parallelize scan task finalization [iceberg-go]
Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka commented on code in PR #2149:
URL: https://github.com/apache/iceberg-go/pull/2149#discussion_r4234106982
##########
table/scan_task_finalization.go:
##########
@@ -0,0 +1,199 @@
+// 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 (
+ "fmt"
+ "sync"
+
+ "github.com/apache/iceberg-go"
+)
+
+// Keep enough work in each finalization worker to amortize goroutine and
+// result-merging overhead on small scans.
+const scanTaskFinalizationMinTasksPerWorker = 64
+
+type scanTaskSplitReplacement struct {
+ index int
+ tasks []FileScanTask
+}
+
+type scanTaskFinalizationResult struct {
+ metrics scanMetricsAccumulator
+ replacements []scanTaskSplitReplacement
+ err error
+}
+
+// finalizePlannedTasks applies task residuals, records result metrics, and
+// expands Parquet byte-range splits. Workers own disjoint task ranges, so base
+// tasks can be updated in place. Only tasks that actually split need replacement
+// slices; unsplit scans return plannedTasks directly without another O(files)
+// copy.
+func (scan *Scan) finalizePlannedTasks(
+ plannedTasks []FileScanTask,
+ schema *iceberg.Schema,
+ acc *scanMetricsAccumulator,
+) ([]FileScanTask, error) {
+ var boundRowFilter iceberg.BooleanExpression
+ if scan.rowFilter != nil && !scan.rowFilter.Equals(iceberg.AlwaysTrue{}) {
+ var err error
+ boundRowFilter, err = iceberg.BindExpr(schema, scan.rowFilter, scan.caseSensitive)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ var residualEvaluators *keyDefaultMapErr[int, *partitionResidualEvaluator]
+ if boundRowFilter != nil {
+ residualEvaluators = newKeyDefaultMapWrapErr(func(specID int) (*partitionResidualEvaluator, error) {
+ return newPartitionResidualEvaluator(
+ schema, scan.metadata.PartitionSpecByID(specID), boundRowFilter, scan.caseSensitive)
+ })
+ }
+
+ splitTargetSize := scan.metadata.Properties().GetInt64(
+ ReadSplitTargetSizeKey, ReadSplitTargetSizeDefault)
+ acc.resultDataFiles = int64(len(plannedTasks))
+ if len(plannedTasks) == 0 {
+ return []FileScanTask{}, nil
+ }
+
+ workerCount := min(max(scan.concurrency, 1), max(1, len(plannedTasks)/scanTaskFinalizationMinTasksPerWorker))
Review Comment:
`scan.concurrency` is the manifest-IO fan-out knob and can easily be 32 or more, but this work is CPU-bound, so with no `GOMAXPROCS` bound we can spawn far more CPU-bound goroutines than cores. The benchmark already shows the cost: `identity_residual` is 11.2ms at 4 workers and 14.2ms at 8, so 8 is slower. I'd clamp the worker count to `runtime.GOMAXPROCS(0)`, and given that regression raise the per-worker floor well above 64.
##########
table/scan_task_finalization.go:
##########
@@ -0,0 +1,199 @@
+// 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 (
+ "fmt"
+ "sync"
+
+ "github.com/apache/iceberg-go"
+)
+
+// Keep enough work in each finalization worker to amortize goroutine and
+// result-merging overhead on small scans.
+const scanTaskFinalizationMinTasksPerWorker = 64
+
+type scanTaskSplitReplacement struct {
+ index int
+ tasks []FileScanTask
+}
+
+type scanTaskFinalizationResult struct {
+ metrics scanMetricsAccumulator
+ replacements []scanTaskSplitReplacement
+ err error
+}
+
+// finalizePlannedTasks applies task residuals, records result metrics, and
+// expands Parquet byte-range splits. Workers own disjoint task ranges, so base
+// tasks can be updated in place. Only tasks that actually split need replacement
Review Comment:
The doc says tasks "can be updated in place" but not that `finalizePlannedTasks` consumes the slice. It writes `Residual` into the caller's array, including on the error path where it leaves the slice half-updated, and the unsplit path returns that same backing array. That's safe today because `planFilesLocal` owns the slice, but this reads like a general helper on `Scan`, and the incremental and changelog planners use similar shapes. I'd spell the ownership out: callers hand off `plannedTasks` and must not reuse it after the call, and the returned slice may alias it.
##########
table/scan_task_finalization.go:
##########
@@ -0,0 +1,199 @@
+// 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 (
+ "fmt"
+ "sync"
+
+ "github.com/apache/iceberg-go"
+)
+
+// Keep enough work in each finalization worker to amortize goroutine and
+// result-merging overhead on small scans.
+const scanTaskFinalizationMinTasksPerWorker = 64
+
+type scanTaskSplitReplacement struct {
+ index int
+ tasks []FileScanTask
+}
+
+type scanTaskFinalizationResult struct {
+ metrics scanMetricsAccumulator
+ replacements []scanTaskSplitReplacement
+ err error
+}
+
+// finalizePlannedTasks applies task residuals, records result metrics, and
+// expands Parquet byte-range splits. Workers own disjoint task ranges, so base
+// tasks can be updated in place. Only tasks that actually split need replacement
+// slices; unsplit scans return plannedTasks directly without another O(files)
+// copy.
+func (scan *Scan) finalizePlannedTasks(
+ plannedTasks []FileScanTask,
+ schema *iceberg.Schema,
+ acc *scanMetricsAccumulator,
+) ([]FileScanTask, error) {
+ var boundRowFilter iceberg.BooleanExpression
+ if scan.rowFilter != nil && !scan.rowFilter.Equals(iceberg.AlwaysTrue{}) {
+ var err error
+ boundRowFilter, err = iceberg.BindExpr(schema, scan.rowFilter, scan.caseSensitive)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ var residualEvaluators *keyDefaultMapErr[int, *partitionResidualEvaluator]
+ if boundRowFilter != nil {
+ residualEvaluators = newKeyDefaultMapWrapErr(func(specID int) (*partitionResidualEvaluator, error) {
+ return newPartitionResidualEvaluator(
+ schema, scan.metadata.PartitionSpecByID(specID), boundRowFilter, scan.caseSensitive)
+ })
+ }
+
+ splitTargetSize := scan.metadata.Properties().GetInt64(
+ ReadSplitTargetSizeKey, ReadSplitTargetSizeDefault)
+ acc.resultDataFiles = int64(len(plannedTasks))
+ if len(plannedTasks) == 0 {
+ return []FileScanTask{}, nil
+ }
+
+ workerCount := min(max(scan.concurrency, 1), max(1, len(plannedTasks)/scanTaskFinalizationMinTasksPerWorker))
+ results := make([]scanTaskFinalizationResult, workerCount)
+ chunkSize := (len(plannedTasks) + workerCount - 1) / workerCount
+
+ finalizeRange := func(worker, start, end int) {
+ results[worker] = scan.finalizeTaskRange(
+ plannedTasks, start, end, residualEvaluators, splitTargetSize)
+ }
+
+ if workerCount == 1 {
+ finalizeRange(0, 0, len(plannedTasks))
+ } else {
+ var wg sync.WaitGroup
+ for worker := range workerCount {
+ start := worker * chunkSize
+ end := min(start+chunkSize, len(plannedTasks))
+
+ wg.Add(1)
+ go func(worker, start, end int) {
+ defer wg.Done()
+ finalizeRange(worker, start, end)
+ }(worker, start, end)
+ }
+ wg.Wait()
+ }
+
+ // Each worker stops at its first error, and results follow contiguous task
+ // ranges. The first error in result order is therefore also the first error
+ // in task order, regardless of which worker finished first.
+ for i := range results {
+ if results[i].err != nil {
+ return nil, results[i].err
+ }
+ }
+
+ totalTasks := len(plannedTasks)
+ for i := range results {
+ mergeTaskFinalizationMetrics(acc, &results[i].metrics)
+ for _, replacement := range results[i].replacements {
+ totalTasks += len(replacement.tasks) - 1
+ }
+ }
+ if totalTasks == len(plannedTasks) {
+ return plannedTasks, nil
+ }
+
+ finalized := make([]FileScanTask, 0, totalTasks)
Review Comment:
On the split path we hold `plannedTasks`, every per-split replacement slice, and `finalized` live at the same time, then copy every task again into `finalized`, so peak footprint is roughly double on exactly the large-table, many-splits case. That's the case `planFilesLocal` just worked to shrink by releasing the delete indexes first, and the split benchmark barely scales (22ms to 17ms across 1 to 8 workers). I'd have each worker emit its range already in final order, unsplit tasks and splits inline, and concatenate the per-worker slices once, so there's a single copy and no separate replacement bookkeeping.
##########
table/scan_task_finalization_test.go:
##########
@@ -0,0 +1,317 @@
+// 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 (
+ "fmt"
+ "testing"
+
+ "github.com/apache/iceberg-go"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestFinalizePlannedTasksParallelMatchesSerial(t *testing.T) {
Review Comment:
Two gaps here, both on the most intricate code in the PR. Every file splits into four (offsets `[8,25,50,75]`, target 25), so `plannedTasks[next:replacement.index]` is always empty and the gap-stitching in reassembly never runs; deleting that copy line would still pass this test. And "matches serial" compares `concurrency: 8` against `concurrency: 1` of the same function, so a regression that dropped a gap or a metric would pass both sides.
I'd build an independent serial reference straight from `splitParquetScanTask` and assert against that, with a mix of split and unsplit tasks (splits at index 0, the last index, adjacent, and straddling a chunk boundary). Varying the task count across the 64-per-worker threshold (0, 1, 63, 128, 200) while here would cover the chunk arithmetic too.
##########
table/scan_task_finalization.go:
##########
@@ -0,0 +1,199 @@
+// 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 (
+ "fmt"
+ "sync"
+
+ "github.com/apache/iceberg-go"
+)
+
+// Keep enough work in each finalization worker to amortize goroutine and
+// result-merging overhead on small scans.
+const scanTaskFinalizationMinTasksPerWorker = 64
+
+type scanTaskSplitReplacement struct {
+ index int
+ tasks []FileScanTask
+}
+
+type scanTaskFinalizationResult struct {
+ metrics scanMetricsAccumulator
+ replacements []scanTaskSplitReplacement
+ err error
+}
+
+// finalizePlannedTasks applies task residuals, records result metrics, and
+// expands Parquet byte-range splits. Workers own disjoint task ranges, so base
+// tasks can be updated in place. Only tasks that actually split need replacement
+// slices; unsplit scans return plannedTasks directly without another O(files)
+// copy.
+func (scan *Scan) finalizePlannedTasks(
+ plannedTasks []FileScanTask,
+ schema *iceberg.Schema,
+ acc *scanMetricsAccumulator,
+) ([]FileScanTask, error) {
+ var boundRowFilter iceberg.BooleanExpression
+ if scan.rowFilter != nil && !scan.rowFilter.Equals(iceberg.AlwaysTrue{}) {
+ var err error
+ boundRowFilter, err = iceberg.BindExpr(schema, scan.rowFilter, scan.caseSensitive)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ var residualEvaluators *keyDefaultMapErr[int, *partitionResidualEvaluator]
+ if boundRowFilter != nil {
+ residualEvaluators = newKeyDefaultMapWrapErr(func(specID int) (*partitionResidualEvaluator, error) {
+ return newPartitionResidualEvaluator(
+ schema, scan.metadata.PartitionSpecByID(specID), boundRowFilter, scan.caseSensitive)
+ })
+ }
+
+ splitTargetSize := scan.metadata.Properties().GetInt64(
+ ReadSplitTargetSizeKey, ReadSplitTargetSizeDefault)
+ acc.resultDataFiles = int64(len(plannedTasks))
+ if len(plannedTasks) == 0 {
+ return []FileScanTask{}, nil
+ }
+
+ workerCount := min(max(scan.concurrency, 1), max(1, len(plannedTasks)/scanTaskFinalizationMinTasksPerWorker))
+ results := make([]scanTaskFinalizationResult, workerCount)
+ chunkSize := (len(plannedTasks) + workerCount - 1) / workerCount
+
+ finalizeRange := func(worker, start, end int) {
+ results[worker] = scan.finalizeTaskRange(
+ plannedTasks, start, end, residualEvaluators, splitTargetSize)
+ }
+
+ if workerCount == 1 {
+ finalizeRange(0, 0, len(plannedTasks))
+ } else {
+ var wg sync.WaitGroup
+ for worker := range workerCount {
+ start := worker * chunkSize
+ end := min(start+chunkSize, len(plannedTasks))
+
+ wg.Add(1)
+ go func(worker, start, end int) {
Review Comment:
A panic in `residual` or `splitParquetScanTask` now unwinds this anonymous goroutine with no recover, so it takes down the process. Before, it unwound on the caller's goroutine, where a `recover` around `PlanFiles` could catch it. It's not a regression in kind, since the manifest `errgroup` has the same gap, but it does widen the exposure to callers that recover. I'd add a `defer` in the worker that converts a panic into `result.err` so it flows through the same first-error path.
##########
table/scan_task_finalization_test.go:
##########
@@ -0,0 +1,317 @@
+// 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 (
+ "fmt"
+ "testing"
+
+ "github.com/apache/iceberg-go"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestFinalizePlannedTasksParallelMatchesSerial(t *testing.T) {
+ schema := iceberg.NewSchema(1, iceberg.NestedField{
+ ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true,
+ })
+ metadata, err := NewMetadata(
+ schema,
+ iceberg.UnpartitionedSpec,
+ UnsortedSortOrder,
+ "mem://table",
+ iceberg.Properties{ReadSplitTargetSizeKey: "25"},
+ )
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 256)
+ for i := range tasks {
+ file := finalizationTestDataFile(
+ t, *iceberg.UnpartitionedSpec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i), nil,
+ 100, []int64{8, 25, 50, 75})
+ tasks[i] = FileScanTask{File: file, Start: 0, Length: file.FileSizeBytes()}
+ if i%3 == 0 {
+ tasks[i].DeleteFiles = []iceberg.DataFile{file}
Review Comment:
These cases populate `DeleteFiles` and `EqualityDeleteFiles` but never a deletion vector, so the `dvs` count and the `content_size_in_bytes` size path through the per-worker merge go untested; a regression that dropped either from `mergeTaskFinalizationMetrics` would still pass. I'd add a case with a Puffin DV delete file and assert `dvs`, `totalDeleteFileSize`, and `resultDeleteFiles`.
##########
table/scan_task_finalization_test.go:
##########
@@ -0,0 +1,317 @@
+// 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 (
+ "fmt"
+ "testing"
+
+ "github.com/apache/iceberg-go"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestFinalizePlannedTasksParallelMatchesSerial(t *testing.T) {
+ schema := iceberg.NewSchema(1, iceberg.NestedField{
+ ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true,
+ })
+ metadata, err := NewMetadata(
+ schema,
+ iceberg.UnpartitionedSpec,
+ UnsortedSortOrder,
+ "mem://table",
+ iceberg.Properties{ReadSplitTargetSizeKey: "25"},
+ )
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 256)
+ for i := range tasks {
+ file := finalizationTestDataFile(
+ t, *iceberg.UnpartitionedSpec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i), nil,
+ 100, []int64{8, 25, 50, 75})
+ tasks[i] = FileScanTask{File: file, Start: 0, Length: file.FileSizeBytes()}
+ if i%3 == 0 {
+ tasks[i].DeleteFiles = []iceberg.DataFile{file}
+ }
+ if i%5 == 0 {
+ tasks[i].EqualityDeleteFiles = []iceberg.DataFile{file}
+ }
+ }
+
+ serialScan := &Scan{
+ metadata: metadata, rowFilter: iceberg.AlwaysTrue{}, caseSensitive: true, concurrency: 1,
+ }
+ parallelScan := &Scan{
+ metadata: metadata, rowFilter: iceberg.AlwaysTrue{}, caseSensitive: true, concurrency: 8,
+ }
+ serialInput := append([]FileScanTask(nil), tasks...)
+ parallelInput := append([]FileScanTask(nil), tasks...)
+ var serialMetrics, parallelMetrics scanMetricsAccumulator
+
+ serial, err := serialScan.finalizePlannedTasks(serialInput, schema, &serialMetrics)
+ require.NoError(t, err)
+ parallel, err := parallelScan.finalizePlannedTasks(parallelInput, schema, ¶llelMetrics)
+ require.NoError(t, err)
+
+ assert.Equal(t, serial, parallel)
+ assert.Equal(t, serialMetrics, parallelMetrics)
+ require.Len(t, parallel, len(tasks)*4)
+ for i := range tasks {
+ for split, start := range []int64{0, 25, 50, 75} {
+ task := parallel[i*4+split]
+ assert.Equal(t, fmt.Sprintf("mem://table/data/file-%d.parquet", i), task.File.FilePath())
+ assert.Equal(t, start, task.Start)
+ assert.Equal(t, int64(25), task.Length)
+ }
+ }
+ assert.Equal(t, int64(len(tasks)), parallelMetrics.resultDataFiles)
+ assert.Equal(t, int64(len(tasks)*100), parallelMetrics.totalFileSize)
+ assert.Equal(t, int64(86), parallelMetrics.positionalDeleteFiles)
+ assert.Equal(t, int64(52), parallelMetrics.equalityDeleteFiles)
+ assert.Equal(t, int64(138), parallelMetrics.resultDeleteFiles)
+ assert.Equal(t, int64(13_800), parallelMetrics.totalDeleteFileSize)
+}
+
+func TestFinalizePlannedTasksParallelResidualsMatchSerial(t *testing.T) {
+ schema := simpleSchema()
+ spec := partitionedSpec()
+ unpartitioned := iceberg.NewPartitionSpecID(1)
+ metadata, err := NewMetadata(
+ schema,
+ &spec,
+ UnsortedSortOrder,
+ "mem://table",
+ nil,
+ )
+ require.NoError(t, err)
+ builder, err := MetadataBuilderFromBase(metadata, "")
+ require.NoError(t, err)
+ require.NoError(t, builder.AddPartitionSpec(&unpartitioned, false))
+ metadata, err = builder.Build()
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 256)
+ for i := range tasks {
+ partitionValue := int32(7)
+ if i%2 != 0 {
+ partitionValue = 8
+ }
+ fileSpec := spec
+ if i%4 < 2 {
+ fileSpec = unpartitioned
+ }
+ file := finalizationTestDataFile(
+ t, fileSpec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i),
+ map[int]any{1000: partitionValue}, 100, nil)
+ tasks[i] = FileScanTask{File: file, Start: 0, Length: file.FileSizeBytes()}
+ }
+
+ filter := iceberg.EqualTo(iceberg.Reference("id"), int32(7))
+ serialScan := &Scan{metadata: metadata, rowFilter: filter, caseSensitive: true, concurrency: 1}
+ parallelScan := &Scan{metadata: metadata, rowFilter: filter, caseSensitive: true, concurrency: 8}
+ serialInput := append([]FileScanTask(nil), tasks...)
+ parallelInput := append([]FileScanTask(nil), tasks...)
+ var serialMetrics, parallelMetrics scanMetricsAccumulator
+
+ serial, err := serialScan.finalizePlannedTasks(serialInput, schema, &serialMetrics)
+ require.NoError(t, err)
+ parallel, err := parallelScan.finalizePlannedTasks(parallelInput, schema, ¶llelMetrics)
+ require.NoError(t, err)
+
+ assert.Equal(t, serial, parallel)
+ assert.Equal(t, serialMetrics, parallelMetrics)
+ for i, task := range parallel {
+ if i%4 < 2 {
+ assert.Nil(t, task.Residual, "task %d has no partition projection", i)
+ } else if i%2 == 0 {
+ _, ok := task.Residual.(iceberg.AlwaysTrue)
+ assert.True(t, ok, "task %d should simplify to always true", i)
+ } else {
+ _, ok := task.Residual.(iceberg.AlwaysFalse)
+ assert.True(t, ok, "task %d should simplify to always false", i)
+ }
+ }
+}
+
+func TestFinalizePlannedTasksReturnsFirstErrorInTaskOrder(t *testing.T) {
+ schema := simpleSchema()
+ spec := partitionedSpec()
+ metadata, err := NewMetadata(schema, &spec, UnsortedSortOrder, "mem://table", nil)
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 256)
+ for i := range tasks {
+ var partitionValue any = int32(7)
+ if i == 1 || i == 128 {
+ // Put failures in separate worker ranges. Both must retain the
+ // first file's diagnostic even if a later range finishes first.
+ partitionValue = "invalid integer partition"
+ }
+ file := finalizationTestDataFile(t, spec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i),
+ map[int]any{1000: partitionValue}, 100, nil)
+ tasks[i] = FileScanTask{File: file, Length: file.FileSizeBytes()}
+ }
+
+ for _, concurrency := range []int{1, 8} {
+ scan := &Scan{
+ metadata: metadata, concurrency: concurrency, caseSensitive: true,
+ rowFilter: iceberg.EqualTo(iceberg.Reference("id"), int32(7)),
+ }
+ result, err := scan.finalizePlannedTasks(tasks, schema, &scanMetricsAccumulator{})
+ require.ErrorContains(t, err, "evaluate partition residual for mem://table/data/file-1.parquet")
+ assert.Nil(t, result)
+ }
+}
+
+func TestFinalizePlannedTasksUnsplitReusesInput(t *testing.T) {
+ schema := simpleSchema()
+ metadata, err := NewMetadata(
+ schema,
+ iceberg.UnpartitionedSpec,
+ UnsortedSortOrder,
+ "mem://table",
+ nil,
+ )
+ require.NoError(t, err)
+ file := finalizationTestDataFile(
+ t, *iceberg.UnpartitionedSpec, "mem://table/data/file.parquet", nil, 100, nil)
+ tasks := []FileScanTask{{File: file, Start: 0, Length: file.FileSizeBytes()}}
+ scan := &Scan{metadata: metadata, rowFilter: iceberg.AlwaysTrue{}, caseSensitive: true, concurrency: 8}
+
+ got, err := scan.finalizePlannedTasks(tasks, schema, &scanMetricsAccumulator{})
+ require.NoError(t, err)
+ require.Len(t, got, 1)
+ assert.Same(t, &tasks[0], &got[0])
+}
+
+func finalizationTestDataFile(
+ t testing.TB,
+ spec iceberg.PartitionSpec,
+ path string,
+ partition map[int]any,
+ size int64,
+ offsets []int64,
+) iceberg.DataFile {
+ t.Helper()
+
+ builder, err := iceberg.NewDataFileBuilder(
+ spec,
+ iceberg.EntryContentData,
+ path,
+ iceberg.ParquetFile,
+ partition,
+ nil,
+ nil,
+ 100,
+ size,
+ )
+ require.NoError(t, err)
+ if offsets != nil {
+ builder.SplitOffsets(offsets)
+ }
+
+ return builder.Build()
+}
+
+var scanTaskFinalizationBenchmarkSink int
+
+func BenchmarkFinalizePlannedTasks(b *testing.B) {
+ schema := simpleSchema()
+ spec := partitionedSpec()
+
+ for _, tc := range []struct {
+ name string
+ rowFilter iceberg.BooleanExpression
+ offsets []int64
+ targetSize string
+ fileCount int
+ }{
+ {
+ name: "plain",
+ rowFilter: iceberg.AlwaysTrue{},
+ fileCount: 100_000,
+ },
+ {
+ name: "identity_residual",
+ rowFilter: iceberg.EqualTo(iceberg.Reference("id"), int32(7)),
+ fileCount: 100_000,
+ },
+ {
+ name: "split_offsets",
+ rowFilter: iceberg.AlwaysTrue{},
+ offsets: benchmarkFinalizationOffsets(32, 32),
+ targetSize: "128",
+ fileCount: 20_000,
+ },
+ } {
+ b.Run(tc.name, func(b *testing.B) {
+ properties := iceberg.Properties{}
+ if tc.targetSize != "" {
+ properties[ReadSplitTargetSizeKey] = tc.targetSize
+ }
+ metadata, err := NewMetadata(schema, &spec, UnsortedSortOrder, "mem://benchmark", properties)
+ if err != nil {
+ b.Fatal(err)
+ }
+ tasks := make([]FileScanTask, tc.fileCount)
+ for i := range tasks {
+ file := finalizationTestDataFile(
+ b,
+ spec,
+ fmt.Sprintf("mem://benchmark/data/file-%d.parquet", i),
+ map[int]any{1000: int32(7)},
+ 2048,
+ tc.offsets,
+ )
+ tasks[i] = FileScanTask{File: file, Start: 0, Length: file.FileSizeBytes()}
+ }
+
+ for _, concurrency := range []int{1, 2, 4, 8} {
+ b.Run(fmt.Sprintf("concurrency=%d", concurrency), func(b *testing.B) {
+ scan := &Scan{
+ metadata: metadata, rowFilter: tc.rowFilter,
+ caseSensitive: true, concurrency: concurrency,
+ }
+ b.ReportAllocs()
+ b.ReportMetric(float64(tc.fileCount), "files/op")
+ b.ResetTimer()
Review Comment:
`b.Loop()` resets the timer on its first call, so this `b.ResetTimer()` is a no-op and can go.
##########
table/scan_task_finalization_test.go:
##########
@@ -0,0 +1,317 @@
+// 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 (
+ "fmt"
+ "testing"
+
+ "github.com/apache/iceberg-go"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestFinalizePlannedTasksParallelMatchesSerial(t *testing.T) {
+ schema := iceberg.NewSchema(1, iceberg.NestedField{
+ ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true,
+ })
+ metadata, err := NewMetadata(
+ schema,
+ iceberg.UnpartitionedSpec,
+ UnsortedSortOrder,
+ "mem://table",
+ iceberg.Properties{ReadSplitTargetSizeKey: "25"},
+ )
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 256)
+ for i := range tasks {
+ file := finalizationTestDataFile(
+ t, *iceberg.UnpartitionedSpec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i), nil,
+ 100, []int64{8, 25, 50, 75})
+ tasks[i] = FileScanTask{File: file, Start: 0, Length: file.FileSizeBytes()}
+ if i%3 == 0 {
+ tasks[i].DeleteFiles = []iceberg.DataFile{file}
+ }
+ if i%5 == 0 {
+ tasks[i].EqualityDeleteFiles = []iceberg.DataFile{file}
+ }
+ }
+
+ serialScan := &Scan{
+ metadata: metadata, rowFilter: iceberg.AlwaysTrue{}, caseSensitive: true, concurrency: 1,
+ }
+ parallelScan := &Scan{
+ metadata: metadata, rowFilter: iceberg.AlwaysTrue{}, caseSensitive: true, concurrency: 8,
+ }
+ serialInput := append([]FileScanTask(nil), tasks...)
+ parallelInput := append([]FileScanTask(nil), tasks...)
+ var serialMetrics, parallelMetrics scanMetricsAccumulator
+
+ serial, err := serialScan.finalizePlannedTasks(serialInput, schema, &serialMetrics)
+ require.NoError(t, err)
+ parallel, err := parallelScan.finalizePlannedTasks(parallelInput, schema, ¶llelMetrics)
+ require.NoError(t, err)
+
+ assert.Equal(t, serial, parallel)
+ assert.Equal(t, serialMetrics, parallelMetrics)
+ require.Len(t, parallel, len(tasks)*4)
+ for i := range tasks {
+ for split, start := range []int64{0, 25, 50, 75} {
+ task := parallel[i*4+split]
+ assert.Equal(t, fmt.Sprintf("mem://table/data/file-%d.parquet", i), task.File.FilePath())
+ assert.Equal(t, start, task.Start)
+ assert.Equal(t, int64(25), task.Length)
+ }
+ }
+ assert.Equal(t, int64(len(tasks)), parallelMetrics.resultDataFiles)
+ assert.Equal(t, int64(len(tasks)*100), parallelMetrics.totalFileSize)
+ assert.Equal(t, int64(86), parallelMetrics.positionalDeleteFiles)
+ assert.Equal(t, int64(52), parallelMetrics.equalityDeleteFiles)
+ assert.Equal(t, int64(138), parallelMetrics.resultDeleteFiles)
+ assert.Equal(t, int64(13_800), parallelMetrics.totalDeleteFileSize)
+}
+
+func TestFinalizePlannedTasksParallelResidualsMatchSerial(t *testing.T) {
+ schema := simpleSchema()
+ spec := partitionedSpec()
+ unpartitioned := iceberg.NewPartitionSpecID(1)
+ metadata, err := NewMetadata(
+ schema,
+ &spec,
+ UnsortedSortOrder,
+ "mem://table",
+ nil,
+ )
+ require.NoError(t, err)
+ builder, err := MetadataBuilderFromBase(metadata, "")
+ require.NoError(t, err)
+ require.NoError(t, builder.AddPartitionSpec(&unpartitioned, false))
+ metadata, err = builder.Build()
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 256)
+ for i := range tasks {
+ partitionValue := int32(7)
+ if i%2 != 0 {
+ partitionValue = 8
+ }
+ fileSpec := spec
+ if i%4 < 2 {
+ fileSpec = unpartitioned
+ }
+ file := finalizationTestDataFile(
+ t, fileSpec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i),
+ map[int]any{1000: partitionValue}, 100, nil)
+ tasks[i] = FileScanTask{File: file, Start: 0, Length: file.FileSizeBytes()}
+ }
+
+ filter := iceberg.EqualTo(iceberg.Reference("id"), int32(7))
+ serialScan := &Scan{metadata: metadata, rowFilter: filter, caseSensitive: true, concurrency: 1}
+ parallelScan := &Scan{metadata: metadata, rowFilter: filter, caseSensitive: true, concurrency: 8}
+ serialInput := append([]FileScanTask(nil), tasks...)
+ parallelInput := append([]FileScanTask(nil), tasks...)
+ var serialMetrics, parallelMetrics scanMetricsAccumulator
+
+ serial, err := serialScan.finalizePlannedTasks(serialInput, schema, &serialMetrics)
+ require.NoError(t, err)
+ parallel, err := parallelScan.finalizePlannedTasks(parallelInput, schema, ¶llelMetrics)
+ require.NoError(t, err)
+
+ assert.Equal(t, serial, parallel)
+ assert.Equal(t, serialMetrics, parallelMetrics)
+ for i, task := range parallel {
+ if i%4 < 2 {
+ assert.Nil(t, task.Residual, "task %d has no partition projection", i)
+ } else if i%2 == 0 {
+ _, ok := task.Residual.(iceberg.AlwaysTrue)
+ assert.True(t, ok, "task %d should simplify to always true", i)
+ } else {
+ _, ok := task.Residual.(iceberg.AlwaysFalse)
+ assert.True(t, ok, "task %d should simplify to always false", i)
+ }
+ }
+}
+
+func TestFinalizePlannedTasksReturnsFirstErrorInTaskOrder(t *testing.T) {
+ schema := simpleSchema()
+ spec := partitionedSpec()
+ metadata, err := NewMetadata(schema, &spec, UnsortedSortOrder, "mem://table", nil)
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 256)
+ for i := range tasks {
+ var partitionValue any = int32(7)
+ if i == 1 || i == 128 {
+ // Put failures in separate worker ranges. Both must retain the
+ // first file's diagnostic even if a later range finishes first.
+ partitionValue = "invalid integer partition"
+ }
+ file := finalizationTestDataFile(t, spec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i),
+ map[int]any{1000: partitionValue}, 100, nil)
+ tasks[i] = FileScanTask{File: file, Length: file.FileSizeBytes()}
+ }
+
+ for _, concurrency := range []int{1, 8} {
+ scan := &Scan{
+ metadata: metadata, concurrency: concurrency, caseSensitive: true,
+ rowFilter: iceberg.EqualTo(iceberg.Reference("id"), int32(7)),
+ }
+ result, err := scan.finalizePlannedTasks(tasks, schema, &scanMetricsAccumulator{})
+ require.ErrorContains(t, err, "evaluate partition residual for mem://table/data/file-1.parquet")
+ assert.Nil(t, result)
+ }
+}
+
+func TestFinalizePlannedTasksUnsplitReusesInput(t *testing.T) {
+ schema := simpleSchema()
+ metadata, err := NewMetadata(
+ schema,
+ iceberg.UnpartitionedSpec,
+ UnsortedSortOrder,
+ "mem://table",
+ nil,
+ )
+ require.NoError(t, err)
+ file := finalizationTestDataFile(
+ t, *iceberg.UnpartitionedSpec, "mem://table/data/file.parquet", nil, 100, nil)
+ tasks := []FileScanTask{{File: file, Start: 0, Length: file.FileSizeBytes()}}
+ scan := &Scan{metadata: metadata, rowFilter: iceberg.AlwaysTrue{}, caseSensitive: true, concurrency: 8}
+
+ got, err := scan.finalizePlannedTasks(tasks, schema, &scanMetricsAccumulator{})
+ require.NoError(t, err)
+ require.Len(t, got, 1)
+ assert.Same(t, &tasks[0], &got[0])
Review Comment:
This pins "same backing array" as a contract on a single-task input, which only ever hits the `workerCount==1` path, and it actively blocks the memory-optimal reassembly above: a change that stopped aliasing the input would read as a regression here. If the aliasing is a real guarantee I'd document it on the function and test it at a multi-worker size; otherwise I'd drop the pointer-identity check and assert that `Residual` was written instead.
##########
table/scan_task_finalization_test.go:
##########
@@ -0,0 +1,317 @@
+// 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 (
+ "fmt"
+ "testing"
+
+ "github.com/apache/iceberg-go"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestFinalizePlannedTasksParallelMatchesSerial(t *testing.T) {
+ schema := iceberg.NewSchema(1, iceberg.NestedField{
+ ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true,
+ })
+ metadata, err := NewMetadata(
+ schema,
+ iceberg.UnpartitionedSpec,
+ UnsortedSortOrder,
+ "mem://table",
+ iceberg.Properties{ReadSplitTargetSizeKey: "25"},
+ )
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 256)
+ for i := range tasks {
+ file := finalizationTestDataFile(
+ t, *iceberg.UnpartitionedSpec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i), nil,
+ 100, []int64{8, 25, 50, 75})
+ tasks[i] = FileScanTask{File: file, Start: 0, Length: file.FileSizeBytes()}
+ if i%3 == 0 {
+ tasks[i].DeleteFiles = []iceberg.DataFile{file}
+ }
+ if i%5 == 0 {
+ tasks[i].EqualityDeleteFiles = []iceberg.DataFile{file}
+ }
+ }
+
+ serialScan := &Scan{
+ metadata: metadata, rowFilter: iceberg.AlwaysTrue{}, caseSensitive: true, concurrency: 1,
+ }
+ parallelScan := &Scan{
+ metadata: metadata, rowFilter: iceberg.AlwaysTrue{}, caseSensitive: true, concurrency: 8,
+ }
+ serialInput := append([]FileScanTask(nil), tasks...)
+ parallelInput := append([]FileScanTask(nil), tasks...)
+ var serialMetrics, parallelMetrics scanMetricsAccumulator
+
+ serial, err := serialScan.finalizePlannedTasks(serialInput, schema, &serialMetrics)
+ require.NoError(t, err)
+ parallel, err := parallelScan.finalizePlannedTasks(parallelInput, schema, ¶llelMetrics)
+ require.NoError(t, err)
+
+ assert.Equal(t, serial, parallel)
+ assert.Equal(t, serialMetrics, parallelMetrics)
+ require.Len(t, parallel, len(tasks)*4)
+ for i := range tasks {
+ for split, start := range []int64{0, 25, 50, 75} {
+ task := parallel[i*4+split]
+ assert.Equal(t, fmt.Sprintf("mem://table/data/file-%d.parquet", i), task.File.FilePath())
+ assert.Equal(t, start, task.Start)
+ assert.Equal(t, int64(25), task.Length)
+ }
+ }
+ assert.Equal(t, int64(len(tasks)), parallelMetrics.resultDataFiles)
+ assert.Equal(t, int64(len(tasks)*100), parallelMetrics.totalFileSize)
+ assert.Equal(t, int64(86), parallelMetrics.positionalDeleteFiles)
+ assert.Equal(t, int64(52), parallelMetrics.equalityDeleteFiles)
+ assert.Equal(t, int64(138), parallelMetrics.resultDeleteFiles)
+ assert.Equal(t, int64(13_800), parallelMetrics.totalDeleteFileSize)
+}
+
+func TestFinalizePlannedTasksParallelResidualsMatchSerial(t *testing.T) {
+ schema := simpleSchema()
+ spec := partitionedSpec()
+ unpartitioned := iceberg.NewPartitionSpecID(1)
+ metadata, err := NewMetadata(
+ schema,
+ &spec,
+ UnsortedSortOrder,
+ "mem://table",
+ nil,
+ )
+ require.NoError(t, err)
+ builder, err := MetadataBuilderFromBase(metadata, "")
+ require.NoError(t, err)
+ require.NoError(t, builder.AddPartitionSpec(&unpartitioned, false))
+ metadata, err = builder.Build()
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 256)
+ for i := range tasks {
+ partitionValue := int32(7)
+ if i%2 != 0 {
+ partitionValue = 8
+ }
+ fileSpec := spec
+ if i%4 < 2 {
+ fileSpec = unpartitioned
+ }
+ file := finalizationTestDataFile(
+ t, fileSpec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i),
+ map[int]any{1000: partitionValue}, 100, nil)
+ tasks[i] = FileScanTask{File: file, Start: 0, Length: file.FileSizeBytes()}
+ }
+
+ filter := iceberg.EqualTo(iceberg.Reference("id"), int32(7))
+ serialScan := &Scan{metadata: metadata, rowFilter: filter, caseSensitive: true, concurrency: 1}
+ parallelScan := &Scan{metadata: metadata, rowFilter: filter, caseSensitive: true, concurrency: 8}
+ serialInput := append([]FileScanTask(nil), tasks...)
+ parallelInput := append([]FileScanTask(nil), tasks...)
+ var serialMetrics, parallelMetrics scanMetricsAccumulator
+
+ serial, err := serialScan.finalizePlannedTasks(serialInput, schema, &serialMetrics)
+ require.NoError(t, err)
+ parallel, err := parallelScan.finalizePlannedTasks(parallelInput, schema, ¶llelMetrics)
+ require.NoError(t, err)
+
+ assert.Equal(t, serial, parallel)
+ assert.Equal(t, serialMetrics, parallelMetrics)
+ for i, task := range parallel {
+ if i%4 < 2 {
+ assert.Nil(t, task.Residual, "task %d has no partition projection", i)
+ } else if i%2 == 0 {
+ _, ok := task.Residual.(iceberg.AlwaysTrue)
+ assert.True(t, ok, "task %d should simplify to always true", i)
+ } else {
+ _, ok := task.Residual.(iceberg.AlwaysFalse)
+ assert.True(t, ok, "task %d should simplify to always false", i)
+ }
+ }
+}
+
+func TestFinalizePlannedTasksReturnsFirstErrorInTaskOrder(t *testing.T) {
+ schema := simpleSchema()
+ spec := partitionedSpec()
+ metadata, err := NewMetadata(schema, &spec, UnsortedSortOrder, "mem://table", nil)
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 256)
+ for i := range tasks {
+ var partitionValue any = int32(7)
+ if i == 1 || i == 128 {
+ // Put failures in separate worker ranges. Both must retain the
+ // first file's diagnostic even if a later range finishes first.
+ partitionValue = "invalid integer partition"
+ }
+ file := finalizationTestDataFile(t, spec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i),
+ map[int]any{1000: partitionValue}, 100, nil)
+ tasks[i] = FileScanTask{File: file, Length: file.FileSizeBytes()}
+ }
+
+ for _, concurrency := range []int{1, 8} {
Review Comment:
The ordering guarantee this names, "even if a later range finishes first", isn't actually forced: worker 0 fails at index 1 and so almost always finishes first, so an implementation that returned the last error would still pass most runs. I'd move the first failure late in range 0 and early in range 1 so a wrong selection fails deterministically. Separately, both concurrency values run against the same `tasks` slice that the function mutates, and `err` here shadows the outer one, so I'd clone per iteration and wrap each concurrency in its own `t.Run`.
##########
table/scan_task_finalization_test.go:
##########
@@ -0,0 +1,317 @@
+// 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 (
+ "fmt"
+ "testing"
+
+ "github.com/apache/iceberg-go"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestFinalizePlannedTasksParallelMatchesSerial(t *testing.T) {
+ schema := iceberg.NewSchema(1, iceberg.NestedField{
+ ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true,
+ })
+ metadata, err := NewMetadata(
+ schema,
+ iceberg.UnpartitionedSpec,
+ UnsortedSortOrder,
+ "mem://table",
+ iceberg.Properties{ReadSplitTargetSizeKey: "25"},
+ )
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 256)
+ for i := range tasks {
+ file := finalizationTestDataFile(
+ t, *iceberg.UnpartitionedSpec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i), nil,
+ 100, []int64{8, 25, 50, 75})
+ tasks[i] = FileScanTask{File: file, Start: 0, Length: file.FileSizeBytes()}
+ if i%3 == 0 {
+ tasks[i].DeleteFiles = []iceberg.DataFile{file}
+ }
+ if i%5 == 0 {
+ tasks[i].EqualityDeleteFiles = []iceberg.DataFile{file}
+ }
+ }
+
+ serialScan := &Scan{
+ metadata: metadata, rowFilter: iceberg.AlwaysTrue{}, caseSensitive: true, concurrency: 1,
+ }
+ parallelScan := &Scan{
+ metadata: metadata, rowFilter: iceberg.AlwaysTrue{}, caseSensitive: true, concurrency: 8,
+ }
+ serialInput := append([]FileScanTask(nil), tasks...)
+ parallelInput := append([]FileScanTask(nil), tasks...)
+ var serialMetrics, parallelMetrics scanMetricsAccumulator
+
+ serial, err := serialScan.finalizePlannedTasks(serialInput, schema, &serialMetrics)
+ require.NoError(t, err)
+ parallel, err := parallelScan.finalizePlannedTasks(parallelInput, schema, ¶llelMetrics)
+ require.NoError(t, err)
+
+ assert.Equal(t, serial, parallel)
+ assert.Equal(t, serialMetrics, parallelMetrics)
+ require.Len(t, parallel, len(tasks)*4)
+ for i := range tasks {
+ for split, start := range []int64{0, 25, 50, 75} {
+ task := parallel[i*4+split]
+ assert.Equal(t, fmt.Sprintf("mem://table/data/file-%d.parquet", i), task.File.FilePath())
+ assert.Equal(t, start, task.Start)
+ assert.Equal(t, int64(25), task.Length)
+ }
+ }
+ assert.Equal(t, int64(len(tasks)), parallelMetrics.resultDataFiles)
+ assert.Equal(t, int64(len(tasks)*100), parallelMetrics.totalFileSize)
+ assert.Equal(t, int64(86), parallelMetrics.positionalDeleteFiles)
+ assert.Equal(t, int64(52), parallelMetrics.equalityDeleteFiles)
+ assert.Equal(t, int64(138), parallelMetrics.resultDeleteFiles)
+ assert.Equal(t, int64(13_800), parallelMetrics.totalDeleteFileSize)
+}
+
+func TestFinalizePlannedTasksParallelResidualsMatchSerial(t *testing.T) {
+ schema := simpleSchema()
+ spec := partitionedSpec()
+ unpartitioned := iceberg.NewPartitionSpecID(1)
+ metadata, err := NewMetadata(
+ schema,
+ &spec,
+ UnsortedSortOrder,
+ "mem://table",
+ nil,
+ )
+ require.NoError(t, err)
+ builder, err := MetadataBuilderFromBase(metadata, "")
+ require.NoError(t, err)
+ require.NoError(t, builder.AddPartitionSpec(&unpartitioned, false))
+ metadata, err = builder.Build()
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 256)
+ for i := range tasks {
+ partitionValue := int32(7)
+ if i%2 != 0 {
+ partitionValue = 8
+ }
+ fileSpec := spec
+ if i%4 < 2 {
+ fileSpec = unpartitioned
+ }
+ file := finalizationTestDataFile(
+ t, fileSpec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i),
+ map[int]any{1000: partitionValue}, 100, nil)
+ tasks[i] = FileScanTask{File: file, Start: 0, Length: file.FileSizeBytes()}
+ }
+
+ filter := iceberg.EqualTo(iceberg.Reference("id"), int32(7))
+ serialScan := &Scan{metadata: metadata, rowFilter: filter, caseSensitive: true, concurrency: 1}
+ parallelScan := &Scan{metadata: metadata, rowFilter: filter, caseSensitive: true, concurrency: 8}
+ serialInput := append([]FileScanTask(nil), tasks...)
+ parallelInput := append([]FileScanTask(nil), tasks...)
+ var serialMetrics, parallelMetrics scanMetricsAccumulator
+
+ serial, err := serialScan.finalizePlannedTasks(serialInput, schema, &serialMetrics)
+ require.NoError(t, err)
+ parallel, err := parallelScan.finalizePlannedTasks(parallelInput, schema, ¶llelMetrics)
+ require.NoError(t, err)
+
+ assert.Equal(t, serial, parallel)
+ assert.Equal(t, serialMetrics, parallelMetrics)
+ for i, task := range parallel {
+ if i%4 < 2 {
+ assert.Nil(t, task.Residual, "task %d has no partition projection", i)
+ } else if i%2 == 0 {
+ _, ok := task.Residual.(iceberg.AlwaysTrue)
+ assert.True(t, ok, "task %d should simplify to always true", i)
+ } else {
+ _, ok := task.Residual.(iceberg.AlwaysFalse)
+ assert.True(t, ok, "task %d should simplify to always false", i)
+ }
+ }
+}
+
+func TestFinalizePlannedTasksReturnsFirstErrorInTaskOrder(t *testing.T) {
+ schema := simpleSchema()
+ spec := partitionedSpec()
+ metadata, err := NewMetadata(schema, &spec, UnsortedSortOrder, "mem://table", nil)
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 256)
+ for i := range tasks {
+ var partitionValue any = int32(7)
+ if i == 1 || i == 128 {
+ // Put failures in separate worker ranges. Both must retain the
+ // first file's diagnostic even if a later range finishes first.
+ partitionValue = "invalid integer partition"
+ }
+ file := finalizationTestDataFile(t, spec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i),
+ map[int]any{1000: partitionValue}, 100, nil)
+ tasks[i] = FileScanTask{File: file, Length: file.FileSizeBytes()}
+ }
+
+ for _, concurrency := range []int{1, 8} {
+ scan := &Scan{
+ metadata: metadata, concurrency: concurrency, caseSensitive: true,
+ rowFilter: iceberg.EqualTo(iceberg.Reference("id"), int32(7)),
+ }
+ result, err := scan.finalizePlannedTasks(tasks, schema, &scanMetricsAccumulator{})
+ require.ErrorContains(t, err, "evaluate partition residual for mem://table/data/file-1.parquet")
+ assert.Nil(t, result)
+ }
+}
+
+func TestFinalizePlannedTasksUnsplitReusesInput(t *testing.T) {
+ schema := simpleSchema()
+ metadata, err := NewMetadata(
+ schema,
+ iceberg.UnpartitionedSpec,
+ UnsortedSortOrder,
+ "mem://table",
+ nil,
+ )
+ require.NoError(t, err)
+ file := finalizationTestDataFile(
+ t, *iceberg.UnpartitionedSpec, "mem://table/data/file.parquet", nil, 100, nil)
+ tasks := []FileScanTask{{File: file, Start: 0, Length: file.FileSizeBytes()}}
+ scan := &Scan{metadata: metadata, rowFilter: iceberg.AlwaysTrue{}, caseSensitive: true, concurrency: 8}
+
+ got, err := scan.finalizePlannedTasks(tasks, schema, &scanMetricsAccumulator{})
+ require.NoError(t, err)
+ require.Len(t, got, 1)
+ assert.Same(t, &tasks[0], &got[0])
+}
+
+func finalizationTestDataFile(
+ t testing.TB,
+ spec iceberg.PartitionSpec,
+ path string,
+ partition map[int]any,
+ size int64,
+ offsets []int64,
+) iceberg.DataFile {
+ t.Helper()
+
+ builder, err := iceberg.NewDataFileBuilder(
+ spec,
+ iceberg.EntryContentData,
+ path,
+ iceberg.ParquetFile,
+ partition,
+ nil,
+ nil,
+ 100,
+ size,
+ )
+ require.NoError(t, err)
+ if offsets != nil {
+ builder.SplitOffsets(offsets)
+ }
+
+ return builder.Build()
+}
+
+var scanTaskFinalizationBenchmarkSink int
+
+func BenchmarkFinalizePlannedTasks(b *testing.B) {
Review Comment:
This benchmarks the new function against itself at different worker counts, so it can't show whether we're actually faster than the serial loop we removed, and `concurrency=1` here isn't that loop (it adds the cache indirection and the two-phase merge). To justify this much concurrency machinery I'd want a before/after against the old path, ideally an end-to-end `PlanFiles` benchmark, since local planning is dominated by manifest IO and a few ms on 100K files sits in the noise.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] perf(table): parallelize scan task finalization [iceberg-go]
Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka commented on code in PR #2149:
URL: https://github.com/apache/iceberg-go/pull/2149#discussion_r4328220752
##########
table/scan_task_finalization.go:
##########
@@ -0,0 +1,211 @@
+// 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 (
+ "fmt"
+ "runtime"
+ "sync"
+
+ "github.com/apache/iceberg-go"
+)
+
+// CPU-heavy finalization needs enough work to amortize worker and merge costs.
+const scanTaskFinalizationMinTasksPerWorker = 256
+
+type scanTaskFinalizationResult struct {
+ metrics scanMetricsAccumulator
+ tasks []FileScanTask
+ expanded bool
+ err error
+}
+
+// finalizePlannedTasks applies residuals, records result metrics, and expands
+// Parquet byte-range splits. The caller transfers ownership of plannedTasks:
+// workers mutate residuals in that slice, even when an error is returned.
+// Callers must not reuse it after this call. If no task splits, the returned
+// slice aliases the original backing array.
+func (scan *Scan) finalizePlannedTasks(
+ plannedTasks []FileScanTask,
+ schema *iceberg.Schema,
+ acc *scanMetricsAccumulator,
+) ([]FileScanTask, error) {
+ var boundRowFilter iceberg.BooleanExpression
+ if scan.rowFilter != nil && !scan.rowFilter.Equals(iceberg.AlwaysTrue{}) {
+ var err error
+ boundRowFilter, err = iceberg.BindExpr(schema, scan.rowFilter, scan.caseSensitive)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ var residualEvaluators *keyDefaultMapErr[int, *partitionResidualEvaluator]
+ if boundRowFilter != nil {
+ residualEvaluators = newKeyDefaultMapWrapErr(func(specID int) (*partitionResidualEvaluator, error) {
+ return newPartitionResidualEvaluator(
+ schema, scan.metadata.PartitionSpecByID(specID), boundRowFilter, scan.caseSensitive)
+ })
+ }
+
+ splitTargetSize := scan.metadata.Properties().GetInt64(
+ ReadSplitTargetSizeKey, ReadSplitTargetSizeDefault)
+ acc.resultDataFiles = int64(len(plannedTasks))
+ if len(plannedTasks) == 0 {
+ return []FileScanTask{}, nil
+ }
+
+ workerCount := min(max(scan.concurrency, 1), runtime.GOMAXPROCS(0),
+ max(1, len(plannedTasks)/scanTaskFinalizationMinTasksPerWorker))
+ results := make([]scanTaskFinalizationResult, workerCount)
+
+ finalizeRange := func(worker, start, end int) {
+ defer func() {
+ if recovered := recover(); recovered != nil {
+ results[worker].err = fmt.Errorf("finalize scan tasks [%d:%d]: panic: %v",
Review Comment:
This is a side effect of the recover I asked for last round. It wraps `finalizeRange`, so it also catches the inline `workerCount == 1` path, which covers every scan under 512 tasks. A panic there used to crash with a full stack. Now it comes back as a plain error with no stack, and `%v` hides it from `errors.Is`/`As` when the panic value is an error.
I'd either move the recover into the `go func` so only spawned workers get it, or keep it shared and add `debug.Stack()` plus `%w` when `recovered` is an error. Either way, a one-worker panic test would pin down which behavior we want, since `WorkerPanicReturnsError` only covers the concurrent path.
##########
table/scan_task_finalization.go:
##########
@@ -0,0 +1,211 @@
+// 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 (
+ "fmt"
+ "runtime"
+ "sync"
+
+ "github.com/apache/iceberg-go"
+)
+
+// CPU-heavy finalization needs enough work to amortize worker and merge costs.
+const scanTaskFinalizationMinTasksPerWorker = 256
+
+type scanTaskFinalizationResult struct {
+ metrics scanMetricsAccumulator
+ tasks []FileScanTask
+ expanded bool
+ err error
+}
+
+// finalizePlannedTasks applies residuals, records result metrics, and expands
+// Parquet byte-range splits. The caller transfers ownership of plannedTasks:
+// workers mutate residuals in that slice, even when an error is returned.
+// Callers must not reuse it after this call. If no task splits, the returned
+// slice aliases the original backing array.
+func (scan *Scan) finalizePlannedTasks(
+ plannedTasks []FileScanTask,
+ schema *iceberg.Schema,
+ acc *scanMetricsAccumulator,
+) ([]FileScanTask, error) {
+ var boundRowFilter iceberg.BooleanExpression
+ if scan.rowFilter != nil && !scan.rowFilter.Equals(iceberg.AlwaysTrue{}) {
+ var err error
+ boundRowFilter, err = iceberg.BindExpr(schema, scan.rowFilter, scan.caseSensitive)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ var residualEvaluators *keyDefaultMapErr[int, *partitionResidualEvaluator]
+ if boundRowFilter != nil {
+ residualEvaluators = newKeyDefaultMapWrapErr(func(specID int) (*partitionResidualEvaluator, error) {
+ return newPartitionResidualEvaluator(
+ schema, scan.metadata.PartitionSpecByID(specID), boundRowFilter, scan.caseSensitive)
+ })
+ }
+
+ splitTargetSize := scan.metadata.Properties().GetInt64(
+ ReadSplitTargetSizeKey, ReadSplitTargetSizeDefault)
+ acc.resultDataFiles = int64(len(plannedTasks))
+ if len(plannedTasks) == 0 {
+ return []FileScanTask{}, nil
+ }
+
+ workerCount := min(max(scan.concurrency, 1), runtime.GOMAXPROCS(0),
+ max(1, len(plannedTasks)/scanTaskFinalizationMinTasksPerWorker))
+ results := make([]scanTaskFinalizationResult, workerCount)
+
+ finalizeRange := func(worker, start, end int) {
+ defer func() {
+ if recovered := recover(); recovered != nil {
+ results[worker].err = fmt.Errorf("finalize scan tasks [%d:%d]: panic: %v",
+ start, end, recovered)
+ }
+ }()
+ results[worker] = scan.finalizeTaskRange(
+ plannedTasks, start, end, residualEvaluators, splitTargetSize)
+ }
+
+ if workerCount == 1 {
+ finalizeRange(0, 0, len(plannedTasks))
+ } else {
+ var wg sync.WaitGroup
+ chunkSize, remainder := len(plannedTasks)/workerCount, len(plannedTasks)%workerCount
+ start := 0
+ for worker := range workerCount {
+ // Distribute the remainder instead of rounding every range up:
+ // even large worker counts must stay within the input slice.
+ end := start + chunkSize
+ if worker < remainder {
+ end++
+ }
+
+ wg.Add(1)
+ go func(worker, start, end int) {
+ defer wg.Done()
+ finalizeRange(worker, start, end)
+ }(worker, start, end)
+ start = end
+ }
+ wg.Wait()
+ }
+
+ // Ranges follow task order, regardless of the order workers completed.
+ for i := range results {
+ if results[i].err != nil {
+ return nil, results[i].err
+ }
+ }
+
+ totalTasks := 0
+ anySplit := false
+ for i := range results {
+ mergeTaskFinalizationMetrics(acc, &results[i].metrics)
+ anySplit = anySplit || results[i].expanded
+ totalTasks += len(results[i].tasks)
+ }
+ if !anySplit {
+ return plannedTasks, nil
+ }
+ if workerCount == 1 {
+ return results[0].tasks, nil
+ }
+
+ // Workers that split files emit their ranges in task order. Unsplit
+ // workers reuse their input ranges without temporary replacement lists.
+ // Concatenate once; do not hold an allocation per individual split.
+ finalized := make([]FileScanTask, 0, totalTasks)
Review Comment:
The peak-memory issue from last round is still here on the all-split path. Each worker grows `result.tasks` by append-doubling, and then this loop copies everything into `finalized`, so input, slack and output are all live at once. Pre-sizing `result.tasks` on the first split (roughly `(end-start)*2`, or an estimate from the split offsets) would cover most of it.
##########
table/scan_task_finalization_planfiles_bench_test.go:
##########
@@ -0,0 +1,169 @@
+// 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 (
+ "bytes"
+ "context"
+ "fmt"
+ "testing"
+
+ "github.com/apache/iceberg-go"
+)
+
+const (
+ planFilesFinalizationBenchmarkManifestCount = 8
+ planFilesFinalizationBenchmarkFilesPerManifest = 2_500
+)
+
+var planFilesFinalizationBenchmarkSink int
+
+// BenchmarkPlanFilesTaskFinalization measures the effect of scan-task
+// finalization in the context of local PlanFiles. The benchmark fixture is
+// shared by the pre-change and parallel implementations, so copy this file to
+// the PR base worktree when comparing the two revisions.
+func BenchmarkPlanFilesTaskFinalization(b *testing.B) {
+ tbl := newPlanFilesFinalizationBenchmarkTable(b)
+ fileCount := planFilesFinalizationBenchmarkManifestCount * planFilesFinalizationBenchmarkFilesPerManifest
+
+ for _, tc := range []struct {
+ name string
+ rowFilter iceberg.BooleanExpression
+ }{
+ {name: "plain", rowFilter: iceberg.AlwaysTrue{}},
+ {name: "identity_residual", rowFilter: iceberg.EqualTo(iceberg.Reference("id"), int32(7))},
+ } {
+ b.Run(tc.name, func(b *testing.B) {
+ scan := tbl.Scan(WithMaxConcurrency(8), WithRowFilter(tc.rowFilter))
+ b.ReportAllocs()
+ b.ReportMetric(float64(fileCount), "files/op")
+ for b.Loop() {
+ tasks, err := scan.PlanFiles(context.Background())
+ if err != nil {
+ b.Fatal(err)
+ }
+ if len(tasks) != fileCount {
+ b.Fatalf("PlanFiles returned %d tasks, want %d", len(tasks), fileCount)
+ }
+ planFilesFinalizationBenchmarkSink = len(tasks)
+ }
+ })
+ }
+}
+
+func newPlanFilesFinalizationBenchmarkTable(b testing.TB) *Table {
+ b.Helper()
+
+ const (
+ tableLocation = "mem://plan-files-finalization-benchmark"
+ sequenceNum = int64(1)
+ )
+ snapshotID := int64(1)
+
+ fs := newTrackingIO()
+ schema := simpleSchema()
+ spec := partitionedSpec()
+ meta, err := NewMetadata(schema, &spec, UnsortedSortOrder, tableLocation, nil)
+ if err != nil {
+ b.Fatal(err)
+ }
+ builder, err := MetadataBuilderFromBase(meta, "")
+ if err != nil {
+ b.Fatal(err)
+ }
+
+ manifests := make([]iceberg.ManifestFile, planFilesFinalizationBenchmarkManifestCount)
+ for manifestIndex := range manifests {
+ entries := make([]iceberg.ManifestEntry, planFilesFinalizationBenchmarkFilesPerManifest)
+ for entryIndex := range entries {
+ dataPath := fmt.Sprintf("%s/data-%d-%d.parquet", tableLocation, manifestIndex, entryIndex)
+ fileBuilder, err := iceberg.NewDataFileBuilder(
+ spec,
+ iceberg.EntryContentData,
+ dataPath,
+ iceberg.ParquetFile,
+ map[int]any{1000: int32(7)},
Review Comment:
Every file here has spec 0, partition value 7, no split offsets and no deletes. So the bench only runs the plain path and a residual that always simplifies to AlwaysTrue, and the in-memory IO pushes finalization's share up. I'd vary the partition value (`i%4`), add a split-offsets case and a case with a positional delete manifest plus a DV, and ideally interleave a second spec. If we keep it this simple, the doc comment should say it's the no-split, no-delete lower bound.
##########
table/scan_task_finalization_test.go:
##########
@@ -0,0 +1,574 @@
+// 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 (
+ "fmt"
+ "runtime"
+ "testing"
+
+ "github.com/apache/iceberg-go"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func setFinalizationTestProcs(t *testing.T, count int) {
+ t.Helper()
+ previous := runtime.GOMAXPROCS(count)
+ t.Cleanup(func() { runtime.GOMAXPROCS(previous) })
+}
+
+func TestFinalizePlannedTasksParallelMatchesSerial(t *testing.T) {
+ // Exercise the concurrent worker path even on single-core CI runners.
+ setFinalizationTestProcs(t, 4)
+ schema := iceberg.NewSchema(1, iceberg.NestedField{
+ ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true,
+ })
+ metadata, err := NewMetadata(
+ schema,
+ iceberg.UnpartitionedSpec,
+ UnsortedSortOrder,
+ "mem://table",
+ iceberg.Properties{ReadSplitTargetSizeKey: "25"},
+ )
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 1024)
+ for i := range tasks {
+ file := finalizationTestDataFile(
+ t, *iceberg.UnpartitionedSpec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i), nil,
+ 100, []int64{8, 25, 50, 75})
+ tasks[i] = FileScanTask{File: file, Start: 0, Length: file.FileSizeBytes()}
+ if i%3 == 0 {
+ tasks[i].DeleteFiles = []iceberg.DataFile{file}
+ }
+ if i%5 == 0 {
+ tasks[i].EqualityDeleteFiles = []iceberg.DataFile{file}
+ }
+ }
+
+ scan := &Scan{
+ metadata: metadata, rowFilter: iceberg.AlwaysTrue{}, caseSensitive: true, concurrency: 8,
+ }
+ serial, serialMetrics, err := serialFinalizationReference(
+ scan, append([]FileScanTask(nil), tasks...), schema)
+ require.NoError(t, err)
+ var parallelMetrics scanMetricsAccumulator
+ parallel, err := scan.finalizePlannedTasks(
+ append([]FileScanTask(nil), tasks...), schema, ¶llelMetrics)
+ require.NoError(t, err)
+
+ assert.Equal(t, serial, parallel)
+ assert.Equal(t, serialMetrics, parallelMetrics)
+ require.Len(t, parallel, len(tasks)*4)
+ for i := range tasks {
+ for split, start := range []int64{0, 25, 50, 75} {
+ task := parallel[i*4+split]
+ assert.Equal(t, fmt.Sprintf("mem://table/data/file-%d.parquet", i), task.File.FilePath())
+ assert.Equal(t, start, task.Start)
+ assert.Equal(t, int64(25), task.Length)
+ }
+ }
+ assert.Equal(t, int64(len(tasks)), parallelMetrics.resultDataFiles)
+ assert.Equal(t, int64(len(tasks)*100), parallelMetrics.totalFileSize)
+ assert.Equal(t, int64(342), parallelMetrics.positionalDeleteFiles)
+ assert.Equal(t, int64(205), parallelMetrics.equalityDeleteFiles)
+ assert.Equal(t, int64(547), parallelMetrics.resultDeleteFiles)
+ assert.Equal(t, int64(54_700), parallelMetrics.totalDeleteFileSize)
+}
+
+func TestFinalizePlannedTasksParallelResidualsMatchSerial(t *testing.T) {
+ // Exercise the concurrent worker path even on single-core CI runners.
+ setFinalizationTestProcs(t, 4)
+ schema := simpleSchema()
+ spec := partitionedSpec()
+ unpartitioned := iceberg.NewPartitionSpecID(1)
+ metadata, err := NewMetadata(
+ schema,
+ &spec,
+ UnsortedSortOrder,
+ "mem://table",
+ nil,
+ )
+ require.NoError(t, err)
+ builder, err := MetadataBuilderFromBase(metadata, "")
+ require.NoError(t, err)
+ require.NoError(t, builder.AddPartitionSpec(&unpartitioned, false))
+ metadata, err = builder.Build()
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 1024)
+ for i := range tasks {
+ partitionValue := int32(7)
+ if i%2 != 0 {
+ partitionValue = 8
+ }
+ fileSpec := spec
+ if i%4 < 2 {
+ fileSpec = unpartitioned
+ }
+ file := finalizationTestDataFile(
+ t, fileSpec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i),
+ map[int]any{1000: partitionValue}, 100, nil)
+ tasks[i] = FileScanTask{File: file, Start: 0, Length: file.FileSizeBytes()}
+ }
+
+ filter := iceberg.EqualTo(iceberg.Reference("id"), int32(7))
+ scan := &Scan{metadata: metadata, rowFilter: filter, caseSensitive: true, concurrency: 8}
+ serial, serialMetrics, err := serialFinalizationReference(
+ scan, append([]FileScanTask(nil), tasks...), schema)
+ require.NoError(t, err)
+ var parallelMetrics scanMetricsAccumulator
+ parallel, err := scan.finalizePlannedTasks(
+ append([]FileScanTask(nil), tasks...), schema, ¶llelMetrics)
+ require.NoError(t, err)
+
+ assert.Equal(t, serial, parallel)
+ assert.Equal(t, serialMetrics, parallelMetrics)
+ for i, task := range parallel {
+ if i%4 < 2 {
+ assert.Nil(t, task.Residual, "task %d has no partition projection", i)
+ } else if i%2 == 0 {
+ _, ok := task.Residual.(iceberg.AlwaysTrue)
+ assert.True(t, ok, "task %d should simplify to always true", i)
+ } else {
+ _, ok := task.Residual.(iceberg.AlwaysFalse)
+ assert.True(t, ok, "task %d should simplify to always false", i)
+ }
+ }
+}
+
+func TestFinalizePlannedTasksReturnsFirstErrorInTaskOrder(t *testing.T) {
+ schema := simpleSchema()
+ spec := partitionedSpec()
+ metadata, err := NewMetadata(schema, &spec, UnsortedSortOrder, "mem://table", nil)
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 1024)
+ for i := range tasks {
+ var partitionValue any = int32(7)
+ if i == 255 || i == 256 {
+ // The earlier failing task is at the end of worker range 0;
+ // worker 1 can fail first at the start of its own range.
+ partitionValue = "invalid integer partition"
+ }
+ file := finalizationTestDataFile(t, spec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i),
+ map[int]any{1000: partitionValue}, 100, nil)
+ tasks[i] = FileScanTask{File: file, Length: file.FileSizeBytes()}
+ }
+
+ for _, concurrency := range []int{1, 8} {
+ t.Run(fmt.Sprintf("concurrency=%d", concurrency), func(t *testing.T) {
+ scan := &Scan{
+ metadata: metadata, concurrency: concurrency, caseSensitive: true,
+ rowFilter: iceberg.EqualTo(iceberg.Reference("id"), int32(7)),
+ }
+ input := append([]FileScanTask(nil), tasks...)
+ if concurrency > 1 {
+ // With four CPU workers and 1024 tasks, worker 0 owns
+ // [0:256] and worker 1 owns [256:512].
+ previous := runtime.GOMAXPROCS(4)
+ defer runtime.GOMAXPROCS(previous)
+
+ laterErrorReached := make(chan struct{})
+ input[255].File = finalizationOrderFile{
+ DataFile: input[255].File, wait: laterErrorReached,
+ }
+ input[256].File = finalizationOrderFile{
+ DataFile: input[256].File, signal: laterErrorReached,
+ }
+ }
+ result, planErr := scan.finalizePlannedTasks(input, schema, &scanMetricsAccumulator{})
+ require.ErrorContains(t, planErr, "evaluate partition residual for mem://table/data/file-255.parquet")
+ assert.Nil(t, result)
+ })
+ }
+}
+
+// Controls which worker reaches its partition error first, without relying on
+// scheduler timing. The wrapper intentionally does not forward the built-in
+// borrowed-partition interface, so residual evaluation calls Partition.
+type finalizationOrderFile struct {
+ iceberg.DataFile
+ wait <-chan struct{}
+ signal chan struct{}
+}
+
+func (f finalizationOrderFile) Partition() map[int]any {
+ if f.signal != nil {
+ close(f.signal)
Review Comment:
`close(f.signal)` has no `sync.Once`. If `Partition()` runs twice on task 256, the second close panics and the recover turns it into `results[1].err`. Worker 0's error still wins, so the test passes without proving the ordering. Separately, `<-f.wait` has no timeout, so if the worker split ever shifts, this hangs until the 10-minute test timeout. I'd add a `*sync.Once` field (the wrapper is a value type) and `select` on `time.After(5 * time.Second)` with a panic, which the recover turns into a failed `ErrorContains`.
##########
table/scan_task_finalization.go:
##########
@@ -0,0 +1,211 @@
+// 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 (
+ "fmt"
+ "runtime"
+ "sync"
+
+ "github.com/apache/iceberg-go"
+)
+
+// CPU-heavy finalization needs enough work to amortize worker and merge costs.
+const scanTaskFinalizationMinTasksPerWorker = 256
Review Comment:
Nothing measures 256 yet. Both benches run at 20K to 100K tasks where it never binds, so the first parallel point at 512 tasks has nothing behind it. A quick sweep in the micro-bench (512, 1K, 2K, 4K) would show where break-even sits for `plain` vs `identity_residual`. Otherwise, call it a heuristic in the comment. Do we have a rough sense of where it crosses over?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] perf(table): parallelize scan task finalization [iceberg-go]
Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka commented on code in PR #2149:
URL: https://github.com/apache/iceberg-go/pull/2149#discussion_r4337002562
##########
table/scan_task_finalization_test.go:
##########
@@ -0,0 +1,645 @@
+// 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 (
+ "fmt"
+ "runtime"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/apache/iceberg-go"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func setFinalizationTestProcs(t *testing.T, count int) {
+ t.Helper()
+ previous := runtime.GOMAXPROCS(count)
+ t.Cleanup(func() { runtime.GOMAXPROCS(previous) })
+}
+
+func TestFinalizePlannedTasksParallelMatchesSerial(t *testing.T) {
+ // Exercise the concurrent worker path even on single-core CI runners.
+ setFinalizationTestProcs(t, 4)
+ schema := iceberg.NewSchema(1, iceberg.NestedField{
+ ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true,
+ })
+ metadata, err := NewMetadata(
+ schema,
+ iceberg.UnpartitionedSpec,
+ UnsortedSortOrder,
+ "mem://table",
+ iceberg.Properties{ReadSplitTargetSizeKey: "25"},
+ )
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 1024)
+ for i := range tasks {
+ file := finalizationTestDataFile(
+ t, *iceberg.UnpartitionedSpec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i), nil,
+ 100, []int64{8, 25, 50, 75})
+ tasks[i] = FileScanTask{File: file, Start: 0, Length: file.FileSizeBytes()}
+ if i%3 == 0 {
+ tasks[i].DeleteFiles = []iceberg.DataFile{file}
+ }
+ if i%5 == 0 {
+ tasks[i].EqualityDeleteFiles = []iceberg.DataFile{file}
+ }
+ }
+
+ scan := &Scan{
+ metadata: metadata, rowFilter: iceberg.AlwaysTrue{}, caseSensitive: true, concurrency: 8,
+ }
+ serial, serialMetrics, err := serialFinalizationReference(
+ scan, append([]FileScanTask(nil), tasks...), schema)
+ require.NoError(t, err)
+ var parallelMetrics scanMetricsAccumulator
+ parallel, err := scan.finalizePlannedTasks(
+ append([]FileScanTask(nil), tasks...), schema, ¶llelMetrics)
+ require.NoError(t, err)
+
+ assert.Equal(t, serial, parallel)
+ assert.Equal(t, serialMetrics, parallelMetrics)
+ require.Len(t, parallel, len(tasks)*4)
+ for i := range tasks {
+ for split, start := range []int64{0, 25, 50, 75} {
+ task := parallel[i*4+split]
+ assert.Equal(t, fmt.Sprintf("mem://table/data/file-%d.parquet", i), task.File.FilePath())
+ assert.Equal(t, start, task.Start)
+ assert.Equal(t, int64(25), task.Length)
+ }
+ }
+ assert.Equal(t, int64(len(tasks)), parallelMetrics.resultDataFiles)
+ assert.Equal(t, int64(len(tasks)*100), parallelMetrics.totalFileSize)
+ assert.Equal(t, int64(342), parallelMetrics.positionalDeleteFiles)
+ assert.Equal(t, int64(205), parallelMetrics.equalityDeleteFiles)
+ assert.Equal(t, int64(547), parallelMetrics.resultDeleteFiles)
+ assert.Equal(t, int64(54_700), parallelMetrics.totalDeleteFileSize)
+}
+
+func TestFinalizePlannedTasksParallelResidualsMatchSerial(t *testing.T) {
+ // Exercise the concurrent worker path even on single-core CI runners.
+ setFinalizationTestProcs(t, 4)
+ schema := simpleSchema()
+ spec := partitionedSpec()
+ unpartitioned := iceberg.NewPartitionSpecID(1)
+ metadata, err := NewMetadata(
+ schema,
+ &spec,
+ UnsortedSortOrder,
+ "mem://table",
+ nil,
+ )
+ require.NoError(t, err)
+ builder, err := MetadataBuilderFromBase(metadata, "")
+ require.NoError(t, err)
+ require.NoError(t, builder.AddPartitionSpec(&unpartitioned, false))
+ metadata, err = builder.Build()
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 1024)
+ for i := range tasks {
+ partitionValue := int32(7)
+ if i%2 != 0 {
+ partitionValue = 8
+ }
+ fileSpec := spec
+ if i%4 < 2 {
+ fileSpec = unpartitioned
+ }
+ file := finalizationTestDataFile(
+ t, fileSpec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i),
+ map[int]any{1000: partitionValue}, 100, nil)
+ tasks[i] = FileScanTask{File: file, Start: 0, Length: file.FileSizeBytes()}
+ }
+
+ filter := iceberg.EqualTo(iceberg.Reference("id"), int32(7))
+ scan := &Scan{metadata: metadata, rowFilter: filter, caseSensitive: true, concurrency: 8}
+ serial, serialMetrics, err := serialFinalizationReference(
+ scan, append([]FileScanTask(nil), tasks...), schema)
+ require.NoError(t, err)
+ var parallelMetrics scanMetricsAccumulator
+ parallel, err := scan.finalizePlannedTasks(
+ append([]FileScanTask(nil), tasks...), schema, ¶llelMetrics)
+ require.NoError(t, err)
+
+ assert.Equal(t, serial, parallel)
+ assert.Equal(t, serialMetrics, parallelMetrics)
+ for i, task := range parallel {
+ if i%4 < 2 {
+ assert.Nil(t, task.Residual, "task %d has no partition projection", i)
+ } else if i%2 == 0 {
+ _, ok := task.Residual.(iceberg.AlwaysTrue)
+ assert.True(t, ok, "task %d should simplify to always true", i)
+ } else {
+ _, ok := task.Residual.(iceberg.AlwaysFalse)
+ assert.True(t, ok, "task %d should simplify to always false", i)
+ }
+ }
+}
+
+func TestFinalizePlannedTasksReturnsFirstErrorInTaskOrder(t *testing.T) {
+ schema := simpleSchema()
+ spec := partitionedSpec()
+ metadata, err := NewMetadata(schema, &spec, UnsortedSortOrder, "mem://table", nil)
+ require.NoError(t, err)
+
+ tasks := make([]FileScanTask, 1024)
+ for i := range tasks {
+ var partitionValue any = int32(7)
+ if i == 255 || i == 256 {
+ // The earlier failing task is at the end of worker range 0;
+ // worker 1 can fail first at the start of its own range.
+ partitionValue = "invalid integer partition"
+ }
+ file := finalizationTestDataFile(t, spec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i),
+ map[int]any{1000: partitionValue}, 100, nil)
+ tasks[i] = FileScanTask{File: file, Length: file.FileSizeBytes()}
+ }
+
+ for _, concurrency := range []int{1, 8} {
+ t.Run(fmt.Sprintf("concurrency=%d", concurrency), func(t *testing.T) {
+ scan := &Scan{
+ metadata: metadata, concurrency: concurrency, caseSensitive: true,
+ rowFilter: iceberg.EqualTo(iceberg.Reference("id"), int32(7)),
+ }
+ input := append([]FileScanTask(nil), tasks...)
+ if concurrency > 1 {
+ // With four CPU workers and 1024 tasks, worker 0 owns
+ // [0:256] and worker 1 owns [256:512].
+ previous := runtime.GOMAXPROCS(4)
+ defer runtime.GOMAXPROCS(previous)
+
+ laterErrorReached := make(chan struct{})
+ input[255].File = finalizationOrderFile{
+ DataFile: input[255].File, wait: laterErrorReached,
+ }
+ input[256].File = finalizationOrderFile{
+ DataFile: input[256].File, signal: laterErrorReached, signalOnce: new(sync.Once),
+ }
+ }
+ result, planErr := scan.finalizePlannedTasks(input, schema, &scanMetricsAccumulator{})
+ require.ErrorContains(t, planErr, "evaluate partition residual for mem://table/data/file-255.parquet")
+ assert.Nil(t, result)
+ })
+ }
+}
+
+// Controls which worker reaches its partition error first, without relying on
+// scheduler timing. The wrapper intentionally does not forward the built-in
+// borrowed-partition interface, so residual evaluation calls Partition.
+type finalizationOrderFile struct {
+ iceberg.DataFile
+ wait <-chan struct{}
+ signal chan struct{}
+ signalOnce *sync.Once
+}
+
+func (f finalizationOrderFile) Partition() map[int]any {
+ if f.signal != nil {
+ f.signalOnce.Do(func() { close(f.signal) })
+ }
+ if f.wait != nil {
+ select {
+ case <-f.wait:
+ case <-time.After(5 * time.Second):
+ panic("timed out waiting for later worker to reach its error")
+ }
+ }
+
+ return f.DataFile.Partition()
+}
+
+func TestFinalizePlannedTasksUnsplitReusesInput(t *testing.T) {
+ // Exercise the concurrent worker path even on single-core CI runners.
+ setFinalizationTestProcs(t, 4)
+ schema := simpleSchema()
+ metadata, err := NewMetadata(
+ schema,
+ iceberg.UnpartitionedSpec,
+ UnsortedSortOrder,
+ "mem://table",
+ nil,
+ )
+ require.NoError(t, err)
+ file := finalizationTestDataFile(
+ t, *iceberg.UnpartitionedSpec, "mem://table/data/file.parquet", nil, 100, nil)
+ tasks := make([]FileScanTask, 512)
+ for i := range tasks {
+ tasks[i] = FileScanTask{File: file, Start: 0, Length: file.FileSizeBytes()}
+ }
+ scan := &Scan{metadata: metadata, rowFilter: iceberg.AlwaysTrue{}, caseSensitive: true, concurrency: 8}
+
+ got, err := scan.finalizePlannedTasks(tasks, schema, &scanMetricsAccumulator{})
+ require.NoError(t, err)
+ require.Len(t, got, len(tasks))
+ assert.Same(t, &tasks[0], &got[0])
+ assert.Same(t, &tasks[len(tasks)-1], &got[len(got)-1])
+ assert.Nil(t, got[0].Residual)
+}
+
+func TestFinalizePlannedTasksManyWorkersCoverEveryTask(t *testing.T) {
+ // A rounded-up chunk size can put the last worker past the input when
+ // there are more workers than tasks per worker and a short remainder.
+ const workers = 300
+ previous := runtime.GOMAXPROCS(workers)
+ defer runtime.GOMAXPROCS(previous)
+
+ schema := simpleSchema()
+ metadata, err := NewMetadata(schema, iceberg.UnpartitionedSpec, UnsortedSortOrder,
+ "mem://table", iceberg.Properties{ReadSplitTargetSizeKey: "25"})
+ require.NoError(t, err)
+ file := finalizationTestDataFile(t, *iceberg.UnpartitionedSpec,
+ "mem://table/data/unsplit.parquet", nil, 100, nil)
+ splitFile := finalizationTestDataFile(t, *iceberg.UnpartitionedSpec,
+ "mem://table/data/split.parquet", nil, 100, []int64{8, 25, 50, 75})
+ lastFile := finalizationTestDataFile(t, *iceberg.UnpartitionedSpec,
+ "mem://table/data/last.parquet", nil, 100, nil)
+ tasks := make([]FileScanTask, workers*scanTaskFinalizationMinTasksPerWorker+1)
+ firstRowIDs := make([]int64, len(tasks))
+ for i := range tasks {
+ firstRowIDs[i] = int64(i * 100)
+ tasks[i] = FileScanTask{File: file, Length: 100, FirstRowID: &firstRowIDs[i]}
+ }
+ tasks[0].File = splitFile
+ tasks[len(tasks)-1].File = lastFile
+ scan := &Scan{metadata: metadata, rowFilter: iceberg.AlwaysTrue{}, concurrency: workers}
+
+ var acc scanMetricsAccumulator
+ got, err := scan.finalizePlannedTasks(tasks, schema, &acc)
+ require.NoError(t, err)
+ require.Len(t, got, len(tasks)+3)
+ for i := range 4 {
+ assert.Equal(t, splitFile.FilePath(), got[i].File.FilePath())
+ assert.Equal(t, int64(i*25), got[i].Start)
+ assert.Equal(t, int64(25), got[i].Length)
+ assert.Same(t, tasks[0].FirstRowID, got[i].FirstRowID)
+ }
+ for i, task := range got[4 : len(got)-1] {
+ if task.File != file || task.Start != 0 || task.Length != 100 || task.FirstRowID != tasks[i+1].FirstRowID {
+ t.Fatalf("unsplit task %d changed or moved: %+v", i+1, task)
+ }
+ }
+ assert.Equal(t, lastFile.FilePath(), got[len(got)-1].File.FilePath())
+ assert.Same(t, tasks[len(tasks)-1].FirstRowID, got[len(got)-1].FirstRowID)
+ assert.Equal(t, int64(len(tasks)), acc.resultDataFiles)
+ assert.Equal(t, int64(len(tasks)*100), acc.totalFileSize)
+}
+
+// serialFinalizationReference reproduces the pre-parallelization loop. It is
+// deliberately independent of finalizeTaskRange and the worker merge logic.
+func serialFinalizationReference(
+ scan *Scan,
+ tasks []FileScanTask,
+ schema *iceberg.Schema,
+) ([]FileScanTask, scanMetricsAccumulator, error) {
+ var acc scanMetricsAccumulator
+ var filter iceberg.BooleanExpression
+ if scan.rowFilter != nil && !scan.rowFilter.Equals(iceberg.AlwaysTrue{}) {
+ var err error
+ filter, err = iceberg.BindExpr(schema, scan.rowFilter, scan.caseSensitive)
+ if err != nil {
+ return nil, acc, err
+ }
+ }
+ evaluators := make(map[int]*partitionResidualEvaluator)
+ acc.resultDataFiles = int64(len(tasks))
+ result := make([]FileScanTask, 0, len(tasks))
+ target := scan.metadata.Properties().GetInt64(ReadSplitTargetSizeKey, ReadSplitTargetSizeDefault)
+ for _, task := range tasks {
+ if filter != nil {
+ specID := int(task.File.SpecID())
+ evaluator, ok := evaluators[specID]
+ if !ok {
+ var err error
+ evaluator, err = newPartitionResidualEvaluator(
+ schema, scan.metadata.PartitionSpecByID(specID), filter, scan.caseSensitive)
+ if err != nil {
+ return nil, acc, fmt.Errorf("build partition residual evaluator for spec %d: %w", specID, err)
+ }
+ evaluators[specID] = evaluator
+ }
+ if evaluator != nil {
+ var err error
+ var simplified bool
+ task.Residual, simplified, err = evaluator.residual(dataFilePartition(task.File))
+ if err != nil {
+ return nil, acc, fmt.Errorf(
+ "evaluate partition residual for %s: %w", task.File.FilePath(), err)
+ }
+ if !simplified {
+ task.Residual = nil
+ }
+ }
+ }
+ acc.addResultDeleteMetrics(task)
+ acc.totalFileSize += task.File.FileSizeBytes()
+ if splits, ok := splitParquetScanTask(task, target); ok {
+ result = append(result, splits...)
+ } else {
+ result = append(result, task)
+ }
+ }
+
+ return result, acc, nil
+}
+
+func TestFinalizePlannedTasksMixedSplitsAgainstIndependentReference(t *testing.T) {
+ // Exercise the concurrent worker path even on single-core CI runners.
+ setFinalizationTestProcs(t, 4)
+ schema := iceberg.NewSchema(1, iceberg.NestedField{
+ ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true,
+ })
+ metadata, err := NewMetadata(schema, iceberg.UnpartitionedSpec, UnsortedSortOrder,
+ "mem://table", iceberg.Properties{ReadSplitTargetSizeKey: "25"})
+ require.NoError(t, err)
+
+ dvBuilder, err := iceberg.NewDataFileBuilder(
+ *iceberg.UnpartitionedSpec, iceberg.EntryContentPosDeletes,
+ "mem://table/deletes.dv.puffin", iceberg.PuffinFile, nil, nil, nil, 1, 2048)
+ require.NoError(t, err)
+ dv := dvBuilder.ContentSizeInBytes(17).ContentOffset(100).Build()
+
+ for _, count := range []int{0, 1, 255, 256, 257, 512, 1024} {
+ t.Run(fmt.Sprintf("files=%d", count), func(t *testing.T) {
+ tasks := make([]FileScanTask, count)
+ splits := 0
+ for i := range tasks {
+ offsets := []int64(nil)
+ if i%7 < 2 || i == count-1 || i == 255 || i == 256 {
+ offsets = []int64{8, 25, 50, 75}
+ splits++
+ }
+ file := finalizationTestDataFile(t, *iceberg.UnpartitionedSpec,
+ fmt.Sprintf("mem://table/data/file-%d.parquet", i), nil, 100, offsets)
+ tasks[i] = FileScanTask{File: file, Length: 100}
+ if i%9 == 0 {
+ tasks[i].DeleteFiles = []iceberg.DataFile{file}
+ }
+ if i%11 == 0 {
+ tasks[i].EqualityDeleteFiles = []iceberg.DataFile{file}
+ }
+ if i%13 == 0 {
+ tasks[i].DeletionVectorFiles = []iceberg.DataFile{dv}
+ }
+ }
+ scan := &Scan{
+ metadata: metadata, rowFilter: iceberg.AlwaysTrue{},
Review Comment:
Could one case here use a real row filter? Every split test runs with `AlwaysTrue`, and the residual test passes `nil` offsets ([L131](https://github.com/apache/iceberg-go/blob/59ccb1e2718a8721186384457f210fdefd2190cd/table/scan_task_finalization_test.go#L131)), so nothing checks that split tasks keep the `Residual` written at [L172](https://github.com/apache/iceberg-go/blob/59ccb1e2718a8721186384457f210fdefd2190cd/table/scan_task_finalization.go#L172). As I read it, a refactor that sets residuals after splitting would still pass. A partitioned spec with `EqualTo(id, 7)` checked against `serialFinalizationReference` would pin it.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] perf(table): parallelize scan task finalization [iceberg-go]
Posted by "laskoviymishka (via GitHub)" <gi...@apache.org>.
laskoviymishka merged PR #2149:
URL: https://github.com/apache/iceberg-go/pull/2149
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org