You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iceberg.apache.org by ze...@apache.org on 2026/08/17 19:20:26 UTC

(iceberg-go) branch main updated: perf(manifest): update partition summaries incrementally (#1770)

This is an automated email from the ASF dual-hosted git repository.

zeroshade pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg-go.git


The following commit(s) were added to refs/heads/main by this push:
     new f6622e697 perf(manifest): update partition summaries incrementally (#1770)
f6622e697 is described below

commit f6622e697c8814851df3939bbbe80e0f08076125
Author: Minh Vu <vu...@gmail.com>
AuthorDate: Mon Aug 17 21:20:20 2026 +0200

    perf(manifest): update partition summaries incrementally (#1770)
    
    * perf(manifest): update partition summaries incrementally
    
    * fix(manifest): copy binary partition bounds
    
    * fix(manifest): simplify partition bound copying
---
 manifest.go                   |  80 +++++++++++-------
 manifest_test.go              | 183 +++++++++++++++++++++++++++++++++++++++++-
 manifest_writer_bench_test.go | 127 +++++++++++++++++++++++++++++
 3 files changed, 356 insertions(+), 34 deletions(-)

diff --git a/manifest.go b/manifest.go
index 0f978007c..4bee8331e 100644
--- a/manifest.go
+++ b/manifest.go
@@ -1266,6 +1266,9 @@ func (p *partitionFieldStats[T]) update(value any) (err error) {
 	}
 
 	actualVal = v.Convert(reflect.TypeOf(actualVal)).Interface().(T)
+	if data, ok := any(actualVal).([]byte); ok {
+		actualVal = any(slices.Clone(data)).(T)
+	}
 
 	switch f := any(actualVal).(type) {
 	case float32:
@@ -1298,36 +1301,47 @@ func (p *partitionFieldStats[T]) update(value any) (err error) {
 	return nil
 }
 
-func constructPartitionSummaries(spec PartitionSpec, schema *Schema, partitions []map[int]any) ([]FieldSummary, error) {
-	partType := spec.PartitionType(schema)
-	fieldStats := make([]fieldStats, len(partType.FieldList))
+type partitionSummaryStats struct {
+	fields []NestedField
+	stats  []fieldStats
+}
+
+func newPartitionSummaryStats(spec PartitionSpec, schema *Schema) (*partitionSummaryStats, error) {
+	fields := spec.PartitionType(schema).FieldList
+	stats := make([]fieldStats, len(fields))
 	var err error
-	for i, field := range partType.FieldList {
+	for i, field := range fields {
 		pt, ok := field.Type.(PrimitiveType)
 		if !ok {
 			return nil, fmt.Errorf("expected primitive type for partition field, got %s", field.Type)
 		}
 
-		fieldStats[i], err = newPartitionFieldStat(pt)
+		stats[i], err = newPartitionFieldStat(pt)
 		if err != nil {
 			return nil, fmt.Errorf("error constructing field stats for partition %d: %s: %s", i, field.Name, err)
 		}
 	}
 
-	for _, part := range partitions {
-		for i, field := range partType.FieldList {
-			if err := fieldStats[i].update(part[field.ID]); err != nil {
-				return nil, fmt.Errorf("error updating field stats for partition %d: %s: %s", i, field.Name, err)
-			}
+	return &partitionSummaryStats{fields: fields, stats: stats}, nil
+}
+
+func (p *partitionSummaryStats) update(partition map[int]any) error {
+	for i, field := range p.fields {
+		if err := p.stats[i].update(partition[field.ID]); err != nil {
+			return fmt.Errorf("error updating field stats for partition %d: %s: %s", i, field.Name, err)
 		}
 	}
 
-	summaries := make([]FieldSummary, len(fieldStats))
-	for i, stat := range fieldStats {
+	return nil
+}
+
+func (p *partitionSummaryStats) summaries() []FieldSummary {
+	summaries := make([]FieldSummary, len(p.stats))
+	for i, stat := range p.stats {
 		summaries[i] = stat.toSummary()
 	}
 
-	return summaries, nil
+	return summaries
 }
 
 type ManifestWriter struct {
@@ -1353,9 +1367,10 @@ type ManifestWriter struct {
 	deletedFiles  int32
 	deletedRows   int64
 
-	partitions  []map[int]any
-	minSeqNum   int64
-	reusedEntry manifestEntry
+	partitionStats    *partitionSummaryStats
+	partitionStatsErr error
+	minSeqNum         int64
+	reusedEntry       manifestEntry
 }
 
 type ManifestWriterOption func(w *ManifestWriter)
@@ -1391,18 +1406,20 @@ func NewManifestWriter(version int, out io.Writer, spec PartitionSpec, schema *S
 	}
 
 	fieldMaps := getFieldIDMap(fileSchema)
+	partitionStats, partitionStatsErr := newPartitionSummaryStats(spec, schema)
 
 	w := &ManifestWriter{
-		impl:          impl,
-		version:       version,
-		output:        out,
-		spec:          spec,
-		content:       ManifestContentData,
-		schema:        schema,
-		partFieldMaps: fieldMaps,
-		snapshotID:    snapshotID,
-		minSeqNum:     -1,
-		partitions:    make([]map[int]any, 0),
+		impl:              impl,
+		version:           version,
+		output:            out,
+		spec:              spec,
+		content:           ManifestContentData,
+		schema:            schema,
+		partFieldMaps:     fieldMaps,
+		snapshotID:        snapshotID,
+		partitionStats:    partitionStats,
+		partitionStatsErr: partitionStatsErr,
+		minSeqNum:         -1,
 	}
 
 	for _, apply := range opts {
@@ -1470,10 +1487,10 @@ func (w *ManifestWriter) ToManifestFile(location string, length int64, opts ...M
 		return nil, err
 	}
 
-	partitions, err := constructPartitionSummaries(w.spec, w.schema, w.partitions)
-	if err != nil {
-		return nil, err
+	if w.partitionStatsErr != nil {
+		return nil, w.partitionStatsErr
 	}
+	partitions := w.partitionStats.summaries()
 
 	mf := manifestFile{
 		version:            w.version,
@@ -1568,7 +1585,6 @@ func (w *ManifestWriter) addEntry(entry *manifestEntry) error {
 	if err := w.writer.Encode(toEncode); err != nil {
 		return err
 	}
-	w.partitions = append(w.partitions, clonePartitionMap(partition))
 
 	switch status {
 	case EntryStatusADDED:
@@ -1582,6 +1598,10 @@ func (w *ManifestWriter) addEntry(entry *manifestEntry) error {
 		w.deletedRows += count
 	}
 
+	if w.partitionStatsErr == nil {
+		w.partitionStatsErr = w.partitionStats.update(partition)
+	}
+
 	if status == EntryStatusADDED || status == EntryStatusEXISTING {
 		if seq := entry.SequenceNum(); seq >= 0 && (w.minSeqNum < 0 || seq < w.minSeqNum) {
 			w.minSeqNum = seq
diff --git a/manifest_test.go b/manifest_test.go
index 6893b5e4a..17a3721eb 100644
--- a/manifest_test.go
+++ b/manifest_test.go
@@ -486,10 +486,14 @@ func TestConstructPartitionSummariesWithDroppedSource(t *testing.T) {
 	})
 	schema := NewSchema(0)
 
-	summaries, err := constructPartitionSummaries(spec, schema, []map[int]any{{1000: "historical-value"}})
+	stats, err := newPartitionSummaryStats(spec, schema)
 	if err != nil {
 		t.Fatal(err)
 	}
+	if err := stats.update(map[int]any{1000: "historical-value"}); err != nil {
+		t.Fatal(err)
+	}
+	summaries := stats.summaries()
 	if len(summaries) != 1 {
 		t.Fatalf("expected one partition summary, got %d", len(summaries))
 	}
@@ -501,6 +505,169 @@ func TestConstructPartitionSummariesWithDroppedSource(t *testing.T) {
 	}
 }
 
+func TestManifestWriterUpdatesPartitionSummariesIncrementally(t *testing.T) {
+	schema := NewSchema(0,
+		NestedField{ID: 1, Name: "region", Type: PrimitiveTypes.String},
+		NestedField{ID: 2, Name: "temperature", Type: PrimitiveTypes.Float64},
+		NestedField{ID: 3, Name: "shard", Type: PrimitiveTypes.Binary},
+	)
+	spec := NewPartitionSpec(
+		PartitionField{SourceIDs: []int{1}, FieldID: 1000, Name: "region", Transform: IdentityTransform{}},
+		PartitionField{SourceIDs: []int{2}, FieldID: 1001, Name: "temperature", Transform: IdentityTransform{}},
+		PartitionField{SourceIDs: []int{3}, FieldID: 1002, Name: "shard", Transform: IdentityTransform{}},
+	)
+	snapshotID := int64(1234)
+	sequenceNumber := int64(1)
+
+	newEntry := func(path string, partition map[int]any) ManifestEntry {
+		builder, err := NewDataFileBuilder(
+			spec,
+			EntryContentData,
+			path,
+			ParquetFile,
+			partition,
+			nil,
+			nil,
+			1,
+			1,
+		)
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		return NewManifestEntry(
+			EntryStatusADDED,
+			&snapshotID,
+			&sequenceNumber,
+			&sequenceNumber,
+			builder.Build(),
+		)
+	}
+
+	writer, err := NewManifestWriter(2, io.Discard, spec, schema, snapshotID)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	entries := []ManifestEntry{
+		newEntry("east.parquet", map[int]any{1000: "east", 1001: 1.0, 1002: []byte{2}}),
+		newEntry("null.parquet", map[int]any{1000: nil, 1001: math.NaN(), 1002: []byte{1}}),
+		newEntry("west.parquet", map[int]any{1000: "west", 1001: 3.0, 1002: []byte{3}}),
+	}
+	if err := writer.Add(entries[0]); err != nil {
+		t.Fatal(err)
+	}
+	if err := writer.Existing(entries[1]); err != nil {
+		t.Fatal(err)
+	}
+	if err := writer.Delete(entries[2]); err != nil {
+		t.Fatal(err)
+	}
+
+	manifest, err := writer.ToManifestFile("manifest.avro", 0)
+	if err != nil {
+		t.Fatal(err)
+	}
+	summaries := manifest.Partitions()
+	if len(summaries) != 3 {
+		t.Fatalf("expected three partition summaries, got %d", len(summaries))
+	}
+
+	assertSummary := func(index int, containsNull, containsNaN bool, lower, upper Literal) {
+		t.Helper()
+		lowerBytes, err := lower.MarshalBinary()
+		if err != nil {
+			t.Fatal(err)
+		}
+		upperBytes, err := upper.MarshalBinary()
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		summary := summaries[index]
+		if summary.ContainsNull != containsNull || summary.ContainsNaN == nil || *summary.ContainsNaN != containsNaN {
+			t.Fatalf("summary %d flags = (%v, %v), want (%v, %v)", index, summary.ContainsNull, summary.ContainsNaN, containsNull, containsNaN)
+		}
+		if summary.LowerBound == nil || !bytes.Equal(*summary.LowerBound, lowerBytes) {
+			t.Fatalf("summary %d lower bound = %v, want %v", index, summary.LowerBound, lowerBytes)
+		}
+		if summary.UpperBound == nil || !bytes.Equal(*summary.UpperBound, upperBytes) {
+			t.Fatalf("summary %d upper bound = %v, want %v", index, summary.UpperBound, upperBytes)
+		}
+	}
+
+	assertSummary(0, true, false, NewLiteral("east"), NewLiteral("west"))
+	assertSummary(1, false, true, NewLiteral(1.0), NewLiteral(3.0))
+	assertSummary(2, false, false, NewLiteral([]byte{1}), NewLiteral([]byte{3}))
+}
+
+func TestManifestWriterCopiesBinaryPartitionSummaryBounds(t *testing.T) {
+	schema := NewSchema(0,
+		NestedField{ID: 1, Name: "shard", Type: PrimitiveTypes.Binary},
+	)
+	spec := NewPartitionSpec(
+		PartitionField{SourceIDs: []int{1}, FieldID: 1000, Name: "shard", Transform: IdentityTransform{}},
+	)
+	snapshotID := int64(1234)
+	sequenceNumber := int64(1)
+	low := []byte{1}
+	high := []byte{2}
+
+	newEntry := func(path string, partition []byte) ManifestEntry {
+		builder, err := NewDataFileBuilder(
+			spec,
+			EntryContentData,
+			path,
+			ParquetFile,
+			map[int]any{1000: partition},
+			nil,
+			nil,
+			1,
+			1,
+		)
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		return NewManifestEntry(
+			EntryStatusADDED,
+			&snapshotID,
+			&sequenceNumber,
+			&sequenceNumber,
+			builder.Build(),
+		)
+	}
+
+	writer, err := NewManifestWriter(2, io.Discard, spec, schema, snapshotID)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if err := writer.Add(newEntry("low.parquet", low)); err != nil {
+		t.Fatal(err)
+	}
+	if err := writer.Add(newEntry("high.parquet", high)); err != nil {
+		t.Fatal(err)
+	}
+
+	low[0] = 3
+
+	manifest, err := writer.ToManifestFile("manifest.avro", 0)
+	if err != nil {
+		t.Fatal(err)
+	}
+	summaries := manifest.Partitions()
+	if len(summaries) != 1 {
+		t.Fatalf("expected one partition summary, got %d", len(summaries))
+	}
+	summary := summaries[0]
+	if summary.LowerBound == nil || !bytes.Equal(*summary.LowerBound, []byte{1}) {
+		t.Fatalf("lower bound = %v, want [1]", summary.LowerBound)
+	}
+	if summary.UpperBound == nil || !bytes.Equal(*summary.UpperBound, []byte{2}) {
+		t.Fatalf("upper bound = %v, want [2]", summary.UpperBound)
+	}
+}
+
 type ManifestTestSuite struct {
 	suite.Suite
 
@@ -3015,12 +3182,13 @@ func (m *ManifestTestSuite) TestManifestWriterDoesNotCommitStateOnEncodeError()
 	m.Zero(writer.existingRows)
 	m.Zero(writer.deletedFiles)
 	m.Zero(writer.deletedRows)
-	m.Empty(writer.partitions)
+	m.NoError(writer.partitionStatsErr)
+	m.Equal([]FieldSummary{{ContainsNaN: &falseBool}}, writer.partitionStats.summaries())
 	m.Equal(int64(-1), writer.minSeqNum)
 	m.Equal(originalPartitionData, dataFile.PartitionData)
 }
 
-func (m *ManifestTestSuite) TestManifestWriterCopiesBorrowedPartitionBeforeRetaining() {
+func (m *ManifestTestSuite) TestManifestWriterCopiesBorrowedPartitionSummaryBounds() {
 	schema := NewSchema(1, NestedField{ID: 1, Name: "part", Type: PrimitiveTypes.Binary})
 	partitionSpec := NewPartitionSpecID(
 		1,
@@ -3050,7 +3218,14 @@ func (m *ManifestTestSuite) TestManifestWriterCopiesBorrowedPartitionBeforeRetai
 	borrowed[1000].([]byte)[0] = 0xff
 	borrowed[1000] = []byte{0xff, 0xff}
 
-	m.Equal([]byte{0x01, 0x02}, writer.partitions[0][1000])
+	manifest, err := writer.ToManifestFile("manifest.avro", 0)
+	m.Require().NoError(err)
+	summaries := manifest.Partitions()
+	m.Require().Len(summaries, 1)
+	m.Require().NotNil(summaries[0].LowerBound)
+	m.Require().NotNil(summaries[0].UpperBound)
+	m.Equal([]byte{0x01, 0x02}, *summaries[0].LowerBound)
+	m.Equal([]byte{0x01, 0x02}, *summaries[0].UpperBound)
 }
 
 func newDatePartitionManifestEntry(t *testing.T, partitionSpec PartitionSpec, snapshotID int64, partitionValue any) ManifestEntry {
diff --git a/manifest_writer_bench_test.go b/manifest_writer_bench_test.go
new file mode 100644
index 000000000..555d7d845
--- /dev/null
+++ b/manifest_writer_bench_test.go
@@ -0,0 +1,127 @@
+// 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 iceberg
+
+import (
+	"fmt"
+	"io"
+	"testing"
+)
+
+func BenchmarkManifestWriterPartitionSummaries(b *testing.B) {
+	for _, entryCount := range []int{100, 1_000, 10_000} {
+		schema, spec, snapshotID, entries := manifestWriterBenchmarkData(b, entryCount)
+
+		b.Run(fmt.Sprintf("entries_%d", entryCount), func(b *testing.B) {
+			b.ReportAllocs()
+			for b.Loop() {
+				writer, err := NewManifestWriter(2, io.Discard, spec, schema, snapshotID)
+				if err != nil {
+					b.Fatal(err)
+				}
+				for _, entry := range entries {
+					if err := writer.Add(entry); err != nil {
+						b.Fatal(err)
+					}
+				}
+				if _, err := writer.ToManifestFile("manifest.avro", 0); err != nil {
+					b.Fatal(err)
+				}
+			}
+		})
+	}
+}
+
+func BenchmarkManifestWriterPartitionSummaryFinalization(b *testing.B) {
+	for _, entryCount := range []int{100, 1_000, 10_000} {
+		schema, spec, snapshotID, entries := manifestWriterBenchmarkData(b, entryCount)
+
+		b.Run(fmt.Sprintf("entries_%d", entryCount), func(b *testing.B) {
+			writer, err := NewManifestWriter(2, io.Discard, spec, schema, snapshotID)
+			if err != nil {
+				b.Fatal(err)
+			}
+			for _, entry := range entries {
+				if err := writer.Add(entry); err != nil {
+					b.Fatal(err)
+				}
+			}
+			if err := writer.Close(); err != nil {
+				b.Fatal(err)
+			}
+
+			b.ReportAllocs()
+			b.ResetTimer()
+			for b.Loop() {
+				if _, err := writer.ToManifestFile("manifest.avro", 0); err != nil {
+					b.Fatal(err)
+				}
+			}
+		})
+	}
+}
+
+func manifestWriterBenchmarkData(b *testing.B, entryCount int) (*Schema, PartitionSpec, int64, []ManifestEntry) {
+	b.Helper()
+
+	schema := NewSchema(0,
+		NestedField{ID: 1, Name: "region", Type: PrimitiveTypes.String},
+		NestedField{ID: 2, Name: "day", Type: PrimitiveTypes.Date},
+		NestedField{ID: 3, Name: "bucket", Type: PrimitiveTypes.Int32},
+		NestedField{ID: 4, Name: "shard", Type: PrimitiveTypes.Binary},
+	)
+	spec := NewPartitionSpec(
+		PartitionField{SourceIDs: []int{1}, FieldID: 1000, Name: "region", Transform: IdentityTransform{}},
+		PartitionField{SourceIDs: []int{2}, FieldID: 1001, Name: "day", Transform: IdentityTransform{}},
+		PartitionField{SourceIDs: []int{3}, FieldID: 1002, Name: "bucket", Transform: IdentityTransform{}},
+		PartitionField{SourceIDs: []int{4}, FieldID: 1003, Name: "shard", Transform: IdentityTransform{}},
+	)
+	snapshotID := int64(1234)
+	sequenceNumber := int64(1)
+	entries := make([]ManifestEntry, entryCount)
+	for i := range entries {
+		builder, err := NewDataFileBuilder(
+			spec,
+			EntryContentData,
+			fmt.Sprintf("s3://bucket/data/%05d.parquet", i),
+			ParquetFile,
+			map[int]any{
+				1000: fmt.Sprintf("region-%02d", i%32),
+				1001: Date(i % 365),
+				1002: int32(i % 128),
+				1003: []byte{byte(i >> 8), byte(i)},
+			},
+			nil,
+			nil,
+			1_000,
+			1_000_000,
+		)
+		if err != nil {
+			b.Fatal(err)
+		}
+		entries[i] = NewManifestEntry(
+			EntryStatusADDED,
+			&snapshotID,
+			&sequenceNumber,
+			&sequenceNumber,
+			builder.Build(),
+		)
+	}
+
+	return schema, spec, snapshotID, entries
+}