This is an automated email from the ASF dual-hosted git repository.
laskoviymishka 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 e8b14a721 refactor(table): move shared helpers out of the inspect
files (#2582)
e8b14a721 is described below
commit e8b14a721e9a7122baac72dc3e500e34c4d2aa6f
Author: Revanth <[email protected]>
AuthorDate: Sun Nov 15 02:41:48 2026 -0600
refactor(table): move shared helpers out of the inspect files (#2582)
---
table/arrow_utils.go | 4 +
table/inspect_all_manifests.go | 6 +-
table/inspect_content_file_builder.go | 42 +---
table/inspect_entries.go | 2 +-
table/inspect_files.go | 116 +---------
table/inspect_internal_test.go | 246 ++-------------------
table/inspect_partitions.go | 179 ++-------------
table/inspect_partitions_batch_test.go | 26 +--
table/inspect_partitions_bench_test.go | 20 +-
table/inspect_partitions_internal_test.go | 99 ---------
table/inspect_partitions_parallel_test.go | 6 +-
table/inspect_position_deletes.go | 8 +-
table/partition_aggregate.go | 164 ++++++++++++++
table/partition_aggregate_test.go | 175 +++++++++++++++
table/partition_statistics_v2_v3_test.go | 30 +--
table/partition_statistics_write.go | 34 +--
table/partition_statistics_write_test.go | 12 +-
...tion_builder.go => partition_struct_builder.go} | 80 +++++--
...nd_test.go => partition_struct_builder_test.go} | 60 +++--
...hot_prefetch.go => snapshot_manifest_stream.go} | 24 +-
...ch_test.go => snapshot_manifest_stream_test.go} | 24 +-
table/unified_partition_type.go | 134 +++++++++++
table/unified_partition_type_test.go | 138 ++++++++++++
23 files changed, 853 insertions(+), 776 deletions(-)
diff --git a/table/arrow_utils.go b/table/arrow_utils.go
index fa6152ae3..efabff084 100644
--- a/table/arrow_utils.go
+++ b/table/arrow_utils.go
@@ -60,6 +60,10 @@ const (
ArrowParquetFieldIDKey = "PARQUET:field_id"
defaultBinPackLookback = 20
+
+ // recordBatchSize is the number of rows per Arrow record batch
produced by
+ // metadata tables and partition statistics.
+ recordBatchSize = 4096
)
// ArrowSchemaVisitor is an interface that can be implemented and used to
diff --git a/table/inspect_all_manifests.go b/table/inspect_all_manifests.go
index 9a16890f0..5e1b28c9e 100644
--- a/table/inspect_all_manifests.go
+++ b/table/inspect_all_manifests.go
@@ -53,7 +53,7 @@ func (i InspectTable) AllManifests(ctx context.Context)
(array.RecordReader, err
rows := 0
emitted := false
- chunk := make([]iceberg.ManifestFile, 0, inspectRecordBatchSize)
+ chunk := make([]iceberg.ManifestFile, 0, recordBatchSize)
emit := func() bool {
if rows == 0 {
return true
@@ -90,7 +90,7 @@ func (i InspectTable) AllManifests(ctx context.Context)
(array.RecordReader, err
}
// Gather manifests into a reused chunk so each record
batch is
- // filled to inspectRecordBatchSize across snapshot
boundaries.
+ // filled to recordBatchSize across snapshot boundaries.
referenceSnapshotID := snapshot.SnapshotID
appendChunk := func() bool {
if err := i.appendManifestRows(ctx, bldr,
slices.Values(chunk), &referenceSnapshotID); err != nil {
@@ -105,7 +105,7 @@ func (i InspectTable) AllManifests(ctx context.Context)
(array.RecordReader, err
}
for manifest := range manifests {
chunk = append(chunk, manifest)
- if rows+len(chunk) < inspectRecordBatchSize {
+ if rows+len(chunk) < recordBatchSize {
continue
}
if !appendChunk() || !emit() {
diff --git a/table/inspect_content_file_builder.go
b/table/inspect_content_file_builder.go
index 2529e5ef1..c07b23e6a 100644
--- a/table/inspect_content_file_builder.go
+++ b/table/inspect_content_file_builder.go
@@ -59,7 +59,7 @@ type inspectContentFileBuilder struct {
filePath *array.StringBuilder
fileFormat *array.StringBuilder
specID *array.Int32Builder
- partition *inspectPartitionBuilder
+ partition *partitionStructBuilder
recordCount *array.Int64Builder
fileSize *array.Int64Builder
columnSizes *array.MapBuilder
@@ -105,11 +105,11 @@ func newInspectContentFileBuilderFromFields(
builder func(int) array.Builder,
partitionType *iceberg.StructType,
) (inspectContentFileBuilder, error) {
- lookup, err := newInspectBuilderLookup("content-file", fields, builder)
+ lookup, err := newBuilderLookup("content-file", fields, builder)
if err != nil {
return inspectContentFileBuilder{}, err
}
- if err := validateInspectBuilderLookup("content-file", lookup,
inspectContentFileFieldIDs(partitionType)); err != nil {
+ if err := validateBuilderLookup("content-file", lookup,
inspectContentFileFieldIDs(partitionType)); err != nil {
return inspectContentFileBuilder{}, err
}
@@ -131,7 +131,7 @@ func newInspectContentFileBuilderFromFields(
if bindErr != nil {
return out, bindErr
}
- if out.partition, err =
newInspectPartitionBuilder(partitionBuilder, partitionType); err != nil {
+ if out.partition, err =
newPartitionStructBuilder(partitionBuilder, partitionType); err != nil {
return out, err
}
}
@@ -269,40 +269,6 @@ func inspectContentFileFieldIDs(partitionType
*iceberg.StructType) map[int]struc
return ids
}
-func newInspectBuilderLookup(scope string, fields []arrow.Field, builder
func(int) array.Builder) (map[int]array.Builder, error) {
- lookup := make(map[int]array.Builder, len(fields))
- for idx, field := range fields {
- id := getFieldID(field)
- if id == nil {
- return nil, fmt.Errorf("%s field %q is missing a valid
field ID", scope, field.Name)
- }
- if _, exists := lookup[*id]; exists {
- return nil, fmt.Errorf("%s schema contains duplicate
field ID %d", scope, *id)
- }
- lookup[*id] = builder(idx)
- }
-
- return lookup, nil
-}
-
-func validateInspectBuilderLookup(scope string, lookup map[int]array.Builder,
expected map[int]struct{}) error {
- if len(lookup) != len(expected) {
- return fmt.Errorf("%s schema has %d fields, want %d", scope,
len(lookup), len(expected))
- }
- for id := range lookup {
- if _, ok := expected[id]; !ok {
- return fmt.Errorf("%s schema contains unexpected field
ID %d", scope, id)
- }
- }
- for id := range expected {
- if _, ok := lookup[id]; !ok {
- return fmt.Errorf("%s schema is missing field ID %d",
scope, id)
- }
- }
-
- return nil
-}
-
func inspectBuilderAs[T any](lookup map[int]array.Builder, id int, name
string) (T, error) {
var zero T
builder, ok := lookup[id]
diff --git a/table/inspect_entries.go b/table/inspect_entries.go
index cd5948aef..7cb166fbb 100644
--- a/table/inspect_entries.go
+++ b/table/inspect_entries.go
@@ -38,7 +38,7 @@ func (i InspectTable) inspectEntries(
allSnapshots bool,
schemaFn func(*iceberg.StructType) *iceberg.Schema,
) (array.RecordReader, error) {
- partitionType, err := inspectPartitionType(i.tbl.Metadata())
+ partitionType, err := unifiedPartitionType(i.tbl.Metadata())
if err != nil {
return nil, fmt.Errorf("inspect %s: %w", name, err)
}
diff --git a/table/inspect_files.go b/table/inspect_files.go
index 4f49ee793..a1aff8be3 100644
--- a/table/inspect_files.go
+++ b/table/inspect_files.go
@@ -21,14 +21,11 @@ import (
"context"
"fmt"
"iter"
- "slices"
- "sort"
"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"
- iceinternal "github.com/apache/iceberg-go/internal"
iceio "github.com/apache/iceberg-go/io"
)
@@ -81,7 +78,7 @@ func (i InspectTable) inspectFiles(
allSnapshots bool,
includeManifest func(iceberg.ManifestFile) bool,
) (array.RecordReader, error) {
- partitionType, err := inspectPartitionType(i.tbl.Metadata())
+ partitionType, err := unifiedPartitionType(i.tbl.Metadata())
if err != nil {
return nil, fmt.Errorf("inspect %s: %w", name, err)
}
@@ -107,8 +104,6 @@ func (i InspectTable) inspectFiles(
return rr, nil
}
-const inspectRecordBatchSize = 4096
-
// manifestEntryReader streams manifest entries into bounded Arrow record
// batches. It keeps only the current batch and manifest decoder state in
// memory instead of materializing every entry before returning a reader.
@@ -238,7 +233,7 @@ func (i InspectTable) manifestEntryReaderFromManifestSource(
return
}
rows++
- if rows == inspectRecordBatchSize && !emit() {
+ if rows == recordBatchSize && !emit() {
return
}
}
@@ -261,110 +256,3 @@ func emptyInspectRecordBatch(alloc memory.Allocator,
schema *arrow.Schema) iter.
_ = yield(batch, nil)
}
}
-
-// inspectPartitionType returns the table-wide partition type. It contains the
-// union of partition fields from every spec, which lets metadata tables
-// represent live files written before partition evolution.
-func inspectPartitionType(metadata Metadata) (*iceberg.StructType, error) {
- return inspectPartitionTypeWithSchema(metadata,
metadata.CurrentSchema())
-}
-
-func inspectPartitionTypeWithSchema(
- metadata Metadata,
- currentSchema *iceberg.Schema,
-) (*iceberg.StructType, error) {
- specs := metadata.PartitionSpecs()
- sort.Slice(specs, func(left, right int) bool {
- return specs[left].ID() > specs[right].ID()
- })
-
- selected := make(map[int]iceberg.PartitionField)
- fieldsByID := make(map[int]iceberg.NestedField)
- for _, spec := range specs {
- for _, field := range spec.Fields() {
- if isInspectUnknownTransform(field.Transform) {
- return nil, fmt.Errorf("%w: cannot build
metadata partition type for field %d with unknown transform %s",
- iceberg.ErrInvalidPartitionSpec,
field.FieldID, field.Transform)
- }
- }
-
- partitionType := spec.PartitionType(currentSchema)
- for idx, field := range spec.Fields() {
- active := true
- for _, sourceID := range field.SourceIDs {
- // This is an existence check only.
FindTypeByID clones the
- // complete nested type on every call, which is
wasteful while
- // building the union of position-delete
partition fields.
- if _, ok :=
currentSchema.FindFieldByIDRef(sourceID, iceinternal.SchemaRef{}); !ok {
- active = false
-
- break
- }
- }
- if !active || idx >= partitionType.NumFields() {
- continue
- }
-
- if previous, exists := selected[field.FieldID]; exists {
- if !slices.Equal(previous.SourceIDs,
field.SourceIDs) {
- return nil, fmt.Errorf("%w: partition
field ID %d has incompatible source IDs %v and %v",
-
iceberg.ErrInvalidPartitionSpec, field.FieldID, previous.SourceIDs,
field.SourceIDs)
- }
-
- previousVoid :=
isInspectVoidTransform(previous.Transform)
- fieldVoid :=
isInspectVoidTransform(field.Transform)
- if previousVoid || fieldVoid {
- if previousVoid && !fieldVoid {
- selected[field.FieldID] = field
- old := fieldsByID[field.FieldID]
- old.Type =
partitionType.Field(idx).Type
- fieldsByID[field.FieldID] = old
- }
-
- continue
- }
-
- if !previous.Transform.Equals(field.Transform) {
- return nil, fmt.Errorf("%w: partition
field ID %d has incompatible transforms %q and %q",
-
iceberg.ErrInvalidPartitionSpec, field.FieldID, previous.Transform,
field.Transform)
- }
-
- continue
- }
-
- selected[field.FieldID] = field
- fieldsByID[field.FieldID] = iceberg.NestedField{
- ID: field.FieldID,
- Name: field.Name,
- Type: partitionType.Field(idx).Type,
- Required: false,
- }
- }
- }
-
- fields := make([]iceberg.NestedField, 0, len(fieldsByID))
- for _, field := range fieldsByID {
- fields = append(fields, field)
- }
- sort.Slice(fields, func(left, right int) bool { return fields[left].ID
< fields[right].ID })
-
- return iceberg.NewStructType(fields...), nil
-}
-
-func isInspectVoidTransform(transform iceberg.Transform) bool {
- switch transform.(type) {
- case iceberg.VoidTransform, *iceberg.VoidTransform:
- return true
- default:
- return false
- }
-}
-
-func isInspectUnknownTransform(transform iceberg.Transform) bool {
- switch transform.(type) {
- case iceberg.UnknownTransform, *iceberg.UnknownTransform:
- return true
- default:
- return false
- }
-}
diff --git a/table/inspect_internal_test.go b/table/inspect_internal_test.go
index 4127b195a..7b1966cfe 100644
--- a/table/inspect_internal_test.go
+++ b/table/inspect_internal_test.go
@@ -1244,7 +1244,7 @@ func TestInspectAllManifestsPreservesSnapshotReferences(t
*testing.T) {
}
func TestInspectAllManifestsStreamsRecordBatches(t *testing.T) {
- const manifestCount = inspectRecordBatchSize + 1
+ const manifestCount = recordBatchSize + 1
manifests := make([]iceberg.ManifestFile, manifestCount)
for idx := range manifests {
@@ -1266,7 +1266,7 @@ func TestInspectAllManifestsStreamsRecordBatches(t
*testing.T) {
batchSizes = append(batchSizes, rr.RecordBatch().NumRows())
}
require.NoError(t, rr.Err())
- require.Equal(t, []int64{inspectRecordBatchSize, 1}, batchSizes)
+ require.Equal(t, []int64{recordBatchSize, 1}, batchSizes)
}
func TestInspectAllManifestsAllocator(t *testing.T) {
@@ -1276,7 +1276,7 @@ func TestInspectAllManifestsAllocator(t *testing.T) {
next bool
}{
{name: "before first batch", manifestCount: 1},
- {name: "after first batch", manifestCount:
inspectRecordBatchSize + 1, next: true},
+ {name: "after first batch", manifestCount: recordBatchSize + 1,
next: true},
} {
t.Run(tt.name, func(t *testing.T) {
checked :=
memory.NewCheckedAllocator(memory.DefaultAllocator)
@@ -1871,7 +1871,7 @@ func TestInspectAllEntriesIncludesDeleteManifests(t
*testing.T) {
func TestInspectAllEntriesStreamsBatches(t *testing.T) {
spec := *iceberg.UnpartitionedSpec
tbl := inspectDataFilesTable(t, spec,
- inspectDataFileEntries(t, spec, inspectRecordBatchSize+1))
+ inspectDataFileEntries(t, spec, recordBatchSize+1))
rr, err := tbl.Inspect().AllEntries(context.Background())
require.NoError(t, err)
@@ -1882,7 +1882,7 @@ func TestInspectAllEntriesStreamsBatches(t *testing.T) {
batchRows = append(batchRows, int(rr.RecordBatch().NumRows()))
}
require.NoError(t, rr.Err())
- require.Equal(t, []int{inspectRecordBatchSize, 1}, batchRows)
+ require.Equal(t, []int{recordBatchSize, 1}, batchRows)
}
func TestInspectAllEntriesEmptyTableEarlyRelease(t *testing.T) {
@@ -2335,8 +2335,8 @@ func TestInspectDataFilesStreamsBatchesAndSkipsDeleted(t
*testing.T) {
txn, memIO := createTestTransactionWithMemIO(t, spec)
schema := simpleSchema()
- entries := make([]iceberg.ManifestEntry, 0, inspectRecordBatchSize+2)
- for index := range inspectRecordBatchSize + 1 {
+ entries := make([]iceberg.ManifestEntry, 0, recordBatchSize+2)
+ for index := range recordBatchSize + 1 {
file := newTestDataFile(t, spec,
"mem://default/table-location/data/live-"+strconv.Itoa(index)+".parquet", nil)
sequenceNumber := int64(1)
@@ -2389,8 +2389,8 @@ func TestInspectDataFilesStreamsBatchesAndSkipsDeleted(t
*testing.T) {
}
}
require.NoError(t, rr.Err())
- require.Equal(t, []int{inspectRecordBatchSize, 1}, batchRows)
- require.Len(t, paths, inspectRecordBatchSize+1)
+ require.Equal(t, []int{recordBatchSize, 1}, batchRows)
+ require.Len(t, paths, recordBatchSize+1)
require.NotContains(t, paths, deletedPath)
}
@@ -2464,7 +2464,7 @@ func TestInspectDataFilesAllocator(t *testing.T) {
t.Cleanup(func() { checked.AssertSize(t, 0) })
spec := *iceberg.UnpartitionedSpec
- tbl := inspectDataFilesTable(t, spec,
inspectDataFileEntries(t, spec, inspectRecordBatchSize+1))
+ tbl := inspectDataFilesTable(t, spec,
inspectDataFileEntries(t, spec, recordBatchSize+1))
rr, err :=
tbl.Inspect(WithInspectAllocator(checked)).DataFiles(context.Background())
require.NoError(t, err)
@@ -2538,118 +2538,6 @@ func TestAppendContentFileRecordUsesPartitionFieldIDs(t
*testing.T) {
require.EqualValues(t, 7, partition.Field(1).(*array.Int32).Value(0))
}
-func TestInspectPartitionTypeUsesAllActiveSpecs(t *testing.T) {
- schema := iceberg.NewSchema(0,
- iceberg.NestedField{ID: 1, Name: "region", Type:
iceberg.PrimitiveTypes.String, Required: true},
- iceberg.NestedField{ID: 2, Name: "category", Type:
iceberg.PrimitiveTypes.String, Required: true},
- )
- oldSpec := iceberg.NewPartitionSpecID(0, iceberg.PartitionField{
- SourceIDs: []int{1}, FieldID: 1000, Name: "region", Transform:
iceberg.IdentityTransform{},
- })
- newSpec := iceberg.NewPartitionSpecID(1, iceberg.PartitionField{
- SourceIDs: []int{2}, FieldID: 1001, Name: "category",
Transform: iceberg.IdentityTransform{},
- })
- lastPartitionID := 1001
- meta := &metadataV2{commonMetadata: commonMetadata{
- FormatVersion: 2,
- UUID: uuid.New(),
- LastColumnId: 2,
- SchemaList: []*iceberg.Schema{schema},
- CurrentSchemaID: 0,
- Specs: []iceberg.PartitionSpec{oldSpec, newSpec},
- DefaultSpecID: 1,
- LastPartitionID: &lastPartitionID,
- SnapshotRefs: map[string]SnapshotRef{},
- }}
-
- partitionType, err := inspectPartitionType(meta)
- require.NoError(t, err)
- require.Equal(t, []int{1000, 1001}, []int{
- partitionType.Field(0).ID,
- partitionType.Field(1).ID,
- })
- require.Equal(t, []string{"region", "category"}, []string{
- partitionType.Field(0).Name,
- partitionType.Field(1).Name,
- })
-}
-
-func TestInspectPartitionTypeRejectsIncompatibleFieldReuse(t *testing.T) {
- schema := iceberg.NewSchema(0,
- iceberg.NestedField{ID: 1, Name: "first", Type:
iceberg.PrimitiveTypes.Int32, Required: true},
- iceberg.NestedField{ID: 2, Name: "second", Type:
iceberg.PrimitiveTypes.Int32, Required: true},
- )
- metadataFor := func(specs []iceberg.PartitionSpec) Metadata {
- lastPartitionID := 1000
-
- return &metadataV2{commonMetadata: commonMetadata{
- FormatVersion: 2,
- UUID: uuid.New(),
- LastColumnId: 2,
- SchemaList: []*iceberg.Schema{schema},
- CurrentSchemaID: 0,
- Specs: specs,
- DefaultSpecID: specs[len(specs)-1].ID(),
- LastPartitionID: &lastPartitionID,
- }}
- }
- field := func(specID, sourceID int, transform iceberg.Transform)
iceberg.PartitionSpec {
- return iceberg.NewPartitionSpecID(specID,
iceberg.PartitionField{
- SourceIDs: []int{sourceID}, FieldID: 1000, Name:
"part", Transform: transform,
- })
- }
-
- tests := []struct {
- name string
- specs []iceberg.PartitionSpec
- valid bool
- }{
- {
- name: "void transition is compatible",
- specs: []iceberg.PartitionSpec{field(0, 1,
iceberg.IdentityTransform{}), field(1, 1, iceberg.VoidTransform{})},
- valid: true,
- },
- {
- name: "pointer void transition is compatible",
- specs: []iceberg.PartitionSpec{field(0, 1,
iceberg.IdentityTransform{}), field(1, 1, &iceberg.VoidTransform{})},
- valid: true,
- },
- {
- name: "different source ids",
- specs: []iceberg.PartitionSpec{field(0, 1,
iceberg.IdentityTransform{}), field(1, 2, iceberg.IdentityTransform{})},
- },
- {
- name: "different transforms",
- specs: []iceberg.PartitionSpec{field(0, 1,
iceberg.IdentityTransform{}), field(1, 1, iceberg.BucketTransform{NumBuckets:
16})},
- },
- {
- name: "void cannot hide incompatible history",
- specs: []iceberg.PartitionSpec{
- field(0, 1, iceberg.BucketTransform{NumBuckets:
16}),
- field(1, 1, iceberg.IdentityTransform{}),
- field(2, 1, iceberg.VoidTransform{}),
- },
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- _, err := inspectPartitionType(metadataFor(tt.specs))
- if tt.valid {
- require.NoError(t, err)
-
- return
- }
- require.ErrorIs(t, err, iceberg.ErrInvalidPartitionSpec)
- })
- }
-
- unknown, err := iceberg.ParseTransform("future_transform")
- require.NoError(t, err)
- _, err =
inspectPartitionType(metadataFor([]iceberg.PartitionSpec{field(0, 1, unknown)}))
- require.ErrorIs(t, err, iceberg.ErrInvalidPartitionSpec)
-}
-
func TestPartitionsSchema(t *testing.T) {
partitionType := iceberg.NewStructType(
iceberg.NestedField{ID: 1000, Name: "bucket", Type:
iceberg.PrimitiveTypes.Int32, Required: true},
@@ -2674,81 +2562,6 @@ func TestPartitionsSchema(t *testing.T) {
}, testFieldNames(unpartitioned))
}
-func TestInspectPartitionAggregateTreeHandlesBinaryAndNaNValues(t *testing.T) {
- tree := newInspectPartitionAggregateTree()
- aggregate := &inspectPartitionAggregate{specID: 1}
- record := partitionRecord{[]byte{1, 2, 3}, math.NaN()}
- tree.insert(record, aggregate)
-
- require.Same(t, aggregate, tree.lookup(partitionRecord{[]byte{1, 2, 3},
math.NaN()}))
- require.Nil(t, tree.lookup(partitionRecord{[]byte{1, 2, 4},
math.NaN()}))
-}
-
-func TestInspectPartitionAggregateTreeDistinguishesFloatWidthsAndSignedZero(t
*testing.T) {
- tree := newInspectPartitionAggregateTree()
- float32Aggregate := &inspectPartitionAggregate{specID: 1}
- float32Record := partitionRecord{math.Float32frombits(0xffc00001)}
- tree.insert(float32Record, float32Aggregate)
-
- require.Same(t, float32Aggregate,
tree.lookup(partitionRecord{math.Float32frombits(0x7fc00002)}))
- require.Nil(t,
tree.lookup(partitionRecord{math.Float64frombits(0x7ff8000000000001)}))
-
- negativeZeroAggregate := &inspectPartitionAggregate{specID: 2}
- tree.insert(partitionRecord{math.Copysign(0, -1)},
negativeZeroAggregate)
- require.Same(t, negativeZeroAggregate,
tree.lookup(partitionRecord{math.Copysign(0, -1)}))
- require.Nil(t, tree.lookup(partitionRecord{float64(0)}))
-}
-
-func TestInspectPartitionAggregateTreeLookupPartition(t *testing.T) {
- partitionType := iceberg.NewStructType(
- iceberg.NestedField{ID: 1000, Name: "id", Type:
iceberg.PrimitiveTypes.Int32},
- iceberg.NestedField{ID: 1001, Name: "payload", Type:
iceberg.PrimitiveTypes.Binary},
- iceberg.NestedField{ID: 1002, Name: "score", Type:
iceberg.PrimitiveTypes.Float64},
- )
- partition := map[int]any{
- 1000: int32(7),
- 1001: []byte{1, 2, 3},
- 1002: math.NaN(),
- }
- record := newPartitionRecord(inspectCoercePartition(partition,
partitionType), partitionType)
- aggregate := &inspectPartitionAggregate{specID: 1}
- tree := newInspectPartitionAggregateTree()
- tree.insert(record, aggregate)
-
- require.Same(t, aggregate, tree.lookupPartition(partition,
partitionType))
- require.Nil(t, tree.lookupPartition(map[int]any{
- 1000: int32(7),
- 1001: []byte{1, 2, 4},
- 1002: math.NaN(),
- }, partitionType))
-
- // A file written with an older partition spec does not have the field
- // added by a later spec. Both lookup paths must key the missing field
as nil.
- evolvedPartition := map[int]any{
- 1000: int32(7),
- 1002: math.NaN(),
- }
- evolvedRecord :=
newPartitionRecord(inspectCoercePartition(evolvedPartition, partitionType),
partitionType)
- evolvedAggregate := &inspectPartitionAggregate{specID: 2}
- tree.insert(evolvedRecord, evolvedAggregate)
-
- require.Same(t, evolvedAggregate,
tree.lookupPartition(evolvedPartition, partitionType))
- require.Same(t, evolvedAggregate, tree.lookup(evolvedRecord))
-}
-
-func TestCloneInspectPartitionClonesBinaryValues(t *testing.T) {
- value := []byte{1, 2, 3}
- cloned := cloneInspectPartition(map[int]any{1000: value})
-
- value[0] = 4
- require.Equal(t, []byte{1, 2, 3}, cloned[1000])
-
- clonedValue := cloned[1000].([]byte)
- clonedValue[1] = 5
-
- require.Equal(t, []byte{4, 2, 3}, value)
-}
-
func TestInspectPartitionsAggregatesDataAndDeletes(t *testing.T) {
const snapshotID = int64(1)
spec := partitionedSpec()
@@ -3218,7 +3031,7 @@ func TestInspectPositionDeletesDefersLaterManifestReads(t
*testing.T) {
dataPath := "mem://position-deletes/table/data/data.parquet"
var deleteRows bytes.Buffer
deleteRows.WriteByte('[')
- for pos := range inspectRecordBatchSize {
+ for pos := range recordBatchSize {
if pos > 0 {
deleteRows.WriteByte(',')
}
@@ -3234,7 +3047,7 @@ func TestInspectPositionDeletesDefersLaterManifestReads(t
*testing.T) {
*iceberg.UnpartitionedSpec, tableSchema, snapshotID,
iceberg.ManifestContentDeletes,
[]iceberg.ManifestEntry{iceberg.NewManifestEntry(
iceberg.EntryStatusADDED, &snapshotID, &sequenceNumber,
&sequenceNumber,
- newPosDeleteFile(t, deletePath, inspectRecordBatchSize,
128),
+ newPosDeleteFile(t, deletePath, recordBatchSize, 128),
)},
)
missingManifest := iceberg.NewManifestBuilder(
@@ -3249,7 +3062,7 @@ func TestInspectPositionDeletesDefersLaterManifestReads(t
*testing.T) {
require.NoError(t, err)
defer rr.Release()
require.True(t, rr.Next(), "reader error: %v", rr.Err())
- require.EqualValues(t, inspectRecordBatchSize,
rr.RecordBatch().NumRows())
+ require.EqualValues(t, recordBatchSize, rr.RecordBatch().NumRows())
}
func TestAppendParquetPositionDeleteRowsRejectsNullRow(t *testing.T) {
@@ -4238,39 +4051,6 @@ func testFieldNames(sc *iceberg.Schema) []string {
return names
}
-func TestInspectValueScalarDecimal(t *testing.T) {
- typ := iceberg.MustDecimalTypeOf(10, 2)
- arrowType := &arrow.Decimal128Type{Precision: 10, Scale: 2}
- value := iceberg.DecimalLiteral{Val: decimal128.FromI64(123), Scale: 2}
-
- got, err := inspectValueScalar(value, typ, arrowType)
- require.NoError(t, err)
- require.Equal(t, value.Val, got.(*scalar.Decimal128).Value)
-}
-
-func TestInspectValueScalarRejectsMismatchedPartitionValues(t *testing.T) {
- tests := []struct {
- name string
- value any
- typ iceberg.Type
- arrowType arrow.DataType
- want string
- }{
- {name: "date", value: int64(1), typ:
iceberg.PrimitiveTypes.Date, arrowType: arrow.FixedWidthTypes.Date32, want:
"unsupported date"},
- {name: "time", value: int64(1), typ:
iceberg.PrimitiveTypes.Time, arrowType: arrow.FixedWidthTypes.Time64us, want:
"unsupported time"},
- {name: "timestamp", value: int64(1), typ:
iceberg.PrimitiveTypes.Timestamp, arrowType:
arrow.FixedWidthTypes.Timestamp_us, want: "unsupported timestamp"},
- {name: "timestamp nanos", value: int64(1), typ:
iceberg.PrimitiveTypes.TimestampNs, arrowType:
arrow.FixedWidthTypes.Timestamp_ns, want: "unsupported nanosecond timestamp"},
- {name: "UUID", value: []byte("not-a-UUID"), typ:
iceberg.PrimitiveTypes.UUID, arrowType: &arrow.FixedSizeBinaryType{ByteWidth:
16}, want: "unsupported UUID"},
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- _, err := inspectValueScalar(tt.value, tt.typ,
tt.arrowType)
- require.ErrorContains(t, err, tt.want)
- })
- }
-}
-
func TestInspectInt32ValueRejectsOverflow(t *testing.T) {
if strconv.IntSize == 32 {
t.Skip("int32 is the native int width")
diff --git a/table/inspect_partitions.go b/table/inspect_partitions.go
index 8ccd34d94..32e9302bd 100644
--- a/table/inspect_partitions.go
+++ b/table/inspect_partitions.go
@@ -20,7 +20,6 @@ package table
import (
"context"
"fmt"
- "slices"
"sort"
"strconv"
"strings"
@@ -33,120 +32,11 @@ import (
"golang.org/x/sync/errgroup"
)
-type inspectPartitionAggregate struct {
- specID int32
- partition map[int]any
- dataRecordCount int64
- dataFileCount int32
- dataFileSize int64
- positionDeleteCount int64
- positionDeleteFiles int32
- equalityDeleteCount int64
- equalityDeleteFiles int32
- lastUpdatedAt *int64
- lastUpdatedSnapshot *int64
- orderingKey string
- // Persisted partition statistics distinguish DVs from classic delete
files
- // and expose an exact live-row total only when metadata proves it.
- deletionVectorCount int32
- totalRecordCount *int64
- // Partition statistics store timestamps in milliseconds, while the
inspect
- // Arrow output above uses microseconds.
- statisticsUpdatedAt *int64
- statisticsUpdatedSnapshot *int64
-}
-
-type inspectPartitionAggregateTree struct {
- children map[any]*inspectPartitionAggregateTree
- binaryChildren map[string]*inspectPartitionAggregateTree
- aggregate *inspectPartitionAggregate
-}
-
-func newInspectPartitionAggregateTree() *inspectPartitionAggregateTree {
- return &inspectPartitionAggregateTree{}
-}
-
-// child uses a typed map for binary values to avoid interface-backed keys
-// during repeated lookups. Other values retain their existing key types.
-func (t *inspectPartitionAggregateTree) child(value any)
(*inspectPartitionAggregateTree, bool) {
- if binary, ok := value.([]byte); ok {
- child, found := t.binaryChildren[string(binary)]
-
- return child, found
- }
-
- child, found := t.children[comparablePartitionKey(value)]
-
- return child, found
-}
-
-func (t *inspectPartitionAggregateTree) setChild(value any, child
*inspectPartitionAggregateTree) {
- if binary, ok := value.([]byte); ok {
- if t.binaryChildren == nil {
- t.binaryChildren =
make(map[string]*inspectPartitionAggregateTree)
- }
- // A stored string key owns its bytes even if the input buffer
changes.
- t.binaryChildren[string(binary)] = child
-
- return
- }
-
- if t.children == nil {
- t.children = make(map[any]*inspectPartitionAggregateTree)
- }
- t.children[comparablePartitionKey(value)] = child
-}
-
-func (t *inspectPartitionAggregateTree) lookup(record partitionRecord)
*inspectPartitionAggregate {
- node := t
- for _, value := range record {
- child, ok := node.child(value)
- if !ok {
- return nil
- }
- node = child
- }
-
- return node.aggregate
-}
-
-func (t *inspectPartitionAggregateTree) lookupPartition(
- partition map[int]any,
- partitionType *iceberg.StructType,
-) *inspectPartitionAggregate {
- node := t
- for i := range partitionType.NumFields() {
- child, ok := node.child(partition[partitionType.Field(i).ID])
- if !ok {
- return nil
- }
- node = child
- }
-
- return node.aggregate
-}
-
-// insert walks the positional record, while lookupPartition walks partition
-// field IDs. Build records with the same partition type so their field order
-// stays aligned.
-func (t *inspectPartitionAggregateTree) insert(record partitionRecord,
aggregate *inspectPartitionAggregate) {
- node := t
- for _, value := range record {
- child, ok := node.child(value)
- if !ok {
- child = newInspectPartitionAggregateTree()
- node.setChild(value, child)
- }
- node = child
- }
- node.aggregate = aggregate
-}
-
// Partitions returns one row per live partition, aggregating data and delete
// files from the current snapshot. Files from evolved specs are coerced into
// the table-wide partition type before grouping.
func (i InspectTable) Partitions(ctx context.Context) (array.RecordReader,
error) {
- partitionType, err := inspectPartitionType(i.tbl.Metadata())
+ partitionType, err := unifiedPartitionType(i.tbl.Metadata())
if err != nil {
return nil, fmt.Errorf("inspect partitions: %w", err)
}
@@ -164,14 +54,14 @@ func (i InspectTable) Partitions(ctx context.Context)
(array.RecordReader, error
return i.partitionAggregateReader(ctx, arrowSchema, partitionType,
aggregates), nil
}
-// partitionAggregateReader encodes at most inspectRecordBatchSize partitions
per
+// partitionAggregateReader encodes at most recordBatchSize partitions per
// Arrow batch. Aggregate discovery is eager, but the Arrow buffers are bounded
// and released as each record is consumed.
func (i InspectTable) partitionAggregateReader(
ctx context.Context,
arrowSchema *arrow.Schema,
partitionType *iceberg.StructType,
- aggregates []*inspectPartitionAggregate,
+ aggregates []*partitionAggregate,
) array.RecordReader {
return array.ReaderFromIter(arrowSchema, func(yield
func(arrow.RecordBatch, error) bool) {
bldr := array.NewRecordBuilder(i.alloc, arrowSchema)
@@ -190,7 +80,7 @@ func (i InspectTable) partitionAggregateReader(
return
}
- if (index+1)%inspectRecordBatchSize == 0 {
+ if (index+1)%recordBatchSize == 0 {
if !yield(bldr.NewRecordBatch(), nil) {
return
}
@@ -199,7 +89,7 @@ func (i InspectTable) partitionAggregateReader(
// Match the prior single-batch API for empty tables, but do
not emit
// an extra empty batch after an exact multiple of the batch
size.
- if len(aggregates) == 0 ||
len(aggregates)%inspectRecordBatchSize != 0 {
+ if len(aggregates) == 0 || len(aggregates)%recordBatchSize != 0
{
_ = yield(bldr.NewRecordBatch(), nil)
}
})
@@ -209,7 +99,7 @@ func (i InspectTable) partitionAggregateReader(
// per-manifest partition aggregation state.
const inspectPartitionManifestConcurrency = 8
-func (i InspectTable) partitionAggregates(ctx context.Context, partitionType
*iceberg.StructType) ([]*inspectPartitionAggregate, error) {
+func (i InspectTable) partitionAggregates(ctx context.Context, partitionType
*iceberg.StructType) ([]*partitionAggregate, error) {
snapshot := i.tbl.Metadata().CurrentSnapshot()
if snapshot == nil {
return nil, nil
@@ -230,8 +120,8 @@ func (i InspectTable) partitionAggregates(ctx
context.Context, partitionType *ic
snapshotTimes[snapshot.SnapshotID] = snapshot.TimestampMs
}
- aggregates := make([]*inspectPartitionAggregate, 0)
- aggregateTree := newInspectPartitionAggregateTree()
+ aggregates := make([]*partitionAggregate, 0)
+ aggregateTree := newPartitionAggregateTree()
// Buffer only a bounded number of manifests. Workers group their
entries
// independently, then their results are merged in manifest order.
@@ -242,11 +132,11 @@ func (i InspectTable) partitionAggregates(ctx
context.Context, partitionType *ic
snapshotTimes, aggregateTree, &aggregates)
}
- partial := make([][]*inspectPartitionAggregate, len(batch))
+ partial := make([][]*partitionAggregate, len(batch))
g, gctx := errgroup.WithContext(ctx)
for index, manifest := range batch {
g.Go(func() error {
- localTree := newInspectPartitionAggregateTree()
+ localTree := newPartitionAggregateTree()
return i.foldInspectPartitionManifest(gctx, fs,
manifest, partitionType,
snapshotTimes, localTree,
&partial[index])
@@ -316,8 +206,8 @@ func (i InspectTable) foldInspectPartitionManifest(
manifest iceberg.ManifestFile,
partitionType *iceberg.StructType,
snapshotTimes map[int64]int64,
- aggregateTree *inspectPartitionAggregateTree,
- aggregates *[]*inspectPartitionAggregate,
+ aggregateTree *partitionAggregateTree,
+ aggregates *[]*partitionAggregate,
) error {
// Avoid opening remote manifest files after the caller has canceled.
if err := ctx.Err(); err != nil {
@@ -340,10 +230,10 @@ func (i InspectTable) foldInspectPartitionManifest(
partitionValues := dataFilePartition(file)
aggregate := aggregateTree.lookupPartition(partitionValues,
partitionType)
if aggregate == nil {
- partition := inspectCoercePartition(partitionValues,
partitionType)
+ partition := coercePartition(partitionValues,
partitionType)
record := newPartitionRecord(partition, partitionType)
- aggregate = &inspectPartitionAggregate{
- partition: cloneInspectPartition(partition),
+ aggregate = &partitionAggregate{
+ partition: clonePartition(partition),
orderingKey: inspectPartitionKey(partition),
}
*aggregates = append(*aggregates, aggregate)
@@ -373,7 +263,7 @@ func (i InspectTable) foldInspectPartitionManifest(
return ctx.Err()
}
-func mergeInspectPartitionAggregate(dst, src *inspectPartitionAggregate) {
+func mergeInspectPartitionAggregate(dst, src *partitionAggregate) {
dst.dataRecordCount += src.dataRecordCount
dst.dataFileCount += src.dataFileCount
dst.dataFileSize += src.dataFileSize
@@ -391,7 +281,7 @@ func mergeInspectPartitionAggregate(dst, src
*inspectPartitionAggregate) {
}
func (i InspectTable) updatePartitionTimestamp(
- aggregate *inspectPartitionAggregate,
+ aggregate *partitionAggregate,
snapshotTimes map[int64]int64,
snapshotID int64,
specID int32,
@@ -413,22 +303,6 @@ func (i InspectTable) updatePartitionTimestamp(
aggregate.specID = specID
}
-func inspectCoercePartition(values map[int]any, partitionType
*iceberg.StructType) map[int]any {
- if partitionType == nil || partitionType.NumFields() == 0 {
- return nil
- }
-
- coerced := make(map[int]any, partitionType.NumFields())
- for i := range partitionType.NumFields() {
- id := partitionType.Field(i).ID
- if value, ok := values[id]; ok {
- coerced[id] = value
- }
- }
-
- return coerced
-}
-
func inspectPartitionKey(partition map[int]any) string {
ids := make([]int, 0, len(partition))
for id := range partition {
@@ -481,21 +355,6 @@ func inspectPartitionKey(partition map[int]any) string {
return key.String()
}
-func cloneInspectPartition(partition map[int]any) map[int]any {
- if partition == nil {
- return nil
- }
- returnMap := make(map[int]any, len(partition))
- for id, value := range partition {
- if bytes, ok := value.([]byte); ok {
- value = slices.Clone(bytes)
- }
- returnMap[id] = value
- }
-
- return returnMap
-}
-
// PartitionsSchema returns the partition metadata-table schema. For an
// unpartitioned table the partition and spec_id columns are omitted, matching
// Java's PartitionsTable behavior.
@@ -529,7 +388,7 @@ func PartitionsSchema(partitionType *iceberg.StructType)
*iceberg.Schema {
)
}
-func appendPartitionAggregate(bldr *array.RecordBuilder, partitionType
*iceberg.StructType, aggregate inspectPartitionAggregate) error {
+func appendPartitionAggregate(bldr *array.RecordBuilder, partitionType
*iceberg.StructType, aggregate partitionAggregate) error {
idx := 0
if partitionType != nil && partitionType.NumFields() > 0 {
partition := bldr.Field(idx).(*array.StructBuilder)
@@ -543,7 +402,7 @@ func appendPartitionAggregate(bldr *array.RecordBuilder,
partitionType *iceberg.
continue
}
- valueScalar, err := inspectValueScalar(value,
field.Type, arrowType.Field(fieldIndex).Type)
+ valueScalar, err := partitionValueScalar(value,
field.Type, arrowType.Field(fieldIndex).Type)
if err != nil {
return fmt.Errorf("partition field %q: %w",
field.Name, err)
}
diff --git a/table/inspect_partitions_batch_test.go
b/table/inspect_partitions_batch_test.go
index 5938cd96e..920956493 100644
--- a/table/inspect_partitions_batch_test.go
+++ b/table/inspect_partitions_batch_test.go
@@ -32,7 +32,7 @@ import (
func inspectPartitionBatchFixture(
tb testing.TB,
count int,
-) (*iceberg.StructType, *arrow.Schema, []*inspectPartitionAggregate) {
+) (*iceberg.StructType, *arrow.Schema, []*partitionAggregate) {
tb.Helper()
partitionType := iceberg.NewStructType(
@@ -43,9 +43,9 @@ func inspectPartitionBatchFixture(
tb.Fatal(err)
}
- aggregates := make([]*inspectPartitionAggregate, count)
+ aggregates := make([]*partitionAggregate, count)
for i := range aggregates {
- aggregates[i] = &inspectPartitionAggregate{
+ aggregates[i] = &partitionAggregate{
partition: map[int]any{1000: int32(i)},
dataRecordCount: int64(i + 1),
dataFileCount: 1,
@@ -57,8 +57,8 @@ func inspectPartitionBatchFixture(
func TestInspectPartitionAggregateReaderBoundedBatches(t *testing.T) {
for _, count := range []int{
- 0, 1, inspectRecordBatchSize - 1, inspectRecordBatchSize,
- inspectRecordBatchSize + 1, 2*inspectRecordBatchSize + 1,
+ 0, 1, recordBatchSize - 1, recordBatchSize,
+ recordBatchSize + 1, 2*recordBatchSize + 1,
} {
t.Run(fmt.Sprintf("partitions=%d", count), func(t *testing.T) {
partitionType, arrowSchema, aggregates :=
inspectPartitionBatchFixture(t, count)
@@ -74,7 +74,7 @@ func TestInspectPartitionAggregateReaderBoundedBatches(t
*testing.T) {
for reader.Next() {
batch := reader.RecordBatch()
batchSizes = append(batchSizes,
int(batch.NumRows()))
- require.LessOrEqual(t, batch.NumRows(),
int64(inspectRecordBatchSize))
+ require.LessOrEqual(t, batch.NumRows(),
int64(recordBatchSize))
partition :=
batch.Column(0).(*array.Struct).Field(0).(*array.Int32)
recordCount := batch.Column(2).(*array.Int64)
@@ -89,9 +89,9 @@ func TestInspectPartitionAggregateReaderBoundedBatches(t
*testing.T) {
if count == 0 {
require.Equal(t, []int{0}, batchSizes)
} else {
- want := make([]int, 0,
(count+inspectRecordBatchSize-1)/inspectRecordBatchSize)
- for remaining := count; remaining > 0;
remaining -= inspectRecordBatchSize {
- want = append(want, min(remaining,
inspectRecordBatchSize))
+ want := make([]int, 0,
(count+recordBatchSize-1)/recordBatchSize)
+ for remaining := count; remaining > 0;
remaining -= recordBatchSize {
+ want = append(want, min(remaining,
recordBatchSize))
}
require.Equal(t, want, batchSizes)
}
@@ -102,7 +102,7 @@ func TestInspectPartitionAggregateReaderBoundedBatches(t
*testing.T) {
// Exercise the public metadata-table reader across a real manifest, including
// the boundary between two Arrow batches.
func TestInspectPartitionsAcrossRecordBatchBoundary(t *testing.T) {
- const count = inspectRecordBatchSize + 1
+ const count = recordBatchSize + 1
spec := partitionedSpec()
const snapshotID = int64(1)
@@ -146,12 +146,12 @@ func TestInspectPartitionsAcrossRecordBatchBoundary(t
*testing.T) {
}
require.NoError(t, reader.Err())
require.Len(t, seen, count)
- require.Equal(t, []int{inspectRecordBatchSize, 1}, batchSizes)
+ require.Equal(t, []int{recordBatchSize, 1}, batchSizes)
}
func TestInspectPartitionAggregateReaderCancellation(t *testing.T) {
partitionType, arrowSchema, aggregates := inspectPartitionBatchFixture(
- t, 2*inspectRecordBatchSize)
+ t, 2*recordBatchSize)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
@@ -160,7 +160,7 @@ func TestInspectPartitionAggregateReaderCancellation(t
*testing.T) {
defer reader.Release()
require.True(t, reader.Next())
- require.EqualValues(t, inspectRecordBatchSize,
reader.RecordBatch().NumRows())
+ require.EqualValues(t, recordBatchSize, reader.RecordBatch().NumRows())
cancel()
require.False(t, reader.Next())
require.ErrorIs(t, reader.Err(), context.Canceled)
diff --git a/table/inspect_partitions_bench_test.go
b/table/inspect_partitions_bench_test.go
index 3aa5d8c18..179415fe1 100644
--- a/table/inspect_partitions_bench_test.go
+++ b/table/inspect_partitions_bench_test.go
@@ -63,17 +63,17 @@ func benchmarkInspectPartitionAggregation(
b.ReportAllocs()
b.ReportMetric(float64(len(files)), "files/op")
for b.Loop() {
- tree := newInspectPartitionAggregateTree()
+ tree := newPartitionAggregateTree()
aggregateCount := 0
for _, file := range files {
- var aggregate *inspectPartitionAggregate
+ var aggregate *partitionAggregate
if materialize {
- partition :=
inspectCoercePartition(file.Partition(), partitionType)
+ partition := coercePartition(file.Partition(),
partitionType)
record := newPartitionRecord(partition,
partitionType)
aggregate = tree.lookup(record)
if aggregate == nil {
- aggregate = &inspectPartitionAggregate{
- partition:
cloneInspectPartition(partition),
+ aggregate = &partitionAggregate{
+ partition:
clonePartition(partition),
orderingKey:
inspectPartitionKey(partition),
}
tree.insert(record, aggregate)
@@ -83,10 +83,10 @@ func benchmarkInspectPartitionAggregation(
partitionValues := dataFilePartition(file)
aggregate =
tree.lookupPartition(partitionValues, partitionType)
if aggregate == nil {
- partition :=
inspectCoercePartition(partitionValues, partitionType)
+ partition :=
coercePartition(partitionValues, partitionType)
record := newPartitionRecord(partition,
partitionType)
- aggregate = &inspectPartitionAggregate{
- partition:
cloneInspectPartition(partition),
+ aggregate = &partitionAggregate{
+ partition:
clonePartition(partition),
orderingKey:
inspectPartitionKey(partition),
}
tree.insert(record, aggregate)
@@ -166,7 +166,7 @@ func BenchmarkInspectPartitionBinaryLookup(b *testing.B) {
}
partitionType := iceberg.NewStructType(fields...)
- tree := newInspectPartitionAggregateTree()
+ tree := newPartitionAggregateTree()
partitions := make([]map[int]any, partitionCount)
for i := range partitions {
record := make(partitionRecord, fieldCount)
@@ -176,7 +176,7 @@ func BenchmarkInspectPartitionBinaryLookup(b *testing.B) {
record[j] = value
partition[field.ID] = value
}
- tree.insert(record, &inspectPartitionAggregate{})
+ tree.insert(record, &partitionAggregate{})
partitions[i] = partition
}
diff --git a/table/inspect_partitions_internal_test.go
b/table/inspect_partitions_internal_test.go
deleted file mode 100644
index 7601453ac..000000000
--- a/table/inspect_partitions_internal_test.go
+++ /dev/null
@@ -1,99 +0,0 @@
-// 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 (
- "math"
- "testing"
-
- "github.com/apache/iceberg-go"
-)
-
-func TestInspectPartitionAggregateTreeBinaryKeys(t *testing.T) {
- partitionType := iceberg.NewStructType(
- iceberg.NestedField{ID: 1000, Name: "first", Type:
iceberg.PrimitiveTypes.Binary},
- iceberg.NestedField{ID: 1001, Name: "second", Type:
iceberg.PrimitiveTypes.Binary},
- )
- tree := newInspectPartitionAggregateTree()
-
- check := func(first, second any, want *inspectPartitionAggregate) {
- t.Helper()
- if got := tree.lookup(partitionRecord{first, second}); got !=
want {
- t.Fatalf("positional lookup (%v, %v) = %p, want %p",
first, second, got, want)
- }
- partition := map[int]any{1000: first, 1001: second}
- if got := tree.lookupPartition(partition, partitionType); got
!= want {
- t.Fatalf("map lookup (%v, %v) = %p, want %p", first,
second, got, want)
- }
- }
-
- check([]byte("missing"), []byte("value"), nil)
-
- first := []byte{0, 0xff}
- second := []byte("x/y")
- original := &inspectPartitionAggregate{}
- tree.insert(partitionRecord{first, second}, original)
- first[0] = 1
- second[0] = 'z'
- check([]byte{0, 0xff}, []byte("x/y"), original)
- check(first, second, nil)
-
- nullFirst := &inspectPartitionAggregate{}
- emptyFirst := &inspectPartitionAggregate{}
- tree.insert(partitionRecord{nil, []byte("x")}, nullFirst)
- tree.insert(partitionRecord{[]byte{}, []byte("x")}, emptyFirst)
- check(nil, []byte("x"), nullFirst)
- check([]byte{}, []byte("x"), emptyFirst)
- check([]byte(nil), []byte("x"), emptyFirst)
-
- binaryFirst := &inspectPartitionAggregate{}
- stringFirst := &inspectPartitionAggregate{}
- tree.insert(partitionRecord{[]byte("same"), []byte("tail")},
binaryFirst)
- tree.insert(partitionRecord{"same", []byte("tail")}, stringFirst)
- check([]byte("same"), []byte("tail"), binaryFirst)
- check("same", []byte("tail"), stringFirst)
-
- otherNested := &inspectPartitionAggregate{}
- tree.insert(partitionRecord{[]byte("same"), []byte("other")},
otherNested)
- check([]byte("same"), []byte("other"), otherNested)
- check([]byte("same"), []byte("tail"), binaryFirst)
-}
-
-func TestInspectPartitionAggregateTreeMixedKeys(t *testing.T) {
- tree := newInspectPartitionAggregateTree()
- negativeZero := &inspectPartitionAggregate{}
- positiveZero := &inspectPartitionAggregate{}
- nan := &inspectPartitionAggregate{}
-
- tree.insert(partitionRecord{[]byte("scope"), math.Copysign(0, -1)},
negativeZero)
- tree.insert(partitionRecord{[]byte("scope"), float64(0)}, positiveZero)
- tree.insert(partitionRecord{[]byte("scope"),
math.Float64frombits(0x7ff8000000000001)}, nan)
-
- for _, test := range []struct {
- value float64
- want *inspectPartitionAggregate
- }{
- {math.Copysign(0, -1), negativeZero},
- {0, positiveZero},
- {math.Float64frombits(0x7ff8000000000002), nan},
- } {
- if got := tree.lookup(partitionRecord{[]byte("scope"),
test.value}); got != test.want {
- t.Fatalf("lookup (%v) = %p, want %p", test.value, got,
test.want)
- }
- }
-}
diff --git a/table/inspect_partitions_parallel_test.go
b/table/inspect_partitions_parallel_test.go
index 9802c1273..624e97c98 100644
--- a/table/inspect_partitions_parallel_test.go
+++ b/table/inspect_partitions_parallel_test.go
@@ -166,11 +166,11 @@ func TestMergeInspectPartitionAggregateTimestampTies(t
*testing.T) {
const timestamp = int64(123000)
firstSnapshot := int64(10)
secondSnapshot := int64(20)
- dst := &inspectPartitionAggregate{
+ dst := &partitionAggregate{
dataRecordCount: 3, dataFileCount: 1, specID: 1,
lastUpdatedAt: new(timestamp), lastUpdatedSnapshot:
&firstSnapshot,
}
- sameTime := &inspectPartitionAggregate{
+ sameTime := &partitionAggregate{
dataRecordCount: 5, dataFileCount: 2, specID: 2,
lastUpdatedAt: new(timestamp), lastUpdatedSnapshot:
&secondSnapshot,
}
@@ -183,7 +183,7 @@ func TestMergeInspectPartitionAggregateTimestampTies(t
*testing.T) {
require.Equal(t, firstSnapshot, *dst.lastUpdatedSnapshot)
newerTime := timestamp + 1
- newer := &inspectPartitionAggregate{
+ newer := &partitionAggregate{
specID: 3, lastUpdatedAt: &newerTime, lastUpdatedSnapshot:
&secondSnapshot,
}
mergeInspectPartitionAggregate(dst, newer)
diff --git a/table/inspect_position_deletes.go
b/table/inspect_position_deletes.go
index ae273d306..817f79361 100644
--- a/table/inspect_position_deletes.go
+++ b/table/inspect_position_deletes.go
@@ -104,7 +104,7 @@ type positionDeleteRecordAppender struct {
filePath *array.StringBuilder
pos *array.Int64Builder
row *array.StructBuilder
- partition *inspectPartitionBuilder
+ partition *partitionStructBuilder
specID *array.Int32Builder
deleteFilePath *array.StringBuilder
contentOffset *array.Int64Builder
@@ -182,7 +182,7 @@ func newPositionDeleteRecordAppender(
projection: projection,
}
if partitionType.NumFields() > 0 {
- partitionBuilder, err := newInspectPartitionBuilder(
+ partitionBuilder, err := newPartitionStructBuilder(
bldr.Field(nextField).(*array.StructBuilder),
partitionType)
if err != nil {
return out, err
@@ -537,7 +537,7 @@ func (i InspectTable) positionDeleteRecordReader(
return false, err
}
rows++
- if rows == inspectRecordBatchSize {
+ if rows == recordBatchSize {
return emit(), nil
}
@@ -804,7 +804,7 @@ func positionDeletesPartitionType(
metadata Metadata,
) (*iceberg.StructType, map[int]int, error) {
currentSchema := metadata.CurrentSchema()
- base, err := inspectPartitionTypeWithSchema(metadata, currentSchema)
+ base, err := unifiedPartitionTypeWithSchema(metadata, currentSchema)
if err != nil {
return nil, nil, err
}
diff --git a/table/partition_aggregate.go b/table/partition_aggregate.go
new file mode 100644
index 000000000..fa7ffdfbd
--- /dev/null
+++ b/table/partition_aggregate.go
@@ -0,0 +1,164 @@
+// 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 (
+ "slices"
+
+ "github.com/apache/iceberg-go"
+)
+
+type partitionAggregate struct {
+ specID int32
+ partition map[int]any
+ dataRecordCount int64
+ dataFileCount int32
+ dataFileSize int64
+ positionDeleteCount int64
+ positionDeleteFiles int32
+ equalityDeleteCount int64
+ equalityDeleteFiles int32
+ lastUpdatedAt *int64
+ lastUpdatedSnapshot *int64
+ orderingKey string
+ // Persisted partition statistics distinguish DVs from classic delete
files
+ // and expose an exact live-row total only when metadata proves it.
+ deletionVectorCount int32
+ totalRecordCount *int64
+ // Partition statistics store timestamps in milliseconds, while the
inspect
+ // Arrow output above uses microseconds.
+ statisticsUpdatedAt *int64
+ statisticsUpdatedSnapshot *int64
+}
+
+type partitionAggregateTree struct {
+ children map[any]*partitionAggregateTree
+ binaryChildren map[string]*partitionAggregateTree
+ aggregate *partitionAggregate
+}
+
+func newPartitionAggregateTree() *partitionAggregateTree {
+ return &partitionAggregateTree{}
+}
+
+// child uses a typed map for binary values to avoid interface-backed keys
+// during repeated lookups. Other values retain their existing key types.
+func (t *partitionAggregateTree) child(value any) (*partitionAggregateTree,
bool) {
+ if binary, ok := value.([]byte); ok {
+ child, found := t.binaryChildren[string(binary)]
+
+ return child, found
+ }
+
+ child, found := t.children[comparablePartitionKey(value)]
+
+ return child, found
+}
+
+func (t *partitionAggregateTree) setChild(value any, child
*partitionAggregateTree) {
+ if binary, ok := value.([]byte); ok {
+ if t.binaryChildren == nil {
+ t.binaryChildren =
make(map[string]*partitionAggregateTree)
+ }
+ // A stored string key owns its bytes even if the input buffer
changes.
+ t.binaryChildren[string(binary)] = child
+
+ return
+ }
+
+ if t.children == nil {
+ t.children = make(map[any]*partitionAggregateTree)
+ }
+ t.children[comparablePartitionKey(value)] = child
+}
+
+func (t *partitionAggregateTree) lookup(record partitionRecord)
*partitionAggregate {
+ node := t
+ for _, value := range record {
+ child, ok := node.child(value)
+ if !ok {
+ return nil
+ }
+ node = child
+ }
+
+ return node.aggregate
+}
+
+func (t *partitionAggregateTree) lookupPartition(
+ partition map[int]any,
+ partitionType *iceberg.StructType,
+) *partitionAggregate {
+ node := t
+ for i := range partitionType.NumFields() {
+ child, ok := node.child(partition[partitionType.Field(i).ID])
+ if !ok {
+ return nil
+ }
+ node = child
+ }
+
+ return node.aggregate
+}
+
+// insert walks the positional record, while lookupPartition walks partition
+// field IDs. Build records with the same partition type so their field order
+// stays aligned.
+func (t *partitionAggregateTree) insert(record partitionRecord, aggregate
*partitionAggregate) {
+ node := t
+ for _, value := range record {
+ child, ok := node.child(value)
+ if !ok {
+ child = newPartitionAggregateTree()
+ node.setChild(value, child)
+ }
+ node = child
+ }
+ node.aggregate = aggregate
+}
+
+func coercePartition(values map[int]any, partitionType *iceberg.StructType)
map[int]any {
+ if partitionType == nil || partitionType.NumFields() == 0 {
+ return nil
+ }
+
+ coerced := make(map[int]any, partitionType.NumFields())
+ for i := range partitionType.NumFields() {
+ id := partitionType.Field(i).ID
+ if value, ok := values[id]; ok {
+ coerced[id] = value
+ }
+ }
+
+ return coerced
+}
+
+func clonePartition(partition map[int]any) map[int]any {
+ if partition == nil {
+ return nil
+ }
+ returnMap := make(map[int]any, len(partition))
+ for id, value := range partition {
+ if bytes, ok := value.([]byte); ok {
+ value = slices.Clone(bytes)
+ }
+ returnMap[id] = value
+ }
+
+ return returnMap
+}
diff --git a/table/partition_aggregate_test.go
b/table/partition_aggregate_test.go
new file mode 100644
index 000000000..968cb270b
--- /dev/null
+++ b/table/partition_aggregate_test.go
@@ -0,0 +1,175 @@
+// 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 (
+ "math"
+ "testing"
+
+ "github.com/apache/iceberg-go"
+ "github.com/stretchr/testify/require"
+)
+
+func TestPartitionAggregateTreeBinaryKeys(t *testing.T) {
+ partitionType := iceberg.NewStructType(
+ iceberg.NestedField{ID: 1000, Name: "first", Type:
iceberg.PrimitiveTypes.Binary},
+ iceberg.NestedField{ID: 1001, Name: "second", Type:
iceberg.PrimitiveTypes.Binary},
+ )
+ tree := newPartitionAggregateTree()
+
+ check := func(first, second any, want *partitionAggregate) {
+ t.Helper()
+ if got := tree.lookup(partitionRecord{first, second}); got !=
want {
+ t.Fatalf("positional lookup (%v, %v) = %p, want %p",
first, second, got, want)
+ }
+ partition := map[int]any{1000: first, 1001: second}
+ if got := tree.lookupPartition(partition, partitionType); got
!= want {
+ t.Fatalf("map lookup (%v, %v) = %p, want %p", first,
second, got, want)
+ }
+ }
+
+ check([]byte("missing"), []byte("value"), nil)
+
+ first := []byte{0, 0xff}
+ second := []byte("x/y")
+ original := &partitionAggregate{}
+ tree.insert(partitionRecord{first, second}, original)
+ first[0] = 1
+ second[0] = 'z'
+ check([]byte{0, 0xff}, []byte("x/y"), original)
+ check(first, second, nil)
+
+ nullFirst := &partitionAggregate{}
+ emptyFirst := &partitionAggregate{}
+ tree.insert(partitionRecord{nil, []byte("x")}, nullFirst)
+ tree.insert(partitionRecord{[]byte{}, []byte("x")}, emptyFirst)
+ check(nil, []byte("x"), nullFirst)
+ check([]byte{}, []byte("x"), emptyFirst)
+ check([]byte(nil), []byte("x"), emptyFirst)
+
+ binaryFirst := &partitionAggregate{}
+ stringFirst := &partitionAggregate{}
+ tree.insert(partitionRecord{[]byte("same"), []byte("tail")},
binaryFirst)
+ tree.insert(partitionRecord{"same", []byte("tail")}, stringFirst)
+ check([]byte("same"), []byte("tail"), binaryFirst)
+ check("same", []byte("tail"), stringFirst)
+
+ otherNested := &partitionAggregate{}
+ tree.insert(partitionRecord{[]byte("same"), []byte("other")},
otherNested)
+ check([]byte("same"), []byte("other"), otherNested)
+ check([]byte("same"), []byte("tail"), binaryFirst)
+}
+
+func TestPartitionAggregateTreeMixedKeys(t *testing.T) {
+ tree := newPartitionAggregateTree()
+ negativeZero := &partitionAggregate{}
+ positiveZero := &partitionAggregate{}
+ nan := &partitionAggregate{}
+
+ tree.insert(partitionRecord{[]byte("scope"), math.Copysign(0, -1)},
negativeZero)
+ tree.insert(partitionRecord{[]byte("scope"), float64(0)}, positiveZero)
+ tree.insert(partitionRecord{[]byte("scope"),
math.Float64frombits(0x7ff8000000000001)}, nan)
+
+ for _, test := range []struct {
+ value float64
+ want *partitionAggregate
+ }{
+ {math.Copysign(0, -1), negativeZero},
+ {0, positiveZero},
+ {math.Float64frombits(0x7ff8000000000002), nan},
+ } {
+ if got := tree.lookup(partitionRecord{[]byte("scope"),
test.value}); got != test.want {
+ t.Fatalf("lookup (%v) = %p, want %p", test.value, got,
test.want)
+ }
+ }
+}
+
+func TestPartitionAggregateTreeHandlesBinaryAndNaNValues(t *testing.T) {
+ tree := newPartitionAggregateTree()
+ aggregate := &partitionAggregate{specID: 1}
+ record := partitionRecord{[]byte{1, 2, 3}, math.NaN()}
+ tree.insert(record, aggregate)
+
+ require.Same(t, aggregate, tree.lookup(partitionRecord{[]byte{1, 2, 3},
math.NaN()}))
+ require.Nil(t, tree.lookup(partitionRecord{[]byte{1, 2, 4},
math.NaN()}))
+}
+
+func TestPartitionAggregateTreeDistinguishesFloatWidthsAndSignedZero(t
*testing.T) {
+ tree := newPartitionAggregateTree()
+ float32Aggregate := &partitionAggregate{specID: 1}
+ float32Record := partitionRecord{math.Float32frombits(0xffc00001)}
+ tree.insert(float32Record, float32Aggregate)
+
+ require.Same(t, float32Aggregate,
tree.lookup(partitionRecord{math.Float32frombits(0x7fc00002)}))
+ require.Nil(t,
tree.lookup(partitionRecord{math.Float64frombits(0x7ff8000000000001)}))
+
+ negativeZeroAggregate := &partitionAggregate{specID: 2}
+ tree.insert(partitionRecord{math.Copysign(0, -1)},
negativeZeroAggregate)
+ require.Same(t, negativeZeroAggregate,
tree.lookup(partitionRecord{math.Copysign(0, -1)}))
+ require.Nil(t, tree.lookup(partitionRecord{float64(0)}))
+}
+
+func TestPartitionAggregateTreeLookupPartition(t *testing.T) {
+ partitionType := iceberg.NewStructType(
+ iceberg.NestedField{ID: 1000, Name: "id", Type:
iceberg.PrimitiveTypes.Int32},
+ iceberg.NestedField{ID: 1001, Name: "payload", Type:
iceberg.PrimitiveTypes.Binary},
+ iceberg.NestedField{ID: 1002, Name: "score", Type:
iceberg.PrimitiveTypes.Float64},
+ )
+ partition := map[int]any{
+ 1000: int32(7),
+ 1001: []byte{1, 2, 3},
+ 1002: math.NaN(),
+ }
+ record := newPartitionRecord(coercePartition(partition, partitionType),
partitionType)
+ aggregate := &partitionAggregate{specID: 1}
+ tree := newPartitionAggregateTree()
+ tree.insert(record, aggregate)
+
+ require.Same(t, aggregate, tree.lookupPartition(partition,
partitionType))
+ require.Nil(t, tree.lookupPartition(map[int]any{
+ 1000: int32(7),
+ 1001: []byte{1, 2, 4},
+ 1002: math.NaN(),
+ }, partitionType))
+
+ // A file written with an older partition spec does not have the field
+ // added by a later spec. Both lookup paths must key the missing field
as nil.
+ evolvedPartition := map[int]any{
+ 1000: int32(7),
+ 1002: math.NaN(),
+ }
+ evolvedRecord := newPartitionRecord(coercePartition(evolvedPartition,
partitionType), partitionType)
+ evolvedAggregate := &partitionAggregate{specID: 2}
+ tree.insert(evolvedRecord, evolvedAggregate)
+
+ require.Same(t, evolvedAggregate,
tree.lookupPartition(evolvedPartition, partitionType))
+ require.Same(t, evolvedAggregate, tree.lookup(evolvedRecord))
+}
+
+func TestClonePartitionClonesBinaryValues(t *testing.T) {
+ value := []byte{1, 2, 3}
+ cloned := clonePartition(map[int]any{1000: value})
+
+ value[0] = 4
+ require.Equal(t, []byte{1, 2, 3}, cloned[1000])
+
+ clonedValue := cloned[1000].([]byte)
+ clonedValue[1] = 5
+
+ require.Equal(t, []byte{4, 2, 3}, value)
+}
diff --git a/table/partition_statistics_v2_v3_test.go
b/table/partition_statistics_v2_v3_test.go
index 04e32c72b..6d0d02f59 100644
--- a/table/partition_statistics_v2_v3_test.go
+++ b/table/partition_statistics_v2_v3_test.go
@@ -425,18 +425,18 @@ func TestPartitionStatisticsAllMetricOverflows(t
*testing.T) {
spec := partitionedSpec()
for _, tt := range []struct {
name string
- row inspectPartitionAggregate
+ row partitionAggregate
content iceberg.ManifestEntryContent
path string
}{
- {"data records", inspectPartitionAggregate{dataRecordCount:
math.MaxInt64}, iceberg.EntryContentData, "data.parquet"},
- {"data files", inspectPartitionAggregate{dataFileCount:
math.MaxInt32}, iceberg.EntryContentData, "data.parquet"},
- {"data bytes", inspectPartitionAggregate{dataFileSize:
math.MaxInt64}, iceberg.EntryContentData, "data.parquet"},
- {"position records",
inspectPartitionAggregate{positionDeleteCount: math.MaxInt64},
iceberg.EntryContentPosDeletes, "delete.parquet"},
- {"position files",
inspectPartitionAggregate{positionDeleteFiles: math.MaxInt32},
iceberg.EntryContentPosDeletes, "delete.parquet"},
- {"equality records",
inspectPartitionAggregate{equalityDeleteCount: math.MaxInt64},
iceberg.EntryContentEqDeletes, "delete.parquet"},
- {"equality files",
inspectPartitionAggregate{equalityDeleteFiles: math.MaxInt32},
iceberg.EntryContentEqDeletes, "delete.parquet"},
- {"vectors", inspectPartitionAggregate{deletionVectorCount:
math.MaxInt32}, iceberg.EntryContentPosDeletes, "delete.puffin"},
+ {"data records", partitionAggregate{dataRecordCount:
math.MaxInt64}, iceberg.EntryContentData, "data.parquet"},
+ {"data files", partitionAggregate{dataFileCount:
math.MaxInt32}, iceberg.EntryContentData, "data.parquet"},
+ {"data bytes", partitionAggregate{dataFileSize: math.MaxInt64},
iceberg.EntryContentData, "data.parquet"},
+ {"position records", partitionAggregate{positionDeleteCount:
math.MaxInt64}, iceberg.EntryContentPosDeletes, "delete.parquet"},
+ {"position files", partitionAggregate{positionDeleteFiles:
math.MaxInt32}, iceberg.EntryContentPosDeletes, "delete.parquet"},
+ {"equality records", partitionAggregate{equalityDeleteCount:
math.MaxInt64}, iceberg.EntryContentEqDeletes, "delete.parquet"},
+ {"equality files", partitionAggregate{equalityDeleteFiles:
math.MaxInt32}, iceberg.EntryContentEqDeletes, "delete.parquet"},
+ {"vectors", partitionAggregate{deletionVectorCount:
math.MaxInt32}, iceberg.EntryContentPosDeletes, "delete.puffin"},
} {
t.Run(tt.name, func(t *testing.T) {
file := partitionStatsFile(t, spec, tt.content,
tt.path, map[int]any{1000: int32(2)}, 1).Build()
@@ -549,18 +549,18 @@ func TestPartitionStatisticsVectorTotalsValidateTargets(t
*testing.T) {
{name: "unknown vector sequence", dataSequence: 1,
vectorSequence: -1, vectorCount: 3, wantUnknown: true},
} {
t.Run(tt.name, func(t *testing.T) {
- row := &inspectPartitionAggregate{dataRecordCount: 10}
+ row := &partitionAggregate{dataRecordCount: 10}
vectorRow := row
if tt.differentPartition {
- vectorRow = &inspectPartitionAggregate{}
+ vectorRow = &partitionAggregate{}
}
data := make(map[string]partitionStatisticsDataFile)
if !tt.missing {
data["data.parquet"] =
partitionStatisticsDataFile{row: row, count: 10, sequence: tt.dataSequence}
}
vectors :=
map[string][]partitionStatisticsVector{"data.parquet": {{row: vectorRow, count:
tt.vectorCount, sequence: tt.vectorSequence}}}
- unrelated :=
&inspectPartitionAggregate{dataRecordCount: 20}
- allRows := []*inspectPartitionAggregate{row, unrelated}
+ unrelated := &partitionAggregate{dataRecordCount: 20}
+ allRows := []*partitionAggregate{row, unrelated}
if vectorRow != row {
allRows = append(allRows, vectorRow)
}
@@ -752,7 +752,7 @@ func TestPartitionStatisticsV2V3FailureAndEmptySnapshots(t
*testing.T) {
fs, err := tbl.FS(t.Context())
require.NoError(t, err)
_, err = writePartitionStatisticsParquet(ctx,
fs.(iceio.WriteFileIO), "mem://stats/table/metadata/cancelled.parquet",
statsTestPartitionType(),
- []*inspectPartitionAggregate{{partition:
map[int]any{1000: int32(2)}}}, version)
+ []*partitionAggregate{{partition: map[int]any{1000:
int32(2)}}}, version)
require.ErrorIs(t, err, context.Canceled)
_, err = fs.Open(t.Context(),
"mem://stats/table/metadata/cancelled.parquet")
require.Error(t, err)
@@ -797,7 +797,7 @@ func
TestPartitionStatisticsV2V3RemovesFileAfterCloseFailure(t *testing.T) {
failure := errors.New("injected close failure")
path := "mem://stats/table/metadata/failed.parquet"
_, err := writePartitionStatisticsParquet(t.Context(),
partitionStatisticsCloseFailureIO{WriteFileIO: fs, failure: failure}, path,
- statsTestPartitionType(),
[]*inspectPartitionAggregate{{partition: map[int]any{1000: int32(2)},
dataRecordCount: 10}}, version)
+ statsTestPartitionType(),
[]*partitionAggregate{{partition: map[int]any{1000: int32(2)}, dataRecordCount:
10}}, version)
require.ErrorIs(t, err, failure)
_, err = fs.Open(t.Context(), path)
require.Error(t, err, "a failed file must not remain available
for registration")
diff --git a/table/partition_statistics_write.go
b/table/partition_statistics_write.go
index 8d9b6dc5a..ab46c3573 100644
--- a/table/partition_statistics_write.go
+++ b/table/partition_statistics_write.go
@@ -171,7 +171,7 @@ func (t *Transaction) ComputePartitionStatistics(ctx
context.Context) (*Partitio
if err := validatePartitionStatisticsSourceTypes(t.tbl.Metadata()); err
!= nil {
return nil, err
}
- partitionType, err := inspectPartitionType(t.tbl.Metadata())
+ partitionType, err := unifiedPartitionType(t.tbl.Metadata())
if err != nil {
return nil, fmt.Errorf("partition statistics: %w", err)
}
@@ -320,7 +320,7 @@ func collectPartitionStatistics(
specs []iceberg.PartitionSpec,
formatVersion int,
snapshotTimes map[int64]int64,
-) ([]*inspectPartitionAggregate, error) {
+) ([]*partitionAggregate, error) {
specByID := make(map[int32]iceberg.PartitionSpec, len(specs))
for _, spec := range specs {
specByID[int32(spec.ID())] = spec
@@ -330,7 +330,7 @@ func collectPartitionStatistics(
return nil, err
}
- trees := make(map[int32]*inspectPartitionAggregateTree)
+ trees := make(map[int32]*partitionAggregateTree)
files := partitionStatisticsFileIndex{paths: make(map[string]string)}
var dataFiles map[string]partitionStatisticsDataFile
if formatVersion == 3 {
@@ -338,7 +338,7 @@ func collectPartitionStatistics(
}
vectors := make(map[string][]partitionStatisticsVector)
exactTotals := true
- rows := make([]*inspectPartitionAggregate, 0)
+ rows := make([]*partitionAggregate, 0)
for _, manifest := range manifests {
if err := ctx.Err(); err != nil {
return nil, err
@@ -356,7 +356,7 @@ func collectPartitionStatistics(
}
tree := trees[specID]
if tree == nil {
- tree = newInspectPartitionAggregateTree()
+ tree = newPartitionAggregateTree()
trees[specID] = tree
}
@@ -397,7 +397,7 @@ func collectPartitionStatistics(
if err := validatePartitionStatisticsTuple(spec,
file.FilePath(), values); err != nil {
return nil, err
}
- partition := inspectCoercePartition(values,
partitionType)
+ partition := coercePartition(values, partitionType)
for i := range partitionType.NumFields() {
field := partitionType.Field(i)
value := partition[field.ID]
@@ -420,9 +420,9 @@ func collectPartitionStatistics(
}
row := tree.lookupPartition(partition, partitionType)
if row == nil {
- row = &inspectPartitionAggregate{
+ row = &partitionAggregate{
specID: specID,
- partition:
cloneInspectPartition(partition),
+ partition: clonePartition(partition),
}
rows = append(rows, row)
tree.insert(newPartitionRecord(partition,
partitionType), row)
@@ -464,7 +464,7 @@ func collectPartitionStatistics(
}
type partitionStatisticsDataFile struct {
- row *inspectPartitionAggregate
+ row *partitionAggregate
count int64
sequence int64
}
@@ -526,7 +526,7 @@ func (i *partitionStatisticsFileIndex) add(file
iceberg.DataFile, manifest strin
return vector, nil
}
-func accumulatePartitionStatistics(row *inspectPartitionAggregate, file
iceberg.DataFile) error {
+func accumulatePartitionStatistics(row *partitionAggregate, file
iceberg.DataFile) error {
var records *int64
var files *int32
switch file.ContentType() {
@@ -555,7 +555,7 @@ func accumulatePartitionStatistics(row
*inspectPartitionAggregate, file iceberg.
return nil
}
-func finishPartitionStatistics(ctx context.Context, rows
[]*inspectPartitionAggregate, dataFiles map[string]partitionStatisticsDataFile,
vectors map[string][]partitionStatisticsVector, exactTotals bool) error {
+func finishPartitionStatistics(ctx context.Context, rows
[]*partitionAggregate, dataFiles map[string]partitionStatisticsDataFile,
vectors map[string][]partitionStatisticsVector, exactTotals bool) error {
for _, row := range rows {
row.totalRecordCount = nil
if exactTotals {
@@ -612,11 +612,11 @@ func validatePartitionStatisticsTuple(spec
iceberg.PartitionSpec, path string, v
// sortPartitionStatistics obeys the spec's NULL FIRST tuple ordering, not
// inspectPartitionKey's text ordering (where "10" sorts before "2").
// A spec ID only breaks equal tuple ties; it is not the primary sort key.
-func sortPartitionStatistics(rows []*inspectPartitionAggregate, partitionType
*iceberg.StructType) error {
+func sortPartitionStatistics(rows []*partitionAggregate, partitionType
*iceberg.StructType) error {
// Collection already validates each partition value before using it as
// an aggregate key. Do not repeat that validation for every output row.
var sortErr error
- slices.SortStableFunc(rows, func(a, b *inspectPartitionAggregate) int {
+ slices.SortStableFunc(rows, func(a, b *partitionAggregate) int {
for i := range partitionType.NumFields() {
field := partitionType.Field(i)
comp, err :=
comparePartitionStatisticValues(a.partition[field.ID], b.partition[field.ID])
@@ -790,7 +790,7 @@ func writePartitionStatisticsParquet(
fs iceio.WriteFileIO,
path string,
partitionType *iceberg.StructType,
- rows []*inspectPartitionAggregate,
+ rows []*partitionAggregate,
formatVersion int,
) (_ int64, err error) {
statsSchema, err := PartitionStatisticsSchema(partitionType,
formatVersion)
@@ -821,21 +821,21 @@ func writePartitionStatisticsParquet(
bldr := array.NewRecordBuilder(memory.DefaultAllocator, sc)
defer bldr.Release()
- part, err :=
newInspectPartitionBuilder(bldr.Field(0).(*array.StructBuilder), partitionType)
+ part, err :=
newPartitionStructBuilder(bldr.Field(0).(*array.StructBuilder), partitionType)
if err != nil {
_ = writer.Close()
_ = fw.Close()
return 0, err
}
- for start := 0; start < len(rows); start += inspectRecordBatchSize {
+ for start := 0; start < len(rows); start += recordBatchSize {
if err := ctx.Err(); err != nil {
_ = writer.Close()
_ = fw.Close()
return 0, err
}
- end := min(start+inspectRecordBatchSize, len(rows))
+ end := min(start+recordBatchSize, len(rows))
for _, row := range rows[start:end] {
if err := part.append(row.partition); err != nil {
_ = writer.Close()
diff --git a/table/partition_statistics_write_test.go
b/table/partition_statistics_write_test.go
index a28bb95fc..fa4b052fb 100644
--- a/table/partition_statistics_write_test.go
+++ b/table/partition_statistics_write_test.go
@@ -112,7 +112,7 @@ func
TestPartitionStatisticValuesNullFirstNumericAndBinary(t *testing.T) {
func TestSortPartitionStatisticsByTupleThenSpecID(t *testing.T) {
pt := statsTestPartitionType()
- rows := []*inspectPartitionAggregate{
+ rows := []*partitionAggregate{
{partition: map[int]any{1000: int32(10), 1001: "z"}, specID: 3},
{partition: map[int]any{1000: int32(2), 1001: "z"}, specID: 4},
{partition: map[int]any{1000: int32(-1), 1001: "a"}, specID: 1},
@@ -135,7 +135,7 @@ func TestSortPartitionStatisticsFloatAndUUID(t *testing.T) {
pt := iceberg.NewStructType(
iceberg.NestedField{ID: 1000, Name: "value", Type:
iceberg.PrimitiveTypes.Float64},
)
- rows := []*inspectPartitionAggregate{
+ rows := []*partitionAggregate{
{partition: map[int]any{1000: math.NaN()}, specID: 6},
{partition: map[int]any{1000: float64(0)}, specID: 3},
{partition: map[int]any{1000: math.Inf(1)}, specID: 5},
@@ -156,7 +156,7 @@ func TestSortPartitionStatisticsFloatAndUUID(t *testing.T) {
pt := iceberg.NewStructType(
iceberg.NestedField{ID: 1000, Name: "value", Type:
iceberg.PrimitiveTypes.UUID},
)
- rows := []*inspectPartitionAggregate{
+ rows := []*partitionAggregate{
{partition: map[int]any{1000:
uuid.MustParse("7fffffff-ffff-ffff-0000-000000000000")}, specID: 4},
{partition: map[int]any{1000:
uuid.MustParse("00000000-0000-0000-7fff-ffffffffffff")}, specID: 3},
{partition: map[int]any{1000:
uuid.MustParse("80000000-0000-0000-0000-000000000000")}, specID: 1},
@@ -173,7 +173,7 @@ func TestPartitionStatisticsParquetWrite(t *testing.T) {
ctx := t.Context()
fs := iceio.NewMemFS()
path := "mem://bucket/table/metadata/v1-stats.parquet"
- rows := []*inspectPartitionAggregate{
+ rows := []*partitionAggregate{
{
specID: 0, partition: map[int]any{1000: int32(-3),
1001: "a"},
dataRecordCount: 17, dataFileCount: 2, dataFileSize:
2048,
@@ -245,7 +245,7 @@ func TestCollectPartitionStatisticsFromLiveManifests(t
*testing.T) {
ctx := t.Context()
fs, err := tbl.FS(ctx)
require.NoError(t, err)
- pt, err := inspectPartitionType(tbl.Metadata())
+ pt, err := unifiedPartitionType(tbl.Metadata())
require.NoError(t, err)
rows, err := collectPartitionStatistics(ctx, fs,
*tbl.CurrentSnapshot(), pt, tbl.Metadata().PartitionSpecs(), 1, nil)
@@ -464,7 +464,7 @@ func
TestCollectPartitionStatisticsRejectsDuplicateLiveFiles(t *testing.T) {
})
fs, err := tbl.FS(t.Context())
require.NoError(t, err)
- pt, err := inspectPartitionType(tbl.Metadata())
+ pt, err := unifiedPartitionType(tbl.Metadata())
require.NoError(t, err)
_, err = collectPartitionStatistics(t.Context(), fs,
*tbl.CurrentSnapshot(), pt, tbl.Metadata().PartitionSpecs(), 1, nil)
diff --git a/table/inspect_partition_builder.go
b/table/partition_struct_builder.go
similarity index 65%
rename from table/inspect_partition_builder.go
rename to table/partition_struct_builder.go
index d8d8fac82..bd0f495fb 100644
--- a/table/inspect_partition_builder.go
+++ b/table/partition_struct_builder.go
@@ -27,12 +27,12 @@ import (
"github.com/google/uuid"
)
-type inspectPartitionBuilder struct {
+type partitionStructBuilder struct {
builder *array.StructBuilder
- fields []inspectPartitionFieldBuilder
+ fields []partitionFieldBuilder
}
-type inspectPartitionFieldBuilder struct {
+type partitionFieldBuilder struct {
id int
name string
typ iceberg.Type
@@ -41,15 +41,15 @@ type inspectPartitionFieldBuilder struct {
appendValue func(any) error
}
-func newInspectPartitionBuilder(
+func newPartitionStructBuilder(
builder *array.StructBuilder,
partitionType *iceberg.StructType,
-) (*inspectPartitionBuilder, error) {
+) (*partitionStructBuilder, error) {
arrowType, ok := builder.Type().(*arrow.StructType)
if !ok {
return nil, fmt.Errorf("partition builder has type %T, want
struct", builder.Type())
}
- lookup, err := newInspectBuilderLookup("partition", arrowType.Fields(),
builder.FieldBuilder)
+ lookup, err := newBuilderLookup("partition", arrowType.Fields(),
builder.FieldBuilder)
if err != nil {
return nil, err
}
@@ -57,28 +57,28 @@ func newInspectPartitionBuilder(
for _, field := range partitionType.Fields() {
expected[field.ID] = struct{}{}
}
- if err := validateInspectBuilderLookup("partition", lookup, expected);
err != nil {
+ if err := validateBuilderLookup("partition", lookup, expected); err !=
nil {
return nil, err
}
- fields := make([]inspectPartitionFieldBuilder, 0,
partitionType.NumFields())
+ fields := make([]partitionFieldBuilder, 0, partitionType.NumFields())
for _, field := range partitionType.Fields() {
fieldBuilder := lookup[field.ID]
- partitionField := inspectPartitionFieldBuilder{
+ partitionField := partitionFieldBuilder{
id: field.ID,
name: field.Name,
typ: field.Type,
arrowType: fieldBuilder.Type(),
builder: fieldBuilder,
}
- partitionField.appendValue =
newInspectPartitionFieldAppender(partitionField)
+ partitionField.appendValue =
newPartitionFieldAppender(partitionField)
fields = append(fields, partitionField)
}
- return &inspectPartitionBuilder{builder: builder, fields: fields}, nil
+ return &partitionStructBuilder{builder: builder, fields: fields}, nil
}
-func (b *inspectPartitionBuilder) append(values map[int]any) error {
+func (b *partitionStructBuilder) append(values map[int]any) error {
b.builder.Append(true)
for _, field := range b.fields {
if err := field.appendValue(values[field.id]); err != nil {
@@ -89,9 +89,9 @@ func (b *inspectPartitionBuilder) append(values map[int]any)
error {
return nil
}
-func newInspectPartitionFieldAppender(field inspectPartitionFieldBuilder)
func(any) error {
+func newPartitionFieldAppender(field partitionFieldBuilder) func(any) error {
appendScalar := func(value any) error {
- sc, err := inspectValueScalar(value, field.typ, field.arrowType)
+ sc, err := partitionValueScalar(value, field.typ,
field.arrowType)
if err != nil {
return fmt.Errorf("partition field %q: %w", field.name,
err)
}
@@ -105,31 +105,31 @@ func newInspectPartitionFieldAppender(field
inspectPartitionFieldBuilder) func(a
switch field.typ.(type) {
case iceberg.BooleanType:
if builder, ok := field.builder.(*array.BooleanBuilder); ok {
- return newInspectTypedPartitionAppender(builder.Append,
builder.AppendNull, appendScalar)
+ return newTypedPartitionAppender(builder.Append,
builder.AppendNull, appendScalar)
}
case iceberg.Int32Type:
if builder, ok := field.builder.(*array.Int32Builder); ok {
- return newInspectTypedPartitionAppender(builder.Append,
builder.AppendNull, appendScalar)
+ return newTypedPartitionAppender(builder.Append,
builder.AppendNull, appendScalar)
}
case iceberg.Int64Type:
if builder, ok := field.builder.(*array.Int64Builder); ok {
- return newInspectTypedPartitionAppender(builder.Append,
builder.AppendNull, appendScalar)
+ return newTypedPartitionAppender(builder.Append,
builder.AppendNull, appendScalar)
}
case iceberg.Float32Type:
if builder, ok := field.builder.(*array.Float32Builder); ok {
- return newInspectTypedPartitionAppender(builder.Append,
builder.AppendNull, appendScalar)
+ return newTypedPartitionAppender(builder.Append,
builder.AppendNull, appendScalar)
}
case iceberg.Float64Type:
if builder, ok := field.builder.(*array.Float64Builder); ok {
- return newInspectTypedPartitionAppender(builder.Append,
builder.AppendNull, appendScalar)
+ return newTypedPartitionAppender(builder.Append,
builder.AppendNull, appendScalar)
}
case iceberg.StringType:
if builder, ok := field.builder.(*array.StringBuilder); ok {
- return newInspectTypedPartitionAppender(builder.Append,
builder.AppendNull, appendScalar)
+ return newTypedPartitionAppender(builder.Append,
builder.AppendNull, appendScalar)
}
case iceberg.BinaryType:
if builder, ok := field.builder.(*array.BinaryBuilder); ok {
- return newInspectTypedPartitionAppender(builder.Append,
builder.AppendNull, appendScalar)
+ return newTypedPartitionAppender(builder.Append,
builder.AppendNull, appendScalar)
}
}
@@ -144,7 +144,7 @@ func newInspectPartitionFieldAppender(field
inspectPartitionFieldBuilder) func(a
}
}
-func newInspectTypedPartitionAppender[T any](
+func newTypedPartitionAppender[T any](
appendValue func(T),
appendNull func(),
appendScalar func(any) error,
@@ -165,7 +165,7 @@ func newInspectTypedPartitionAppender[T any](
}
}
-func inspectValueScalar(value any, typ iceberg.Type, arrowType arrow.DataType)
(scalar.Scalar, error) {
+func partitionValueScalar(value any, typ iceberg.Type, arrowType
arrow.DataType) (scalar.Scalar, error) {
switch typ.(type) {
case iceberg.DateType:
switch value := value.(type) {
@@ -213,3 +213,37 @@ func inspectValueScalar(value any, typ iceberg.Type,
arrowType arrow.DataType) (
return scalar.MakeScalarParam(value, arrowType)
}
+
+func newBuilderLookup(scope string, fields []arrow.Field, builder func(int)
array.Builder) (map[int]array.Builder, error) {
+ lookup := make(map[int]array.Builder, len(fields))
+ for idx, field := range fields {
+ id := getFieldID(field)
+ if id == nil {
+ return nil, fmt.Errorf("%s field %q is missing a valid
field ID", scope, field.Name)
+ }
+ if _, exists := lookup[*id]; exists {
+ return nil, fmt.Errorf("%s schema contains duplicate
field ID %d", scope, *id)
+ }
+ lookup[*id] = builder(idx)
+ }
+
+ return lookup, nil
+}
+
+func validateBuilderLookup(scope string, lookup map[int]array.Builder,
expected map[int]struct{}) error {
+ if len(lookup) != len(expected) {
+ return fmt.Errorf("%s schema has %d fields, want %d", scope,
len(lookup), len(expected))
+ }
+ for id := range lookup {
+ if _, ok := expected[id]; !ok {
+ return fmt.Errorf("%s schema contains unexpected field
ID %d", scope, id)
+ }
+ }
+ for id := range expected {
+ if _, ok := lookup[id]; !ok {
+ return fmt.Errorf("%s schema is missing field ID %d",
scope, id)
+ }
+ }
+
+ return nil
+}
diff --git a/table/inspect_partition_append_test.go
b/table/partition_struct_builder_test.go
similarity index 75%
rename from table/inspect_partition_append_test.go
rename to table/partition_struct_builder_test.go
index 9a9ba2fdb..27214ab98 100644
--- a/table/inspect_partition_append_test.go
+++ b/table/partition_struct_builder_test.go
@@ -25,11 +25,12 @@ import (
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/arrow-go/v18/arrow/decimal128"
"github.com/apache/arrow-go/v18/arrow/memory"
+ "github.com/apache/arrow-go/v18/arrow/scalar"
"github.com/apache/iceberg-go"
"github.com/stretchr/testify/require"
)
-func TestInspectPartitionBuilderAppendsTypedAndFallbackValues(t *testing.T) {
+func TestPartitionStructBuilderAppendsTypedAndFallbackValues(t *testing.T) {
tests := []struct {
name string
typ iceberg.Type
@@ -148,7 +149,7 @@ func
TestInspectPartitionBuilderAppendsTypedAndFallbackValues(t *testing.T) {
fields[i] = iceberg.NestedField{ID: i + 2, Name: tt.name, Type:
tt.typ}
values[i+2] = tt.value
}
- builder, partitionBuilder := newInspectPartitionBuilderForTest(t,
fields)
+ builder, partitionBuilder := newPartitionStructBuilderForTest(t, fields)
require.NoError(t, partitionBuilder.append(values))
partition := builder.NewArray().(*array.Struct)
@@ -160,8 +161,8 @@ func
TestInspectPartitionBuilderAppendsTypedAndFallbackValues(t *testing.T) {
}
}
-func TestInspectPartitionBuilderAppendsNullValues(t *testing.T) {
- builder, partitionBuilder := newInspectPartitionBuilderForTest(t,
[]iceberg.NestedField{
+func TestPartitionStructBuilderAppendsNullValues(t *testing.T) {
+ builder, partitionBuilder := newPartitionStructBuilderForTest(t,
[]iceberg.NestedField{
{ID: 2, Name: "value", Type: iceberg.PrimitiveTypes.Int32},
})
require.NoError(t, partitionBuilder.append(nil))
@@ -171,7 +172,7 @@ func TestInspectPartitionBuilderAppendsNullValues(t
*testing.T) {
require.True(t, partition.Field(0).IsNull(0))
}
-func TestInspectPartitionBuilderScalarFallbackPreservesValidation(t
*testing.T) {
+func TestPartitionStructBuilderScalarFallbackPreservesValidation(t *testing.T)
{
tests := []struct {
name string
typ iceberg.Type
@@ -186,7 +187,7 @@ func
TestInspectPartitionBuilderScalarFallbackPreservesValidation(t *testing.T)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- builder, partitionBuilder :=
newInspectPartitionBuilderForTest(t, []iceberg.NestedField{
+ builder, partitionBuilder :=
newPartitionStructBuilderForTest(t, []iceberg.NestedField{
{ID: 2, Name: "value", Type: tt.typ},
})
err := partitionBuilder.append(map[int]any{2: tt.value})
@@ -203,10 +204,10 @@ func
TestInspectPartitionBuilderScalarFallbackPreservesValidation(t *testing.T)
}
}
-func newInspectPartitionBuilderForTest(
+func newPartitionStructBuilderForTest(
t *testing.T,
fields []iceberg.NestedField,
-) (*array.StructBuilder, *inspectPartitionBuilder) {
+) (*array.StructBuilder, *partitionStructBuilder) {
t.Helper()
partitionType := iceberg.NewStructType(fields...)
schema, err := SchemaToArrowSchema(iceberg.NewSchema(0,
iceberg.NestedField{
@@ -217,13 +218,13 @@ func newInspectPartitionBuilderForTest(
require.True(t, ok)
builder := array.NewStructBuilder(memory.DefaultAllocator, structType)
t.Cleanup(builder.Release)
- partitionBuilder, err := newInspectPartitionBuilder(builder,
partitionType)
+ partitionBuilder, err := newPartitionStructBuilder(builder,
partitionType)
require.NoError(t, err)
return builder, partitionBuilder
}
-func TestInspectPartitionBuilderPreservesEmptyAndSpecialValues(t *testing.T) {
+func TestPartitionStructBuilderPreservesEmptyAndSpecialValues(t *testing.T) {
for _, tt := range []struct {
name string
typ iceberg.Type
@@ -236,7 +237,7 @@ func
TestInspectPartitionBuilderPreservesEmptyAndSpecialValues(t *testing.T) {
{"float64 NaN", iceberg.PrimitiveTypes.Float64, math.NaN(),
func(t *testing.T, a arrow.Array) { require.True(t,
math.IsNaN(a.(*array.Float64).Value(0))) }},
} {
t.Run(tt.name, func(t *testing.T) {
- builder, partitionBuilder :=
newInspectPartitionBuilderForTest(t, []iceberg.NestedField{{ID: 2, Name:
"value", Type: tt.typ}})
+ builder, partitionBuilder :=
newPartitionStructBuilderForTest(t, []iceberg.NestedField{{ID: 2, Name:
"value", Type: tt.typ}})
require.NoError(t,
partitionBuilder.append(map[int]any{2: tt.value}))
require.NoError(t, partitionBuilder.append(nil))
partition := builder.NewArray().(*array.Struct)
@@ -248,8 +249,8 @@ func
TestInspectPartitionBuilderPreservesEmptyAndSpecialValues(t *testing.T) {
}
}
-func TestInspectPartitionBuilderCopiesBinaryValues(t *testing.T) {
- builder, partitionBuilder := newInspectPartitionBuilderForTest(t,
[]iceberg.NestedField{{ID: 2, Name: "value", Type:
iceberg.PrimitiveTypes.Binary}})
+func TestPartitionStructBuilderCopiesBinaryValues(t *testing.T) {
+ builder, partitionBuilder := newPartitionStructBuilderForTest(t,
[]iceberg.NestedField{{ID: 2, Name: "value", Type:
iceberg.PrimitiveTypes.Binary}})
value := []byte("abc")
require.NoError(t, partitionBuilder.append(map[int]any{2: value}))
value[0] = 'x'
@@ -257,3 +258,36 @@ func TestInspectPartitionBuilderCopiesBinaryValues(t
*testing.T) {
defer partition.Release()
require.Equal(t, []byte("abc"),
partition.Field(0).(*array.Binary).Value(0))
}
+
+func TestPartitionValueScalarDecimal(t *testing.T) {
+ typ := iceberg.MustDecimalTypeOf(10, 2)
+ arrowType := &arrow.Decimal128Type{Precision: 10, Scale: 2}
+ value := iceberg.DecimalLiteral{Val: decimal128.FromI64(123), Scale: 2}
+
+ got, err := partitionValueScalar(value, typ, arrowType)
+ require.NoError(t, err)
+ require.Equal(t, value.Val, got.(*scalar.Decimal128).Value)
+}
+
+func TestPartitionValueScalarRejectsMismatchedPartitionValues(t *testing.T) {
+ tests := []struct {
+ name string
+ value any
+ typ iceberg.Type
+ arrowType arrow.DataType
+ want string
+ }{
+ {name: "date", value: int64(1), typ:
iceberg.PrimitiveTypes.Date, arrowType: arrow.FixedWidthTypes.Date32, want:
"unsupported date"},
+ {name: "time", value: int64(1), typ:
iceberg.PrimitiveTypes.Time, arrowType: arrow.FixedWidthTypes.Time64us, want:
"unsupported time"},
+ {name: "timestamp", value: int64(1), typ:
iceberg.PrimitiveTypes.Timestamp, arrowType:
arrow.FixedWidthTypes.Timestamp_us, want: "unsupported timestamp"},
+ {name: "timestamp nanos", value: int64(1), typ:
iceberg.PrimitiveTypes.TimestampNs, arrowType:
arrow.FixedWidthTypes.Timestamp_ns, want: "unsupported nanosecond timestamp"},
+ {name: "UUID", value: []byte("not-a-UUID"), typ:
iceberg.PrimitiveTypes.UUID, arrowType: &arrow.FixedSizeBinaryType{ByteWidth:
16}, want: "unsupported UUID"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ _, err := partitionValueScalar(tt.value, tt.typ,
tt.arrowType)
+ require.ErrorContains(t, err, tt.want)
+ })
+ }
+}
diff --git a/table/inspect_snapshot_prefetch.go
b/table/snapshot_manifest_stream.go
similarity index 87%
rename from table/inspect_snapshot_prefetch.go
rename to table/snapshot_manifest_stream.go
index 82e79ccfc..6041b9421 100644
--- a/table/inspect_snapshot_prefetch.go
+++ b/table/snapshot_manifest_stream.go
@@ -24,9 +24,9 @@ import (
"github.com/apache/iceberg-go"
)
-const inspectSnapshotManifestPrefetch = 8
+const snapshotManifestPrefetch = 8
-type inspectSnapshotManifestRead struct {
+type snapshotManifestRead struct {
set snapshotManifestSet
err error
}
@@ -85,8 +85,8 @@ func streamSnapshotManifests(
if cached != nil {
start := 0
for start < len(snapshots) {
- count := min(inspectSnapshotManifestPrefetch,
len(snapshots)-start)
- var sets
[inspectSnapshotManifestPrefetch]snapshotManifestSet
+ count := min(snapshotManifestPrefetch,
len(snapshots)-start)
+ var sets [snapshotManifestPrefetch]snapshotManifestSet
allCached := true
for i := range count {
set, ok := cached(snapshots[start+i])
@@ -145,10 +145,10 @@ func streamSnapshotManifests(
workers.Wait()
}()
- window := min(len(snapshots), inspectSnapshotManifestPrefetch)
- results := make([]chan inspectSnapshotManifestRead, window)
+ window := min(len(snapshots), snapshotManifestPrefetch)
+ results := make([]chan snapshotManifestRead, window)
ready := make([]bool, window)
- readyResults := make([]inspectSnapshotManifestRead, window)
+ readyResults := make([]snapshotManifestRead, window)
startRead := func(index int) {
if cancel == nil {
@@ -157,12 +157,12 @@ func streamSnapshotManifests(
slot := index % window
if results[slot] == nil {
// Buffer one result so a cancelled worker never blocks
sending it.
- results[slot] = make(chan inspectSnapshotManifestRead,
1)
+ results[slot] = make(chan snapshotManifestRead, 1)
}
ready[slot] = false
workers.Go(func() {
set, err := load(readCtx, snapshots[index])
- results[slot] <- inspectSnapshotManifestRead{set: set,
err: err}
+ results[slot] <- snapshotManifestRead{set: set, err:
err}
})
}
@@ -170,7 +170,7 @@ func streamSnapshotManifests(
if cached != nil {
if set, ok := cached(snapshots[i]); ok {
ready[i] = true
- readyResults[i] =
inspectSnapshotManifestRead{set: set}
+ readyResults[i] = snapshotManifestRead{set: set}
continue
}
@@ -186,7 +186,7 @@ func streamSnapshotManifests(
}
slot := i % window
- var result inspectSnapshotManifestRead
+ var result snapshotManifestRead
if ready[slot] {
result = readyResults[slot]
ready[slot] = false
@@ -212,7 +212,7 @@ func streamSnapshotManifests(
if cached != nil {
if set, ok := cached(snapshots[next]); ok {
ready[slot] = true
- readyResults[slot] =
inspectSnapshotManifestRead{set: set}
+ readyResults[slot] =
snapshotManifestRead{set: set}
} else {
startRead(next)
}
diff --git a/table/inspect_snapshot_prefetch_test.go
b/table/snapshot_manifest_stream_test.go
similarity index 91%
rename from table/inspect_snapshot_prefetch_test.go
rename to table/snapshot_manifest_stream_test.go
index bb61abc10..a6c5a7037 100644
--- a/table/inspect_snapshot_prefetch_test.go
+++ b/table/snapshot_manifest_stream_test.go
@@ -29,14 +29,14 @@ import (
"github.com/stretchr/testify/require"
)
-func TestInspectSnapshotManifestPrefetchPreservesOrderAndBoundsReads(t
*testing.T) {
+func TestSnapshotManifestPrefetchPreservesOrderAndBoundsReads(t *testing.T) {
snapshots := make([]Snapshot, 25)
for i := range snapshots {
snapshots[i].SnapshotID = int64(i + 1)
}
ctx := t.Context()
- started := make(chan int64, inspectSnapshotManifestPrefetch)
+ started := make(chan int64, snapshotManifestPrefetch)
release := make(chan struct{})
defer func() {
select {
@@ -61,7 +61,7 @@ func
TestInspectSnapshotManifestPrefetchPreservesOrderAndBoundsReads(t *testing.
}
}
- if snapshot.SnapshotID <=
inspectSnapshotManifestPrefetch {
+ if snapshot.SnapshotID <=
snapshotManifestPrefetch {
started <- snapshot.SnapshotID
}
select {
@@ -89,7 +89,7 @@ func
TestInspectSnapshotManifestPrefetchPreservesOrderAndBoundsReads(t *testing.
}()
var firstWindow []int64
- for range inspectSnapshotManifestPrefetch {
+ for range snapshotManifestPrefetch {
select {
case id := <-started:
firstWindow = append(firstWindow, id)
@@ -101,7 +101,7 @@ func
TestInspectSnapshotManifestPrefetchPreservesOrderAndBoundsReads(t *testing.
for i, id := range firstWindow {
require.Equal(t, int64(i+1), id)
}
- require.EqualValues(t, inspectSnapshotManifestPrefetch,
maxActive.Load())
+ require.EqualValues(t, snapshotManifestPrefetch, maxActive.Load())
close(release)
select {
@@ -114,10 +114,10 @@ func
TestInspectSnapshotManifestPrefetchPreservesOrderAndBoundsReads(t *testing.
t.Fatal("manifest prefetch failed to finish")
}
require.EqualValues(t, 0, active.Load())
- require.LessOrEqual(t, maxActive.Load(),
int32(inspectSnapshotManifestPrefetch))
+ require.LessOrEqual(t, maxActive.Load(),
int32(snapshotManifestPrefetch))
}
-func TestInspectSnapshotManifestPrefetchUsesCachedSets(t *testing.T) {
+func TestSnapshotManifestPrefetchUsesCachedSets(t *testing.T) {
snapshots := make([]Snapshot, 12)
cachedSets := make(map[int64]snapshotManifestSet)
for i := range snapshots {
@@ -158,7 +158,7 @@ func TestInspectSnapshotManifestPrefetchUsesCachedSets(t
*testing.T) {
}
}
-func TestInspectSnapshotManifestPrefetchDeduplicatesPaths(t *testing.T) {
+func TestSnapshotManifestPrefetchDeduplicatesPaths(t *testing.T) {
snapshots := []Snapshot{{SnapshotID: 1}, {SnapshotID: 2}, {SnapshotID:
3}}
manifests := [][]string{{"a.avro", "shared.avro"}, {"shared.avro",
"b.avro"}, {"a.avro", "c.avro"}}
var paths []string
@@ -181,7 +181,7 @@ func TestInspectSnapshotManifestPrefetchDeduplicatesPaths(t
*testing.T) {
require.Equal(t, []string{"a.avro", "shared.avro", "b.avro", "c.avro"},
paths)
}
-func TestInspectSnapshotManifestPrefetchStopsReadersOnEarlyExit(t *testing.T) {
+func TestSnapshotManifestPrefetchStopsReadersOnEarlyExit(t *testing.T) {
snapshots := make([]Snapshot, 30)
for i := range snapshots {
snapshots[i].SnapshotID = int64(i + 1)
@@ -212,7 +212,7 @@ func
TestInspectSnapshotManifestPrefetchStopsReadersOnEarlyExit(t *testing.T) {
require.EqualValues(t, 0, active.Load(), "all workers must finish
before return")
}
-func TestInspectSnapshotManifestPrefetchReportsFirstOrderedError(t *testing.T)
{
+func TestSnapshotManifestPrefetchReportsFirstOrderedError(t *testing.T) {
failure := errors.New("manifest load failed")
snapshots := []Snapshot{{SnapshotID: 1}, {SnapshotID: 2}, {SnapshotID:
3}}
var paths []string
@@ -244,7 +244,7 @@ func
TestInspectSnapshotManifestPrefetchReportsFirstOrderedError(t *testing.T) {
require.ErrorContains(t, gotErr, "snapshot 2")
}
-func BenchmarkInspectSnapshotManifestListPrefetch(b *testing.B) {
+func BenchmarkSnapshotManifestListPrefetch(b *testing.B) {
const snapshotCount = 64
snapshots := make([]Snapshot, snapshotCount)
for i := range snapshots {
@@ -289,7 +289,7 @@ func BenchmarkInspectSnapshotManifestListPrefetch(b
*testing.B) {
})
}
-func BenchmarkInspectSnapshotManifestListCacheHit(b *testing.B) {
+func BenchmarkSnapshotManifestListCacheHit(b *testing.B) {
cache := newSnapshotManifestCache()
for _, count := range []int{1, 64} {
diff --git a/table/unified_partition_type.go b/table/unified_partition_type.go
new file mode 100644
index 000000000..ad3e65af3
--- /dev/null
+++ b/table/unified_partition_type.go
@@ -0,0 +1,134 @@
+// 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"
+ "slices"
+ "sort"
+
+ "github.com/apache/iceberg-go"
+ iceinternal "github.com/apache/iceberg-go/internal"
+)
+
+// unifiedPartitionType returns the table-wide partition type. It contains the
+// union of partition fields from every spec, which lets metadata tables
+// represent live files written before partition evolution.
+func unifiedPartitionType(metadata Metadata) (*iceberg.StructType, error) {
+ return unifiedPartitionTypeWithSchema(metadata,
metadata.CurrentSchema())
+}
+
+func unifiedPartitionTypeWithSchema(
+ metadata Metadata,
+ currentSchema *iceberg.Schema,
+) (*iceberg.StructType, error) {
+ specs := metadata.PartitionSpecs()
+ sort.Slice(specs, func(left, right int) bool {
+ return specs[left].ID() > specs[right].ID()
+ })
+
+ selected := make(map[int]iceberg.PartitionField)
+ fieldsByID := make(map[int]iceberg.NestedField)
+ for _, spec := range specs {
+ for _, field := range spec.Fields() {
+ if isUnknownPartitionTransform(field.Transform) {
+ return nil, fmt.Errorf("%w: cannot build
metadata partition type for field %d with unknown transform %s",
+ iceberg.ErrInvalidPartitionSpec,
field.FieldID, field.Transform)
+ }
+ }
+
+ partitionType := spec.PartitionType(currentSchema)
+ for idx, field := range spec.Fields() {
+ active := true
+ for _, sourceID := range field.SourceIDs {
+ // This is an existence check only.
FindTypeByID clones the
+ // complete nested type on every call, which is
wasteful while
+ // building the union of position-delete
partition fields.
+ if _, ok :=
currentSchema.FindFieldByIDRef(sourceID, iceinternal.SchemaRef{}); !ok {
+ active = false
+
+ break
+ }
+ }
+ if !active || idx >= partitionType.NumFields() {
+ continue
+ }
+
+ if previous, exists := selected[field.FieldID]; exists {
+ if !slices.Equal(previous.SourceIDs,
field.SourceIDs) {
+ return nil, fmt.Errorf("%w: partition
field ID %d has incompatible source IDs %v and %v",
+
iceberg.ErrInvalidPartitionSpec, field.FieldID, previous.SourceIDs,
field.SourceIDs)
+ }
+
+ previousVoid :=
isVoidPartitionTransform(previous.Transform)
+ fieldVoid :=
isVoidPartitionTransform(field.Transform)
+ if previousVoid || fieldVoid {
+ if previousVoid && !fieldVoid {
+ selected[field.FieldID] = field
+ old := fieldsByID[field.FieldID]
+ old.Type =
partitionType.Field(idx).Type
+ fieldsByID[field.FieldID] = old
+ }
+
+ continue
+ }
+
+ if !previous.Transform.Equals(field.Transform) {
+ return nil, fmt.Errorf("%w: partition
field ID %d has incompatible transforms %q and %q",
+
iceberg.ErrInvalidPartitionSpec, field.FieldID, previous.Transform,
field.Transform)
+ }
+
+ continue
+ }
+
+ selected[field.FieldID] = field
+ fieldsByID[field.FieldID] = iceberg.NestedField{
+ ID: field.FieldID,
+ Name: field.Name,
+ Type: partitionType.Field(idx).Type,
+ Required: false,
+ }
+ }
+ }
+
+ fields := make([]iceberg.NestedField, 0, len(fieldsByID))
+ for _, field := range fieldsByID {
+ fields = append(fields, field)
+ }
+ sort.Slice(fields, func(left, right int) bool { return fields[left].ID
< fields[right].ID })
+
+ return iceberg.NewStructType(fields...), nil
+}
+
+func isVoidPartitionTransform(transform iceberg.Transform) bool {
+ switch transform.(type) {
+ case iceberg.VoidTransform, *iceberg.VoidTransform:
+ return true
+ default:
+ return false
+ }
+}
+
+func isUnknownPartitionTransform(transform iceberg.Transform) bool {
+ switch transform.(type) {
+ case iceberg.UnknownTransform, *iceberg.UnknownTransform:
+ return true
+ default:
+ return false
+ }
+}
diff --git a/table/unified_partition_type_test.go
b/table/unified_partition_type_test.go
new file mode 100644
index 000000000..de8c1ec86
--- /dev/null
+++ b/table/unified_partition_type_test.go
@@ -0,0 +1,138 @@
+// 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 (
+ "testing"
+
+ "github.com/apache/iceberg-go"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+)
+
+func TestUnifiedPartitionTypeUsesAllActiveSpecs(t *testing.T) {
+ schema := iceberg.NewSchema(0,
+ iceberg.NestedField{ID: 1, Name: "region", Type:
iceberg.PrimitiveTypes.String, Required: true},
+ iceberg.NestedField{ID: 2, Name: "category", Type:
iceberg.PrimitiveTypes.String, Required: true},
+ )
+ oldSpec := iceberg.NewPartitionSpecID(0, iceberg.PartitionField{
+ SourceIDs: []int{1}, FieldID: 1000, Name: "region", Transform:
iceberg.IdentityTransform{},
+ })
+ newSpec := iceberg.NewPartitionSpecID(1, iceberg.PartitionField{
+ SourceIDs: []int{2}, FieldID: 1001, Name: "category",
Transform: iceberg.IdentityTransform{},
+ })
+ lastPartitionID := 1001
+ meta := &metadataV2{commonMetadata: commonMetadata{
+ FormatVersion: 2,
+ UUID: uuid.New(),
+ LastColumnId: 2,
+ SchemaList: []*iceberg.Schema{schema},
+ CurrentSchemaID: 0,
+ Specs: []iceberg.PartitionSpec{oldSpec, newSpec},
+ DefaultSpecID: 1,
+ LastPartitionID: &lastPartitionID,
+ SnapshotRefs: map[string]SnapshotRef{},
+ }}
+
+ partitionType, err := unifiedPartitionType(meta)
+ require.NoError(t, err)
+ require.Equal(t, []int{1000, 1001}, []int{
+ partitionType.Field(0).ID,
+ partitionType.Field(1).ID,
+ })
+ require.Equal(t, []string{"region", "category"}, []string{
+ partitionType.Field(0).Name,
+ partitionType.Field(1).Name,
+ })
+}
+
+func TestUnifiedPartitionTypeRejectsIncompatibleFieldReuse(t *testing.T) {
+ schema := iceberg.NewSchema(0,
+ iceberg.NestedField{ID: 1, Name: "first", Type:
iceberg.PrimitiveTypes.Int32, Required: true},
+ iceberg.NestedField{ID: 2, Name: "second", Type:
iceberg.PrimitiveTypes.Int32, Required: true},
+ )
+ metadataFor := func(specs []iceberg.PartitionSpec) Metadata {
+ lastPartitionID := 1000
+
+ return &metadataV2{commonMetadata: commonMetadata{
+ FormatVersion: 2,
+ UUID: uuid.New(),
+ LastColumnId: 2,
+ SchemaList: []*iceberg.Schema{schema},
+ CurrentSchemaID: 0,
+ Specs: specs,
+ DefaultSpecID: specs[len(specs)-1].ID(),
+ LastPartitionID: &lastPartitionID,
+ }}
+ }
+ field := func(specID, sourceID int, transform iceberg.Transform)
iceberg.PartitionSpec {
+ return iceberg.NewPartitionSpecID(specID,
iceberg.PartitionField{
+ SourceIDs: []int{sourceID}, FieldID: 1000, Name:
"part", Transform: transform,
+ })
+ }
+
+ tests := []struct {
+ name string
+ specs []iceberg.PartitionSpec
+ valid bool
+ }{
+ {
+ name: "void transition is compatible",
+ specs: []iceberg.PartitionSpec{field(0, 1,
iceberg.IdentityTransform{}), field(1, 1, iceberg.VoidTransform{})},
+ valid: true,
+ },
+ {
+ name: "pointer void transition is compatible",
+ specs: []iceberg.PartitionSpec{field(0, 1,
iceberg.IdentityTransform{}), field(1, 1, &iceberg.VoidTransform{})},
+ valid: true,
+ },
+ {
+ name: "different source ids",
+ specs: []iceberg.PartitionSpec{field(0, 1,
iceberg.IdentityTransform{}), field(1, 2, iceberg.IdentityTransform{})},
+ },
+ {
+ name: "different transforms",
+ specs: []iceberg.PartitionSpec{field(0, 1,
iceberg.IdentityTransform{}), field(1, 1, iceberg.BucketTransform{NumBuckets:
16})},
+ },
+ {
+ name: "void cannot hide incompatible history",
+ specs: []iceberg.PartitionSpec{
+ field(0, 1, iceberg.BucketTransform{NumBuckets:
16}),
+ field(1, 1, iceberg.IdentityTransform{}),
+ field(2, 1, iceberg.VoidTransform{}),
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ _, err := unifiedPartitionType(metadataFor(tt.specs))
+ if tt.valid {
+ require.NoError(t, err)
+
+ return
+ }
+ require.ErrorIs(t, err, iceberg.ErrInvalidPartitionSpec)
+ })
+ }
+
+ unknown, err := iceberg.ParseTransform("future_transform")
+ require.NoError(t, err)
+ _, err =
unifiedPartitionType(metadataFor([]iceberg.PartitionSpec{field(0, 1, unknown)}))
+ require.ErrorIs(t, err, iceberg.ErrInvalidPartitionSpec)
+}