zeroshade commented on code in PR #2660: URL: https://github.com/apache/iceberg-go/pull/2660#discussion_r4722021314
########## table/sort_append_bench_test.go: ########## @@ -0,0 +1,154 @@ +// 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_test + +import ( + "context" + "fmt" + "math/rand/v2" + "path/filepath" + "strings" + "testing" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/memory" + "github.com/apache/iceberg-go" + iceio "github.com/apache/iceberg-go/io" + "github.com/apache/iceberg-go/table" +) + +// BenchmarkAppendSorted appends 1M rows in 64K-row batches to an +// unpartitioned table and commits, for several default sort orders. The +// unsorted case is the control: the difference to it is the cost of +// sorting on write. It uses only the public API so the same benchmark +// can run on a base revision for comparison. +func BenchmarkAppendSorted(b *testing.B) { + const ( + batches = 16 + batchRows = 1 << 16 + ) + schema := iceberg.NewSchema(0, + iceberg.NestedField{ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true}, + iceberg.NestedField{ID: 2, Name: "id_nulls", Type: iceberg.PrimitiveTypes.Int64}, + iceberg.NestedField{ID: 3, Name: "name", Type: iceberg.PrimitiveTypes.String}, + iceberg.NestedField{ID: 4, Name: "loc", Type: iceberg.NewStructType( + iceberg.NestedField{ID: 5, Name: "lat", Type: iceberg.PrimitiveTypes.Float64}, + )}, + iceberg.NestedField{ID: 6, Name: "value", Type: iceberg.PrimitiveTypes.Float64}, + iceberg.NestedField{ID: 7, Name: "payload", Type: iceberg.PrimitiveTypes.String}, + ) + sc, err := table.SchemaToArrowSchema(schema, nil, false, false) + if err != nil { + b.Fatal(err) + } + + mem := memory.NewGoAllocator() + rng := rand.New(rand.NewPCG(1, 2)) + recs := make([]arrow.RecordBatch, batches) + for n := range recs { + bldr := array.NewRecordBuilder(mem, sc) + loc := bldr.Field(3).(*array.StructBuilder) + for range batchRows { + bldr.Field(0).(*array.Int64Builder).Append(rng.Int64N(1 << 40)) + if rng.IntN(10) == 0 { + bldr.Field(1).AppendNull() + } else { + bldr.Field(1).(*array.Int64Builder).Append(rng.Int64N(1 << 40)) + } + bldr.Field(2).(*array.StringBuilder).Append(fmt.Sprintf("name-%012d", rng.Int64N(1<<40))) + loc.Append(true) + loc.FieldBuilder(0).(*array.Float64Builder).Append(rng.Float64()*180 - 90) + bldr.Field(4).(*array.Float64Builder).Append(rng.Float64()) + bldr.Field(5).(*array.StringBuilder).Append(fmt.Sprintf("%064x", rng.Uint64())) + } + recs[n] = bldr.NewRecordBatch() + bldr.Release() + } + defer func() { + for _, r := range recs { + r.Release() + } + }() + + for _, tc := range []struct { + name string + sourceID int + }{ + {"none", 0}, + {"int64", 1}, + {"int64-nulls", 2}, + {"string", 3}, + {"nested-float64", 5}, + } { + order := table.UnsortedSortOrder + if tc.sourceID != 0 { + order, err = table.NewSortOrder(1, []table.SortField{{ + SourceIDs: []int{tc.sourceID}, Transform: iceberg.IdentityTransform{}, + Direction: table.SortASC, NullOrder: table.NullsFirst, + }}) + if err != nil { + b.Fatal(err) + } + } + + b.Run("order="+tc.name, func(b *testing.B) { + dir := filepath.ToSlash(b.TempDir()) + appendOnce := func(i int) error { + location := fmt.Sprintf("%s/t%d", dir, i) + meta, err := table.NewMetadata(schema, iceberg.UnpartitionedSpec, order, location, + iceberg.Properties{table.PropertyFormatVersion: "2"}) + if err != nil { + return err + } + tbl := table.New(table.Identifier{"db", "append_bench"}, meta, location+"/metadata/v1.metadata.json", + func(context.Context) (iceio.IO, error) { return iceio.LocalFS{}, nil }, + &rowDeltaCatalog{metadata: meta}) + rdr, err := array.NewRecordReader(sc, recs) + if err != nil { + return err + } + defer rdr.Release() + + tx := tbl.NewTransaction() + if err := tx.Append(b.Context(), rdr, nil); err != nil { + return err + } + _, err = tx.Commit(b.Context()) + + return err + } + + // A revision whose writer rejects nested sort keys skips that case. + if err := appendOnce(-1); err != nil { + if strings.Contains(err.Error(), "not a top-level column") { Review Comment: The `"not a top-level column"` skip only helps when benchmarking against the pre-PR revision. After merge, that message only comes from `resolveSortKeys`, which runs only when `allTopLevelSortSources` is true, so if the two ever disagree this benchmark would skip silently instead of failing. Could we drop the probe-and-skip, or `b.Fatal` on any error? ########## table/sort_compaction.go: ########## @@ -85,43 +86,80 @@ func (s sortStrategy) writeOptions() []WriteRecordOption { // sortKeyColumn is one field of a rowComparator. type sortKeyColumn struct { - col int + // path is the struct-child index path from a top-level column down to + // the sort source; a path of length 1 is a top-level column. + path []int desc bool nullsFirst bool values valueComparator } +// chain returns the arrays along k's path in rec, top-level column first +// and sort source last. +func (k sortKeyColumn) chain(rec arrow.RecordBatch) []arrow.Array { + chain := make([]arrow.Array, len(k.path)) + col := rec.Column(k.path[0]) + chain[0] = col + for d, idx := range k.path[1:] { + col = col.(*array.Struct).Field(idx) + chain[d+1] = col + } + + return chain +} + +// leaf returns the sort source of k in rec, and reports whether its value +// at row is null. A null enclosing struct makes the value null, whatever +// the child array holds at that row, and returns a nil array. +func (k sortKeyColumn) leaf(rec arrow.RecordBatch, row int) (arrow.Array, bool) { + col := rec.Column(k.path[0]) + for _, idx := range k.path[1:] { + if col.IsNull(row) { + return nil, true + } + col = col.(*array.Struct).Field(idx) + } + + return col, col.IsNull(row) +} + // rowComparator orders the rows of record batches that share one schema // by the source columns of a sort order, following the Iceberg spec: each // field's null order places nulls whatever its direction, floating-point // values order as -NaN < -Inf < -x < -0 < 0 < x < Inf < NaN, and strings // and binary compare as unsigned bytes. A descending field reverses the -// order of its non-null values. +// order of its non-null values. A source nested in structs is null where +// any enclosing struct is null. +// +// Each field is ordered by its first source column, so order-preserving +// transforms (identity, truncate, year/month/day/hour) order as their +// source does and bucket orders by the unbucketed source. +// +// The write path orders batches with Arrow's sort kernel instead (see +// resolveSortKeys and sortRecordBatch), with the same order. type rowComparator []sortKeyColumn -// newRowComparator resolves order against the scan output schema sc. -// Sort fields are matched by name through schema because the scan emits -// the table schema's top-level columns by name. +// newRowComparator resolves order against the record schema sc. Sort +// sources are found by id in schema and then matched by name in sc, level +// by level. func newRowComparator(order SortOrder, schema *iceberg.Schema, sc *arrow.Schema) (rowComparator, error) { - fields := schema.Fields() + fields := schema.FieldsRef(iceberginternal.SchemaRef{}) keys := make(rowComparator, 0, order.Len()) for _, field := range order.fields { - idx, ok := topLevelFieldIndex(fields, field.FirstSourceID()) - if !ok { - return nil, fmt.Errorf("sort order %d: source id %d is not a top-level column in schema", - order.OrderID(), field.FirstSourceID()) + schemaPath, err := sortFieldPath(schema, fields, field.FirstSourceID(), order.OrderID()) + if err != nil { + return nil, err } - colIdx := sc.FieldIndices(fields[idx].Name) - if len(colIdx) != 1 { - return nil, fmt.Errorf("sort order %d: column %q not found in scan output", - order.OrderID(), fields[idx].Name) + path, leaf, err := arrowColumnPath(fields, schemaPath, sc) + if err != nil { + return nil, fmt.Errorf("sort order %d: %w", order.OrderID(), err) } - values, err := newValueComparator(sc.Field(colIdx[0]).Type) + values, err := newValueComparator(leaf.Type) if err != nil { - return nil, fmt.Errorf("sort order %d: column %q: %w", order.OrderID(), fields[idx].Name, err) + return nil, fmt.Errorf("sort order %d: column %q: %w", order.OrderID(), leaf.Name, err) Review Comment: Nit: for a nested source `leaf.Name` is just the last segment (`"lat"`). `arrowColumnPath` already builds the dotted path (`loc.lat`); returning it from there would make this error clearer. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
